diff --git a/docs/advanced-guides/Utils/Distance.md b/docs/advanced-guides/Utils/Distance.md index a3d758f8..1ac5aba8 100644 --- a/docs/advanced-guides/Utils/Distance.md +++ b/docs/advanced-guides/Utils/Distance.md @@ -16,7 +16,9 @@ def hamming(u: npt.NDArray, v: npt.NDArray) -> np.float64: The function to calculate the normalized Hamming distance between two points. -$$\frac{(x_1 \neq y_1) + (x_2 \neq y_2) + \cdots + (x_n \neq y_n)}{n}$$ +$$ +\frac{(x_1 \neq y_1) + (x_2 \neq y_2) + \cdots + (x_n \neq y_n)}{n} +$$ **Parameters:** @@ -37,7 +39,9 @@ def euclidean(u: npt.NDArray[np.float64], v: npt.NDArray[np.float64]) -> np.floa Function to calculate the normalized Euclidean distance between two points. -$$\sqrt{(X_{1} - X_{1})^2 + (Y_{2} - Y_{2})^2 + \cdots + (Y_{n} - Y_{n})^2}$$ +$$ +\sqrt{(X_{1} - X_{1})^2 + (Y_{2} - Y_{2})^2 + \cdots + (Y_{n} - Y_{n})^2} +$$ **Parameters:** @@ -58,7 +62,9 @@ def cityblock(u: npt.NDArray[np.float64], v: npt.NDArray[np.float64]) -> np.floa Function to calculate the normalized Manhattan distance between two points. -$$\frac{(|X_{1} - X_{1}| + |Y_{2} - Y_{2}| + \cdots + |Y_{n} - Y_{n}|)}{n}$$ +$$ +\frac{(|X_{1} - X_{1}| + |Y_{2} - Y_{2}| + \cdots + |Y_{n} - Y_{n}|)}{n} +$$ **Parameters:** @@ -79,7 +85,9 @@ def minkowski(u: npt.NDArray[np.float64], v: npt.NDArray[np.float64], p: float = Function to calculate the normalized Minkowski distance between two points. -$$\frac{((|X_{1} - Y_{1}|^p + |X_{2} - Y_{2}|^p + \cdots + |X_{n} - Y_{n}|^p)^\frac{1}{p})}{n}$$ +$$ +\frac{((|X_{1} - Y_{1}|^p + |X_{2} - Y_{2}|^p + \cdots + |X_{n} - Y_{n}|^p)^\frac{1}{p})}{n} +$$ **Parameters:** diff --git a/docs/advanced-guides/Utils/Multiclass.md b/docs/advanced-guides/Utils/Multiclass.md index 83c58b1d..dc919f82 100644 --- a/docs/advanced-guides/Utils/Multiclass.md +++ b/docs/advanced-guides/Utils/Multiclass.md @@ -8,7 +8,7 @@ author: João Paulo This file contains internal utility functions designed to simplify data manipulation and processing in multiclass classification scenarios within the AISP package. -### def slice_index_list_by_class(...) +## def slice_index_list_by_class(...) ```python def slice_index_list_by_class(classes: Union[npt.NDArray, list], y: npt.NDArray) -> dict @@ -26,3 +26,29 @@ the output is the class being trained. **returns**: * dict: A dictionary with the list of array positions(``y``), with the classes as key. + +--- + +## def predict_knn_affinity(...) + +```python +def predict_knn_affinity( + X: npt.NDArray, + k: int, + all_cell_vectors: List[Tuple[Union[str, int], npt.NDArray]], + affinity_func: Callable[[npt.NDArray, npt.NDArray], float] +) -> npt.NDArray +``` + +Function to predict classes using k-nearest neighbors and trained cells. + +**Parameters:** + +* ***X*** (`npt.NDArray`): Input data to be classified. +* ***k*** (`int`): Number of nearest neighbors to consider for prediction. +* ***all_cell_vectors*** (`List[Tuple[Union[str, int], npt.NDArray]]`): List of tuples containing (class_name, cell vector) pairs. +* ***affinity_func*** (`Callable[[npt.NDArray, npt.NDArray], float]`): Function that takes two vectors and returns an affinity value. + +**Returns:** + +* `npt.NDArray`: Array of predicted labels for each sample in X, based on the k nearest neighbors. diff --git a/docs/advanced-guides/Utils/Random.md b/docs/advanced-guides/Utils/Random.md new file mode 100644 index 00000000..8bcd0393 --- /dev/null +++ b/docs/advanced-guides/Utils/Random.md @@ -0,0 +1,17 @@ +# Random + +Utility functions for random number generation and reproducibility. + +## Function set_seed_numba(...) + +```python +@njit(cache=True) +def set_seed_numba(seed: int) +``` + +Set the seed for random numbers used by functions compiled with Numba. + +**Parameters**: + +* **seed**: `int` + Integer value used to initialize Numba's random number generator. diff --git a/docs/advanced-guides/Utils/Validation.md b/docs/advanced-guides/Utils/Validation.md index fdbcb573..c0d5bba6 100644 --- a/docs/advanced-guides/Utils/Validation.md +++ b/docs/advanced-guides/Utils/Validation.md @@ -16,14 +16,89 @@ This function analyzes the input vector and classifies its data as one of the su * **continuous**: Float values within the normalized range `[0.0, 1.0]`. * **ranged**: Float values outside the normalized range. -**Parameters** +### Parameters * `vector` (`npt.NDArray`): An array containing the data to be classified. -**Returns** +### Returns * `FeatureType` (`Literal["binary-features", "continuous-features", "ranged-features"]`): The detected type of data in the vector. -**Raises** +### Raises * `UnsupportedDataTypeError`: Raised if the vector contains an unsupported data type. + +--- + +## def check_array_type(...) + +```python +def check_array_type(x, name: str = "X") -> npt.NDArray: +``` + +Ensure X is a numpy array. Convert from list if needed. + +### Parameters + +* `x` (`Any`): Array, containing the samples and their characteristics, \[`N samples` (rows)\]\[`N features` (columns)\]. +* `name` (`str`, default='X'): Variable name used in error messages. + +### Returns + +* `npt.NDArray`: The converted or validated array. + +### Raises + +* `TypeError`: If X or y are not ndarrays or have incompatible shapes. + +--- + +## def check_shape_match(...) + +```python +def check_shape_match(x: npt.NDArray, y: npt.NDArray): +``` + +Ensure X and y have compatible first dimensions. + +### Parameters + +* `x` (`npt.NDArray`): Array, containing the samples and their characteristics, \[`N samples` (rows)\]\[`N features` (columns)\]. +* `y` (`npt.NDArray`): Array of target classes of `x` with [`N samples` (lines)]. + +### Raises + +* `TypeError`: If x or y are not ndarrays or have incompatible shapes. + +--- + +## def check_feature_dimension(...) + +```python +def check_feature_dimension(x: npt.NDArray, expected: int): +``` + +Ensure X has the expected number of features. + +### Parameters + +* `x` (`npt.NDArray`): Input array for prediction, containing the samples and their characteristics, \[`N samples` (rows)\]\[`N features` (columns)\]. +* `expected` (`int`): Expected number of features per sample (columns in X). + +### Raises + +* `FeatureDimensionMismatch`: If the number of features in X does not match the expected number. + +--- + +## def check_binary_array(...) + +```python +def check_binary_array(x: npt.NDArray): +``` + +Ensure X contains only 0 and 1. + +### Raises + +* `ValueError`: If feature_type is binary-features and X contains values that are not composed only of 0 and 1. diff --git a/docs/advanced-guides/base-classes-reference/_category_.json b/docs/advanced-guides/base-classes-reference/_category_.json deleted file mode 100644 index d5ae9afd..00000000 --- a/docs/advanced-guides/base-classes-reference/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "label": "Base classes reference", - "position": 2, - "description": "Base classes for implementing the algorithms provided in this package." -} \ No newline at end of file diff --git a/docs/advanced-guides/base-classes-reference/csa/README.mdx b/docs/advanced-guides/base-classes-reference/csa/README.mdx deleted file mode 100644 index 2b7d8d5c..00000000 --- a/docs/advanced-guides/base-classes-reference/csa/README.mdx +++ /dev/null @@ -1,11 +0,0 @@ ---- -sidebar_position: 2.61 ---- - -import DocCardList from '@theme/DocCardList'; - -# Clonal Selection Algorithms - -The base classes provide the core framework for implementing Clonal Selection Algorithm techniques. - - \ No newline at end of file diff --git a/docs/advanced-guides/base-classes-reference/csa/airs.md b/docs/advanced-guides/base-classes-reference/csa/airs.md deleted file mode 100644 index 9b48c5d6..00000000 --- a/docs/advanced-guides/base-classes-reference/csa/airs.md +++ /dev/null @@ -1,91 +0,0 @@ ---- -sidebar_position: 1 -title: Artificial Immune Recognition System Base -sidebar_label: Artificial Immune Recognition System -lastUpdatedAt: 2025/05/25 -author: João Paulo -keywords: - - BaseAIRS - - AIRS - - Artificial Immune Recognition System - - Artificial Immune Systems - - Base Classifier - - Continuous Features - - Binary Features - - Feature Validation - - Machine Learning - - Classification ---- - -Base class for algorithm **AIRS**. - -## ``BaseAIRS(BaseClassifier, ABC)`` - -The base class contains functions that are used by more than one class in the package, and -therefore are considered essential for the overall functioning of the system. - ---- - -### def _check_and_raise_exceptions_fit(...) - - Verify the fit parameters and throw exceptions if the verification is not successful. - -```python -@staticmethod -def _check_and_raise_exceptions_fit( - X: npt.NDArray = None, - y: npt.NDArray = None, - algorithm: Literal[ - "continuous-features", "binary-features" - ] = "continuous-features" -): -``` - -**Parameters**: - -* ***X*** (``npt.NDArray``): Training array, containing the samples and their characteristics, \[``N samples`` (rows)\]\[``N features`` (columns)\]. -* ***y*** (``npt.NDArray``): Array of target classes of ``X`` with \[``N samples`` (lines)]. -* ***algorithm*** (``Literal["continuous-features", "binary-features"], optional``): Specifies the type of algorithm to use, depending -on whether the input data has continuous or binary features. - -**Raises** - -* `TypeError`: - If X or y are not ndarrays or have incompatible shapes. -* `ValueError` - If *class* is BNSA and X contains values that are not composed only of 0 and 1. - ---- - -### def _check_and_raise_exceptions_predict(...) - - Verify the fit parameters and throw exceptions if the verification is not successful. - -```python -@staticmethod -def _check_and_raise_exceptions_predict( - X: npt.NDArray = None, - expected: int = 0, - algorithm: Literal[ - "continuous-features", "binary-features" - ] = "continuous-features" -) -> None: -``` - -**Parameters**: - -* ***X*** (``npt.NDArray``): Training array, containing the samples and their characteristics, \[``N samples`` (rows)\]\[``N features`` (columns)]. -* ***expected*** (``int``): Expected number of features per sample (columns in X). -* ***algorithm*** (``Literal["continuous-features", "binary-features"], optional``): Specifies the type of algorithm to use, depending -on whether the input data has continuous or binary features. - -**Raises** - -* ``TypeError`` - If X is not a ndarray or list. -* `FeatureDimensionMismatch` - If the number of features in X does not match the expected number. -* `ValueError` - If algorithm is binary-features and X contains values that are not composed only of 0 and 1. - ---- diff --git a/docs/advanced-guides/base-classes-reference/ina/README.mdx b/docs/advanced-guides/base-classes-reference/ina/README.mdx deleted file mode 100644 index 92be3d08..00000000 --- a/docs/advanced-guides/base-classes-reference/ina/README.mdx +++ /dev/null @@ -1,11 +0,0 @@ ---- -sidebar_position: 2.71 ---- - -import DocCardList from '@theme/DocCardList'; - -# Immune Network Algorithms - -The base classes provide the core framework for implementing Immune Network Algorithm techniques. - - \ No newline at end of file diff --git a/docs/advanced-guides/base-classes-reference/ina/ainet.md b/docs/advanced-guides/base-classes-reference/ina/ainet.md deleted file mode 100644 index 7a21c8b5..00000000 --- a/docs/advanced-guides/base-classes-reference/ina/ainet.md +++ /dev/null @@ -1,99 +0,0 @@ ---- -sidebar_position: 1 -title: Artificial Immune Network Base -sidebar_label: Artificial Immune Network -lastUpdatedAt: 2025/05/25 -author: João Paulo -keywords: - - AiNet - - Immune Network Theory - - Clustering - - BaseAiNet - - Artificial Immune Systems - - Antibodies ---- - -Base class for Network Theory algorithms based on AiNet. - -## ``BaseAiNet(BaseClusterer, ABC)`` - -The base class contains functions that are used by multiple classes in the AiNet package and -are considered essential for proper functioning of clustering algorithms based on immune network theory. - ---- - -### def _check_and_raise_exceptions_fit(...) - -Verify the fit parameters and throw exceptions if the verification is not successful. - -```python -@staticmethod -def _check_and_raise_exceptions_fit(X: npt.NDArray) -``` - -**Parameters**: - -* ***X*** (`npt.NDArray`): Training array, containing the samples and their characteristics, \\[`N samples` (rows)]\\[`N features` (columns)]. - -**Raises**: - -* `TypeError`: If X is not an ndarray or list. - ---- - -### def _check_and_raise_exceptions_predict(...) - -Verify the predict parameters and throw exceptions if the verification is not successful. - -```python -@staticmethod -def _check_and_raise_exceptions_predict( - X: npt.NDArray, - expected: int = 0, - feature_type: FeatureType = "continuous-features" -) -> None -``` - -**Parameters**: - -* ***X*** (`npt.NDArray`): Input array for prediction, containing the samples and their characteristics, \\[`N samples` (rows)]\\[`N features` (columns)]. -* ***expected*** (`int`, default=0): Expected number of features per sample (columns in X). -* ***feature_type*** (`FeatureType`, default="continuous-features"): Specifies the type of features: "continuous-features", "binary-features", or "ranged-features". - -**Raises**: - -* `TypeError`: If X is not an ndarray or list. -* `FeatureDimensionMismatch`: If the number of features in X does not match the expected number. -* `ValueError`: If feature_type is "binary-features" and X contains values other than 0 and 1. - ---- - -### def _generate_random_antibodies(...) - -Generate a random antibody population. - -```python -@staticmethod -def _generate_random_antibodies( - n_samples: int, - n_features: int, - feature_type: FeatureType = "continuous-features", - bounds: Optional[npt.NDArray[np.float64]] = None -) -> npt.NDArray -``` - -**Parameters**: - -* ***n_samples*** (`int`): Number of antibodies (samples) to generate. -* ***n_features*** (`int`): Number of features (dimensions) for each antibody. -* ***feature_type*** (`FeatureType`, default="continuous-features"): Specifies the type of features: "continuous-features", "binary-features", or "ranged-features". -* ***bounds*** (`Optional[npt.NDArray[np.float64]]`): Array of shape (n_features, 2) with min and max per dimension (used only for ranged features). - -**Returns**: - -* `npt.NDArray`: Array of shape (n_samples, n_features) containing the generated antibodies. - Data type depends on the feature_type (float for continuous/ranged, bool for binary). - -**Raises**: - -* `ValueError`: If n_features $<=$ 0. diff --git a/docs/advanced-guides/base-classes-reference/nsa.md b/docs/advanced-guides/base-classes-reference/nsa.md deleted file mode 100644 index 021c4575..00000000 --- a/docs/advanced-guides/base-classes-reference/nsa.md +++ /dev/null @@ -1,88 +0,0 @@ ---- -sidebar_position: 1 -title: Negative Selection Base -sidebar_label: Negative Selection -lastUpdatedAt: 2025/04/04 -author: João Paulo -keywords: - - BaseNSA - - Negative Selection - - Artificial Immune Systems - - RNSA - - BNSA - - Base Classifier - - Machine Learning - - Anomaly Detection - - Continuous Features - - Binary Features - - Feature Validation - - Classification ---- - -## ``class BaseNSA(BaseClassifier, ABC)`` - -The ``BaseNSA`` class contains utility functions with the ``protected`` modifier that can be inherited by various classes for ease of use. It includes functions for distance calculation, data separation to improve training and prediction efficiency, accuracy measurement and other functions. - -### Protected Functions - ---- - -#### Function _check_and_raise_exceptions_fit(...) - -```python -def _check_and_raise_exceptions_fit( - X: npt.NDArray = None, - y: npt.NDArray = None, - _class_: Literal["RNSA", "BNSA"] = "RNSA", -) -> None: -``` - -Function responsible for verifying fit function parameters and throwing exceptions if the verification is not successful. - -**Parameters**: - -* ***X*** (``npt.NDArray``): Training array, containing the samples and their characteristics, \[``N samples`` (rows)\]\[``N features`` (columns)]. -* ***y*** (``npt.NDArray``): Array of target classes of ``X`` with \[``N samples`` (lines)]. -* ****class**** (Literal[RNSA, BNSA], optional): Current class. Defaults to 'RNSA'. - -**Raises** - -* ``TypeError``: If X or y are not ndarrays or have incompatible shapes. -* ``ValueError``: If *class* is BNSA and X contains values that are not composed only of 0 and 1. - ---- - -#### Function _check_and_raise_exceptions_predict(...) - -```python -def _check_and_raise_exceptions_predict( - X: npt.NDArray = None, - expected: int = 0, - _class_: Literal["RNSA", "BNSA"] = "RNSA", -) -> None: -``` - -Function responsible for verifying predict function parameters and throwing exceptions if the verification is not successful. - -**Parameters**: - -* ***X*** (``npt.NDArray``): Input array for prediction, containing the samples and their characteristics, \[``N samples`` (rows)\]\[``N features`` (columns)]. -* ***expected*** (``int``): Expected number of features per sample (columns in X). -* *class* (``Literal[RNSA, BNSA], optional``): Current class. Defaults to 'RNSA'. - -**Raises** - -* ``TypeError``: If X is not an ndarray or list. -* ``FeatureDimensionMismatch``: If the number of features in X does not match the expected number. -* ``ValueError``: If *class* is BNSA and X contains values that are not composed only of 0 and 1. - ---- - -## Detector class - -Represents a non-self detector of the RNSA class. - -**Attributes:** - -* ***position*** (``np.ndarray``): Detector feature vector. -* ***radius*** (``float, optional``): Detector radius, used in the V-detector algorithm. diff --git a/docs/advanced-guides/base-module/Base.md b/docs/advanced-guides/base-module/core/Base.md similarity index 81% rename from docs/advanced-guides/base-module/Base.md rename to docs/advanced-guides/base-module/core/Base.md index cf9da1dc..2d458c1b 100644 --- a/docs/advanced-guides/base-module/Base.md +++ b/docs/advanced-guides/base-module/core/Base.md @@ -55,21 +55,3 @@ Return a dictionary with the object's main parameters. Ensures compatibility wit * params: `dict` Dictionary containing the object's attributes that do not start with "_". - ---- - -## Utility Functions - -### Function set_seed_numba(...) - -```python -@njit(cache=True) -def set_seed_numba(seed: int) -``` - -Set the seed for random numbers used by functions compiled with Numba. - -**Parameters**: - -* **seed**: `int` - Integer value used to initialize Numba's random number generator. diff --git a/docs/advanced-guides/base-module/Classifier.md b/docs/advanced-guides/base-module/core/Classifier.md similarity index 80% rename from docs/advanced-guides/base-module/Classifier.md rename to docs/advanced-guides/base-module/core/Classifier.md index 697cd21b..86baa60f 100644 --- a/docs/advanced-guides/base-module/Classifier.md +++ b/docs/advanced-guides/base-module/core/Classifier.md @@ -37,9 +37,9 @@ Fit the model to the training data. Implementation: -- [RNSA](../../aisp-techniques/negative-selection/RNSA.md#Function-fit) -- [BNSA](../../aisp-techniques/negative-selection/BNSA.md#Function-fit) -- [AIRS](../../aisp-techniques/clonal-selection-algorithms/airs/#Function-fit) +- [RNSA](../../../aisp-techniques/negative-selection/RNSA.md#Function-fit) +- [BNSA](../../../aisp-techniques/negative-selection/BNSA.md#Function-fit) +- [AIRS](../../../aisp-techniques/clonal-selection-algorithms/airs/#Function-fit) ### def predict(...) @@ -51,9 +51,9 @@ Performs label prediction for the given data. Implementation: -- [RNSA](../../aisp-techniques/negative-selection/RNSA.md#Function-predict) -- [BNSA](../../aisp-techniques/negative-selection/BNSA.md#Function-predict) -- [AIRS](../../aisp-techniques/clonal-selection-algorithms/airs/#Function-predict) +- [RNSA](../../../aisp-techniques/negative-selection/RNSA.md#Function-predict) +- [BNSA](../../../aisp-techniques/negative-selection/BNSA.md#Function-predict) +- [AIRS](../../../aisp-techniques/clonal-selection-algorithms/airs/#Function-predict) --- diff --git a/docs/advanced-guides/base-module/Clusterer.md b/docs/advanced-guides/base-module/core/Clusterer.md similarity index 93% rename from docs/advanced-guides/base-module/Clusterer.md rename to docs/advanced-guides/base-module/core/Clusterer.md index 565b9c96..559c3049 100644 --- a/docs/advanced-guides/base-module/Clusterer.md +++ b/docs/advanced-guides/base-module/core/Clusterer.md @@ -52,7 +52,7 @@ This abstract method must be implemented by subclasses. **Implementation**: -* [AiNet](../../aisp-techniques/immune-network-theory/AiNet.md#Function-fit) +* [AiNet](../../../aisp-techniques/immune-network-theory/AiNet.md#Function-fit) --- @@ -77,7 +77,7 @@ This abstract method must be implemented by subclasses. **Implementation**: -* [AiNet](../../aisp-techniques/immune-network-theory/AiNet.md#Function-predict) +* [AiNet](../../../aisp-techniques/immune-network-theory/AiNet.md#Function-predict) --- diff --git a/docs/advanced-guides/base-module/Optimizer.md b/docs/advanced-guides/base-module/core/Optimizer.md similarity index 97% rename from docs/advanced-guides/base-module/Optimizer.md rename to docs/advanced-guides/base-module/core/Optimizer.md index 3e0d99cf..aa33b86c 100644 --- a/docs/advanced-guides/base-module/Optimizer.md +++ b/docs/advanced-guides/base-module/core/Optimizer.md @@ -152,7 +152,7 @@ Execute the optimization process. This method must be implemented by the subclas **Implementation**: -* [Clonalg](../../aisp-techniques/clonal-selection-algorithms/clonalg.md#Function-optimize) +* [Clonalg](../../../aisp-techniques/clonal-selection-algorithms/clonalg.md#Function-optimize) --- diff --git a/docs/advanced-guides/base-module/immune/cell.md b/docs/advanced-guides/base-module/immune/cell.md new file mode 100644 index 00000000..1ceacb91 --- /dev/null +++ b/docs/advanced-guides/base-module/immune/cell.md @@ -0,0 +1,116 @@ +--- +title: Cell Classes +sidebar_label: Cell Classes +keywords: + - Binary + - classifying + - affinity threshold + - Real-Valued + - classifying + - anomalies + - K-Nearest Neighbors + - memory B-cell +lastUpdatedAt: 2025/05/25 +author: João Paulo +--- + +Representation of immune system cells. + +## Cell + +Represents a basic immune cell. + +```python +@dataclass(slots=True) +class Cell: + vector: np.ndarray +``` + +### Attributes + +* **vector** (`np.ndarray`): A vector of cell features. + +### Methods + +* `__eq__(other)`: Check if two cells are equal based on their vectors. +* `__array__()`: Array interface to NumPy, allows the instance to be treated as a `np.ndarray`. +* `__getitem__(item)`: Get elements from the feature vector using indexing. + +--- + +## BCell + +Represents a memory B-cell. + +```python +@dataclass(slots=True, eq=False) +class BCell(Cell): + vector: np.ndarray +``` + +### Methods + +#### hyper_clonal_mutate(...) + +```python +def hyper_clonal_mutate( + self, + n: int, + feature_type: FeatureType = "continuous-features", + bounds: Optional[npt.NDArray[np.float64]] = None +) -> np.ndarray +``` + +Clones N features from a cell's features, generating a set of mutated vectors. + +##### Parameters + +* **n** (`int`): Number of clones to be generated from mutations of the original cell. +* **feature_type** (`Literal["binary-features", "continuous-features", "ranged-features"]`): + Specifies the type of feature_type to use based on the nature of the input features +* **bounds** (`Optional[npt.NDArray[np.float64]]`): Array (n_features, 2) with min and max per dimension. + +##### Returns + +* **npt.NDArray**: An array containing N mutated vectors from the original cell. + +--- + +## Antibody + +Represent an antibody. + +```python +@dataclass(slots=True) +class Antibody(Cell): + vector: np.ndarray + affinity: float +``` + +### Attributes + +* **vector** (`npt.NDArray`): A vector of cell features. +* **affinity** (`float`): Affinity value for the antibody. + +### Methods + +* `__lt__(other)`: Compare this cell with another Antibody cell based on affinity. +* `__eq__(other)`: Check if this cell has the same affinity as another cell. + +--- + +## Detector + +Represents a non-self detector of the RNSA class. + +```python +@dataclass(slots=True) +class Detector: + position: npt.NDArray[np.float64] + radius: Optional[float] = None +``` + +### Attributes + +* **position** (`npt.NDArray[np.float64]`): Detector feature vector. +* **radius** (`Optional[float]`): Detector radius, used in the V-detector algorithm. diff --git a/docs/advanced-guides/base-module/Mutation.md b/docs/advanced-guides/base-module/immune/mutation.md similarity index 99% rename from docs/advanced-guides/base-module/Mutation.md rename to docs/advanced-guides/base-module/immune/mutation.md index f7d906db..d6c3082c 100644 --- a/docs/advanced-guides/base-module/Mutation.md +++ b/docs/advanced-guides/base-module/immune/mutation.md @@ -1,5 +1,4 @@ --- -sidebar_position: 5 title: Mutation sidebar_label: Mutation lastUpdatedAt: 2025/04/04 diff --git a/docs/advanced-guides/base-module/immune/populations.md b/docs/advanced-guides/base-module/immune/populations.md new file mode 100644 index 00000000..3944371f --- /dev/null +++ b/docs/advanced-guides/base-module/immune/populations.md @@ -0,0 +1,49 @@ +--- +title: Populations Module +sidebar_label: Populations +pagination_next: null +keywords: + - Binary + - classifying + - affinity threshold + - Real-Valued + - classifying + - anomalies + - K-Nearest Neighbors + - memory B-cell + - Clonal Expansion + - Immune System + - Artificial Immune Systems +lastUpdatedAt: 2025/11/21 +author: João Paulo +--- + +Utility functions for generating antibody populations in immunological algorithms. + +## generate_random_antibodies(...) + +```python +def generate_random_antibodies( + n_samples: int, + n_features: int, + feature_type: FeatureTypeAll = "continuous-features", + bounds: Optional[npt.NDArray[np.float64]] = None +) -> npt.NDArray +``` + +Generate a random antibody population. + +### Parameters + +* **n_samples** (`int`): Number of antibodies (samples) to generate. +* **n_features** (`int`): Number of features (dimensions) for each antibody. +* **feature_type** (`FeatureTypeAll`, default="continuous-features"): Specifies the type of features: "continuous-features", "binary-features", "ranged-features", or "permutation-features". +* **bounds** (`Optional[npt.NDArray[np.float64]]`): Array (n_features, 2) with min and max per dimension. + +### Returns + +* **npt.NDArray**: Array of shape (n_samples, n_features) containing the generated antibodies. + +### Raises + +* **ValueError**: If the number of features is less than or equal to zero. \ No newline at end of file diff --git a/docs/aisp-techniques/clonal-selection-algorithms/Cell.md b/docs/aisp-techniques/clonal-selection-algorithms/Cell.md deleted file mode 100644 index 8992d823..00000000 --- a/docs/aisp-techniques/clonal-selection-algorithms/Cell.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -id: cell -title: Memory B-cell -sidebar_label: Cell - Memory B-cell -sidebar_position: 2 -pagination_next: null -keywords: - - Binary - - classifying - - affinity threshold - - Real-Valued - - classifying - - anomalies - - K-Nearest Neighbors - - memory B-cell -lastUpdatedAt: 2025/05/25 -author: João Paulo ---- - -Representa uma célula-B de memória. - -### Constructor - -Parameters: - -* **vector** (``Optional[npt.NDArray]``): A feature vector of the cell. Defaults to None. - ---- - -### Function hyper_clonal_mutate(...) - -Parameters: - -* **n** (``int``): The number of clones to be generated from mutations in the original cell. -* **feature_type** (``Literal["continuous-features", "binary-features", "ranged-features"]``): Specifies the type of -algorithm to use based on the nature of the input features -* **bounds** (``np.ndarray``): Array (n_features, 2) with min and max per dimension. - -```python -def hyper_clonal_mutate( - self, - n: int, - feature_type: Literal[ - "binary-features", - "continuous-features", - "ranged-features" - ], - bounds: Optional[npt.NDArray[np.float64]] = None -) -> npt.NDArray -``` - -Returns an array containing N mutated vectors from the original cell. diff --git a/docs/aisp-techniques/clonal-selection-algorithms/airs/README.md b/docs/aisp-techniques/clonal-selection-algorithms/airs/README.md index f391f96e..9e523121 100644 --- a/docs/aisp-techniques/clonal-selection-algorithms/airs/README.md +++ b/docs/aisp-techniques/clonal-selection-algorithms/airs/README.md @@ -29,7 +29,7 @@ Based on Algorithm 16.5 from Brabazon et al. [1](#1). :::info -**``AIRS``** extends the **[``_ABR`` class](abr)**, inheriting its base functionality. +**``AIRS``** extends the **[``BaseClassifier`` class](../../../advanced-guides/base-module/core/Classifier.md)**, inheriting its base functionality. ::: @@ -45,11 +45,18 @@ Based on Algorithm 16.5 from Brabazon et al. [1](#1). - **max_iters** (``int``): Maximum number of interactions in the refinement process of the ARB set exposed to aᵢ. Defaults to 100. - **resource_amplified** (``float``): Resource consumption amplifier is multiplied with the incentive to subtract resources. Defaults to 1.0 without amplification. - **metric** (Literal["manhattan", "minkowski", "euclidean"]): Way to calculate the distance between the detector and the sample: - - ``'Euclidean'`` ➜ The calculation of the distance is given by the expression: - $$\sqrt{(X_{1} - X_{1})^2 + (Y_{2} - Y_{2})^2 + \cdots + (Y_{n} - Y_{n})^2}$$ - - ``'minkowski'`` ➜ The calculation of the distance is given by the expression: - $$\frac{((|X_{1} - Y_{1}|^p + |X_{2} - Y_{2}|^p + \cdots + |X_{n} - Y_{n}|^p)^\frac{1}{p})}{n}$$. - - ``'manhattan'`` ➜ The calculation of the distance is given by the expression: $$\frac{(|X_{1} - X_{1}| + |Y_{2} - Y_{2}| + \cdots + |Y_{n} - Y_{n}|)}{n}$$. + - ``'Euclidean'`` ➜ The calculation of the distance is given by the expression: + $$ + \sqrt{(X_{1} - X_{1})^2 + (Y_{2} - Y_{2})^2 + \cdots + (Y_{n} - Y_{n})^2} + $$ + - ``'minkowski'`` ➜ The calculation of the distance is given by the expression: + $$ + \frac{((|X_{1} - Y_{1}|^p + |X_{2} - Y_{2}|^p + \cdots + |X_{n} - Y_{n}|^p)^\frac{1}{p})}{n} + $$ + - ``'manhattan'`` ➜ The calculation of the distance is given by the expression: + $$ + \frac{(|X_{1} - X_{1}| + |Y_{2} - Y_{2}| + \cdots + |Y_{n} - Y_{n}|)}{n} + $$ Defaults to **"Euclidean"**. @@ -74,7 +81,7 @@ Based on Algorithm 16.5 from Brabazon et al. [1](#1). The ``fit(...)`` function generates detectors for the non-owners relative to the samples: ```python -def fit(self, X: npt.NDArray, y: npt.NDArray): +def fit(self, X: npt.NDArray, y: npt.NDArray, verbose: bool = True) -> AIRS: ``` It performs the training according to ``X`` and ``y``, using the method Artificial Immune Recognition System (``AIRS``). @@ -126,15 +133,15 @@ Returns accuracy as a ``float``. The function "_refinement_arb(...)" refines the ARB set until the average stimulation value exceeds the defined threshold (``affinity_threshold_scalar``). +```python +def _refinement_arb(self, ai: npt.NDArray, c_match: Cell, arb_list: List[_ARB]) -> _ARB: +``` + Parameters: - **c_match** (``Cell``): Cell with the highest stimulation relative to aᵢ. - **arb_list** (``List[_ARB]``): ARB set. -```python -def _refinement_arb(self, ai: npt.NDArray, c_match: Cell, arb_list: List[_ARB]) -> _ARB: -``` - Returns the cell (_ARB) with the highest ARB stimulation. --- @@ -163,15 +170,15 @@ def _cells_affinity_threshold(self, antigens_list: npt.NDArray): The function "_affinity(...)" calculates the stimulus between two vectors using metrics. +```python +def _affinity(self, u: npt.NDArray, v: npt.NDArray) -> float: +``` + Parameters: - **u** (``npt.NDArray``): Coordinates of the first point. - **v** (``npt.NDArray``): Coordinates of the second point. -```python -def _affinity(self, u: npt.NDArray, v: npt.NDArray) -> float: -``` - Returns the stimulus rate between the vectors. --- @@ -180,13 +187,17 @@ Returns the stimulus rate between the vectors. The function "_init_memory_c(...)" initializes memory cells by randomly selecting `n_antigens_selected` from the list of training antigens. +```python +def _init_memory_c(self, antigens_list: npt.NDArray) -> List[BCell]: +``` + Parameters: - **antigens_list** (``NDArray``): List of training antigens. -```python -def _init_memory_c(self, antigens_list: npt.NDArray) -> List[Cell]: -``` +Returns + +- ``List[BCell]``: List of initialized memories. --- diff --git a/docs/aisp-techniques/clonal-selection-algorithms/airs/abr.md b/docs/aisp-techniques/clonal-selection-algorithms/airs/abr.md index 13ad2b94..bf2bcf61 100644 --- a/docs/aisp-techniques/clonal-selection-algorithms/airs/abr.md +++ b/docs/aisp-techniques/clonal-selection-algorithms/airs/abr.md @@ -21,7 +21,7 @@ Individual from the set of recognizing cells (ABR), inherits characteristics fro :::info -**``ABR``** extends the **[``Cell`` class](../cell)**, inheriting its base functionality. +**``ABR``** extends the **[``BCell`` class](../../../advanced-guides/base-module/immune/cell.md#BCell)**, inheriting its base functionality. ::: diff --git a/docs/aisp-techniques/clonal-selection-algorithms/clonalg.md b/docs/aisp-techniques/clonal-selection-algorithms/clonalg.md index 634a0334..7ee8a2da 100644 --- a/docs/aisp-techniques/clonal-selection-algorithms/clonalg.md +++ b/docs/aisp-techniques/clonal-selection-algorithms/clonalg.md @@ -31,6 +31,12 @@ specific implementation. This adaptation aims to generalize CLONALG to minimizat maximization tasks, in addition to supporting continuous, discrete, and permutation problems. ::: +:::info + +**``Clonalg``** extends the **[``BaseOptimizer`` class](../../advanced-guides/base-module/core/Optimizer.md)**, inheriting its base functionality. + +::: + --- ## CLONALG Constructor @@ -61,9 +67,9 @@ The constructor initializes the CLONALG instance with key parameters that define def optimize( self, max_iters: int = 50, - n_iter_no_change=10, + n_iter_no_change=10, verbose: bool = True -) -> npt.NDArray: +) -> List[Antibody]: ``` This method execute the optimization process and return the population. @@ -76,7 +82,7 @@ This method execute the optimization process and return the population. **Returns:** -* `npt.NDArray`: The best antibody population after clonal expansion. +* population : ``List[Antibody]``, [Antibody](../../advanced-guides/base-module/immune/cell.md#Antibody) population after clonal expansion. --- diff --git a/docs/aisp-techniques/immune-network-theory/AiNet.md b/docs/aisp-techniques/immune-network-theory/AiNet.md index 44016b0c..5f6807b9 100644 --- a/docs/aisp-techniques/immune-network-theory/AiNet.md +++ b/docs/aisp-techniques/immune-network-theory/AiNet.md @@ -40,7 +40,7 @@ For clustering, the class uses SciPy's implementation of the [**Minimum Spanning :::info -**``AiNet``** extends the **[``BaseAiNet`` class](../../advanced-guides/base-classes-reference/ina/ainet.md)**, inheriting its base functionality. +**``AiNet``** extends the **[``BaseClusterer`` class](../../advanced-guides/base-module/core/Clusterer.md)**, inheriting its base functionality. ::: @@ -77,11 +77,18 @@ class AiNet( * **max_iterations** (``int``): Maximum number of training iterations. Defaults to 10. * **k** (``int``): Number of nearest neighbors used for label prediction. Defaults to 3. * **metric** (Literal["manhattan", "minkowski", "euclidean"]): Way to calculate the distance between the detector and the sample: - * ``'Euclidean'`` ➜ The calculation of the distance is given by the expression: - $$\sqrt{(X_{1} - X_{1})^2 + (Y_{2} - Y_{2})^2 + \cdots + (Y_{n} - Y_{n})^2}$$ - * ``'minkowski'`` ➜ The calculation of the distance is given by the expression: - $$\frac{((|X_{1} - Y_{1}|^p + |X_{2} - Y_{2}|^p + \cdots + |X_{n} - Y_{n}|^p)^\frac{1}{p})}{n}$$. - * ``'manhattan'`` ➜ The calculation of the distance is given by the expression: $$\frac{(|X_{1} - X_{1}| + |Y_{2} - Y_{2}| + \cdots + |Y_{n} - Y_{n}|)}{n}$$. + * ``'Euclidean'`` ➜ The calculation of the distance is given by the expression: + $$ + \sqrt{(X_{1} - X_{1})^2 + (Y_{2} - Y_{2})^2 + \cdots + (Y_{n} - Y_{n})^2} + $$ + * ``'minkowski'`` ➜ The calculation of the distance is given by the expression: + $$ + \frac{((|X_{1} - Y_{1}|^p + |X_{2} - Y_{2}|^p + \cdots + |X_{n} - Y_{n}|^p)^\frac{1}{p})}{n} + $$ + * ``'manhattan'`` ➜ The calculation of the distance is given by the expression: + $$ + \frac{(|X_{1} - X_{1}| + |Y_{2} - Y_{2}| + \cdots + |Y_{n} - Y_{n}|)}{n} + $$ Defaults to **"Euclidean"**. @@ -108,7 +115,7 @@ class AiNet( Trains the AiNet model on input data: ```python -def fit(self, X: npt.NDArray, verbose: bool = True): +def fit(self, X: npt.NDArray, verbose: bool = True) -> AiNet: ``` **Input parameters:** diff --git a/docs/aisp-techniques/negative-selection/BNSA.md b/docs/aisp-techniques/negative-selection/BNSA.md index 3a4e0e0b..a8f7cd82 100644 --- a/docs/aisp-techniques/negative-selection/BNSA.md +++ b/docs/aisp-techniques/negative-selection/BNSA.md @@ -23,6 +23,12 @@ last_update: # BNSA (Binary Negative Selection Algorithm) +:::info + +**``BNSA``** extends the **[``BaseClassifier`` class](../../advanced-guides/base-module/core/Classifier.md)**, inheriting its base functionality. + +::: + ## Constructor RNSA The ``BNSA`` (Binary Negative Selection Algorithm) class has the purpose of classifying and identifying anomalies through the self and not self methods. @@ -45,9 +51,9 @@ class BNSA( * *N* (``int``): Number of detectors. Defaults to ``100``. * *aff_thresh* (``float``): The variable ('affinity threshold') represents the percentage of dissimilarity between the T cell and the own samples. The default value is 10% (0.1), while a value of 1.0 represents 100% dissimilarity. -:::note -Setting the difference percentage too high can result in the inability to generate detectors for non-self. -::: + :::note + Setting the difference percentage too high can result in the inability to generate detectors for non-self. + ::: * *max_discards* (``int``): This parameter indicates the maximum number of detector discards in sequence, which aims to avoid a possible infinite loop if a radius is defined that it is not possible to generate non-self detectors. Defaults to ``1000``. diff --git a/docs/aisp-techniques/negative-selection/RNSA.md b/docs/aisp-techniques/negative-selection/RNSA.md index 530f8959..3c102d26 100644 --- a/docs/aisp-techniques/negative-selection/RNSA.md +++ b/docs/aisp-techniques/negative-selection/RNSA.md @@ -20,6 +20,12 @@ last_update: # RNSA (Real-Valued Negative Selection Algorithm) +:::info + +**``RNSA``** extends the **[``BaseClassifier`` class](../../advanced-guides/base-module/core/Classifier.md)**, inheriting its base functionality. + +::: + ## Constructor RNSA The ``RNSA`` (Real-Valued Negative Selection Algorithm) class has the purpose of classifying and identifying anomalies through the self and not self methods. @@ -44,17 +50,26 @@ class RNSA( * *N* (``int``): Number of detectors. Defaults to ``100``. * *r* (``float``): Radius of the detector. Defaults to ``0.05``. -:::note -it is important to consider that setting a very low radius for the detector can significantly reduce the detection rate. On the other hand, a very large radius can make it impossible to incorporate the detector into the search space, which can also compromise detection performance. It is essential to find a balance between the radius size and detection efficiency to achieve the best possible results. -::: + :::note + it is important to consider that setting a very low radius for the detector can significantly reduce the detection rate. On the other hand, a very large radius can make it impossible to incorporate the detector into the search space, which can also compromise detection performance. It is essential to find a balance between the radius size and detection efficiency to achieve the best possible results. + ::: * *k* (``int``): Number of neighbors near the randomly generated detectors to perform the distance average calculation. Defaults to ``1``. * *metric* (``str``): Way to calculate the distance between the detector and the sample: - * ``'Euclidean'`` ➜ The calculation of the distance is given by the expression: $$\sqrt{(X_{1} - X_{1})^2 + (Y_{2} - Y_{2})^2 + \cdots + (Y_{n} - Y_{n})^2}$$. - - * ``'minkowski'`` ➜ The calculation of the distance is given by the expression: $$\frac{((|X_{1} - Y_{1}|^p + |X_{2} - Y_{2}|^p + \cdots + |X_{n} - Y_{n}|^p)^\frac{1}{p})}{n}$$. - * ``'manhattan'`` ➜ The calculation of the distance is given by the expression: $$\frac{(|X_{1} - X_{1}| + |Y_{2} - Y_{2}| + \cdots + |Y_{n} - Y_{n}|)}{n}$$. + * ``'Euclidean'`` ➜ The calculation of the distance is given by the expression: + $$ + \sqrt{(X_{1} - X_{1})^2 + (Y_{2} - Y_{2})^2 + \cdots + (Y_{n} - Y_{n})^2} + $$ + + * ``'minkowski'`` ➜ The calculation of the distance is given by the expression: + $$ + \frac{((|X_{1} - Y_{1}|^p + |X_{2} - Y_{2}|^p + \cdots + |X_{n} - Y_{n}|^p)^\frac{1}{p})}{n} + $$ + * ``'manhattan'`` ➜ The calculation of the distance is given by the expression: + $$ + \frac{(|X_{1} - X_{1}| + |Y_{2} - Y_{2}| + \cdots + |Y_{n} - Y_{n}|)}{n} + $$ Defaults to ``'euclidean'``. diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/Utils/Distance.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/Utils/Distance.md index 4c4e896f..f4b5939b 100644 --- a/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/Utils/Distance.md +++ b/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/Utils/Distance.md @@ -16,7 +16,9 @@ def hamming(u: npt.NDArray, v: npt.NDArray) -> np.float64: Função para calcular a distância de Hamming normalizada entre dois pontos. -$((x₁ ≠ x₂) + (y₁ ≠ y₂) + ... + (y_n ≠ y_n)) / n$ +$$ +\frac{(x_1 \neq y_1) + (x_2 \neq y_2) + \cdots + (x_n \neq y_n)}{n} +$$ **Parameters:** @@ -37,7 +39,9 @@ def euclidean(u: npt.NDArray[np.float64], v: npt.NDArray[np.float64]) -> np.floa Função para calcular a distância euclidiana normalizada entre dois pontos. -$√( (x₁ - x₂)² + (y₁ - y₂)² + ... + (y_n - y_n)²)$ +$$ +\sqrt{(X_{1} - X_{1})^2 + (Y_{2} - Y_{2})^2 + \cdots + (Y_{n} - Y_{n})^2} +$$ **Parameters:** @@ -58,7 +62,9 @@ def cityblock(u: npt.NDArray[np.float64], v: npt.NDArray[np.float64]) -> np.floa Função para calcular a distância Manhattan normalizada entre dois pontos. -$(|x₁ - x₂| + |y₁ - y₂| + ... + |y_n - y_n|) / n$ +$$ +\frac{(|X_{1} - X_{1}| + |Y_{2} - Y_{2}| + \cdots + |Y_{n} - Y_{n}|)}{n} +$$ **Parameters:** diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/Utils/Multiclass.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/Utils/Multiclass.md index 8dc80f3b..fbe8d25e 100644 --- a/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/Utils/Multiclass.md +++ b/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/Utils/Multiclass.md @@ -27,3 +27,29 @@ a classe que está sendo treinada. **Returns:** * dict: Um dicionário com a lista de posições do array(``y``), com as classes como chave. + +--- + +### def predict_knn_affinity(...) + +Função para prever classes usando k-vizinhos mais próximos e células treinadas. + +```python +def predict_knn_affinity( + X: npt.NDArray, + k: int, + all_cell_vectors: List[Tuple[Union[str, int], npt.NDArray]], + affinity_func: Callable[[npt.NDArray, npt.NDArray], float] +) -> npt.NDArray +``` + +**Parâmetros:** + +* **_X_** (`npt.NDArray`): Dados de entrada a serem classificados. +* **_k_** (`int`): Número de vizinhos mais próximos a considerar para a previsão. +* **_all_cell_vectors_** (`List[Tuple[Union[str, int], npt.NDArray]]`): Lista de tuplas contendo pares (nome_da_classe, vetor_da_célula). +* **_affinity_func_** (`Callable[[npt.NDArray, npt.NDArray], float]`): Função que recebe dois vetores e retorna um valor de afinidade. + +**Retorna:** + +* `npt.NDArray`: Array de rótulos previstos para cada amostra em X, baseado nos k vizinhos mais próximos. \ No newline at end of file diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/Utils/Random.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/Utils/Random.md new file mode 100644 index 00000000..b6554071 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/Utils/Random.md @@ -0,0 +1,16 @@ +# Random + +Funções utilitárias para geração e reprodutibilidade de números aleatórios. + +## Função set_seed_numba(...) + +```python +@njit(cache=True) +def set_seed_numba(seed: int) +``` + +Define a semente para números aleatórios usados por funções compiladas com Numba. + +**Parâmetros**: + +* **seed**: `int` - Valor inteiro usado para inicializar o gerador de números aleatórios do Numba. \ No newline at end of file diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/Utils/Validation.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/Utils/Validation.md index 711e2392..030678fc 100644 --- a/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/Utils/Validation.md +++ b/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/Utils/Validation.md @@ -16,14 +16,93 @@ Esta função analisa o vetor de entrada e classifica seus dados como um dos tip * **contínuo**: Valores float dentro do intervalo normalizado `[0.0, 1.0]`. * **intervalo**: Valores float fora do intervalo normalizado. -**Parâmetros** +### Parâmetros * `vetor` (`npt.NDArray`): Um array contendo os dados a serem classificados. -**Returns:** +### Retorna * `FeatureType` (`Literal["binary-features", "continuous-features", "ranged-features"]`): O tipo de dado detectado no vetor. -**Lança** +### Gera * `UnsupportedDataTypeError`: Gerado se o vetor contiver um tipo de dado não suportado. + +--- + +## def check_array_type(...) + +```python +def check_array_type(x, name: str = "X") -> npt.NDArray: +``` + +Garante que o parâmetro recebido é um array numpy. Converte de lista se necessário. + +**Parâmetros:** + +* `x`: Array ou lista contendo as amostras e características. +* `name`: Nome da variável para mensagens de erro. + +**Retorna:** + +* `npt.NDArray`: O array convertido ou validado. + +**Lança:** + +* `TypeError`: Se não for possível converter para ndarray. + +--- + +## def check_shape_match(...) + +```python +def check_shape_match(x: npt.NDArray, y: npt.NDArray): +``` + +Garante que os arrays `x` e `y` possuem o mesmo número de amostras (primeira dimensão). + +**Parâmetros:** + +* `x`: Array de amostras. +* `y`: Array de classes alvo. + +**Lança:** + +* `TypeError`: Se as dimensões não forem compatíveis. + +--- + +## def check_feature_dimension(...) + +```python +def check_feature_dimension(x: npt.NDArray, expected: int): +``` + +Garante que o array possui o número esperado de características (features). + +**Parâmetros:** + +* `x`: Array de entrada para predição. +* `expected`: Número esperado de características por amostra. + +**Lança:** + +* `FeatureDimensionMismatch`: Se o número de características não corresponder ao esperado. + +--- + +## def check_binary_array(...) + +```python +def check_binary_array(x: npt.NDArray): +``` + +Garante que o array contém apenas valores 0 e 1. + +**Parâmetros:** + +* `x`: Array a ser verificado. + +**Lança:** + +* `ValueError`: Se o array contiver valores diferentes de 0 e 1. diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-classes-reference/_category_.json b/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-classes-reference/_category_.json deleted file mode 100644 index c25b4f9a..00000000 --- a/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-classes-reference/_category_.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "position": 2, - "description": "Classes base para implementar os algoritmos fornecidos neste pacote." -} \ No newline at end of file diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-classes-reference/csa/README.mdx b/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-classes-reference/csa/README.mdx deleted file mode 100644 index 5c6e7378..00000000 --- a/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-classes-reference/csa/README.mdx +++ /dev/null @@ -1,11 +0,0 @@ ---- -sidebar_position: 2.61 ---- - -import DocCardList from '@theme/DocCardList'; - -# Algoritmos de Seleção Clonal - -As classes base fornecem a estrutura central para a implementação das técnicas de Algoritmo de Seleção Clonal. - - \ No newline at end of file diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-classes-reference/csa/airs.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-classes-reference/csa/airs.md deleted file mode 100644 index 0e2c5d23..00000000 --- a/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-classes-reference/csa/airs.md +++ /dev/null @@ -1,88 +0,0 @@ ---- -sidebar_position: 1 -title: Classe Base do Sistema Imunológico Artificial de Reconhecimento -sidebar_label: Sistema Imunológico Artificial de Reconhecimento -lastUpdatedAt: 2025/05/25 -author: João Paulo -keywords: - - BaseAIRS - - AIRS - - Sistema Imunológico Artificial de Reconhecimento - - Sistemas Imunológicos Artificiais - - Classificador Base - - Atributos Contínuos - - Atributos Binários - - Validação de Atributos - - Aprendizado de Máquina - - Classificação ---- - -## ``BaseAIRS(BaseClassifier, ABC)`` - -Classe base para o algoritmo **AIRS**. - -A classe base contém funções que são utilizadas por mais de uma classe no pacote e, portanto, são consideradas essenciais para o funcionamento geral do sistema. - ---- - -### def _check_and_raise_exceptions_fit(...) - -Verifica os parâmetros de ajuste (*fit*) e lança exceções caso a verificação não seja bem-sucedida. - -```python -@staticmethod -def _check_and_raise_exceptions_fit( - X: npt.NDArray = None, - y: npt.NDArray = None, - algorithm: Literal[ - "continuous-features", "binary-features" - ] = "continuous-features" -): -``` - -**Parâmetros**: - -* ***X*** (`npt.NDArray`): Array de treinamento, contendo as amostras e suas características, com formato \[`N amostras` (linhas)]\[`N características` (colunas)]. -* ***y*** (`npt.NDArray`): Array das classes alvo de `X` com \[`N amostras` (linhas)]. -* ***algorithm*** (`Literal["continuous-features", "binary-features"], opcional`): Especifica o tipo de algoritmo a ser usado, dependendo se os dados de entrada possuem características contínuas ou binárias. - -**Exceções**: - -* `TypeError`: - Se X ou y não forem ndarrays ou tiverem formatos incompatíveis. -* `ValueError`: - Se a *classe* for BNSA e X contiver valores que não sejam compostos apenas por 0 e 1. - ---- - -### def _check_and_raise_exceptions_predict(...) - -Verifica os parâmetros de predição e lança exceções caso a verificação não seja bem-sucedida. - -```python -@staticmethod -def _check_and_raise_exceptions_predict( - X: npt.NDArray = None, - expected: int = 0, - algorithm: Literal[ - "continuous-features", "binary-features" - ] = "continuous-features" -) -> None: -``` - -**Parâmetros**: - -* ***X*** (`npt.NDArray`): Array de entrada, contendo as amostras e suas características, com formato \[`N amostras` (linhas)]\[`N características` (colunas)]. -* ***expected*** (`int`): Número esperado de características por amostra (colunas de X). -* ***algorithm*** (`Literal["continuous-features", "binary-features"], opcional`): Especifica o tipo de algoritmo a ser usado, dependendo se os dados de entrada possuem características contínuas ou binárias. - -**Exceções**: - -* `TypeError`: - Se X não for um ndarray ou lista. -* `FeatureDimensionMismatch`: - Se o número de características em X não corresponder ao número esperado. -* `ValueError`: - Se o algoritmo for "binary-features" e X contiver valores que não sejam compostos apenas por 0 e 1. - ---- diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-classes-reference/ina/README.mdx b/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-classes-reference/ina/README.mdx deleted file mode 100644 index 88e4a961..00000000 --- a/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-classes-reference/ina/README.mdx +++ /dev/null @@ -1,11 +0,0 @@ ---- -sidebar_position: 2.71 ---- - -import DocCardList from '@theme/DocCardList'; - -# Algoritmos de Rede Imunológica - -As classes base fornecem a estrutura central para a implementação das técnicas de Algoritmo de Rede Imunológica. - - \ No newline at end of file diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-classes-reference/ina/ainet.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-classes-reference/ina/ainet.md deleted file mode 100644 index 7f6abe70..00000000 --- a/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-classes-reference/ina/ainet.md +++ /dev/null @@ -1,99 +0,0 @@ ---- -sidebar_position: 1 -title: Base da Rede Imunológica Artificial -sidebar_label: Rede Imunológica Artificial -lastUpdatedAt: 2025/05/25 -author: João Paulo -keywords: - - AiNet - - Teoria da Rede Imunológica - - Agrupamento - - BaseAiNet - - Sistemas Imunológicos Artificiais - - Anticorpos ---- - -## ``BaseAiNet(BaseClusterer, ABC)`` - -Classe base para algoritmos de Teoria de Redes baseados em AiNet. - -A classe base contém funções utilizadas por múltiplas classes no pacote AiNet e -são consideradas essenciais para o funcionamento adequado de algoritmos de clustering baseados na teoria de redes imunes. - ---- - -### def _check_and_raise_exceptions_fit(...) - -Verifica os parâmetros do método `fit` e lança exceções caso a verificação não seja bem-sucedida. - -```python -@staticmethod -def _check_and_raise_exceptions_fit(X: npt.NDArray) -``` - -**Parâmetros**: - -* ***X*** (`npt.NDArray`): Matriz de treinamento contendo as amostras e suas características, \[`N amostras` (linhas)]\[`N atributos` (colunas)]. - -**Exceções**: - -* `TypeError`: Se X não for um `ndarray` ou uma `list`. - ---- - -### def _check_and_raise_exceptions_predict(...) - -Verifica os parâmetros do método `predict` e lança exceções caso a verificação não seja bem-sucedida. - -```python -@staticmethod -def _check_and_raise_exceptions_predict( - X: npt.NDArray, - expected: int = 0, - feature_type: FeatureType = "continuous-features" -) -> None -``` - -**Parâmetros**: - -* ***X*** (`npt.NDArray`): Matriz de entrada para predição, contendo as amostras e suas características, \[`N amostras` (linhas)]\[`N atributos` (colunas)]. -* ***expected*** (`int`, default=0): Número esperado de atributos por amostra (colunas em X). -* ***feature_type*** (`FeatureType`, default="continuous-features"): Especifica o tipo de atributos: `"continuous-features"`, `"binary-features"` ou `"ranged-features"`. - -**Exceções**: - -* `TypeError`: Se X não for um `ndarray` ou uma `list`. -* `FeatureDimensionMismatch`: Se o número de atributos em X não corresponder ao esperado. -* `ValueError`: Se `feature_type` for `"binary-features"` e X contiver valores diferentes de 0 e 1. - ---- - -### def _generate_random_antibodies(...) - -Gera uma população aleatória de anticorpos. - -```python -@staticmethod -def _generate_random_antibodies( - n_samples: int, - n_features: int, - feature_type: FeatureType = "continuous-features", - bounds: Optional[npt.NDArray[np.float64]] = None -) -> npt.NDArray -``` - -**Parâmetros**: - -* ***n_samples*** (`int`): Número de anticorpos (amostras) a serem gerados. -* ***n_features*** (`int`): Número de atributos (dimensões) para cada anticorpo. -* ***feature_type*** (`FeatureType`, default="continuous-features"): Especifica o tipo de atributos: `"continuous-features"`, `"binary-features"` ou `"ranged-features"`. -* ***bounds*** (`Optional[npt.NDArray[np.float64]]`): Matriz de formato `(n_features, 2)` com valores mínimos e máximos por dimensão (usado apenas para atributos do tipo "ranged"). - -**Retorna**: - -* `npt.NDArray`: Matriz de formato `(n_samples, n_features)` contendo os anticorpos gerados. - O tipo dos dados depende de `feature_type` (float para contínuo/ranged, bool para binário). - -**Exceções**: - -* `ValueError`: Se `n_features <= 0`. diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-classes-reference/nsa.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-classes-reference/nsa.md deleted file mode 100644 index 0d2fc458..00000000 --- a/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-classes-reference/nsa.md +++ /dev/null @@ -1,88 +0,0 @@ ---- -sidebar_position: 1 -title: Classe Base de Seleção Negativa -sidebar_label: Seleção Negativa -lastUpdatedAt: 2025/04/04 -author: João Paulo -keywords: - - BaseNSA - - Seleção Negativa - - Sistemas Imunológicos Artificiais - - RNSA - - BNSA - - Classificador Base - - Aprendizado de Máquina - - Detecção de Anomalias - - Atributos Contínuos - - Atributos Binários - - Validação de Atributos - - Classificação ---- - -## ``class BaseNSA(BaseClassifier, ABC)`` - -A classe ``BaseNSA`` contém funções utilitárias com o modificador ``protected`` que podem ser herdadas por várias classes para facilitar o uso. Ela inclui funções para calcular distância, separar dados para melhorar a eficiência de treinamento e previsão, medir precisão e outras funções. - ---- - -### Funções Protegidas - ---- - -#### def _check_and_raise_exceptions_fit(...) - -```python -def _check_and_raise_exceptions_fit( - X: npt.NDArray = None, - y: npt.NDArray = None, - _class_: Literal["RNSA", "BNSA"] = "RNSA", -) -> None: -``` - -Função responsável por verificar os parâmetros da função fit e lançar exceções se a verificação não for bem-sucedida. - -**Parâmetros**: - -* **X** (``npt.NDArray``): Array de treinamento, contendo as amostras e suas características, \[``N samples`` (linhas)\]\[``N features`` (colunas)]. -* ***y*** (``npt.NDArray``): Array de classes alvo de ``X`` com \[``N samples`` (linhas)]. -* ****class**** (Literal[RNSA, BNSA], opcional): Classe atual. O padrão é 'RNSA'. - -**Lança:** - -* ``TypeError``: Se X ou y não forem ndarrays ou tiverem formas incompatíveis. -* ``MaxDiscardsReachedError``: O número máximo de descartes do detector foi atingido durante -a maturação. Verifique o valor do raio definido e considere reduzi-lo. - -#### def _check_and_raise_exceptions_predict(...) - -```python -def _check_and_raise_exceptions_predict( - X: npt.NDArray = None, - expected: int = 0, - _class_: Literal["RNSA", "BNSA"] = "RNSA", -) -> None: -``` - -Função responsável por verificar os parâmetros da função predict e lançar exceções caso a verificação não seja bem-sucedida. -**Parâmetros**: - -* ***X*** (``npt.NDArray``): Array de treinamento, contendo as amostras e suas características, \[``N samples`` (linhas)\]\[``N features`` (colunas)]. -* ***expected*** (``int``): Número esperado de características por amostra (colunas em X). -* ****class**** (``Literal[RNSA, BNSA], opcional``): Classe atual. O padrão é 'RNSA'. - -**Lança:** - -* ``TypeError``: Se X ou y não forem ndarrays ou tiverem formas incompatíveis. -* ``MaxDiscardsReachedError``: O número máximo de descartes do detector foi atingido durante -a maturação. Verifique o valor do raio definido e considere reduzi-lo. - ---- - -## ``Class Detector`` - -Representa um detector não-próprio do class RNSA. - -**Atributos:** - -* ***position*** (``np.ndarray``): Vetor de características do detector. -* ***radius*** (``float, opcional``): Raio do detector, utilizado no algoritmo V-detector. diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-module/Base.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-module/core/Base.md similarity index 80% rename from i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-module/Base.md rename to i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-module/core/Base.md index dc887ed5..bd5f0f0e 100644 --- a/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-module/Base.md +++ b/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-module/core/Base.md @@ -53,18 +53,3 @@ Retorna um dicionário com os principais parâmetros do objeto. Garante compatib * params: `dict` - Dicionário contendo os atributos do objeto que não começam com "_". --- - -## Funções utilitárias - -### Função set_seed_numba(...) - -```python -@njit(cache=True) -def set_seed_numba(seed: int) -``` - -Define a semente para números aleatórios usados por funções compiladas com Numba. - -**Parâmetros**: - -* **seed**: `int` - Valor inteiro usado para inicializar o gerador de números aleatórios do Numba. diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-module/Classifier.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-module/core/Classifier.md similarity index 81% rename from i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-module/Classifier.md rename to i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-module/core/Classifier.md index eef99a11..546e22f9 100644 --- a/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-module/Classifier.md +++ b/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-module/core/Classifier.md @@ -24,9 +24,9 @@ Ajusta o modelo aos dados de treinamento. Implementação: -- [RNSA](../../aisp-techniques/negative-selection/RNSA.md#Função-fit) -- [BNSA](../../aisp-techniques/negative-selection/BNSA.md#Função-fit) -- [AIRS](../../aisp-techniques/clonal-selection-algorithms/airs/#Método-fit) +- [RNSA](../../../aisp-techniques/negative-selection/RNSA.md#Função-fit) +- [BNSA](../../../aisp-techniques/negative-selection/BNSA.md#Função-fit) +- [AIRS](../../../aisp-techniques/clonal-selection-algorithms/airs/#Método-fit) ### def predict(...) @@ -38,9 +38,9 @@ Realiza a previsão dos rótulos para os dados fornecidos. Implementação: -- [RNSA](../../aisp-techniques/negative-selection/RNSA.md#Função-predict) -- [BNSA](../../aisp-techniques/negative-selection/BNSA.md#Função-predict) -- [AIRS](../../aisp-techniques/clonal-selection-algorithms/airs/#Método-predict) +- [RNSA](../../../aisp-techniques/negative-selection/RNSA.md#Função-predict) +- [BNSA](../../../aisp-techniques/negative-selection/BNSA.md#Função-predict) +- [AIRS](../../../aisp-techniques/clonal-selection-algorithms/airs/#Método-predict) --- diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-module/Clusterer.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-module/core/Clusterer.md similarity index 93% rename from i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-module/Clusterer.md rename to i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-module/core/Clusterer.md index ced74add..aea519ce 100644 --- a/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-module/Clusterer.md +++ b/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-module/core/Clusterer.md @@ -48,7 +48,7 @@ Este método abstrato deve ser implementado pelas subclasses. **Implementação**: -* [AiNet](../../aisp-techniques/immune-network-theory/AiNet.md#Função-fit) +* [AiNet](../../../aisp-techniques/immune-network-theory/AiNet.md#Função-fit) --- @@ -71,7 +71,7 @@ Este método abstrato deve ser implementado pelas subclasses. **Implementação**: -* [AiNet](../../aisp-techniques/immune-network-theory/AiNet.md#Função-predict) +* [AiNet](../../../aisp-techniques/immune-network-theory/AiNet.md#Função-predict) --- diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-module/Optimizer.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-module/core/Optimizer.md similarity index 100% rename from i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-module/Optimizer.md rename to i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-module/core/Optimizer.md diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-module/immune/cell.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-module/immune/cell.md new file mode 100644 index 00000000..ef81da74 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-module/immune/cell.md @@ -0,0 +1,117 @@ +--- +title: Cell Classes +sidebar_label: Cell Classes +keywords: + - Binário + - classificação + - limiar de afinidade + - Valores Reais + - classificação + - anomalias + - K-Vizinhos Mais Próximos + - célula-B de memória +lastUpdatedAt: 2025/05/25 +author: João Paulo +--- + +Representação de células do sistema imunológico. + +## Cell + +Representa uma célula imune básica. + +```python +@dataclass(slots=True) +class Cell: + vector: np.ndarray +``` + +### Atributos + +* **vector** (`np.ndarray`): Um vetor de características da célula. + +### Métodos + +* `__eq__(other)`: Verifica se duas células são iguais com base em seus vetores. +* `__array__()`: Interface de array para NumPy, permite que a instância seja tratada como um `np.ndarray`. +* `__getitem__(item)`: Obtém elementos do vetor de características usando indexação. + +--- + +## BCell + +Representa uma célula B de memória, derivada de `Cell`. + +```python +@dataclass(slots=True, eq=False) +class BCell(Cell): + vector: np.ndarray +``` + +### Métodos + +### hyper_clonal_mutate(...) + +```python +def hyper_clonal_mutate( + self, + n: int, + feature_type: FeatureType = "continuous-features", + bounds: Optional[npt.NDArray[np.float64]] = None +) -> np.ndarray +``` + +Clona N características das características de uma célula, gerando um conjunto de vetores mutados. + +#### Parâmetros + +* **n** (`int`): Número de clones a serem gerados a partir de mutações da célula original. +* **feature_type** (`Literal["binary-features", "continuous-features", "ranged-features"]`): Especifica o tipo de características com base na natureza das características de entrada. +* **bounds** (`Optional[npt.NDArray[np.float64]]`): Array (n_features, 2) com mínimo e máximo por dimensão. + +#### Retorna + +* **npt.NDArray**: Um array contendo N vetores mutados da célula original. + +--- + +## Antibody + +Representa um anticorpo com afinidade, derivado de `Cell`. + +```python +@dataclass(slots=True) +class Antibody(Cell): + vector: np.ndarray + affinity: float +``` + +### Atributos + +* **vector** (`npt.NDArray`): Um vetor de características da célula. +* **affinity** (`float`): Valor de afinidade do anticorpo. + +### Métodos + +* `__lt__(other)`: Compara este anticorpo com outro com base na afinidade. +* `__eq__(other)`: Verifica se dois anticorpos têm a mesma afinidade. + +--- + +## Detector + +Representa um detector não-próprio da classe RNSA. + +```python +@dataclass(slots=True) +class Detector: + position: npt.NDArray[np.float64] + radius: Optional[float] = None +``` + +### Atributos + +* **position** (`npt.NDArray[np.float64]`): Vetor de características do detector. +* **radius** (`Optional[float]`): Raio do detector, usado no algoritmo V-detector. + +--- diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-module/Mutation.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-module/immune/mutation.md similarity index 99% rename from i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-module/Mutation.md rename to i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-module/immune/mutation.md index 4eaef904..d9e29b66 100644 --- a/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-module/Mutation.md +++ b/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-module/immune/mutation.md @@ -1,5 +1,4 @@ --- -sidebar_position: 4 title: Mutation sidebar_label: Mutation lastUpdatedAt: 2025/04/04 diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-module/immune/populations.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-module/immune/populations.md new file mode 100644 index 00000000..f3cbae8d --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/current/advanced-guides/base-module/immune/populations.md @@ -0,0 +1,49 @@ +--- +title: Módulo de Populações +sidebar_label: Populações +pagination_next: null +keywords: + - Binary + - classifying + - affinity threshold + - Real-Valued + - classifying + - anomalies + - K-Nearest Neighbors + - memory B-cell + - Clonal Expansion + - Immune System + - Artificial Immune Systems +lastUpdatedAt: 2025/11/21 +author: João Paulo +--- + +Fornece funções utilitárias para gerar populações de anticorpos em algoritmos imunológicos. + +## generate_random_antibodies(...) + +Gera uma população aleatória de anticorpos. + +```python +def generate_random_antibodies( + n_samples: int, + n_features: int, + feature_type: FeatureTypeAll = "continuous-features", + bounds: Optional[npt.NDArray[np.float64]] = None +) -> npt.NDArray +``` + +### Parâmetros + +* **n_samples** (`int`): Número de anticorpos (amostras) a serem gerados. +* **n_features** (`int`): Número de características (dimensões) para cada anticorpo. +* **feature_type** (`FeatureTypeAll`, default="continuous-features"): Especifica o tipo das características: "continuous-features", "binary-features", "ranged-features", or "permutation-features". +* **bounds** (`Optional[npt.NDArray[np.float64]]`): Array (n_features, 2) contendo os valores mínimo e máximo por dimensão. + +### Retorno + +* **npt.NDArray**: Array com forma (n_samples, n_features) contendo os anticorpos gerados. + +### Exceções + +* **ValueError**: Caso o número de características seja menor ou igual a zero. diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/clonal-selection-algorithms/Cell.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/clonal-selection-algorithms/Cell.md deleted file mode 100644 index 61d70cf4..00000000 --- a/i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/clonal-selection-algorithms/Cell.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -id: cell -sidebar_label: Célula-B de Memória -sidebar_position: 2 -pagination_next: null -keywords: - - Binário - - classificação - - limiar de afinidade - - Valores Reais - - classificação - - anomalias - - K-Vizinhos Mais Próximos - - célula-B de memória -lastUpdatedAt: 2025/05/25 -author: João Paulo ---- - -# Célula-B de memória - -Representa uma célula-B de memória. - -## Construtor - -Parâmetros: - -* **vector** (`npt.NDArray`): Vetor de características da célula. Padrão é None. - ---- - -## Função hyper_clonal_mutate(...) - -Parâmetros: - -* **n** (`int`): O número de clones a serem gerados a partir de mutações da célula original. -* **feature_type** (`Literal["continuous-features", "binary-features", "ranged-features"]`): Especifica o tipo de algoritmo com base na natureza das características de entrada. -* **bounds** (``np.ndarray``): Array (n_features, 2) com mínimo e máximo por dimensão. - -```python -def hyper_clonal_mutate( - self, - n: int, - feature_type: Literal[ - "binary-features", - "continuous-features", - "ranged-features" - ], - bounds: Optional[npt.NDArray[np.float64]] = None -) -> npt.NDArray -``` - -Retorna um array contendo N vetores mutados a partir da célula original. diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/clonal-selection-algorithms/airs/README.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/clonal-selection-algorithms/airs/README.md index 02a88ed2..1c500308 100644 --- a/i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/clonal-selection-algorithms/airs/README.md +++ b/i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/clonal-selection-algorithms/airs/README.md @@ -28,7 +28,7 @@ Com base no algoritmo 16.5 de Brabazon et al. [1](#1). :::info -**``AIRS``** estende a classe **[``_ABR``](abr)**, herdando sua funcionalidade base. +**``AIRS``** estende a classe **[classe ``BaseClassifier``](../../../advanced-guides/base-module/core/Classifier.md)**, herdando sua funcionalidade base. ::: @@ -54,9 +54,18 @@ A classe `AIRS` tem como objetivo realizar classificação utilizando metáforas - **metric** (Literal["manhattan", "minkowski", "euclidean"]): Forma de calcular a distância entre o detector e a amostra: - - ``'euclidiana'`` ➜ O cálculo da distância dá-se pela expressão: $$\sqrt{(X_1 - X_1)^2 + (Y_2 - Y_2)^2 + ... + (Y_n - Y_n)^2}$$. - - ``'minkowski'`` ➜ O cálculo da distância dá-se pela expressão: $$( |X_1 - Y_1|^p + |X_2 - Y_2|^p + ... |X_n - Y_n|^p)^\frac{1}{p}$$. - - ``'manhattan'`` ➜ O cálculo da distância dá-se pela expressão: $$( |X_1 - X_1| + |Y_2 - Y_2| + ... + |Y_n - Y_n|)$$. + - ``'euclidiana'`` ➜ O cálculo da distância dá-se pela expressão: + $$ + \sqrt{(X_1 - X_1)^2 + (Y_2 - Y_2)^2 + ... + (Y_n - Y_n)^2} + $$ + - ``'minkowski'`` ➜ O cálculo da distância dá-se pela expressão: + $$ + \frac{((|X_{1} - Y_{1}|^p + |X_{2} - Y_{2}|^p + \cdots + |X_{n} - Y_{n}|^p)^\frac{1}{p})}{n} + $$. + - ``'manhattan'`` ➜ O cálculo da distância dá-se pela expressão: + $$ + \frac{(|X_{1} - X_{1}| + |Y_{2} - Y_{2}| + \cdots + |Y_{n} - Y_{n}|)}{n} + $$. Defaults to ``'euclidean'``. diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/clonal-selection-algorithms/airs/abr.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/clonal-selection-algorithms/airs/abr.md index 949c9a47..eb0e525b 100644 --- a/i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/clonal-selection-algorithms/airs/abr.md +++ b/i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/clonal-selection-algorithms/airs/abr.md @@ -21,7 +21,7 @@ Individuo do conjunto de células reconhecedoras (ABR), herda características d :::info -**``ABR``** estende a classe **[``Cell``](../cell)**, herdando sua funcionalidade base. +**``ABR``** estende a classe **[``BCell``](../../../advanced-guides/base-module/immune/cell.md#BCell)**, herdando sua funcionalidade base. ::: diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/clonal-selection-algorithms/clonalg.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/clonal-selection-algorithms/clonalg.md index 94e2ee23..45275396 100644 --- a/i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/clonal-selection-algorithms/clonalg.md +++ b/i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/clonal-selection-algorithms/clonalg.md @@ -28,6 +28,12 @@ específica. Esta adaptação visa generalizar o CLONALG para tarefas de minimiz maximização, além de suportar problemas contínuos, discretos e de permutação. ::: +:::info + +**``Clonalg``** estende a **[classe ``BaseOptimizer`` ](../../advanced-guides/base-module/core/Optimizer.md)**, herdando suas funcionalidades básicas. + +::: + --- ## CLONALG Constructor @@ -55,7 +61,12 @@ O construtor inicializa a instância do CLONALG com os principais parâmetros qu #### Função `optimize(...)` ```python -def optimize(self, max_iters: int = 50, n_iter_no_change=10, verbose: bool = True) -> npt.NDArray: +def optimize( + self, + max_iters: int = 50, + n_iter_no_change=10, + verbose: bool = True +) -> List[Antibody]: ``` Este método executa o processo de otimização e retorna a população de anticorpos. @@ -68,7 +79,7 @@ Este método executa o processo de otimização e retorna a população de antic **Retorna:** -* `npt.NDArray`: A população de anticorpos após a expansão clonal. +* population : ``List[Antibody]``, A população de [anticorpos](../../advanced-guides/base-module/immune/cell.md#Antibody) após a expansão clonal. --- diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/immune-network-theory/AiNet.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/immune-network-theory/AiNet.md index fdaac866..5738f143 100644 --- a/i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/immune-network-theory/AiNet.md +++ b/i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/immune-network-theory/AiNet.md @@ -38,7 +38,7 @@ Para clustering, pode opcionalmente utilizar uma [**Árvore Geradora Mínima** :::info -**``AiNet``** estende a **[classe ``BaseAiNet``](../../advanced-guides/base-classes-reference/ina/ainet.md)**, herdando sua funcionalidade básica. +**``AiNet``** estende a **[classe ``BaseClusterer``](../../advanced-guides/base-module/core/Clusterer.md)**, herdando sua funcionalidade básica. ::: @@ -76,11 +76,18 @@ class AiNet( * **k** (`int`): Número de vizinhos mais próximos usados para predição de rótulos. Padrão: 3. * **metric** (Literal["manhattan", "minkowski", "euclidean"]): Forma de calcular a distância entre o detector e a amostra: - * `'euclidean'` ➜ Distância dada pela expressão: - $$\sqrt{(X_{1} - X_{1})^2 + (Y_{2} - Y_{2})^2 + \cdots + (Y_{n} - Y_{n})^2}$$ - * ``'minkowski'`` ➜ Distância dada pela expressão: - $$\frac{((|X_{1} - Y_{1}|^p + |X_{2} - Y_{2}|^p + \cdots + |X_{n} - Y_{n}|^p)^\frac{1}{p})}{n}$$. - * ``'manhattan'`` ➜ Distância dada pela expressão: $$\frac{(|X_{1} - X_{1}| + |Y_{2} - Y_{2}| + \cdots + |Y_{n} - Y_{n}|)}{n}$$. + * ``'euclidiana'`` ➜ O cálculo da distância dá-se pela expressão: + $$ + \sqrt{(X_1 - X_1)^2 + (Y_2 - Y_2)^2 + ... + (Y_n - Y_n)^2} + $$ + * ``'minkowski'`` ➜ O cálculo da distância dá-se pela expressão: + $$ + \frac{((|X_{1} - Y_{1}|^p + |X_{2} - Y_{2}|^p + \cdots + |X_{n} - Y_{n}|^p)^\frac{1}{p})}{n} + $$ + * ``'manhattan'`` ➜ O cálculo da distância dá-se pela expressão: + $$ + \frac{(|X_{1} - X_{1}| + |Y_{2} - Y_{2}| + \cdots + |Y_{n} - Y_{n}|)}{n} + $$ Padrão: **"Euclidean"**. @@ -107,7 +114,7 @@ class AiNet( Treina o modelo AiNet com os dados de entrada: ```python -def fit(self, X: npt.NDArray, verbose: bool = True): +def fit(self, X: npt.NDArray, verbose: bool = True) -> AiNet: ``` **Parâmetros de entrada:** diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/negative-selection/BNSA.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/negative-selection/BNSA.md index 803f1022..9f619b1e 100644 --- a/i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/negative-selection/BNSA.md +++ b/i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/negative-selection/BNSA.md @@ -21,6 +21,14 @@ keywords: # BNSA (Algoritmo de Seleção Negativa Binária) +:::info + +**``BNSA``** estende a **[classe ``BaseClassifier``](../../advanced-guides/base-module/core/Classifier.md)**, herdando suas funcionalidades básicas. + +::: + +## Construtor RNSA + A classe ``BNSA`` tem a finalidade de classificação e identificação de anomalias através do método self e not self . ```python @@ -39,9 +47,9 @@ class BNSA( * *N* (``int``): Quantidade de detectores. Defaults to ``100``. * *aff_thresh* (``float``): A variável ('affinity threshold') representa a porcentagem de não similaridade entre a célula T e as amostras próprias. O valor padrão é de 10% (0,1), enquanto que o valor de 1,0 representa 100% de não similaridade. -:::note -Definir uma porcentagem de diferença muito alta pode resultar na incapacidade de gerar detectores para não-próprio. -::: + :::note + Definir uma porcentagem de diferença muito alta pode resultar na incapacidade de gerar detectores para não-próprio. + ::: * *max_discards* (``int``): Este parâmetro indica o número máximo de descartes de detectores em sequência, que tem como objetivo evitar um possível loop infinito caso seja definido um raio que não seja possível gerar detectores do não-próprio. Defaults to ``1000``. diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/negative-selection/RNSA.md b/i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/negative-selection/RNSA.md index 8d97e90a..6f1c88e0 100644 --- a/i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/negative-selection/RNSA.md +++ b/i18n/pt-br/docusaurus-plugin-content-docs/current/aisp-techniques/negative-selection/RNSA.md @@ -20,6 +20,12 @@ keywords: # RNSA (Algoritmo de Seleção Negativa de Valor Real) +:::info + +**``RNSA``** estende a **[classe ``BaseClassifier``](../../advanced-guides/base-module/core/Classifier.md)**, herdando suas funcionalidades básicas. + +::: + ## Construtor RNSA A classe ``RNSA`` tem a finalidade de classificação e identificação de anomalias através do método self e not self . @@ -44,16 +50,25 @@ class RNSA( * *N* (``int``): Quantidade de detectores. Defaults to ``100``. * *r* (``float``): Raio do detector. Defaults to ``0.05``. -:::note -É importante considerar que definir um raio muito baixo para o detector pode reduzir significativamente a taxa de detecção. Por outro lado, um raio muito grande pode inviabilizar a incorporação do detector no espaço de busca, o que também pode comprometer o desempenho da detecção. É fundamental encontrar um equilíbrio entre o tamanho do raio e a eficiência da detecção para obter os melhores resultados possíveis. -::: + :::note + É importante considerar que definir um raio muito baixo para o detector pode reduzir significativamente a taxa de detecção. Por outro lado, um raio muito grande pode inviabilizar a incorporação do detector no espaço de busca, o que também pode comprometer o desempenho da detecção. É fundamental encontrar um equilíbrio entre o tamanho do raio e a eficiência da detecção para obter os melhores resultados possíveis. + ::: * *k* (``int``): Quantidade de vizinhos próximos dos detectores gerados aleatoriamente para efetuar o cálculo da média da distância. Defaults to ``1``. * *metric* (``str``): Forma para se calcular a distância entre o detector e a amostra: - * ``'euclidiana'`` ➜ O cálculo da distância dá-se pela expressão: $$\sqrt{(X_1 - X_1)^2 + (Y_2 - Y_2)^2 + ... + (Y_n - Y_n)^2}$$. - * ``'minkowski'`` ➜ O cálculo da distância dá-se pela expressão: $$( |X_1 - Y_1|^p + |X_2 - Y_2|^p + ... |X_n - Y_n|^p)^\frac{1}{p}$$. - * ``'manhattan'`` ➜ O cálculo da distância dá-se pela expressão: $$( |X_1 - X_1| + |Y_2 - Y_2| + ... + |Y_n - Y_n|)$$. + * ``'euclidiana'`` ➜ O cálculo da distância dá-se pela expressão: + $$ + \sqrt{(X_1 - X_1)^2 + (Y_2 - Y_2)^2 + ... + (Y_n - Y_n)^2} + $$ + * ``'minkowski'`` ➜ O cálculo da distância dá-se pela expressão: + $$ + \frac{((|X_{1} - Y_{1}|^p + |X_{2} - Y_{2}|^p + \cdots + |X_{n} - Y_{n}|^p)^\frac{1}{p})}{n} + $$. + * ``'manhattan'`` ➜ O cálculo da distância dá-se pela expressão: + $$ + \frac{(|X_{1} - X_{1}| + |Y_{2} - Y_{2}| + \cdots + |Y_{n} - Y_{n}|)}{n} + $$. Defaults to ``'euclidean'``. diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.1.x/advanced-guides/Utils/Distance.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.1.x/advanced-guides/Utils/Distance.md index 4c4e896f..f4b5939b 100644 --- a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.1.x/advanced-guides/Utils/Distance.md +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.1.x/advanced-guides/Utils/Distance.md @@ -16,7 +16,9 @@ def hamming(u: npt.NDArray, v: npt.NDArray) -> np.float64: Função para calcular a distância de Hamming normalizada entre dois pontos. -$((x₁ ≠ x₂) + (y₁ ≠ y₂) + ... + (y_n ≠ y_n)) / n$ +$$ +\frac{(x_1 \neq y_1) + (x_2 \neq y_2) + \cdots + (x_n \neq y_n)}{n} +$$ **Parameters:** @@ -37,7 +39,9 @@ def euclidean(u: npt.NDArray[np.float64], v: npt.NDArray[np.float64]) -> np.floa Função para calcular a distância euclidiana normalizada entre dois pontos. -$√( (x₁ - x₂)² + (y₁ - y₂)² + ... + (y_n - y_n)²)$ +$$ +\sqrt{(X_{1} - X_{1})^2 + (Y_{2} - Y_{2})^2 + \cdots + (Y_{n} - Y_{n})^2} +$$ **Parameters:** @@ -58,7 +62,9 @@ def cityblock(u: npt.NDArray[np.float64], v: npt.NDArray[np.float64]) -> np.floa Função para calcular a distância Manhattan normalizada entre dois pontos. -$(|x₁ - x₂| + |y₁ - y₂| + ... + |y_n - y_n|) / n$ +$$ +\frac{(|X_{1} - X_{1}| + |Y_{2} - Y_{2}| + \cdots + |Y_{n} - Y_{n}|)}{n} +$$ **Parameters:** diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.1.x/aisp-techniques/Negative Selection/RNSA.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.1.x/aisp-techniques/Negative Selection/RNSA.md index 8d97e90a..ce0cb36d 100644 --- a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.1.x/aisp-techniques/Negative Selection/RNSA.md +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.1.x/aisp-techniques/Negative Selection/RNSA.md @@ -52,8 +52,8 @@ class RNSA( * *metric* (``str``): Forma para se calcular a distância entre o detector e a amostra: * ``'euclidiana'`` ➜ O cálculo da distância dá-se pela expressão: $$\sqrt{(X_1 - X_1)^2 + (Y_2 - Y_2)^2 + ... + (Y_n - Y_n)^2}$$. - * ``'minkowski'`` ➜ O cálculo da distância dá-se pela expressão: $$( |X_1 - Y_1|^p + |X_2 - Y_2|^p + ... |X_n - Y_n|^p)^\frac{1}{p}$$. - * ``'manhattan'`` ➜ O cálculo da distância dá-se pela expressão: $$( |X_1 - X_1| + |Y_2 - Y_2| + ... + |Y_n - Y_n|)$$. + * ``'minkowski'`` ➜ O cálculo da distância dá-se pela expressão: $$\frac{((|X_{1} - Y_{1}|^p + |X_{2} - Y_{2}|^p + \cdots + |X_{n} - Y_{n}|^p)^\frac{1}{p})}{n}$$. + * ``'manhattan'`` ➜ O cálculo da distância dá-se pela expressão: $$\frac{(|X_{1} - X_{1}| + |Y_{2} - Y_{2}| + \cdots + |Y_{n} - Y_{n}|)}{n}$$. Defaults to ``'euclidean'``. diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.2.x/advanced-guides/Utils/Distance.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.2.x/advanced-guides/Utils/Distance.md index 4c4e896f..f4b5939b 100644 --- a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.2.x/advanced-guides/Utils/Distance.md +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.2.x/advanced-guides/Utils/Distance.md @@ -16,7 +16,9 @@ def hamming(u: npt.NDArray, v: npt.NDArray) -> np.float64: Função para calcular a distância de Hamming normalizada entre dois pontos. -$((x₁ ≠ x₂) + (y₁ ≠ y₂) + ... + (y_n ≠ y_n)) / n$ +$$ +\frac{(x_1 \neq y_1) + (x_2 \neq y_2) + \cdots + (x_n \neq y_n)}{n} +$$ **Parameters:** @@ -37,7 +39,9 @@ def euclidean(u: npt.NDArray[np.float64], v: npt.NDArray[np.float64]) -> np.floa Função para calcular a distância euclidiana normalizada entre dois pontos. -$√( (x₁ - x₂)² + (y₁ - y₂)² + ... + (y_n - y_n)²)$ +$$ +\sqrt{(X_{1} - X_{1})^2 + (Y_{2} - Y_{2})^2 + \cdots + (Y_{n} - Y_{n})^2} +$$ **Parameters:** @@ -58,7 +62,9 @@ def cityblock(u: npt.NDArray[np.float64], v: npt.NDArray[np.float64]) -> np.floa Função para calcular a distância Manhattan normalizada entre dois pontos. -$(|x₁ - x₂| + |y₁ - y₂| + ... + |y_n - y_n|) / n$ +$$ +\frac{(|X_{1} - X_{1}| + |Y_{2} - Y_{2}| + \cdots + |Y_{n} - Y_{n}|)}{n} +$$ **Parameters:** diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.2.x/aisp-techniques/Clonal Selection Algorithms/airs/README.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.2.x/aisp-techniques/Clonal Selection Algorithms/airs/README.md index 7cab8820..697df957 100644 --- a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.2.x/aisp-techniques/Clonal Selection Algorithms/airs/README.md +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.2.x/aisp-techniques/Clonal Selection Algorithms/airs/README.md @@ -56,8 +56,8 @@ A classe `AIRS` tem como objetivo realizar classificação utilizando metáforas - **metric** (Literal["manhattan", "minkowski", "euclidean"]): Forma de calcular a distância entre o detector e a amostra: - ``'euclidiana'`` ➜ O cálculo da distância dá-se pela expressão: $$\sqrt{(X_1 - X_1)^2 + (Y_2 - Y_2)^2 + ... + (Y_n - Y_n)^2}$$. - - ``'minkowski'`` ➜ O cálculo da distância dá-se pela expressão: $$( |X_1 - Y_1|^p + |X_2 - Y_2|^p + ... |X_n - Y_n|^p)^\frac{1}{p}$$. - - ``'manhattan'`` ➜ O cálculo da distância dá-se pela expressão: $$( |X_1 - X_1| + |Y_2 - Y_2| + ... + |Y_n - Y_n|)$$. + - ``'minkowski'`` ➜ O cálculo da distância dá-se pela expressão: $$\frac{((|X_{1} - Y_{1}|^p + |X_{2} - Y_{2}|^p + \cdots + |X_{n} - Y_{n}|^p)^\frac{1}{p})}{n}$$. + - ``'manhattan'`` ➜ O cálculo da distância dá-se pela expressão: $$\frac{(|X_{1} - X_{1}| + |Y_{2} - Y_{2}| + \cdots + |Y_{n} - Y_{n}|)}{n}$$. Defaults to ``'euclidean'``. diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.2.x/aisp-techniques/Negative Selection/RNSA.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.2.x/aisp-techniques/Negative Selection/RNSA.md index 8d97e90a..ce0cb36d 100644 --- a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.2.x/aisp-techniques/Negative Selection/RNSA.md +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.2.x/aisp-techniques/Negative Selection/RNSA.md @@ -52,8 +52,8 @@ class RNSA( * *metric* (``str``): Forma para se calcular a distância entre o detector e a amostra: * ``'euclidiana'`` ➜ O cálculo da distância dá-se pela expressão: $$\sqrt{(X_1 - X_1)^2 + (Y_2 - Y_2)^2 + ... + (Y_n - Y_n)^2}$$. - * ``'minkowski'`` ➜ O cálculo da distância dá-se pela expressão: $$( |X_1 - Y_1|^p + |X_2 - Y_2|^p + ... |X_n - Y_n|^p)^\frac{1}{p}$$. - * ``'manhattan'`` ➜ O cálculo da distância dá-se pela expressão: $$( |X_1 - X_1| + |Y_2 - Y_2| + ... + |Y_n - Y_n|)$$. + * ``'minkowski'`` ➜ O cálculo da distância dá-se pela expressão: $$\frac{((|X_{1} - Y_{1}|^p + |X_{2} - Y_{2}|^p + \cdots + |X_{n} - Y_{n}|^p)^\frac{1}{p})}{n}$$. + * ``'manhattan'`` ➜ O cálculo da distância dá-se pela expressão: $$\frac{(|X_{1} - X_{1}| + |Y_{2} - Y_{2}| + \cdots + |Y_{n} - Y_{n}|)}{n}$$. Defaults to ``'euclidean'``. diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.3.x/advanced-guides/Utils/Distance.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.3.x/advanced-guides/Utils/Distance.md index 4c4e896f..f4b5939b 100644 --- a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.3.x/advanced-guides/Utils/Distance.md +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.3.x/advanced-guides/Utils/Distance.md @@ -16,7 +16,9 @@ def hamming(u: npt.NDArray, v: npt.NDArray) -> np.float64: Função para calcular a distância de Hamming normalizada entre dois pontos. -$((x₁ ≠ x₂) + (y₁ ≠ y₂) + ... + (y_n ≠ y_n)) / n$ +$$ +\frac{(x_1 \neq y_1) + (x_2 \neq y_2) + \cdots + (x_n \neq y_n)}{n} +$$ **Parameters:** @@ -37,7 +39,9 @@ def euclidean(u: npt.NDArray[np.float64], v: npt.NDArray[np.float64]) -> np.floa Função para calcular a distância euclidiana normalizada entre dois pontos. -$√( (x₁ - x₂)² + (y₁ - y₂)² + ... + (y_n - y_n)²)$ +$$ +\sqrt{(X_{1} - X_{1})^2 + (Y_{2} - Y_{2})^2 + \cdots + (Y_{n} - Y_{n})^2} +$$ **Parameters:** @@ -58,7 +62,9 @@ def cityblock(u: npt.NDArray[np.float64], v: npt.NDArray[np.float64]) -> np.floa Função para calcular a distância Manhattan normalizada entre dois pontos. -$(|x₁ - x₂| + |y₁ - y₂| + ... + |y_n - y_n|) / n$ +$$ +\frac{(|X_{1} - X_{1}| + |Y_{2} - Y_{2}| + \cdots + |Y_{n} - Y_{n}|)}{n} +$$ **Parameters:** diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.3.x/aisp-techniques/clonal-selection-algorithms/airs/README.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.3.x/aisp-techniques/clonal-selection-algorithms/airs/README.md index 02a88ed2..ec0b543f 100644 --- a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.3.x/aisp-techniques/clonal-selection-algorithms/airs/README.md +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.3.x/aisp-techniques/clonal-selection-algorithms/airs/README.md @@ -55,8 +55,8 @@ A classe `AIRS` tem como objetivo realizar classificação utilizando metáforas - **metric** (Literal["manhattan", "minkowski", "euclidean"]): Forma de calcular a distância entre o detector e a amostra: - ``'euclidiana'`` ➜ O cálculo da distância dá-se pela expressão: $$\sqrt{(X_1 - X_1)^2 + (Y_2 - Y_2)^2 + ... + (Y_n - Y_n)^2}$$. - - ``'minkowski'`` ➜ O cálculo da distância dá-se pela expressão: $$( |X_1 - Y_1|^p + |X_2 - Y_2|^p + ... |X_n - Y_n|^p)^\frac{1}{p}$$. - - ``'manhattan'`` ➜ O cálculo da distância dá-se pela expressão: $$( |X_1 - X_1| + |Y_2 - Y_2| + ... + |Y_n - Y_n|)$$. + - ``'minkowski'`` ➜ O cálculo da distância dá-se pela expressão: $$\frac{((|X_{1} - Y_{1}|^p + |X_{2} - Y_{2}|^p + \cdots + |X_{n} - Y_{n}|^p)^\frac{1}{p})}{n}$$. + - ``'manhattan'`` ➜ O cálculo da distância dá-se pela expressão: $$\frac{(|X_{1} - X_{1}| + |Y_{2} - Y_{2}| + \cdots + |Y_{n} - Y_{n}|)}{n}$$. Defaults to ``'euclidean'``. diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.3.x/aisp-techniques/negative-selection/RNSA.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.3.x/aisp-techniques/negative-selection/RNSA.md index 8d97e90a..ce0cb36d 100644 --- a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.3.x/aisp-techniques/negative-selection/RNSA.md +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.3.x/aisp-techniques/negative-selection/RNSA.md @@ -52,8 +52,8 @@ class RNSA( * *metric* (``str``): Forma para se calcular a distância entre o detector e a amostra: * ``'euclidiana'`` ➜ O cálculo da distância dá-se pela expressão: $$\sqrt{(X_1 - X_1)^2 + (Y_2 - Y_2)^2 + ... + (Y_n - Y_n)^2}$$. - * ``'minkowski'`` ➜ O cálculo da distância dá-se pela expressão: $$( |X_1 - Y_1|^p + |X_2 - Y_2|^p + ... |X_n - Y_n|^p)^\frac{1}{p}$$. - * ``'manhattan'`` ➜ O cálculo da distância dá-se pela expressão: $$( |X_1 - X_1| + |Y_2 - Y_2| + ... + |Y_n - Y_n|)$$. + * ``'minkowski'`` ➜ O cálculo da distância dá-se pela expressão: $$\frac{((|X_{1} - Y_{1}|^p + |X_{2} - Y_{2}|^p + \cdots + |X_{n} - Y_{n}|^p)^\frac{1}{p})}{n}$$. + * ``'manhattan'`` ➜ O cálculo da distância dá-se pela expressão: $$\frac{(|X_{1} - X_{1}| + |Y_{2} - Y_{2}| + \cdots + |Y_{n} - Y_{n}|)}{n}$$. Defaults to ``'euclidean'``. diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.4.x/advanced-guides/Utils/Distance.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.4.x/advanced-guides/Utils/Distance.md index 4c4e896f..f4b5939b 100644 --- a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.4.x/advanced-guides/Utils/Distance.md +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.4.x/advanced-guides/Utils/Distance.md @@ -16,7 +16,9 @@ def hamming(u: npt.NDArray, v: npt.NDArray) -> np.float64: Função para calcular a distância de Hamming normalizada entre dois pontos. -$((x₁ ≠ x₂) + (y₁ ≠ y₂) + ... + (y_n ≠ y_n)) / n$ +$$ +\frac{(x_1 \neq y_1) + (x_2 \neq y_2) + \cdots + (x_n \neq y_n)}{n} +$$ **Parameters:** @@ -37,7 +39,9 @@ def euclidean(u: npt.NDArray[np.float64], v: npt.NDArray[np.float64]) -> np.floa Função para calcular a distância euclidiana normalizada entre dois pontos. -$√( (x₁ - x₂)² + (y₁ - y₂)² + ... + (y_n - y_n)²)$ +$$ +\sqrt{(X_{1} - X_{1})^2 + (Y_{2} - Y_{2})^2 + \cdots + (Y_{n} - Y_{n})^2} +$$ **Parameters:** @@ -58,7 +62,9 @@ def cityblock(u: npt.NDArray[np.float64], v: npt.NDArray[np.float64]) -> np.floa Função para calcular a distância Manhattan normalizada entre dois pontos. -$(|x₁ - x₂| + |y₁ - y₂| + ... + |y_n - y_n|) / n$ +$$ +\frac{(|X_{1} - X_{1}| + |Y_{2} - Y_{2}| + \cdots + |Y_{n} - Y_{n}|)}{n} +$$ **Parameters:** diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.4.x/aisp-techniques/clonal-selection-algorithms/airs/README.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.4.x/aisp-techniques/clonal-selection-algorithms/airs/README.md index 02a88ed2..ec0b543f 100644 --- a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.4.x/aisp-techniques/clonal-selection-algorithms/airs/README.md +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.4.x/aisp-techniques/clonal-selection-algorithms/airs/README.md @@ -55,8 +55,8 @@ A classe `AIRS` tem como objetivo realizar classificação utilizando metáforas - **metric** (Literal["manhattan", "minkowski", "euclidean"]): Forma de calcular a distância entre o detector e a amostra: - ``'euclidiana'`` ➜ O cálculo da distância dá-se pela expressão: $$\sqrt{(X_1 - X_1)^2 + (Y_2 - Y_2)^2 + ... + (Y_n - Y_n)^2}$$. - - ``'minkowski'`` ➜ O cálculo da distância dá-se pela expressão: $$( |X_1 - Y_1|^p + |X_2 - Y_2|^p + ... |X_n - Y_n|^p)^\frac{1}{p}$$. - - ``'manhattan'`` ➜ O cálculo da distância dá-se pela expressão: $$( |X_1 - X_1| + |Y_2 - Y_2| + ... + |Y_n - Y_n|)$$. + - ``'minkowski'`` ➜ O cálculo da distância dá-se pela expressão: $$\frac{((|X_{1} - Y_{1}|^p + |X_{2} - Y_{2}|^p + \cdots + |X_{n} - Y_{n}|^p)^\frac{1}{p})}{n}$$. + - ``'manhattan'`` ➜ O cálculo da distância dá-se pela expressão: $$\frac{(|X_{1} - X_{1}| + |Y_{2} - Y_{2}| + \cdots + |Y_{n} - Y_{n}|)}{n}$$. Defaults to ``'euclidean'``. diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.4.x/aisp-techniques/negative-selection/RNSA.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.4.x/aisp-techniques/negative-selection/RNSA.md index 342e3f01..36ef547f 100644 --- a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.4.x/aisp-techniques/negative-selection/RNSA.md +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.4.x/aisp-techniques/negative-selection/RNSA.md @@ -52,8 +52,8 @@ class RNSA( * *metric* (``str``): Forma para se calcular a distância entre o detector e a amostra: * ``'euclidiana'`` ➜ O cálculo da distância dá-se pela expressão: $$\sqrt{(X_1 - X_1)^2 + (Y_2 - Y_2)^2 + ... + (Y_n - Y_n)^2}$$. - * ``'minkowski'`` ➜ O cálculo da distância dá-se pela expressão: $$( |X_1 - Y_1|^p + |X_2 - Y_2|^p + ... |X_n - Y_n|^p)^\frac{1}{p}$$. - * ``'manhattan'`` ➜ O cálculo da distância dá-se pela expressão: $$( |X_1 - X_1| + |Y_2 - Y_2| + ... + |Y_n - Y_n|)$$. + * ``'minkowski'`` ➜ O cálculo da distância dá-se pela expressão: $$\frac{((|X_{1} - Y_{1}|^p + |X_{2} - Y_{2}|^p + \cdots + |X_{n} - Y_{n}|^p)^\frac{1}{p})}{n}$$. + * ``'manhattan'`` ➜ O cálculo da distância dá-se pela expressão: $$\frac{(|X_{1} - X_{1}| + |Y_{2} - Y_{2}| + \cdots + |Y_{n} - Y_{n}|)}{n}$$. Defaults to ``'euclidean'``. diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x.json b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x.json new file mode 100644 index 00000000..31abed90 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x.json @@ -0,0 +1,62 @@ +{ + "sidebar.docs.category.Implemented techniques": { + "message": "Técnicas implementadas", + "description": "The label for category Implemented techniques in sidebar docs" + }, + "sidebar.docs.category.Negative selection": { + "message": "Seleção negativa", + "description": "The label for category Negative selection in sidebar docs" + }, + "sidebar.docs.category.Getting Started": { + "message": "Primeiros passos", + "description": "The label for category Getting Started in sidebar docs" + }, + "sidebar.docs.category.Técnicas implementadas": { + "message": "Técnicas implementadas", + "description": "The label for category Técnicas implementadas in sidebar docs" + }, + "sidebar.docs.category.Seleção Negativa": { + "message": "Seleção Negativa", + "description": "The label for category Seleção Negativa in sidebar docs" + }, + "sidebar.docs.category.Examples": { + "message": "Exemplos", + "description": "The label for category Examples in sidebar docs" + }, + "sidebar.docs.category.Examples.link.generated-index.description": { + "message": "Abaixo estão alguns exemplos que usam base de dados para classificação com a ferramenta Jupyter notebook.", + "description": "Abaixo estão alguns exemplos que usam base de dados para classificação com a ferramenta Jupyter notebook." + }, + "sidebar.docs.category.Basic usage": { + "message": "Utilização básica", + "description": "The label for category Basic usage in sidebar docs" + }, + "sidebar.docs.category.Advanced Guides": { + "message": "Guias avançados", + "description": "The label for category Advanced Guides in sidebar docs" + }, + "sidebar.docs.category.Base Classes Reference": { + "message": "Referência das Classes Base", + "description": "The label for category Examples in sidebar docs" + }, + "sidebar.docs.category.Advanced Guides.link.generated-index.description": { + "message": "Explore a documentação avançada da biblioteca, que abrange as classes base, além das funções utilitárias do módulo utils voltadas para métricas e manipulação de classificação multiclasse.", + "description": "The generated-index page description for category Advanced Guides in sidebar docs" + }, + "sidebar.docs.category.Base module.description": { + "message": "Classe base para algoritmo de classificação.", + "description": "Classe base para algoritmo de classificação." + }, + "sidebar.docs.category.Base Classes Reference.description": { + "message": "Classes base para implementar os algoritmos fornecidos neste pacote.", + "description": "Classes base para implementar os algoritmos fornecidos neste pacote." + }, + "sidebar.docs.category.Core.description": { + "message": "As funções realizam verificações de detectores e utilizam decoradores Numba para compilação Just-In-Time", + "description": "As funções realizam verificações de detectores e utilizam decoradores Numba para compilação Just-In-Time" + }, + "sidebar.docs.category.utils.description": { + "message": "Funções utilitárias e auxiliares para o desenvolvimento.", + "description": "Funções utilitárias e auxiliares para o desenvolvimento." + } +} diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/about-us.mdx b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/about-us.mdx new file mode 100644 index 00000000..fb136e1e --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/about-us.mdx @@ -0,0 +1,48 @@ +--- +sidebar_position: 3 +pagination_prev: null +--- + +import TeamUser from '@site/src/components/TeamUser'; + +# Sobre nós + +## História + +O AISP, ou pacote de Sistemas Imunológicos Artificiais, teve sua origem em um projeto de pesquisa do IFNMG +(Instituto Federal do Norte de Minas Gerais) no campus de Salinas. A partir de 2 de maio de 2022, com o objetivo +de iniciar a criação de um pacote de software aberto que permita a aplicação, estudo e popularização de técnicas +pertencentes à área de sistemas imunológicos artificiais. + +--- + +## Equipe de colaboradores + +### Coordenador + +
+ + + +
+ +--- + +### Discentes + +
+ + + +
\ No newline at end of file diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/Core/_category_.json b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/Core/_category_.json new file mode 100644 index 00000000..3587f364 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/Core/_category_.json @@ -0,0 +1,3 @@ +{ + "description": "As funções realizam verificações de detectores e utilizam decoradores Numba para compilação Just-In-Time" +} \ No newline at end of file diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/Core/negative-selection.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/Core/negative-selection.md new file mode 100644 index 00000000..9041d2b2 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/Core/negative-selection.md @@ -0,0 +1,85 @@ +--- +last_update: + date: 2025/05/17 + author: João Paulo +--- + +# Seleção Negativa + +As funções realizam verificações de detectores e utilizam decoradores Numba para compilação Just-In-Time. + +## Função check_detector_bnsa_validity(...) + +```python +def check_detector_bnsa_validity( + x_class: npt.NDArray, + vector_x: npt.NDArray, + aff_thresh: float +) -> bool: +``` + +Verifica a validade de um candidato a detector (vector_x) contra amostras de uma classe (x_class) usando a distância de Hamming. Um detector é considerado INVÁLIDO se a sua distância para qualquer amostra em ``x_class`` for menor ou igual a ``aff_thresh``. + +**Os parâmetros de entrada são:** + +* x_class (``npt.NDArray``): Array contendo as amostras da classe. Formato esperado: (n_amostras, n_características). +* vector_x (``npt.NDArray``): Array representando o detector. Formato esperado: (n_características,). +* aff_thresh (``float``): Limiar de afinidade. + +**Retorna:** + +* True se o detector for válido, False caso contrário. + +--- + +## Função bnsa_class_prediction(...) + +```python +def bnsa_class_prediction( + features: npt.NDArray, + class_detectors: npt.NDArray, + aff_thresh: float +) -> int: +``` + +Define a classe de uma amostra a partir dos detectores não-próprios. + +**Os parâmetros de entrada são:** + +* features (``npt.NDArray``): amostra binária a ser classificada (shape: [n_features]). +* class_detectors (``npt.NDArray``): Matriz contendo os detectores de todas as classes (shape: [n_classes, n_detectors, n_features]). +* aff_thresh (``float``): Limiar de afinidade que determina se um detector reconhece a amostra como não-própria. + +**Retorna:** + +* int: Índice da classe predita. Retorna -1 se for não-própria para todas as classes. + +--- + +## Função check_detector_rnsa_validity(...) + +```python +def check_detector_rnsa_validity( + x_class: npt.NDArray, + vector_x: npt.NDArray, + threshold: float, + metric: int, + p: float +) -> bool: +``` + +Verifica a validade de um candidato a detector (vector_x) contra amostras de uma classe (x_class) usando a distância de Hamming. Um detector é considerado INVÁLIDO se a sua distância para qualquer amostra em ``x_class`` for menor ou igual a ``aff_thresh``. + +**Os parâmetros de entrada são:** + +* x_class (``npt.NDArray``): Array contendo as amostras da classe. Formato esperado: (n_amostras, n_características). +* vector_x (``npt.NDArray``): Array representando o detector. Formato esperado: (n_características,). +* threshold (``float``): Afinidade. +* metric (``int``): Métrica de distância a ser utilizada. Opções disponíveis: [0 (Euclidean), 1 (Manhattan), 2 (Minkowski)]. +* p (``float``): Parâmetro da métrica de Minkowski (utilizado apenas se `metric` for "minkowski"). + +**Retorna:** + +* True se o detector for válido, False caso contrário. + +--- diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/Utils/Display.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/Utils/Display.md new file mode 100644 index 00000000..5096345b --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/Utils/Display.md @@ -0,0 +1,152 @@ +# Display + +Funções utilitárias para exibir informações de algoritmos + +## def _supports_box_drawing() + +```python +def _supports_box_drawing() -> bool +``` + +Função para verificar se o terminal suporta caracteres de borda. + +**Retorna**: + +* ***bool*** (`bool`): True se o terminal provavelmente suporta caracteres de borda, False caso contrário. + +--- + +## class TableFormatter + +Classe para formatar dados tabulares em strings para exibição no console. + +**Parâmetros**: + +* ***headers*** (`Mapping[str, int]`): Mapeamento dos nomes das colunas para suas larguras respectivas, no formato `{nome_coluna: largura_coluna}`. + +**Exceções**: + +* `ValueError`: Se `headers` estiver vazio ou não for um mapeamento válido. + +--- + +### def _border(left, middle, right, line, new_line=True) + +```python +def _border(self, left: str, middle: str, right: str, line: str, new_line: bool = True) -> str +``` + +Cria uma borda horizontal para a tabela. + +**Parâmetros**: + +* ***left*** (`str`): Caractere na borda esquerda. +* ***middle*** (`str`): Caractere separador entre colunas. +* ***right*** (`str`): Caractere na borda direita. +* ***line*** (`str`): Caractere usado para preencher a borda. +* ***new_line*** (`bool`, opcional): Se True, adiciona uma quebra de linha antes da borda (padrão é True). + +**Retorna**: + +* ***border*** (`str`): String representando a borda horizontal. + +--- + +### def get_header() + +```python +def get_header(self) -> str +``` + +Gera o cabeçalho da tabela, incluindo a borda superior, os títulos das colunas e a linha separadora. + +**Retorna**: + +* ***header*** (`str`): String formatada do cabeçalho da tabela. + +--- + +### def get_row(values) + +```python +def get_row(self, values: Mapping[str, Union[str, int, float]]) -> str +``` + +Gera uma linha formatada para os dados da tabela. + +**Parâmetros**: + +* ***values*** (`Mapping[str, Union[str, int, float]]`): Dicionário com os valores de cada coluna, no formato `{nome_coluna: valor}`. + +**Retorna**: + +* ***row*** (`str`): String formatada da linha da tabela. + +--- + +### def get_bottom(new_line=False) + +```python +def get_bottom(self, new_line: bool = False) -> str +``` + +Gera a borda inferior da tabela. + +**Parâmetros**: + +* ***new_line*** (`bool`, opcional): Se True, adiciona uma quebra de linha antes da borda (padrão é False). + +**Retorna**: + +* ***bottom*** (`str`): String formatada da borda inferior. + +--- + +## class ProgressTable(TableFormatter) + +Classe para exibir uma tabela formatada no console para acompanhar o progresso de um algoritmo. + +**Parâmetros**: + +* ***headers*** (`Mapping[str, int]`): Mapeamento `{nome_coluna: largura_coluna}`. +* ***verbose*** (`bool`, padrão=True): Se False, não imprime nada no terminal. + +**Exceções**: + +* `ValueError`: Se `headers` estiver vazio ou não for um mapeamento válido. + +--- + +### def _print_header() + +```python +def _print_header(self) -> None +``` + +Imprime o cabeçalho da tabela. + +--- + +### def update(values) + +```python +def update(self, values: Mapping[str, Union[str, int, float]]) -> None +``` + +Adiciona uma nova linha de valores à tabela. + +**Parâmetros**: + +* ***values*** (`Mapping[str, Union[str, int, float]]`): As chaves devem corresponder às colunas definidas em `headers`. + +--- + +### def finish() + +```python +def finish(self) -> None +``` + +Encerra a exibição da tabela, imprimindo a borda inferior e o tempo total. + +--- diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/Utils/Distance.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/Utils/Distance.md new file mode 100644 index 00000000..f4b5939b --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/Utils/Distance.md @@ -0,0 +1,176 @@ +--- +last_update: + date: 2025/05/17 + author: João Paulo +--- + +# Distance + +Funções utilitárias para distância normalizada entre matrizes com decoradores numba. + +## def hamming(...) + +```python +def hamming(u: npt.NDArray, v: npt.NDArray) -> np.float64: +``` + +Função para calcular a distância de Hamming normalizada entre dois pontos. + +$$ +\frac{(x_1 \neq y_1) + (x_2 \neq y_2) + \cdots + (x_n \neq y_n)}{n} +$$ + +**Parameters:** + +* u (``npt.NDArray``): Coordenadas do primeiro ponto +* v (``npt.NDArray``): Coordenadas do segundo ponto. + +**Returns:** + +* Distância (``float``) entre os dois pontos. + +--- + +## def euclidean(...) + +```python +def euclidean(u: npt.NDArray[np.float64], v: npt.NDArray[np.float64]) -> np.float64: +``` + +Função para calcular a distância euclidiana normalizada entre dois pontos. + +$$ +\sqrt{(X_{1} - X_{1})^2 + (Y_{2} - Y_{2})^2 + \cdots + (Y_{n} - Y_{n})^2} +$$ + +**Parameters:** + +* u (``npt.NDArray``): Coordenadas do primeiro ponto +* v (``npt.NDArray``): Coordenadas do segundo ponto. + +**Returns:** + +* Distância (``float``) entre os dois pontos. + +--- + +## def cityblock(...) + +```python +def cityblock(u: npt.NDArray[np.float64], v: npt.NDArray[np.float64]) -> np.float64: +``` + +Função para calcular a distância Manhattan normalizada entre dois pontos. + +$$ +\frac{(|X_{1} - X_{1}| + |Y_{2} - Y_{2}| + \cdots + |Y_{n} - Y_{n}|)}{n} +$$ + +**Parameters:** + +* u (``npt.NDArray``): Coordenadas do primeiro ponto +* v (``npt.NDArray``): Coordenadas do segundo ponto. + +**Returns:** + +* Distância (``float``) entre os dois pontos. + +--- + +## def minkowski(...) + +```python +def minkowski(u: npt.NDArray[np.float64], v: npt.NDArray[np.float64], p: float = 2.0): +``` + +Função para calcular a distância de Minkowski normalizada entre dois pontos. + +$(( |X₁ - Y₁|p + |X₂ - Y₂|p + ... + |X_n - Y_n|p) ¹/ₚ) / n$ + +**Parameters:** + +* u (``npt.NDArray``): Coordenadas do primeiro ponto. +* v (``npt.NDArray``): Coordenadas do segundo ponto. +* p (``float``): O parâmetro p define o tipo de distância a ser calculada: + * p = 1: Distância **Manhattan** — soma das diferenças absolutas. + * p = 2: Distância **Euclidiana** — soma das diferenças ao quadrado (raiz quadrada). + * p > 2: Distância **Minkowski** com uma penalidade crescente à medida que p aumenta. + +**Returns:** + +* Distância (``float``) entre os dois pontos. + +--- + +## def compute_metric_distance(...) + +```python +def compute_metric_distance( + u: npt.NDArray[np.float64], + v: npt.NDArray[np.float64], + metric: int, + p: np.float64 = 2.0 +) -> np.float64: +``` + +Função para calcular a distância entre dois pontos pela ``métrica`` escolhida. + +**Parameters:** + +* u (``npt.NDArray``): Coordenadas do primeiro ponto. +* v (``npt.NDArray``): Coordenadas do segundo ponto. +* metric (``int``): Métrica de distância a ser utilizada. Opções disponíveis: [0 (Euclidean), 1 (Manhattan), 2 (Minkowski)]. +* p (``float``): Parâmetro da métrica de Minkowski (utilizado apenas se `metric` for "minkowski"). + +**Returns:** + +* Distância (``double``) entre os dois pontos com a métrica selecionada. + +--- + +## def min_distance_to_class_vectors(...) + +```python +def min_distance_to_class_vectors( + x_class: npt.NDArray, + vector_x: npt.NDArray, + metric: int, + p: float = 2.0 +) -> float: +``` + +Calcula a menor distância entre um vetor de entrada e os vetores de uma classe. + +**Parameters:** + +* x_class (``npt.NDArray``): Array contendo os vetores da classe com os quais o vetor de entrada será comparado. Formato esperado: (n_amostras, n_características). +* vector_x (``npt.NDArray``): Vetor a ser comparado com os vetores da classe. Formato esperado: (n_características,). +* metric (``int``): Métrica de distância a ser utilizada. Opções disponíveis: [0 (Euclidean), 1 (Manhattan), 2 (Minkowski)]. +* p (``float``): Parâmetro da métrica de Minkowski (utilizado apenas se `metric` for "minkowski"). + +**Returns:** + +* float: A menor distância calculada entre o vetor de entrada e os vetores da classe. +* Retorna -1.0 se as dimensões de entrada forem incompatíveis. + +--- + +## def get_metric_code(...) + +```python +def get_metric_code(metric: str) -> int: +``` + +Retorna o código numérico associado a uma métrica de distância. + +**Parameters:** + +* metric (``str``): Nome da métrica. Pode ser "euclidean", "manhattan", "minkowski" ou "hamming". + +**Raises** + +* ``ValueError``: Se a métrica informada não for suportada. + +**Returns:** + +* ``int``: Código numérico correspondente à métrica. diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/Utils/Metrics.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/Utils/Metrics.md new file mode 100644 index 00000000..1bef4601 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/Utils/Metrics.md @@ -0,0 +1,38 @@ +--- +sidebar_position: 1 +title: Métricas +sidebar_label: Metrics +lastUpdatedAt: 2025/04/04 +author: João Paulo +--- + +O arquivo de métricas fornece utilitários para medir, analisar e comparar o desempenho dos algoritmos do pacote de forma padronizada. + +### def accuracy_score(...) + +```python +def accuracy_score( + y_true: Union[npt.NDArray, list], + y_pred: Union[npt.NDArray, list] +) -> float +``` + +Função para calcular a acurácia de precisão com base em listas de rótulos +verdadeiros e nos rótulos previstos. + +**Parâmetros** + +* y_true (``Union[npt.NDArray, list]``): Rótulos verdadeiros (corretos).. +* y_pred (``Union[npt.NDArray, list]``): Rótulos previstos. + +**Retornos** + +* Precisão (``float``): A proporção de previsões corretas em relação +ao número total de previsões. + +**Lança** + +* ValueError: Se `y_true` ou `y_pred` estiverem vazios ou se não +tiverem o mesmo tamanho. + +--- diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/Utils/Multiclass.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/Utils/Multiclass.md new file mode 100644 index 00000000..fbe8d25e --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/Utils/Multiclass.md @@ -0,0 +1,55 @@ +--- +sidebar_position: 1 +title: Multiclasse +sidebar_label: Multiclass +lastUpdatedAt: 2025/04/04 +author: João Paulo +--- + +Este arquivo contém funções utilitárias internas desenvolvidas para simplificar a manipulação e o processamento de dados em cenários de classificação multiclasse dentro do pacote AISP. + +### def slice_index_list_by_class(...) + +```python +def slice_index_list_by_class(classes: Union[npt.NDArray, list], y: npt.NDArray) -> dict +``` + +A função ``slice_index_list_by_class(...)``, separa os índices das linhas conforme a \ +classe de saída, para percorrer o array de amostra, apenas nas posições que a saída for \ +a classe que está sendo treinada. + +**Parameters:** + +* classes (``list or npt.NDArray``): lista com classes únicas. +* y (npt.NDArray): Recebe um array ``y``[``N amostra``] com as classes de saída do \ + array de amostra ``X``. + +**Returns:** + +* dict: Um dicionário com a lista de posições do array(``y``), com as classes como chave. + +--- + +### def predict_knn_affinity(...) + +Função para prever classes usando k-vizinhos mais próximos e células treinadas. + +```python +def predict_knn_affinity( + X: npt.NDArray, + k: int, + all_cell_vectors: List[Tuple[Union[str, int], npt.NDArray]], + affinity_func: Callable[[npt.NDArray, npt.NDArray], float] +) -> npt.NDArray +``` + +**Parâmetros:** + +* **_X_** (`npt.NDArray`): Dados de entrada a serem classificados. +* **_k_** (`int`): Número de vizinhos mais próximos a considerar para a previsão. +* **_all_cell_vectors_** (`List[Tuple[Union[str, int], npt.NDArray]]`): Lista de tuplas contendo pares (nome_da_classe, vetor_da_célula). +* **_affinity_func_** (`Callable[[npt.NDArray, npt.NDArray], float]`): Função que recebe dois vetores e retorna um valor de afinidade. + +**Retorna:** + +* `npt.NDArray`: Array de rótulos previstos para cada amostra em X, baseado nos k vizinhos mais próximos. \ No newline at end of file diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/Utils/Random.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/Utils/Random.md new file mode 100644 index 00000000..b6554071 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/Utils/Random.md @@ -0,0 +1,16 @@ +# Random + +Funções utilitárias para geração e reprodutibilidade de números aleatórios. + +## Função set_seed_numba(...) + +```python +@njit(cache=True) +def set_seed_numba(seed: int) +``` + +Define a semente para números aleatórios usados por funções compiladas com Numba. + +**Parâmetros**: + +* **seed**: `int` - Valor inteiro usado para inicializar o gerador de números aleatórios do Numba. \ No newline at end of file diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/Utils/Sanitizers.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/Utils/Sanitizers.md new file mode 100644 index 00000000..56be3c29 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/Utils/Sanitizers.md @@ -0,0 +1,82 @@ +--- +last_update: + date: 2025/05/17 + author: João Paulo +--- + +# Sanitizers + +## def sanitize_choice(...) + +```python +def sanitize_choice(value: T, valid_choices: Iterable[T], default: T) -> T +``` + +A função ``sanitize_choice(...)``, retorna o valor se estiver presente no conjunto de opções válidas; caso contrário, retorna o valor padrão. + +**Parameters:** + +* ***value*** (``T``): O valor a ser verificado. +* ***valid_choices*** (``Iterable[T]``): Uma coleção de opções válidas. +* ***default***: O valor padrão a ser retornado se ``value`` não estiver em ``valid_choices``. + +**Returns:** + +* `T`: O valor original, se válido, ou o valor padrão, se não. + +--- + +## def sanitize_param(...) + +```python +def sanitize_param(value: T, default: T, condition: Callable[[T], bool]) -> T: +``` + +A função ``sanitize_param(...)``, retorna o valor se ele satisfizer a condição especificada; caso contrário, retorna o valor padrão. + +**Parameters:** + +* value (``T``): O valor a ser verificado. +* default (``T``): O valor padrão a ser retornado se a condição não for satisfeita. +* condition (``Callable[[T], bool]``): Uma função que recebe um valor e retorna um booleano, determinando se o valor é válido. + +**Returns:** + +* `T`: O valor original se a condição for satisfeita, ou o valor padrão se não for. + +--- + +## def sanitize_seed(...) + +```python +def sanitize_seed(seed: Any) -> Optional[int]: +``` + +A função ``sanitize_param(...)``, retorna a semente se for um inteiro não negativo; caso contrário, retorna Nenhum. + +**Parameters:** + +* seed (``Any``): O valor da seed a ser validado. + +**Returns:** + +* ``Optional[int]``: A seed original se for um inteiro não negativo, ou ``None`` se for inválido. + +--- + +## def sanitize_bounds(...) + +```python +def sanitize_bounds(bounds: Any, problem_size: int) -> Dict[str, npt.NDArray[np.float64]] +``` + +A função `sanitize_bounds(...)` valida e normaliza os limites das características (features). + +**Parâmetros**: + +* ***bounds*** (`Any`): Os limites de entrada, que devem ser `None` ou um dicionário com as chaves `'low'` e `'high'`. +* ***problem_size*** (`int`): O tamanho esperado para as listas de limites normalizadas, correspondente ao número de features do problema. + +**Retorna**: + +* `Dict[str, list]`: Dicionário no formato `{'low': [low_1, ..., low_N], 'high': [high_1, ..., high_N]}`. diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/Utils/Validation.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/Utils/Validation.md new file mode 100644 index 00000000..030678fc --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/Utils/Validation.md @@ -0,0 +1,108 @@ +# Validation + +## def detect_vector_data_type(...) + +```python +def detect_vector_data_type( + vector: npt.NDArray +) -> FeatureType: +``` + +Detecta o tipo de dado em um determinado vetor. + +Esta função analisa o vetor de entrada e classifica seus dados como um dos tipos suportados: + +* **binário**: Valores booleanos (`True`/`False`) ou inteiro `0`/`1`. +* **contínuo**: Valores float dentro do intervalo normalizado `[0.0, 1.0]`. +* **intervalo**: Valores float fora do intervalo normalizado. + +### Parâmetros + +* `vetor` (`npt.NDArray`): Um array contendo os dados a serem classificados. + +### Retorna + +* `FeatureType` (`Literal["binary-features", "continuous-features", "ranged-features"]`): O tipo de dado detectado no vetor. + +### Gera + +* `UnsupportedDataTypeError`: Gerado se o vetor contiver um tipo de dado não suportado. + +--- + +## def check_array_type(...) + +```python +def check_array_type(x, name: str = "X") -> npt.NDArray: +``` + +Garante que o parâmetro recebido é um array numpy. Converte de lista se necessário. + +**Parâmetros:** + +* `x`: Array ou lista contendo as amostras e características. +* `name`: Nome da variável para mensagens de erro. + +**Retorna:** + +* `npt.NDArray`: O array convertido ou validado. + +**Lança:** + +* `TypeError`: Se não for possível converter para ndarray. + +--- + +## def check_shape_match(...) + +```python +def check_shape_match(x: npt.NDArray, y: npt.NDArray): +``` + +Garante que os arrays `x` e `y` possuem o mesmo número de amostras (primeira dimensão). + +**Parâmetros:** + +* `x`: Array de amostras. +* `y`: Array de classes alvo. + +**Lança:** + +* `TypeError`: Se as dimensões não forem compatíveis. + +--- + +## def check_feature_dimension(...) + +```python +def check_feature_dimension(x: npt.NDArray, expected: int): +``` + +Garante que o array possui o número esperado de características (features). + +**Parâmetros:** + +* `x`: Array de entrada para predição. +* `expected`: Número esperado de características por amostra. + +**Lança:** + +* `FeatureDimensionMismatch`: Se o número de características não corresponder ao esperado. + +--- + +## def check_binary_array(...) + +```python +def check_binary_array(x: npt.NDArray): +``` + +Garante que o array contém apenas valores 0 e 1. + +**Parâmetros:** + +* `x`: Array a ser verificado. + +**Lança:** + +* `ValueError`: Se o array contiver valores diferentes de 0 e 1. diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/Utils/_category_.json b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/Utils/_category_.json new file mode 100644 index 00000000..59b3ccf9 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/Utils/_category_.json @@ -0,0 +1,4 @@ +{ + "label": "Utils", + "description": "Funções utilitárias e auxiliares para o desenvolvimento." +} \ No newline at end of file diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/_category_.json b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/_category_.json new file mode 100644 index 00000000..871d71c3 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Advanced Guides", + "position": 2.6, + "link": { + "type": "generated-index", + "description": "Explore a documentação avançada da biblioteca, que abrange as classes base, além das funções utilitárias do módulo utils voltadas para métricas e manipulação de classificação multiclasse." + } +} diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/base-module/_category_.json b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/base-module/_category_.json new file mode 100644 index 00000000..8c11fd00 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/base-module/_category_.json @@ -0,0 +1,4 @@ +{ + "position": 1, + "description": "Classe base para algoritmo de classificação." +} \ No newline at end of file diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/base-module/core/Base.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/base-module/core/Base.md new file mode 100644 index 00000000..bd5f0f0e --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/base-module/core/Base.md @@ -0,0 +1,55 @@ +--- +sidebar_position: 1 +title: Classe Base +sidebar_label: Base +lastUpdatedAt: 2025/08/19 +author: João Paulo +keywords: + - Classe Base + - Modelo Base + - Compatibilidade com Scikit-learn + - get_params + - set_params + - Semente Aleatória + - Classes Python +--- + +Classe base para compatibilidade com a API do scikit-learn. + +Fornece os métodos `get_params` e `set_params` para compatibilidade com a API do scikit-learn, permitindo acesso aos parâmetros públicos do modelo. + +### Função set_params(...) + +```python +def set_params(self, **params) +``` + +Define os parâmetros da instância. Garante compatibilidade com funções do scikit-learn. + +**Parâmetros**: + +* **params**: dict - Dicionário de parâmetros que serão definidos como atributos da instância. Apenas atributos públicos (que não começam com "_") são modificados. + +**Retorno**: + +* self: `Base` - Retorna a própria instância após definir os parâmetros. + +--- + +### Função get_params(...) + +```python +def get_params(self, deep: bool = True) -> dict +``` + +Retorna um dicionário com os principais parâmetros do objeto. Garante compatibilidade com funções do scikit-learn. + +**Parâmetros**: + +* **deep**: `bool` (padrão=True) - Ignorado nesta implementação, mas incluído para compatibilidade com scikit-learn. + +**Retorno**: + +* params: `dict` - Dicionário contendo os atributos do objeto que não começam com "_". + +--- diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/base-module/core/Classifier.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/base-module/core/Classifier.md new file mode 100644 index 00000000..546e22f9 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/base-module/core/Classifier.md @@ -0,0 +1,94 @@ +--- +sidebar_position: 1 +sidebar_label: BaseClassifier +last_update: + date: 2025/05/17 + author: João Paulo +--- + +# Classe base para algoritmo de classificação + +## ``class BaseClassifier(ABC)`` + +Classe base para algoritmos de classificação, definindo os métodos abstratos ``fit`` e ``predict``, e implementando o método ``get_params``. + +## Abstract methods + +### def fit(...) + +```python +def fit(self, X: npt.NDArray, y: npt.NDArray, verbose: bool = True) +``` + +Ajusta o modelo aos dados de treinamento. + +Implementação: + +- [RNSA](../../../aisp-techniques/negative-selection/RNSA.md#Função-fit) +- [BNSA](../../../aisp-techniques/negative-selection/BNSA.md#Função-fit) +- [AIRS](../../../aisp-techniques/clonal-selection-algorithms/airs/#Método-fit) + +### def predict(...) + +```python +def predict(self, X) -> Optional[npt.NDArray]: +``` + +Realiza a previsão dos rótulos para os dados fornecidos. + +Implementação: + +- [RNSA](../../../aisp-techniques/negative-selection/RNSA.md#Função-predict) +- [BNSA](../../../aisp-techniques/negative-selection/BNSA.md#Função-predict) +- [AIRS](../../../aisp-techniques/clonal-selection-algorithms/airs/#Método-predict) + +--- + +## Métodos + +### def score(...) + +```python +def score(self, X: npt.NDArray, y: list) -> float +``` + +A função de pontuação (score) calcula a precisão da previsão. + +Esta função realiza a previsão de X e verifica quantos elementos são iguais entre o vetor y e y_predicted. +Esta função foi adicionada para compatibilidade com algumas funções do scikit-learn. + +**Parâmetros**: + +- ***X***: np.ndarray + Conjunto de características com formato (n_amostras, n_características). +- ***y***: np.ndarray + Valores verdadeiros com formato (n_amostras,). + +**Retorna**: + +- precisão: float + A precisão do modelo. + +--- + +### Método _slice_index_list_by_class(...) + +A função ``_slice_index_list_by_class(...)``, separa os índices das linhas conforme a classe de saída, para percorrer o array de amostra, apenas nas posições que a saída for a classe que está sendo treinada: + +```python +def _slice_index_list_by_class(self, y: npt.NDArray) -> dict: +``` + +Retorna um dicionário com as classes como chave e os índices em ``X`` das amostras. + +--- + +### def get_params(...) + +```python +def get_params(self, deep: bool = True) -> dict: +``` + +A função get_params retorna um dicionário com os parâmetros principais do objeto. + +Esta função é necessária para garantir a compatibilidade com as funções do scikit-learn. diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/base-module/core/Clusterer.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/base-module/core/Clusterer.md new file mode 100644 index 00000000..aea519ce --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/base-module/core/Clusterer.md @@ -0,0 +1,93 @@ +--- +sidebar_position: 3 +title: Base class for clustering algorithm. +sidebar_label: BaseClusterer +lastUpdatedAt: 2025/08/19 +author: João Paulo +keywords: + - Base Clusterer + - Clustering + - Unsupervised Learning + - BaseClusterer + - Abstract Base Class + - fit Method + - predict Method + - fit_predict Method + - AiNet + - Cluster Prediction + - Python ML Classes +--- + +## ``BaseClusterer(ABC, Base)`` + +Classe base abstrata para algoritmos de clustering. + +Esta classe define a interface central para modelos de agrupamento. Ela exige +a implementação dos métodos **`fit`** e **`predict`** em todas as classes derivadas, +e fornece uma implementação padrão para **`fit_predict`** e **`get_params`**. + +--- + +### Função fit(...) + +```python +def fit(self, X: npt.NDArray, verbose: bool = True) -> BaseClusterer +``` + +Ajusta o modelo aos dados de treinamento. +Este método abstrato deve ser implementado pelas subclasses. + +**Parâmetros**: + +* ***X***: `npt.NDArray` - Dados de entrada utilizados para treinar o modelo. +* ***verbose***: `bool`, default=True - Indica se a saída detalhada durante o treinamento deve ser exibida. + +**Retorna**: + +* ***self***: `BaseClusterer` - Instância da classe que implementa este método. + +**Implementação**: + +* [AiNet](../../../aisp-techniques/immune-network-theory/AiNet.md#Função-fit) + +--- + +### Função predict(...) + +```python +def predict(self, X: npt.NDArray) -> Optional[npt.NDArray] +``` + +Gera previsões com base nos dados de entrada. +Este método abstrato deve ser implementado pelas subclasses. + +**Parâmetros**: + +* ***X***: `npt.NDArray` - Dados de entrada para os quais as previsões serão geradas. + +**Retorna**: + +* ***predictions***: `Optional[npt.NDArray]` - Rótulos previstos dos clusters para cada amostra de entrada, ou `None` caso a previsão não seja possível. + +**Implementação**: + +* [AiNet](../../../aisp-techniques/immune-network-theory/AiNet.md#Função-predict) + +--- + +### Função fit_predict(...) + +```python +def fit_predict(self, X: npt.NDArray, verbose: bool = True) -> Optional[npt.NDArray] +``` + +Método de conveniência que combina `fit` e `predict` em uma única chamada. + +**Parâmetros**: + +* ***X***: `npt.NDArray` - Dados de entrada para os quais as previsões serão geradas. +* ***verbose***: `bool`, default=True - Indica se a saída detalhada durante o treinamento deve ser exibida. + +**Retorna**: + +* ***predictions***: `Optional[npt.NDArray]` - Rótulos previstos dos clusters para cada amostra de entrada, ou `None` caso a previsão não seja possível. diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/base-module/core/Optimizer.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/base-module/core/Optimizer.md new file mode 100644 index 00000000..2bbb5b15 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/base-module/core/Optimizer.md @@ -0,0 +1,165 @@ +--- +sidebar_position: 4 +title: Classe base para algoritmos de otimização. +sidebar_label: BaseOptimizer +author: João Paulo +keywords: + - BaseOptimizer + - classe base de otimização + - abstract base class + - otimização em machine learning + - função objetivo + - método optimize + - avaliação de modelos + - metaheurísticas + - algoritmos bio-inspirados + - Python ML +--- + +Esta classe define a interface central para estratégias de otimização e mantém o histórico de custos, soluções avaliadas e a melhor solução encontrada. Subclasses devem implementar os métodos `optimize` e `objective_function`. + +--- + +### Propriedades + +#### `cost_history` + +```python +@property +def cost_history(self) -> List[float] +``` + +Retorna o histórico de custos durante a otimização. + +--- + +#### `solution_history` + +```python +@property +def solution_history(self) -> List +``` + +Retorna o histórico de soluções avaliadas. + +--- + +#### `best_solution` + +```python +@property +def best_solution(self) -> Optional[Any] +``` + +Retorna a melhor solução encontrada até o momento, ou `None` se não disponível. + +--- + +#### `best_cost` + +```python +@property +def best_cost(self) -> Optional[float] +``` + +Retorna o custo da melhor solução encontrada até o momento, ou `None` se não disponível. + +--- + +## Funções + +### Função _record_best(...) + +```python +def _record_best(self, cost: float, best_solution: Any) -> None +``` + +Registra um novo valor de custo e atualiza a melhor solução se houver melhoria. + +**Parâmetros**: + +* ***cost***: `float` - Valor de custo a ser adicionado ao histórico. + +--- + +### Função get_report() + +```python +def get_report(self) -> str +``` + +Gera um relatório resumido e formatado do processo de otimização. O relatório inclui a melhor solução, seu custo associado e a evolução dos valores de custo por iteração. + +**Retorna**: + +* **report**: `str` - String formatada contendo o resumo da otimização. + +--- + +### Função register(...) + +```python +def register(self, alias: str, function: Callable[..., Any]) -> None +``` + +Registra dinamicamente uma função na instância do otimizador. + +**Parâmetros**: + +* ***alias***: `str` - Nome usado para acessar a função como atributo. +* ***function***: `Callable[..., Any]` - Callable a ser registrado. + +**Exceções**: + +* **TypeError**: Se `function` não for chamável. +* **AttributeError**: Se `alias` for protegido e não puder ser modificado, ou se `alias` não existir na classe do otimizador. + +--- + +### Função reset() + +```python +def reset(self) +``` + +Reinicia o estado interno do objeto, limpando o histórico e resetando os valores. + +--- + +### Métodos abstratos + +#### Função optimize(...) + +```python +def optimize(self, max_iters: int = 50, n_iter_no_change=10, verbose: bool = True) -> Any +``` + +Executa o processo de otimização. Este método deve ser implementado pela subclasse para definir como a estratégia de otimização explora o espaço de busca. + +**Parâmetros**: + +* ***max_iters***: `int` - Número máximo de iterações. +* ***n_iter_no_change***: `int`, padrão=10 - Número máximo de iterações sem atualização da melhor solução. +* ***verbose***: `bool`, padrão=True - Flag para habilitar ou desabilitar saída detalhada durante a otimização. + +**Retorna**: + +* **best_solution**: `Any` - A melhor solução encontrada pelo algoritmo de otimização. + +--- + +#### Função affinity_function(...) + +```python +def affinity_function(self, solution: Any) -> float +``` + +Avalia a afinidade de uma solução candidata. Este método deve ser implementado pela subclasse para definir o problema específico. + +**Parâmetros**: + +* ***solution***: `Any` - Solução candidata a ser avaliada. + +**Retorna**: + +* **cost**: `float` - Valor de custo associado à solução fornecida. diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/base-module/immune/cell.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/base-module/immune/cell.md new file mode 100644 index 00000000..ef81da74 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/base-module/immune/cell.md @@ -0,0 +1,117 @@ +--- +title: Cell Classes +sidebar_label: Cell Classes +keywords: + - Binário + - classificação + - limiar de afinidade + - Valores Reais + - classificação + - anomalias + - K-Vizinhos Mais Próximos + - célula-B de memória +lastUpdatedAt: 2025/05/25 +author: João Paulo +--- + +Representação de células do sistema imunológico. + +## Cell + +Representa uma célula imune básica. + +```python +@dataclass(slots=True) +class Cell: + vector: np.ndarray +``` + +### Atributos + +* **vector** (`np.ndarray`): Um vetor de características da célula. + +### Métodos + +* `__eq__(other)`: Verifica se duas células são iguais com base em seus vetores. +* `__array__()`: Interface de array para NumPy, permite que a instância seja tratada como um `np.ndarray`. +* `__getitem__(item)`: Obtém elementos do vetor de características usando indexação. + +--- + +## BCell + +Representa uma célula B de memória, derivada de `Cell`. + +```python +@dataclass(slots=True, eq=False) +class BCell(Cell): + vector: np.ndarray +``` + +### Métodos + +### hyper_clonal_mutate(...) + +```python +def hyper_clonal_mutate( + self, + n: int, + feature_type: FeatureType = "continuous-features", + bounds: Optional[npt.NDArray[np.float64]] = None +) -> np.ndarray +``` + +Clona N características das características de uma célula, gerando um conjunto de vetores mutados. + +#### Parâmetros + +* **n** (`int`): Número de clones a serem gerados a partir de mutações da célula original. +* **feature_type** (`Literal["binary-features", "continuous-features", "ranged-features"]`): Especifica o tipo de características com base na natureza das características de entrada. +* **bounds** (`Optional[npt.NDArray[np.float64]]`): Array (n_features, 2) com mínimo e máximo por dimensão. + +#### Retorna + +* **npt.NDArray**: Um array contendo N vetores mutados da célula original. + +--- + +## Antibody + +Representa um anticorpo com afinidade, derivado de `Cell`. + +```python +@dataclass(slots=True) +class Antibody(Cell): + vector: np.ndarray + affinity: float +``` + +### Atributos + +* **vector** (`npt.NDArray`): Um vetor de características da célula. +* **affinity** (`float`): Valor de afinidade do anticorpo. + +### Métodos + +* `__lt__(other)`: Compara este anticorpo com outro com base na afinidade. +* `__eq__(other)`: Verifica se dois anticorpos têm a mesma afinidade. + +--- + +## Detector + +Representa um detector não-próprio da classe RNSA. + +```python +@dataclass(slots=True) +class Detector: + position: npt.NDArray[np.float64] + radius: Optional[float] = None +``` + +### Atributos + +* **position** (`npt.NDArray[np.float64]`): Vetor de características do detector. +* **radius** (`Optional[float]`): Raio do detector, usado no algoritmo V-detector. + +--- diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/base-module/immune/mutation.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/base-module/immune/mutation.md new file mode 100644 index 00000000..d9e29b66 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/base-module/immune/mutation.md @@ -0,0 +1,94 @@ +--- +title: Mutation +sidebar_label: Mutation +lastUpdatedAt: 2025/04/04 +author: João Paulo +keywords: + - Mutação + - Expansão Clonal + - Sistema Imunológico + - clone_and_mutate + - clone_and_mutate_continuous + - clone_and_mutate_binary + - clone_and_mutate_ranged + - Sistemas Imunológicos Artificiais + - Funções Python Numba + - Mutação Vetorial +--- + +Contém funções que geram conjuntos de clones mutados a partir de vetores contínuos ou binários, simulando o processo de expansão clonal em sistemas imunológicos artificiais. + +## clone_and_mutate_continuous + +```python +@njit([(types.float64[:], types.int64)], cache=True) +def clone_and_mutate_continuous( + vector: npt.NDArray[np.float64], + n: int +) -> npt.NDArray[np.float64]: +``` + +Gera um conjunto de clones mutados a partir de um vetor contínuo. + +Esta função cria `n` clones do vetor de entrada e aplica mutações aleatórias em cada um, simulando o processo de expansão clonal em sistemas imunes artificiais. Cada clone recebe um número aleatório de mutações em posições distintas do vetor original. + +### Parâmetros + +* `vector` (`npt.NDArray[np.float64]`): Vetor contínuo original que representa a célula imune a ser clonada e mutada. +* `n` (`int`): Quantidade de clones mutados a serem gerados. + +### Retorno + +* `clone_set` (`npt.NDArray[np.float64]`): Array com forma `(n, len(vector))` contendo os `n` clones mutados do vetor original. + +--- + +## clone_and_mutate_binary + +```python +@njit([(types.boolean[:], types.int64)], cache=True) +def clone_and_mutate_binary( + vector: npt.NDArray[np.bool_], + n: int +) -> npt.NDArray[np.bool_]: +``` + +Gera um conjunto de clones mutados a partir de um vetor binário. + +Esta função cria `n` clones do vetor binário de entrada e aplica mutações aleatórias em alguns bits, simulando a expansão clonal em sistemas imunes artificiais com representações discretas. + +### Parâmetros + +* `vector` (`npt.NDArray[np.bool_]`): Vetor binário original que representa a célula imune a ser clonada e mutada. +* `n` (`int`): Quantidade de clones mutados a serem gerados. + +### Retorno + +* `clone_set` (`npt.NDArray[np.bool_]`): Array com forma `(n, len(vector))` contendo os `n` clones mutados do vetor original. + +--- + +## clone_and_mutate_ranged + +```python +@njit([(types.float64[:], types.int64, types.float64[:, :])], cache=True) +def clone_and_mutate_ranged( +vector: npt.NDArray[np.float64], +n: int, +bounds: npt.NDArray[np.float64] +) -> npt.NDArray[np.float64]: +``` + +Gera um conjunto de clones mutados a partir de um vetor contínuo usando limites personalizados por dimensão. + +Esta função cria `n` clones do vetor de entrada e aplica mutações aleatórias em cada um, simulando o processo de expansão clonal em sistemas imunes artificiais. Cada clone recebe um número aleatório de mutações em posições distintas do vetor original. + +### Parâmetros + +* `vector` (`npt.NDArray[np.float64]`): Vetor contínuo original que representa a célula imune a ser clonada e mutada. +* `n` (`int`): Quantidade de clones mutados a serem gerados. +* `bounds` (`npt.NDArray[np.float64]`): Um array 2D com o formato `(len(vector), 2)` contendo os valores mínimo e máximo para cada dimensão. + +### Retorna + +* `clone_set` (`npt.NDArray[np.float64]`): Array com forma `(n, len(vector))` contendo os `n` clones mutados do vetor original. diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/base-module/immune/populations.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/base-module/immune/populations.md new file mode 100644 index 00000000..f3cbae8d --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/advanced-guides/base-module/immune/populations.md @@ -0,0 +1,49 @@ +--- +title: Módulo de Populações +sidebar_label: Populações +pagination_next: null +keywords: + - Binary + - classifying + - affinity threshold + - Real-Valued + - classifying + - anomalies + - K-Nearest Neighbors + - memory B-cell + - Clonal Expansion + - Immune System + - Artificial Immune Systems +lastUpdatedAt: 2025/11/21 +author: João Paulo +--- + +Fornece funções utilitárias para gerar populações de anticorpos em algoritmos imunológicos. + +## generate_random_antibodies(...) + +Gera uma população aleatória de anticorpos. + +```python +def generate_random_antibodies( + n_samples: int, + n_features: int, + feature_type: FeatureTypeAll = "continuous-features", + bounds: Optional[npt.NDArray[np.float64]] = None +) -> npt.NDArray +``` + +### Parâmetros + +* **n_samples** (`int`): Número de anticorpos (amostras) a serem gerados. +* **n_features** (`int`): Número de características (dimensões) para cada anticorpo. +* **feature_type** (`FeatureTypeAll`, default="continuous-features"): Especifica o tipo das características: "continuous-features", "binary-features", "ranged-features", or "permutation-features". +* **bounds** (`Optional[npt.NDArray[np.float64]]`): Array (n_features, 2) contendo os valores mínimo e máximo por dimensão. + +### Retorno + +* **npt.NDArray**: Array com forma (n_samples, n_features) contendo os anticorpos gerados. + +### Exceções + +* **ValueError**: Caso o número de características seja menor ou igual a zero. diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/README.mdx b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/README.mdx new file mode 100644 index 00000000..88f30a29 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/README.mdx @@ -0,0 +1,17 @@ +--- +sidebar_position: 2 +--- + +import DocCardList from '@theme/DocCardList'; + +# Técnicas implementadas + +# Classes AISP + +Classes implementadas utilizando as metáforas do sistemas imunológicos artificiais. + +--- + +## Classe do módulo: + + \ No newline at end of file diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/clonal-selection-algorithms/README.mdx b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/clonal-selection-algorithms/README.mdx new file mode 100644 index 00000000..fc3db09d --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/clonal-selection-algorithms/README.mdx @@ -0,0 +1,15 @@ +--- +sidebar_position: 2 +lastUpdatedAt: 2025/05/25 +author: João Paulo +--- +import DocCardList from '@theme/DocCardList'; + +# Algoritmos de Seleção Clonal. + +Os Algoritmos de Seleção Clonal são inspirados no processo de proliferação de anticorpos após a detecção de um antígeno, +durante o qual os anticorpos gerados sofrem mutações na tentativa de aumentar o reconhecimento do patógeno. + +## Classes: + + \ No newline at end of file diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/clonal-selection-algorithms/airs/README.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/clonal-selection-algorithms/airs/README.md new file mode 100644 index 00000000..1c500308 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/clonal-selection-algorithms/airs/README.md @@ -0,0 +1,216 @@ +--- +id: airs +sidebar_label: AIRS - Sistema Imunológico Artificial de Reconhecimento +keywords: + - Binário + - Classificação + - Limiar de Afinidade + - Valores Reais + - Anomalias + - K-Vizinhos Mais Próximos +lastUpdatedAt: 2025/08/22 +author: João Paulo +--- + +# AIRS - Sistema Imunológico Artificial de Reconhecimento + +O ``AIRS`` é um algoritmo de classificação inspirado no processo de seleção clonal. A versão implementada nesta classe é inspirada na sua versão simplificada, o AIRS2, descrito em[Brabazon, O'Neill, and McGarraghy (2015)](#1) + +Esta implementação é inspirada no AIRS2, uma versão simplificada do algoritmo AIRS original, introduzindo adaptações para lidar com conjuntos de dados contínuos e binários. + +Com base no algoritmo 16.5 de Brabazon et al. [1](#1). + +:::tip Trabalhos relacionados e notáveis: + +- [Artificial Immune Recognition System V2 - AZZOUG Aghiles](https://github.com/AghilesAzzoug/Artificial-Immune-System) + +::: + +:::info + +**``AIRS``** estende a classe **[classe ``BaseClassifier``](../../../advanced-guides/base-module/core/Classifier.md)**, herdando sua funcionalidade base. + +::: + +## Construtor AIRS + +A classe `AIRS` tem como objetivo realizar classificação utilizando metáforas de seleção e expansão clonal. + +**Atributos:** + +- **n_resources** (`float`): Quantidade total de recursos disponíveis. O padrão é 10. + +- **rate_clonal** (`float`): Número máximo de clones possíveis de uma classe. Esta quantidade é multiplicada por (estímulo da célula * taxa de hipermutação) para definir o número de clones. O padrão é 10. + +- **rate_hypermutation** (`int`): Taxa de clones mutados derivada de rate_clonal como um fator escalar. O padrão é 0,75. + +- **affinity_threshold_scalar** (`float`): Limiar de afinidade normalizado. O padrão é 0,75. + +- **k** (`int`): Número de vizinhos mais próximos (k-NN) que será usado para escolher um rótulo na predição. O padrão é 10. + +- **max_iters** (`int`): Número máximo de interações no processo de refinamento do conjunto ARB exposto a aᵢ. O padrão é 100. + +- **resource_amplified** (`float`): Amplificador de consumo de recursos, multiplicado com o estímulo para subtrair recursos. O padrão é 1.0 (sem amplificação). + +- **metric** (Literal["manhattan", "minkowski", "euclidean"]): Forma de calcular a distância entre o detector e a amostra: + + - ``'euclidiana'`` ➜ O cálculo da distância dá-se pela expressão: + $$ + \sqrt{(X_1 - X_1)^2 + (Y_2 - Y_2)^2 + ... + (Y_n - Y_n)^2} + $$ + - ``'minkowski'`` ➜ O cálculo da distância dá-se pela expressão: + $$ + \frac{((|X_{1} - Y_{1}|^p + |X_{2} - Y_{2}|^p + \cdots + |X_{n} - Y_{n}|^p)^\frac{1}{p})}{n} + $$. + - ``'manhattan'`` ➜ O cálculo da distância dá-se pela expressão: + $$ + \frac{(|X_{1} - X_{1}| + |Y_{2} - Y_{2}| + \cdots + |Y_{n} - Y_{n}|)}{n} + $$. + + Defaults to ``'euclidean'``. + +- **seed** (``Optional[int]``): Semente para geração aleatória de valores dos detectores. O padrão é None. + +- `**kwargs`: + + - **p** (`float`): Este parâmetro armazena o valor de `p` usado na distância de Minkowski. + O padrão é `2`, que corresponde à distância euclidiana normalizada. Diferentes valores de p resultam em variantes distintas da distância de Minkowski. [Saiba mais](https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.minkowski.html). + +**Outras variáveis inicializadas:** + +- **cells_memory** (`dict`): Armazena uma lista de células de memória por classe. +- **affinity_threshold** (`dict`): Define o limiar de afinidade entre antígenos. +- **classes** (`npt.NDArray`): Lista de classes de saída. + +--- + +## Métodos Públicos + +### Método fit(...) + +A função `fit(...)` gera detectores para os não-pertencentes em relação às amostras: + +```python +def fit(self, X: npt.NDArray, y: npt.NDArray): +``` + +Realiza o treinamento conforme `X` e `y`, utilizando o método Sistema de Reconhecimento Imune Artificial (`AIRS`). + +**Parâmetros de entrada:** + +- **X**: Array com as características das amostras, com **N** amostras (linhas) e **N** características (colunas), normalizado para valores entre [0, 1]. +- **y**: Array com as classes de saída correspondentes às **N** amostras relacionadas a `X`. +- **verbose**: Booleano, padrão `True`, determina se o feedback da geração dos detectores será impresso. + +*Retorna a instância da classe.* + +--- + +### Método predict(...) + +A função `predict(...)` realiza a predição de classes utilizando os detectores gerados: + +```python +def predict(self, X: npt.NDArray) -> npt.NDArray: +``` + +**Parâmetro de entrada:** + +- **X**: Array com as características para predição, com **N** amostras (linhas) e **N** colunas. + +**Retorna:** + +- **C**: Um array de predições com as classes de saída para as características fornecidas. +- **None**: Se não houver detectores. + +--- + +### Método score(...) + +A função `score(...)` calcula a acurácia do modelo treinado realizando predições e calculando a precisão. + +```python +def score(self, X: npt.NDArray, y: list) -> float: +``` + +Retorna a acurácia como um `float`. + +--- + +## Métodos Privados + +### Método _refinement_arb(...) + +A função "_refinement_arb(...)" refina o conjunto ARB até que o valor médio de estímulo ultrapasse o limiar definido (`affinity_threshold_scalar`). + +Parâmetros: + +- **c_match** (`Cell`): Célula com o maior estímulo em relação a aᵢ. +- **arb_list** (`List[_ARB]`): Conjunto ARB. + +```python +def _refinement_arb(self, ai: npt.NDArray, c_match: Cell, arb_list: List[_ARB]) -> _ARB: +``` + +Retorna a célula (_ARB) com o maior estímulo ARB. + +--- + +### Método _cells_affinity_threshold(...) + +A função "_cells_affinity_threshold(...)" calcula o limiar de afinidade com base na afinidade média entre instâncias de treinamento, onde aᵢ e aⱼ são um par de antígenos, e a afinidade é medida pela distância (Euclidiana, Manhattan, Minkowski, Hamming). +**Seguindo a fórmula:** + +$$ +\text{affinity}_{\text{threshold}} = \frac{ +\sum_{i=1}^{n-1} \sum_{j=i+1}^{n} \text{affinity}(a_i, a_j)}{n(n-1)/2} +$$ + +Parâmetros: + +- **antigens_list** (`NDArray`): Lista de antígenos de treinamento. + +```python +def _cells_affinity_threshold(self, antigens_list: npt.NDArray): +``` + +--- + +### Método _affinity(...) + +A função "_affinity(...)" calcula o estímulo entre dois vetores usando métricas. + +Parâmetros: + +- **u** (`npt.NDArray`): Coordenadas do primeiro ponto. +- **v** (`npt.NDArray`): Coordenadas do segundo ponto. + +```python +def _affinity(self, u: npt.NDArray, v: npt.NDArray) -> float: +``` + +Retorna a taxa de estímulo entre os vetores. + +--- + +### Método _init_memory_c(...) + +A função "_init_memory_c(...)" inicializa células de memória selecionando aleatoriamente `n_antigens_selected` da lista de antígenos de treinamento. + +Parâmetros: + +- **antigens_list** (`NDArray`): Lista de antígenos de treinamento. + +```python +def _init_memory_c(self, antigens_list: npt.NDArray) -> List[Cell]: +``` + +--- + +## Referências + +--- + +### 1 +> +> BRABAZON, Anthony; O'NEILL, Michael; MCGARRAGHY, Seán. Natural Computing Algorithms. [S. l.]: Springer Berlin Heidelberg, 2015. DOI 10.1007/978-3-662-43631-8. Disponível em: [https://dx.doi.org/10.1007/978-3-662-43631-8](https://dx.doi.org/10.1007/978-3-662-43631-8). diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/clonal-selection-algorithms/airs/abr.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/clonal-selection-algorithms/airs/abr.md new file mode 100644 index 00000000..eb0e525b --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/clonal-selection-algorithms/airs/abr.md @@ -0,0 +1,47 @@ +--- +id: abr +title: ABR +sidebar_label: ABR - Bolha de reconhecimento artificial +sidebar_position: 2 +keywords: + - Binary + - classifying + - affinity threshold + - Real-Valued + - classifying + - anomalies + - K-Nearest Neighbors +lastUpdatedAt: 2025/05/25 +author: João Paulo +--- + +## ABR (Artificial Recognition Ball) + +Individuo do conjunto de células reconhecedoras (ABR), herda características de uma célula-B, adicionando o consumo de recursos + +:::info + +**``ABR``** estende a classe **[``BCell``](../../../advanced-guides/base-module/immune/cell.md#BCell)**, herdando sua funcionalidade base. + +::: + +### Constructor + +Parameters: + +* vector (``npt.NDArray``): A feature vector of the cell. Defaults to None. + +--- + +### Function consume_resource(...) + +Parameters: + +* n_resource (```float```) : The initial amount of resources. +* amplified (``float``): Amplifier for resource consumption by the cell. It is multiplied by the cell's stimulus. The default value is 1. + +```python +def consume_resource(self, n_resource: float, amplified: float = 1) -> float: +``` + +Returns the remaining amount of resources after consumption. diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/clonal-selection-algorithms/clonalg.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/clonal-selection-algorithms/clonalg.md new file mode 100644 index 00000000..45275396 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/clonal-selection-algorithms/clonalg.md @@ -0,0 +1,197 @@ +--- +id: clonalg +sidebar_label: CLONALG - Algoritmo de Seleção Clonal +keywords: + - CLONALG + - algoritmo de seleção clonal + - otimização bio-inspirada + - inteligência artificial + - problemas binários + - problemas contínuos + - ranged optimization + - permutação + - metaheurísticas +--- + +# CLONALG - Algoritmo de Seleção Clonal + +A classe `Clonalg` é um **algoritmo de otimização** inspirado no processo biológico de seleção clonal do sistema imunológico. Esta implementação é projetada para minimizar ou maximizar funções de custo em diversos tipos de problemas, incluindo problemas binários, contínuos, com valores limitados (ranged) e de permutação. + +:::tip +A implementação do CLONALG foi inspirada na descrição apresentada em [1](#1). +::: + +:::info +Esta implementação do CLONALG contém algumas alterações baseadas no contexto do AISP, para aplicação geral +a diversos problemas, que podem produzir resultados diferentes da implementação padrão ou +específica. Esta adaptação visa generalizar o CLONALG para tarefas de minimização e +maximização, além de suportar problemas contínuos, discretos e de permutação. +::: + +:::info + +**``Clonalg``** estende a **[classe ``BaseOptimizer`` ](../../advanced-guides/base-module/core/Optimizer.md)**, herdando suas funcionalidades básicas. + +::: + +--- + +## CLONALG Constructor + +O construtor inicializa a instância do CLONALG com os principais parâmetros que definem o processo de otimização. + +**Atributos:** + +* **problem_size**: `int` - Dimensão do problema a ser otimizado. +* **N**: `int`, padrão=50 - Número de células de memória (anticorpos) na população. +* **rate_clonal**: `float`, padrão=10 - Número máximo de clones possíveis de uma célula. Este valor é multiplicado pela afinidade da célula para determinar o número de clones. +* **rate_hypermutation**: `float`, padrão=0.75 - Taxa de clones mutados, usada como fator escalar. +* **n_diversity_injection**: `int`, padrão=5 - Número de novas células de memória aleatórias injetadas para manter a diversidade. +* **selection_size**: `int`, padrão=5 - Número de melhores anticorpos selecionados para clonagem. +* **affinity_function**: `Optional[Callable[..., npt.NDArray]]`, padrão=None - Função objetivo usada para avaliar soluções candidatas. +* **feature_type**: `FeatureTypeAll`, padrão='ranged-features' - Tipo de amostra do problema, podendo ser `'continuous-features'`, `'binary-features'`, `'ranged-features'` ou `'permutation-features'`. +* **bounds**: `Optional[Dict]`, padrão=None - Dicionário definindo os limites de busca para problemas `'ranged-features'`. Pode ser um único intervalo ou uma lista de intervalos para cada dimensão. +* **mode**: `Literal["min", "max"]`, padrão="min" - Especifica se o algoritmo minimiza ou maximiza a função de custo. +* **seed**: `Optional[int]`, padrão=None - Semente para geração de números aleatórios. + +--- + +### Métodos Públicos + +#### Função `optimize(...)` + +```python +def optimize( + self, + max_iters: int = 50, + n_iter_no_change=10, + verbose: bool = True +) -> List[Antibody]: +``` + +Este método executa o processo de otimização e retorna a população de anticorpos. + +**Parâmetros de entrada:** + +* **max_iters**: `int`, padrão=50 - Número máximo de interações. +* **n_iter_no_change**: `int`, padrão=10 - Número máximo de iterações sem melhoria na melhor solução. +* **verbose**: `bool`, padrão=True - Flag para habilitar ou desabilitar saída detalhada durante o processo de otimização. + +**Retorna:** + +* population : ``List[Antibody]``, A população de [anticorpos](../../advanced-guides/base-module/immune/cell.md#Antibody) após a expansão clonal. + +--- + +#### Função `affinity_function(...)` + +```python +def affinity_function(self, solution: npt.NDArray) -> np.float64: +``` + +Este método avalia a afinidade de uma solução candidata. Levanta `NotImplementedError` se nenhuma função de afinidade tiver sido fornecida à instância da classe. + +**Parâmetros de entrada:** + +* **solution**: `npt.NDArray` - Solução candidata a ser avaliada. + +**Retorna:** + +* `np.float64`: Valor de afinidade associado à solução. + +--- + +### Métodos Privados + +#### Função `_select_top_antibodies(...)` + +```python +def _select_top_antibodies(self, n: int, antibodies: list[tuple]) -> list[tuple]: +``` + +Seleciona os `n` melhores anticorpos com base em suas pontuações de afinidade, de acordo com o `mode` (`'min'` ou `'max'`). + +**Parâmetros de entrada:** + +* **n**: `int` - Número de anticorpos a serem selecionados. +* **antibodies**: `list[tuple]` - Lista de tuplas, onde cada tupla representa um anticorpo e sua pontuação associada. + +**Retorna:** + +* `list[tuple]`: Lista contendo os `n` anticorpos selecionados. + +--- + +#### Função `_init_population_antibodies(...)` + +```python +def _init_population_antibodies(self) -> npt.NDArray: +``` + +Inicializa aleatoriamente a população inicial de anticorpos. + +**Retorna:** + +* `npt.NDArray`: Lista com os anticorpos inicializados. + +--- + +#### Função `_diversity_introduction(...)` + +```python +def _diversity_introduction(self): +``` + +Introduz novos anticorpos aleatórios na população para manter a diversidade genética e ajudar a evitar convergência prematura. + +**Retorna:** + +* `npt.NDArray`: Array contendo os novos anticorpos aleatórios. + +--- + +#### Função `_clone_and_mutate(...)` + +```python +def _clone_and_mutate(self, antibody: npt.NDArray, n_clone: int, rate_hypermutation: float) -> npt.NDArray: +``` + +Gera clones mutados a partir de um único anticorpo. A estratégia de mutação depende do `feature_type` especificado durante a inicialização (`'binary-features'`, `'continuous-features'`, `'ranged-features'` ou `'permutation-features'`). + +**Parâmetros de entrada:** + +* **antibody**: `npt.NDArray` - Vetor original do anticorpo a ser clonado e mutado. +* **n_clone**: `int` - Número de clones a serem gerados. +* **rate_hypermutation**: `float` - Taxa de hipermutação. + +**Retorna:** + +* `npt.NDArray`: Array contendo os clones mutados. + +--- + +#### Função `_clone_and_hypermutation(...)` + +```python +def _clone_and_hypermutation(self, population: list[tuple]) -> list: +``` + +Clona e aplica hipermutação a uma população de anticorpos. Retorna uma lista de todos os clones e suas afinidades em relação à função de custo. + +**Parâmetros de entrada:** + +* **population**: `list[tuple]` - Lista de anticorpos a serem avaliados e clonados. + +**Retorna:** + +* `list`: Lista contendo os clones mutados. + +--- + +## Referências + +--- + +### 1 +> +> BROWNLEE, Jason. Clonal Selection Algorithm. Clever Algorithms: Nature-inspired Programming Recipes., 2011. Available at: [https://cleveralgorithms.com/nature-inspired/immune/clonal_selection_algorithm.html](https://cleveralgorithms.com/nature-inspired/immune/clonal_selection_algorithm.html) diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/immune-network-theory/AiNet.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/immune-network-theory/AiNet.md new file mode 100644 index 00000000..5738f143 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/immune-network-theory/AiNet.md @@ -0,0 +1,327 @@ +--- +id: ainet +sidebar_label: AiNet - Agrupamento e Compressão +sidebar_position: 1 +pagination_next: null +keywords: + - Rede Imunológica Artificial + - AiNet + - Agrupamento + - Compressão de Dados + - Algoritmos Imunológicos + - Computação Bioinspirada + - Células de Memória + - Limite de Afinidade + - Limite de Supressão + - Seleção Clonal + - Expansão Clonal + - Introdução de Diversidade + - Reconhecimento de Padrões + - Detecção de Anomalias + - Agrupamento MST + - Árvore Geradora Mínima + - Aprendizado Não Supervisionado + - Algoritmos Bioinspirados + - Rede de Anticorpos +lastUpdatedAt: 2025/08/19 +author: João Paulo +--- + +# AiNet - Rede Imunológica Artificial para Agrupamento e Compressão + +A classe AiNet tem como objetivo realizar agrupamento utilizando metáforas inspiradas na teoria da rede imunológica. + +A classe AiNet implementa o algoritmo de Rede Imune Artificial para compressão e clustering. Ela utiliza princípios da teoria de redes imunes, +seleção clonal e maturação por afinidade para comprimir conjuntos de dados e encontrar clusters [1](#1). +Para clustering, pode opcionalmente utilizar uma [**Árvore Geradora Mínima** +(MST)](#2) para separar nós distantes em grupos. + +:::info + +**``AiNet``** estende a **[classe ``BaseClusterer``](../../advanced-guides/base-module/core/Clusterer.md)**, herdando sua funcionalidade básica. + +::: + +## Constructor + +```python +class AiNet( + self, + N: int = 50, + n_clone: int = 10, + top_clonal_memory_size: int = 5, + n_diversity_injection: int = 5, + affinity_threshold: float = 0.5, + suppression_threshold: float = 0.5, + mst_inconsistency_factor: float = 2.0, + max_iterations: int = 10, + k: int = 3, + metric: MetricType = "euclidean", + seed: Optional[int] = None, + use_mst_clustering: bool = True, + **kwargs +) +``` + +**Atributos:** + +* **N** (`int`): Número de células de memória (anticorpos) na população. Padrão: 50. +* **n_clone** (`int`): Número de clones gerados por célula de memória selecionada. Padrão: 10. +* **top_clonal_memory_size** (`Optional[int]`): Número de anticorpos de maior afinidade selecionados para clonagem. Padrão: 5. +* **n_diversity_injection** (`int`): Número de novos anticorpos aleatórios injetados para manter a diversidade. Padrão: 5. +* **affinity_threshold** (`float`): Limite para seleção/supressão de células. Padrão: 0.5. +* **suppression_threshold** (`float`): Limite para remoção de células de memória semelhantes. Padrão: 0.5. +* **mst_inconsistency_factor** (`float`): Fator para determinar arestas inconsistentes na MST. Padrão: 2.0. +* **max_iterations** (`int`): Número máximo de iterações de treinamento. Padrão: 10. +* **k** (`int`): Número de vizinhos mais próximos usados para predição de rótulos. Padrão: 3. +* **metric** (Literal["manhattan", "minkowski", "euclidean"]): Forma de calcular a distância entre o detector e a amostra: + + * ``'euclidiana'`` ➜ O cálculo da distância dá-se pela expressão: + $$ + \sqrt{(X_1 - X_1)^2 + (Y_2 - Y_2)^2 + ... + (Y_n - Y_n)^2} + $$ + * ``'minkowski'`` ➜ O cálculo da distância dá-se pela expressão: + $$ + \frac{((|X_{1} - Y_{1}|^p + |X_{2} - Y_{2}|^p + \cdots + |X_{n} - Y_{n}|^p)^\frac{1}{p})}{n} + $$ + * ``'manhattan'`` ➜ O cálculo da distância dá-se pela expressão: + $$ + \frac{(|X_{1} - X_{1}| + |Y_{2} - Y_{2}| + \cdots + |Y_{n} - Y_{n}|)}{n} + $$ + + Padrão: **"Euclidean"**. + +* **seed** (`Optional[int]`): Semente para geração de números aleatórios. Padrão: None. +* **use_mst_clustering** (`bool`): Define se o clustering baseado em MST deve ser utilizado. Padrão: True. +* **kwargs**: + * **p** (`float`): Parâmetro para distância de Minkowski. Padrão: 2. + +**Outras variáveis inicializadas:** + +* **_population_antibodies** (`npt.NDArray`): Conjunto atual de anticorpos. +* **_memory_network** (`dict`): Dicionário que mapeia clusters para anticorpos. +* **_mst_structure** (`scipy.sparse.csr_matrix`): Estrutura de adjacência da MST. +* **_mst_mean_distance** (`float`): Média das distâncias das arestas da MST. +* **_mst_std_distance** (`float`): Desvio padrão das distâncias das arestas da MST. +* **classes** (`list`): Lista de rótulos dos clusters. + +--- + +## Métodos Públicos + +### Função fit(...) + +Treina o modelo AiNet com os dados de entrada: + +```python +def fit(self, X: npt.NDArray, verbose: bool = True) -> AiNet: +``` + +**Parâmetros de entrada:** + +* **X**: Matriz com amostras (linhas) e atributos (colunas). +* **verbose**: Booleano, padrão True, habilita feedback de progresso. + +*Retorna a instância da classe.* + +--- + +### Função predict(...) + +Prediz os rótulos dos clusters para novas amostras: + +```python +def predict(self, X) -> Optional[npt.NDArray]: +``` + +**Parâmetros de entrada:** + +* **X**: Matriz de atributos de entrada. + +**Retorna:** + +* **Predictions**: Matriz de rótulos de clusters, ou None caso o clustering esteja desabilitado. + +--- + +### Função update_clusters(...) + +Particiona os clusters utilizando a MST: + +```python +def update_clusters(self, mst_inconsistency_factor: Optional[float] = None): +``` + +**Parâmetros de entrada:** + +* **mst_inconsistency_factor**: Valor opcional (float) para sobrescrever o fator de inconsistência da MST. + +**Atualiza:** + +* **_memory_network**: Dicionário de rótulos de clusters para vetores de anticorpos. +* **classes**: Lista de rótulos de clusters. + +--- + +## Métodos Privados + +### Função _init_population_antibodies(...) + +Inicializa a população de anticorpos aleatoriamente. + +```python +def _init_population_antibodies(self) -> npt.NDArray: +``` + +**Parâmetros de entrada:** Nenhum + +**Retorna:** Anticorpos inicializados (`npt.NDArray`). + +--- + +### Função _select_and_clone_population(...) + +Seleciona os melhores anticorpos e gera clones mutados: + +```python +def _select_and_clone_population(self, antigen: npt.NDArray, population: npt.NDArray) -> list: +``` + +**Parâmetros de entrada:** + +* **antigen**: Vetor representando o antígeno para o qual as afinidades serão calculadas. +* **population**: Matriz de anticorpos a serem avaliados e clonados. + +**Retorna:** Lista de clones mutados. + +--- + +### Função _clonal_suppression(...) + +Suprime clones redundantes com base em limiares: + +```python +def _clonal_suppression(self, antigen: npt.NDArray, clones: list): +``` + +**Parâmetros de entrada:** + +* **antigen**: Vetor representando o antígeno. +* **clones**: Lista de clones candidatos a serem suprimidos. + +**Retorna:** Lista de clones não redundantes e de alta afinidade. + +--- + +### Função _memory_suppression(...) + +Remove anticorpos redundantes da memória: + +```python +def _memory_suppression(self, pool_memory: list) -> list: +``` + +**Parâmetros de entrada:** + +* **pool_memory**: Lista de anticorpos atualmente na memória. + +**Retorna:** Memória filtrada (`list`). + +--- + +### Função _diversity_introduction(...) + +Introduce novos anticorpos aleatórios: + +```python +def _diversity_introduction(self) -> npt.NDArray: +``` + +**Parâmetros de entrada:** Nenhum + +**Retorna:** Conjunto de novos anticorpos (`npt.NDArray`). + +--- + +### Função _affinity(...) + +Calcula o estímulo entre dois vetores: + +```python +def _affinity(self, u: npt.NDArray, v: npt.NDArray) -> float: +``` + +**Parâmetros de entrada:** + +* **u**: Vetor representando o primeiro ponto. +* **v**: Vetor representando o segundo ponto. + +**Retorna:** Valor de afinidade (`float`) no intervalo [0,1]. + +--- + +### Função _calculate_affinities(...) + +Calcula a matriz de afinidades entre um vetor de referência e vetores-alvo: + +```python +def _calculate_affinities(self, u: npt.NDArray, v: npt.NDArray) -> npt.NDArray: +``` + +**Parâmetros de entrada:** + +* **u**: Vetor de referência (`npt.NDArray`) de formato `(n_features,)`. +* **v**: Vetores-alvo (`npt.NDArray`) de formato `(n_samples, n_features)`. + +**Retorna:** Vetor de afinidades (`npt.NDArray`) com formato `(n_samples,)`. + +--- + +### Função _clone_and_mutate(...) + +Gera clones mutados: + +```python +def _clone_and_mutate(self, antibody: npt.NDArray, n_clone: int) -> npt.NDArray: +``` + +**Parâmetros de entrada:** + +* **antibody**: Vetor de anticorpo original a ser clonado e mutado. +* **n_clone**: Número de clones a serem gerados. + +**Retorna:** Matriz de clones mutados (`npt.NDArray`) de formato `(n_clone, len(antibody))`. + +--- + +### Função _build_mst(...) + +Constrói a MST e armazena estatísticas: + +```python +def _build_mst(self): +``` + +**Parâmetros de entrada:** Nenhum + +**Exceções:** ValueError se a população de anticorpos estiver vazia. + +**Atualiza variáveis internas:** + +* **_mst_structure**: Estrutura de adjacência da MST. +* **_mst_mean_distance**: Distância média das arestas. +* **_mst_std_distance**: Desvio padrão das distâncias das arestas da MST. + +--- + +## Referências + +### 1 +> +> 1. De Castro, Leandro & José, Fernando & von Zuben, Antonio Augusto. (2001). aiNet: An Artificial Immune Network for Data Analysis. +> Disponível em: [https://www.researchgate.net/publication/228378350_aiNet_An_Artificial_Immune_Network_for_Data_Analysis](https://www.researchgate.net/publication/228378350_aiNet_An_Artificial_Immune_Network_for_Data_Analysis) + +### 2 +> +> 2. SciPy Documentation. *Minimum Spanning Tree*. +> Disponível em: [https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csgraph.minimum_spanning_tree](https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csgraph.minimum_spanning_tree) diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/immune-network-theory/README.mdx b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/immune-network-theory/README.mdx new file mode 100644 index 00000000..cfa989ea --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/immune-network-theory/README.mdx @@ -0,0 +1,39 @@ +--- +sidebar_position: 3 +lastUpdatedAt: 2025/08/19 +author: João Paulo +keywords: + - Teoria da Rede Imunológica + - AiNet + - Sistemas Imunológicos Artificiais + - Agrupamento + - Otimização + - Classificação + - Aprendizado de Máquina + - Algoritmos Imunológicos +--- + +import DocCardList from '@theme/DocCardList'; + +# Teoria da Rede Imunológica + +Esta técnica foi introduzida por **Niels Jerne (1974)** e modela o sistema imunológico como uma rede dinâmica, +na qual células e moléculas são capazes de se reconhecer mutuamente. [1](#1) + +--- + +A Rede Imunológica Artificial pode ser aplicada em diferentes contextos, tais como: +- **Agrupamento (Clustering)** +- **Otimização** +- **Classificação** + +## Classes: + + + +## References + +--- + +### 1 +> BRABAZON, Anthony; O'NEILL, Michael; MCGARRAGHY, Seán. Natural Computing Algorithms. [S. l.]: Springer Berlin Heidelberg, 2015. DOI 10.1007/978-3-662-43631-8. Disponível em: [https://dx.doi.org/10.1007/978-3-662-43631-8](https://dx.doi.org/10.1007/978-3-662-43631-8). diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/negative-selection/BNSA.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/negative-selection/BNSA.md new file mode 100644 index 00000000..9f619b1e --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/negative-selection/BNSA.md @@ -0,0 +1,134 @@ +--- +id: bnsa +sidebar_label: BNSA - Algoritmo de Seleção Negativa Binária +sidebar_position: 2 +pagination_next: null +last_update: + date: 2025/05/17 + author: João Paulo +keywords: + - Binário + - classificação + - anomalias + - not self + - affinity threshold + - Algoritmo de Seleção Negativa + - Sistema Imunológico Artificial (AIS) + - Próprio e não-próprio + - Imune + - Computação Natural +--- + +# BNSA (Algoritmo de Seleção Negativa Binária) + +:::info + +**``BNSA``** estende a **[classe ``BaseClassifier``](../../advanced-guides/base-module/core/Classifier.md)**, herdando suas funcionalidades básicas. + +::: + +## Construtor RNSA + +A classe ``BNSA`` tem a finalidade de classificação e identificação de anomalias através do método self e not self . + +```python +class BNSA( + self, + N: int = 100, + aff_thresh: float = 0.1, + max_discards: int = 1000, + seed: int = None, + no_label_sample_selection: Literal["max_average_difference", "max_nearest_difference"] = "max_average_difference" +) +``` + +**Attributes:** + +* *N* (``int``): Quantidade de detectores. Defaults to ``100``. +* *aff_thresh* (``float``): A variável ('affinity threshold') representa a porcentagem de não similaridade entre a célula T e as amostras próprias. O valor padrão é de 10% (0,1), enquanto que o valor de 1,0 representa 100% de não similaridade. + + :::note + Definir uma porcentagem de diferença muito alta pode resultar na incapacidade de gerar detectores para não-próprio. + ::: + +* *max_discards* (``int``): Este parâmetro indica o número máximo de descartes de detectores em sequência, que tem como objetivo evitar um +possível loop infinito caso seja definido um raio que não seja possível gerar detectores do não-próprio. Defaults to ``1000``. +* *seed* (``int``): Semente para a geração randômica dos valores nos detectores. Defaults to ``None``. +* no_label_sample_selection (``str``): Método para a seleção de rótulos para amostras designadas como não pertencentes por todos os detectores não pertencentes. **Tipos de métodos disponíveis:** + * (``max_average_difference``): Seleciona a classe com a maior diferença média entre os detectores. + * (``max_nearest_difference``): Seleciona a classe com a maior diferença entre o detector mais próximo e mais distante da amostra. + +**Outras variáveis iniciadas:** + +* *detectors* (``dict``): Esta variável armazena uma lista de detectores por classe. + +* *classes* (``npt.NDArray``): lista de classes de saída. + +--- + +## Função fit(...) + +A função ``fit(...)`` gera os detectores para os não próprios com relação às amostras: + +```python +def fit(self, X: npt.NDArray, y: npt.NDArray, verbose: bool = True) +``` + +Nela é realizado o treinamento de acordo com ``X`` e ``y``, usando o método de seleção negativa(``NegativeSelect``). + +**Os parâmetros de entrada são:** + +* ``X``: array com as características das amostras com **N** amostras (linhas) e **N** características (colunas), normalizados para valores entre [0, 1]. +* ``y``: array com as classes de saídas disposto em **N** amostras que são relacionadas ao ``X``. +* ``verbose``: boolean com valor padrão ``True``, determina se o feedback da geração dos detectores será impresso. + +*Retorna a instância da classe.* + +--- + +## Função predict(...) + +A função ``predict(...)`` realiza a previsão das classes utilizando os detectores gerados: + +```python +def predict(self, X: npt.NDArray) -> npt.NDArray: +``` + +**O parâmetro de entrada:** + +* ``X``: array com as características para a previsão, com **N** amostras (Linhas) e **N** colunas. + +**Retorna:** + +* ``C``: Um array de previsão com as classes de saída para as características informadas. +* ``None``: se não houver detectores. + +--- + +## Função score(...) + +A função "score(...)" calcula a precisão do modelo treinado por meio da realização de previsões e do cálculo da acurácia. + +```python +def score(self, X: npt.NDArray, y: list) -> float: +``` + +retorna a acurácia, do tipo ``float``. + +--- + +## Métodos privados + +--- + +## Função __slice_index_list_by_class(...) + +A função ``__slice_index_list_by_class(...)``, separa os índices das linhas conforme a classe de saída, para percorrer o array de amostra, apenas nas posições que a saída for a classe que está sendo treinada: + +```python +def __slice_index_list_by_class(self, y: npt.NDArray) -> dict: +``` + +Retorna um dicionario com as classes como chave e os índices em ``X`` das amostras. + +--- diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/negative-selection/README.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/negative-selection/README.md new file mode 100644 index 00000000..610f032b --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/negative-selection/README.md @@ -0,0 +1,44 @@ +--- +sidebar_position: 1 +--- + +# Seleção Negativa + +A **seleção negativa** é o processo em que o sistema imunológico faz a maturação das células-T conhecidas também por linfócitos-T, no qual tornam-as aptas na detecção dos não-próprios. Assim, o Algoritmo de seleção negativa (NSA), utilizam-se de hiperesferas simbolizando os detectores em um espaço de dados N-dimensional. [1](#1) + +--- + +## classes + +> 1. **[Binary version:](BNSA.md)** +> +>> O algoritmo binário adaptado para múltiplas classes neste projeto tem como base a versão proposta por [Forrest et al. (1994)](#2), originalmente desenvolvida para segurança computacional. +>>> **Exemplo:** +>>> +>>> + [Base de dados Mushrooms](https://github.com/AIS-Package/aisp/blob/main/examples/pt-br/classification/BNSA/mushrooms_dataBase_example_pt-br.ipynb) + +> 2. **[Real-Valued version:](RNSA.md)** +> +>>Este algoritmo possui duas versões diferentes: uma baseada na versão canônica [[1]](#1) e outra com detectores de raio variável [[3]](#3). Ambas estão adaptadas para trabalhar com múltiplas classes e possuem métodos para previsão de dados presentes na região não-self de todos os detectores e classes. +>>> **Exemplos:** +>>> +>>> + [Base de dados Iris](https://github.com/AIS-Package/aisp/blob/main/examples/pt-br/classification/RNSA/iris_dataBase_example_pt-br.ipynb) +>>> + [Base de dados Geyser](https://github.com/AIS-Package/aisp/blob/main/examples/pt-br/classification/RNSA/geyser_dataBase_example_pt-br.ipynb) + +## References + +--- + +### 1 +> +> BRABAZON, Anthony; O'NEILL, Michael; MCGARRAGHY, Seán. Natural Computing Algorithms. [S. l.]: Springer Berlin Heidelberg, 2015. DOI 10.1007/978-3-662-43631-8. Disponível em: [https://dx.doi.org/10.1007/978-3-662-43631-8](https://dx.doi.org/10.1007/978-3-662-43631-8). + +### 2 +> +> S. Forrest, A. S. Perelson, L. Allen and R. Cherukuri, "Self-nonself discrimination in a computer," Proceedings of 1994 IEEE Computer Society Symposium on Research in Security and Privacy, Oakland, CA, USA, 1994, pp. 202-212, doi: [https://dx.doi.org/10.1109/RISP.1994.296580](https://dx.doi.org/10.1109/RISP.1994.296580). + +### 3 +> +> JI, Zhou; DASGUPTA, Dipankar. Real-Valued Negative Selection Algorithm with Variable-Sized Detectors. Genetic and Evolutionary Computation - GECCO 2004. [S. l.]: Springer Berlin Heidelberg, 2004. DOI 10.1007/978-3-540-24854-5_30. Disponível em: [https://dx.doi.org/10.1007/978-3-540-24854-5_30](https://dx.doi.org/10.1007/978-3-540-24854-5_30). + +--- diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/negative-selection/RNSA.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/negative-selection/RNSA.md new file mode 100644 index 00000000..6f1c88e0 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/aisp-techniques/negative-selection/RNSA.md @@ -0,0 +1,248 @@ +--- +id: rnsa +sidebar_label: RNSA - Algoritmo de Seleção Negativa de Valor Real +sidebar_position: 1 +last_update: + date: 2025/05/17 + author: João Paulo +keywords: + - Valor Real + - classificação + - anomalias + - not self + - V-detector + - Algoritmo de Seleção Negativa + - Sistema Imunológico Artificial (AIS) + - Próprio e não-próprio + - Imune + - Computação Natural +--- + +# RNSA (Algoritmo de Seleção Negativa de Valor Real) + +:::info + +**``RNSA``** estende a **[classe ``BaseClassifier``](../../advanced-guides/base-module/core/Classifier.md)**, herdando suas funcionalidades básicas. + +::: + +## Construtor RNSA + +A classe ``RNSA`` tem a finalidade de classificação e identificação de anomalias através do método self e not self . + +```python +class RNSA( + self, + N: int = 100, + r: float = 0.05, + r_s: float = 0.0001, + k: int = 1, + metric: Literal['manhattan', 'minkowski', 'euclidean'] = 'euclidean', + max_discards: int = 1000, + seed: int = None, + algorithm: Literal['default-NSA', 'V-detector'] ='default-NSA', + **kwargs: Dict[str, Union[bool, str, float]] +) +``` + +**Attributes:** + +* *N* (``int``): Quantidade de detectores. Defaults to ``100``. +* *r* (``float``): Raio do detector. Defaults to ``0.05``. + + :::note + É importante considerar que definir um raio muito baixo para o detector pode reduzir significativamente a taxa de detecção. Por outro lado, um raio muito grande pode inviabilizar a incorporação do detector no espaço de busca, o que também pode comprometer o desempenho da detecção. É fundamental encontrar um equilíbrio entre o tamanho do raio e a eficiência da detecção para obter os melhores resultados possíveis. + ::: + +* *k* (``int``): Quantidade de vizinhos próximos dos detectores gerados aleatoriamente para efetuar o cálculo da média da distância. Defaults to ``1``. +* *metric* (``str``): Forma para se calcular a distância entre o detector e a amostra: + + * ``'euclidiana'`` ➜ O cálculo da distância dá-se pela expressão: + $$ + \sqrt{(X_1 - X_1)^2 + (Y_2 - Y_2)^2 + ... + (Y_n - Y_n)^2} + $$ + * ``'minkowski'`` ➜ O cálculo da distância dá-se pela expressão: + $$ + \frac{((|X_{1} - Y_{1}|^p + |X_{2} - Y_{2}|^p + \cdots + |X_{n} - Y_{n}|^p)^\frac{1}{p})}{n} + $$. + * ``'manhattan'`` ➜ O cálculo da distância dá-se pela expressão: + $$ + \frac{(|X_{1} - X_{1}| + |Y_{2} - Y_{2}| + \cdots + |Y_{n} - Y_{n}|)}{n} + $$. + + Defaults to ``'euclidean'``. + +* *max_discards* (``int``): Este parâmetro indica o número máximo de descartes de detectores em sequência, que tem como objetivo evitar um +possível loop infinito caso seja definido um raio que não seja possível gerar detectores do não-próprio. Defaults to ``1000``. + +* *seed* (``int``): Semente para a geração randômica dos valores nos detectores. Defaults to ``None``. +* *algorithm* (``str``), Definir a versão do algoritmo: + + * ``'default-NSA'``: Algoritmo padrão com raio fixo. + * ``'V-detector'``: Este algoritmo é baseado no artigo "[Real-Valued Negative Selection Algorithm with Variable-Sized Detectors](https://doi.org/10.1007/978-3-540-24854-5_30)", de autoria de Ji, Z., Dasgupta, D. (2004), e utiliza um raio variável para a detecção de anomalias em espaços de características. + + Defaults to ``'default-NSA'``. + +* *r_s* (``float``): O valor de ``rₛ`` é o raio das amostras próprias da matriz ``X``. + +* ``**kwargs``: + * *non_self_label* (``str``): Esta variável armazena o rótulo que será atribuído quando os dados possuírem + apenas uma classe de saída, e a amostra for classificada como não pertencente a essa classe. Defaults to ``'non-self'``. + + * *cell_bounds* (``bool``): Se definido como ``True``, esta opção limita a geração dos detectores ao espaço do plano compreendido entre 0 e 1. Isso significa que qualquer detector cujo raio ultrapasse esse limite é descartado, e esta variável é usada exclusivamente no algoritmo ``V-detector``. + * p (``float``): Este parâmetro armazena o valor de ``p`` utilizada na distância de Minkowski. O padrão é ``2``, o que significa distância euclidiana normalizada. Diferentes valores de p levam a diferentes variantes da distância de Minkowski [saiba mais](https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.minkowski.html). + +**Outras variáveis iniciadas:** + +* *detectors* (``dict``): Esta variável armazena uma lista de detectores por classe. + +* *classes* (``npt.NDArray``): lista de classes de saída. + +--- + +### Função fit(...) + +A função ``fit(...)`` gera os detectores para os não próprios com relação às amostras: + +```python +def fit(self, X: npt.NDArray, y: npt.NDArray, verbose: bool = True) +``` + +Nela é realizado o treinamento de acordo com ``X`` e ``y``, usando o método de seleção negativa(``NegativeSelect``). + +**Os parâmetros de entrada são:** + +* ``X``: array com as características das amostras com **N** amostras (linhas) e **N** características (colunas), normalizados para valores entre [0, 1]. +* ``y``: array com as classes de saídas disposto em **N** amostras que são relacionadas ao ``X``. +* ``verbose``: boolean com valor padrão ``True``, determina se o feedback da geração dos detectores será impresso. + +*Retorna a instância da classe.* + +--- + +### Função predict(...) + +A função ``predict(...)`` realiza a previsão das classes utilizando os detectores gerados: + +```python +def predict(self, X: npt.NDArray) -> npt.NDArray: +``` + +**O parâmetro de entrada:** + +* ``X``: array com as características para a previsão, com **N** amostras (Linhas) e **N** colunas. + +**Retorna:** + +* ``C``: Um array de previsão com as classes de saída para as características informadas. +* ``None``: se não houver detectores. + +--- + +### Função score(...) + +A função "score(...)" calcula a precisão do modelo treinado por meio da realização de previsões e do cálculo da acurácia. + +```python +def score(self, X: npt.NDArray, y: list) -> float: +``` + +retorna a acurácia, do tipo ``float``. + +--- + +## Métodos privados + +--- + +### Função __checks_valid_detector(...) + +A função ``def __checks_valid_detector(...)`` verifica se o detector possui raio ``r`` válido para o não-próprio da classe: + +```python +def __checks_valid_detector(self, X: npt.NDArray, vector_x: npt.NDArray, samplesIndexClass: npt.NDArray) -> bool: +``` + +**Os parâmetros de entrada são:** + +* ``X``: array com as características das amostras com **N** amostras (linhas) e **N** características (colunas), normalizados para valores entre [0, 1]. + +* ``vector_x``: Detector candidato gerado aleatoriamente. + +* ``samplesIndexClass``: Array com os indexes de uma classe. + +**Retorna:** Verdadeiro (``True``) para os detectores que não possuam amostras em seu interior ou falso (``False``) se possuir. + +--- + +### Função __compare_KnearestNeighbors_List(...) + +A função ``def __compare_KnearestNeighbors_List(...)`` compara a distância dos k-vizinhos mais próximo, para isso se a distância da nova amostra for menor, substitui ``k-1`` e ordena em ordem crescente: + +```python +def __compare_KnearestNeighbors_List(self, knn: npt.NDArray, distance: float) -> npt.NDArray: +``` + +**Retorna:** uma lista com as distâncias dos k-vizinhos mais próximo. + +--- + +### Função __compare_sample_to_detectors(...) + +Função para comparar uma amostra com os detectores, verificando se a amostra é própria. + +Nesta função, quando possui ambiguidade de classes, retorna a classe que possuir a média de distância maior entre os detectores. + +**Os parâmetros de entrada são:** + +* line: vetor com N-características + +**Retorna:** A classe prevista com os detectores ou None se a amostra não se qualificar a nenhuma classe. + +--- + +### Função __detector_is_valid_to_Vdetector(...) + +Verifique se a distância entre o detector e as amostras, descontando o raio das amostras, é maior do que o raio mínimo. + +```python +def __detector_is_valid_to_Vdetector(self, distance, vector_x): +``` + +**Os parâmetros de entrada são:** + +* distance (``float``): distância mínima calculada entre todas as amostras. +* vector_x (``numpy.ndarray``): vetor x candidato do detector gerado aleatoriamente, com valores entre 0 e 1. + +**Retorna:** + +* ``False``: caso o raio calculado seja menor do que a distância mínima ou ultrapasse a borda do espaço, caso essa opção esteja habilitada. +* ``True`` e a distância menos o raio das amostras, caso o raio seja válido. + +--- + +### Função __distance(...) + +A função ``def __distance(...)`` calcula a distância entre dois pontos utilizando a técnica definida em ``metric``, no qual são: ``'euclidiana', 'minkowski', ou 'manhattan'`` + +```python +def __distance(self, u: npt.NDArray, v: npt.NDArray): +``` + +Os parâmetros de entrada são NDArrays: ``u`` e ``v``, com as coordenadas para os pontos. + +Retorna a distancia (``double``) entre os dois pontos. + +--- + +### Função __slice_index_list_by_class(...) + +A função ``__slice_index_list_by_class(...)``, separa os índices das linhas conforme a classe de saída, para percorrer o array de amostra, apenas nas posições que a saída for a classe que está sendo treinada: + +```python +def __slice_index_list_by_class(self, y: npt.NDArray) -> dict: +``` + +Retorna um dicionario com as classes como chave e os índices em ``X`` das amostras. + +--- diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/assets/ainet_blob.png b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/assets/ainet_blob.png new file mode 100644 index 00000000..f680ec83 Binary files /dev/null and b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/assets/ainet_blob.png differ diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/assets/ainet_circler.png b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/assets/ainet_circler.png new file mode 100644 index 00000000..fdd694bc Binary files /dev/null and b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/assets/ainet_circler.png differ diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/assets/ainet_moon.png b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/assets/ainet_moon.png new file mode 100644 index 00000000..3050614e Binary files /dev/null and b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/assets/ainet_moon.png differ diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/assets/clonalg.png b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/assets/clonalg.png new file mode 100644 index 00000000..2b7be61a Binary files /dev/null and b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/assets/clonalg.png differ diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/assets/exemple_airs_plot.png b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/assets/exemple_airs_plot.png new file mode 100644 index 00000000..614be662 Binary files /dev/null and b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/assets/exemple_airs_plot.png differ diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/assets/exemple_pt_d.png b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/assets/exemple_pt_d.png new file mode 100644 index 00000000..48a4b3df Binary files /dev/null and b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/assets/exemple_pt_d.png differ diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/assets/exemple_pt_v.png b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/assets/exemple_pt_v.png new file mode 100644 index 00000000..28eb9070 Binary files /dev/null and b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/assets/exemple_pt_v.png differ diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/assets/logo.svg b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/assets/logo.svg new file mode 100644 index 00000000..868c42c5 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/assets/logo.svg @@ -0,0 +1,2190 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/assets/matrizBNSA.png b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/assets/matrizBNSA.png new file mode 100644 index 00000000..a24543d3 Binary files /dev/null and b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/assets/matrizBNSA.png differ diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/examples/Classification/README.mdx b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/examples/Classification/README.mdx new file mode 100644 index 00000000..fff17625 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/examples/Classification/README.mdx @@ -0,0 +1,24 @@ +import DocCardList from '@theme/DocCardList'; + +# Classificação + +Acesse os notebooks com a possibilidade de execução online pelo Binder: [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/AIS-Package/aisp/HEAD?labpath=%2Fexamples%2Fpt%2Dbr%2Fclassification) + +--- + +## Os exemplos estão organizados da seguinte forma: + +### Normalização de Dados: +> Mostra como normalizar dados usando as classes de seleção negativa. Na versão de valores reais, os dados são normalizados entre 0 e 1. Na versão binária, eles são normalizados em um vetor de bits. + +### Validação Cruzada K-fold com 50 Interações: +> Neste exemplo, os dados são divididos em conjuntos de treinamento e teste, e o desempenho do modelo é avaliado por meio de validação cruzada. Portanto, dividimos os dados de treinamento em k partes. Em cada iteração, 10% dos dados de treinamento são reservados para teste. + +### Treinamento: +> O modelo treinado é testado neste exemplo com todos os dados de treinamento disponíveis. + +Os exemplos a seguir mostram várias funcionalidades das classes de seleção negativa para que você saiba como usá-las em seu projeto. Sinta-se à vontade para explorar esses exemplos e adaptá-los conforme necessário para atender às suas necessidades específicas. + +## Exemplos: + + \ No newline at end of file diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/examples/Classification/csa.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/examples/Classification/csa.md new file mode 100644 index 00000000..3e622c8f --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/examples/Classification/csa.md @@ -0,0 +1,59 @@ +--- +title: Algoritmo de Seleção Clonal +sidebar_position: 2 +lastUpdatedAt: 2025/05/25 +author: João Paulo +showLastUpdateAuthor: true +showLastUpdateTime: true +last_update: + date: 2025/05/25 + author: João Paulo +keywords: + - Algoritmo de Seleção Clonal + - CSA + - Sistema Imune Artificial + - AIS + - AIRS + - Algoritmo Binário + - algoritmos inspirados no sistema imune + - aprpt-brdizado de máquina + - classificação + - detecção de anomalias + - conjunto de dados de cogumelos + - conjunto de dados Iris + - conjunto de dados Geyse + - detectores com valores reais + - reconhecimpt-brto imune +--- + +Esta página apresenta uma coleção de exemplos práticos demonstrando como usar o Algoritmo de Seleção Clonal. + +## AIRS (Sistema Imunológico Artificial de Reconhecimento) + +Run online via Binder: [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/AIS-Package/aisp/HEAD?labpath=%2Fexamples%2Fpt%2Dbr%2Fclassification%2FAIRS) + +--- + +### Algoritmo Binário + ++ [Exemplo com amostras aleatórias](https://github.com/AIS-Package/aisp/blob/main/examples/pt-br/classification/AIRS/example_with_randomly_gpt-brerated_dataset-pt-br.ipynb) + +> No exemplo apresentado neste notebook, foram geradas 1000 amostras aleatórias, organizadas em dois grupos, um para cada classe. + ++ [Exemplo com banco de dados de cogumelos](https://github.com/AIS-Package/aisp/blob/main/examples/pt-br/classification/AIRS/mushrooms_dataBase_example_pt-br.ipynb) + +> Utiliza o [mushrooms database](https://archive.ics.uci.edu/dataset/73/mushroom), que contém informações sobre cogumelos comestíveis e venenosos. + +### Algoritmo com Valores Reais + ++ [Exemplo com amostras aleatórias](https://github.com/AIS-Package/aisp/blob/main/examples/pt-br/classification/AIRS/example_with_randomly_gpt-brerated_dataset-pt-br.ipynb) + +> No exemplo apresentado neste notebook, foram geradas 500 amostras aleatórias, organizadas em dois grupos, um para cada classe. Podemos ver abaixo os detectores "não-próprio" gerados. + ++ [Exemplo com banco de dados Iris](https://github.com/AIS-Package/aisp/blob/main/examples/pt-br/classification/AIRS/iris_dataBase_example_pt-br.ipynb) + +> Exemplo usando o NSA com o [iris database](https://archive.ics.uci.edu/ml/datasets/iris), que contém amostras com quatro dimensões e três classes de saída (Setosa, Versicolor e Virginica). + ++ [Exemplo com banco de dados Geyser](https://github.com/AIS-Package/aisp/blob/main/examples/pt-br/classification/AIRS/geyser_dataBase_example_pt-br.ipynb) + +> Para classificar erupções de gêiseres no Parque Nacional de Yellowstone, este notebook utiliza o [Old Faithful database](https://github.com/mwaskom/seaborn-data/blob/master/geyser.csv). diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/examples/Classification/nsa.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/examples/Classification/nsa.md new file mode 100644 index 00000000..946c60c6 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/examples/Classification/nsa.md @@ -0,0 +1,61 @@ +--- +sidebar_position: 1 +lastUpdatedAt: 2023/05/30 +author: João Paulo +showLastUpdateAuthor: true +showLastUpdateTime: true +last_update: + date: 2023/05/30 + author: João Paulo +keywords: + - Binário + - classificação + - anomalias + - not self + - affinity threshold + - Algoritmo de Seleção Negativa + - Sistema Imunológico Artificial (AIS) + - Próprio e não-próprio + - Imune + - Computação Natural + - Valor Real + - V-detector +--- + +# Algoritmo de Seleção Negativa + +Nesta página, você encontrará uma coleção de exemplos práticos que demonstram como usar as classes de seleção negativa implementadas em nosso pacote. + +--- + +## BNSA (Algoritmo de Seleção Negativa Binária) + +Execute on-line via Binder: [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/AIS-Package/aisp/HEAD?labpath=%2Fexamples%2Fen%2Fclassification%2FBNSA) + +--- + ++ [Exemplo com amostras aleatórias](https://github.com/AIS-Package/aisp/blob/main/examples/pt-br/classification/BNSA/example_with_randomly_generated_dataset-pt.ipynb) + +> No exemplo presente neste notebook, foram geradas 1000 amostras aleatórias, organizadas em dois grupos, um para cada classe. + ++ [Exemplo de Base de Dados de Cogumelos](https://github.com/AIS-Package/aisp/blob/main/examples/pt-br/classification/BNSA/mushrooms_dataBase_example_pt.ipynb) + +> Ele usa a [base de dados de cogumelos](https://archive.ics.uci.edu/dataset/73/mushroom), que contém informações sobre cogumelos comestíveis e venenosos. + +## RNSA (Algoritmo de Seleção Negativa de Valores Reais) + +Execute on-line via Binder: [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/AIS-Package/aisp/HEAD?labpath=%2Fexamples%2Fen%2Fclassification%2FRNSA) + +--- + ++ [Exemplo com amostras aleatórias](https://github.com/AIS-Package/aisp/blob/main/examples/pt-br/classification/RNSA/example_with_randomly_generated_dataset-pt.ipynb) + +> No exemplo presente neste notebook, foram geradas 500 amostras aleatórias, organizadas em dois grupos, um para cada classe. + ++ [Exemplo de Base de Dados Iris](https://github.com/AIS-Package/aisp/blob/main/examples/pt-br/classification/RNSA/iris_dataBase_example_pt.ipynb) + +> Exemplo usando a base de dados [íris](https://archive.ics.uci.edu/ml/datasets/iris), que contém amostras de quatro dimensões e três classes de saída (Setosa, Versicolor e Virginica). + ++ [Exemplo de Base de Dados Geyser](https://github.com/AIS-Package/aisp/blob/main/examples/pt-br/classification/RNSA/geyser_dataBase_example_pt.ipynb) + +> Para classificar erupções de geysers no Parque Nacional de Yellowstone, este notebook usa a [base de dados Old Faithful](https://github.com/mwaskom/seaborn-data/blob/master/geyser.csv). diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/examples/Clustering/README.mdx b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/examples/Clustering/README.mdx new file mode 100644 index 00000000..81a21118 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/examples/Clustering/README.mdx @@ -0,0 +1,49 @@ +--- +sidebar_position: 1 +lastUpdatedAt: 2025/05/25 +author: João Paulo +showLastUpdateAuthor: true +showLastUpdateTime: true +keywords: + - Binário + - Agrupamento + - Anomalias + - não próprio + - limite de afinidade + - Sistema Imunológico Artificial (AIS) + - Próprio e não-próprio + - Imune + - Computação Natural + - conjunto de dados de cogumelos + - conjunto de dados iris + - conjunto de dados geyser + - Índice de Silhueta + - Índice Rand Ajustado +--- + +import DocCardList from '@theme/DocCardList'; + +# Agrupamento (Clustering) + +Acesse os notebooks com a opção de executá-los online usando o Binder: [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/AIS-Package/aisp/HEAD?labpath=%2Fexamples%2Fpt-br%2Fclustering) + +--- + +## Os exemplos estão organizados abaixo: + +### Normalização de Dados +> Apresenta o uso dos dados originais (não normalizados) e demonstra como normalizá-los entre 0 e 1 +> usando MinMaxScaler, preparando o conjunto de dados para treinamento e melhorando o desempenho do agrupamento. + +### Treinamento do Modelo +> Inicializa e treina o modelo, identifica os clusters e avalia a qualidade do agrupamento usando métricas como +> Índice de Silhueta e Índice Rand Ajustado (ARI). + +### Visualização dos Clusters +> Visualiza os clusters formados, a população de anticorpos e a rede imunológica. + +--- + +## Exemplos: + + \ No newline at end of file diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/examples/Clustering/ina.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/examples/Clustering/ina.md new file mode 100644 index 00000000..fb3f1087 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/examples/Clustering/ina.md @@ -0,0 +1,39 @@ +--- +title: Algoritmos de Rede Imunológica +sidebar_position: 2 +lastUpdatedAt: 2025/05/25 +author: João Paulo +showLastUpdateAuthor: true +showLastUpdateTime: true +last_update: + date: 2025/05/25 + author: João Paulo +keywords: + - Algoritmo de Rede Imunológica + - Sistema Imunológico Artificial + - AIS + - algoritmos inspirados no sistema imunológico + - aprendizado de máquina + - conjunto de dados iris + - conjunto de dados geyser +--- + +Nesta página, você encontrará uma coleção de exemplos práticos que demonstram como usar as classes do Algoritmo de Rede Imunológica implementadas em nosso pacote. + +Execute os notebooks online via Binder: [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/AIS-Package/aisp/HEAD?labpath=%2Fexamples%2Fpt-br%2Fclustering%2FAiNet) + +## AiNet (Rede Imunológica Artificial) + +--- + ++ [Conjuntos de dados aleatórios](https://github.com/AIS-Package/aisp/blob/main/examples/pt-br/clustering/AiNet/example_with_randomly_generated_dataset.ipynb) + +> Neste notebook, o AiNet é demonstrado em três conjuntos de dados sintéticos: +> +> + **Blobs:** clusters esféricos bem definidos, fáceis de separar. +> + **Moons:** clusters não-lineares, ilustrando fronteiras de decisão mais complexas. +> + **Circles:** dois círculos concêntricos, mostrando a capacidade de lidar com separações não-lineares. + ++ [Exemplo com base de dados do geyser](https://github.com/AIS-Package/aisp/blob/main/examples/pt-br/clustering/AiNet/geyser_dataBase_example.ipynb) + +> Para classificar erupções de geysers no Parque Nacional de Yellowstone, este notebook usa a [base de dados Old Faithful](https://github.com/mwaskom/seaborn-data/blob/master/geyser.csv). diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/examples/Optimization/README.mdx b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/examples/Optimization/README.mdx new file mode 100644 index 00000000..4c5dfbcb --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/examples/Optimization/README.mdx @@ -0,0 +1,30 @@ +--- +sidebar_position: 3 +lastUpdatedAt: 2025/09/20 +autor: João Paulo +showLastUpdateAuthor: true +showLastUpdateTime: true +palavras-chave: +- otimização +- sistema imunológico artificial +- limiar de afinidade +- computação natural +- algoritmos heurísticos +- otimização de funções +- computação evolutiva +- tsp +- rastrigin +- mochila +--- + +import DocCardList from '@theme/DocCardList'; + +# Otimização (Optimization) + +Acesse os notebooks com a opção de executá-los online usando o Binder: [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/AIS-Package/aisp/HEAD?labpath=%2Fexamples%pt-br%2Foptimization) + +--- + +## Exemplos: + + \ No newline at end of file diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/examples/Optimization/csa.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/examples/Optimization/csa.md new file mode 100644 index 00000000..ea9b0171 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/examples/Optimization/csa.md @@ -0,0 +1,38 @@ +--- +title: Algoritmos de Seleção Clonal +sidebar_position: 3 +showLastUpdateAuthor: true +showLastUpdateTime: true +palavras-chave: +- clonalg +- algoritmo de seleção clonal +- sistema imunológico artificial +- AIS +- algoritmos inspirados no sistema imunológico +- otimização +- tsp +- Problema do Caixeiro Viajante +- mochila +- rastrigin +- aprendizado de máquina +--- + +Nesta página, você encontrará uma coleção de exemplos práticos que demonstram como usar as classes do Algoritmo de Seleção Clonal implementadas em nosso pacote. + +Execute notebooks online via Binder: [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/AIS-Package/aisp/HEAD?labpath=%2Fexamples%2Fpt-br%2Foptimization%2Fclonalg) + +## Clonalg (Algoritmo de Seleção Clonal) + +--- + ++ [Problema do Caixeiro Viajante](https://github.com/AIS-Package/aisp/blob/main/examples/pt-br/optimization/clonalg/tsp_problem_example.ipynb) + +> Neste notebook, aplique o **Clonalg** ao Problema da Mochila usando algoritmos de otimização do pacote AISP. + ++ [Função Rastrigin](https://github.com/AIS-Package/aisp/blob/main/examples/pt-br/optimization/clonalg/rastrigin_function_example.ipynb) + +> Neste notebook, aplicamos o **Clonalg** à Função Rastrigin, um problema clássico de otimização contínua usando algoritmos de otimização do pacote AISP. + ++ [Problema da Mochila](https://github.com/AIS-Package/aisp/blob/main/examples/pt-br/optimization/clonalg/knapsack_problem_example.ipynb) + +> Neste notebook, aplicamos o **Clonalg** ao Problema da Mochila usando algoritmos de otimização do pacote AISP. diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/examples/README.mdx b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/examples/README.mdx new file mode 100644 index 00000000..77678037 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/examples/README.mdx @@ -0,0 +1,11 @@ +--- +sidebar_position: 2.5 +--- + +import DocCardList from '@theme/DocCardList'; + +# Exemplos + +Abaixo estão alguns exemplos que utilizam o pacote com a ferramenta Jupyter Notebook. + + \ No newline at end of file diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/getting-started/_category_.json b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/getting-started/_category_.json new file mode 100644 index 00000000..560390a4 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/getting-started/_category_.json @@ -0,0 +1,5 @@ +{ + "label": "Getting Started", + "position": 1.5 +} + diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/getting-started/basic-use/AIRS.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/getting-started/basic-use/AIRS.md new file mode 100644 index 00000000..f23c30b7 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/getting-started/basic-use/AIRS.md @@ -0,0 +1,101 @@ +--- +sidebar_label: Usando o AIRS +lastUpdatedAt: 2025/08/22 +author: João Paulo +showLastUpdateAuthor: true +showLastUpdateTime: true +last_update: + date: 2025/08/22 + author: João Paulo +keywords: + - Algoritmo de Seleção Clonal + - CSA + - Sistema Imunológico Artificial + - AIS + - AIRS + - Algoritmo Binário + - NSA + - Algoritmos Inspirados no Sistema Imunológico + - Aprendizado de Máquina + - Classificação + - Detecção de Anomalias + - Conjunto de Dados de Cogumelos + - Conjunto de Dados Íris + - Conjunto de Dados Gêiser + - Detectores de Valores Reais + - Reconhecimento Imunológico +--- + +# Usando o AIRS + +Acesse o notebook Jupyter com o código disponível [aqui](https://github.com/AIS-Package/aisp/blob/main/examples/pt-br/classification/AIRS/example_with_randomly_generated_dataset-pt.ipynb)! + +Executar o notebook online via Binder: [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/AIS-Package/aisp/HEAD?labpath=%2Fexamples%2Fpt-br%2Fclassification%2FAIRS%2Fexample_with_randomly_generated_dataset-pt.ipynb) + +## Importação do Sistema de Reconhecimento Imunológico Artificial + +```python +from aisp.csa import AIRS +``` + +## Gerando bolhas de dados para as classe aleatoriamente + +Utilizando a função make_blobs, são gerados dois conjuntos de dados em forma de bolhas, no intervalo entre 0 e 1, representando cada classe x e y. Em seguida, esses dados são separados em conjuntos de teste e treinamento. + +```python +from sklearn.datasets import make_blobs +from sklearn.model_selection import train_test_split + +# Gerando as amostras e saídas para o treinamento. +samples, output = make_blobs( + n_samples=500, + cluster_std=0.07, + center_box=(0.0, 1.0), + centers=[[0.25, 0.75], [0.75, 0.25]], + random_state=1234, +) +# Separando dados para treinamento e teste. +train_x, test_x, train_y, test_y = train_test_split(samples, output, test_size=0.2) +``` + +--- + +## Testing the model AIRS + +Em seguida, apresenta o resultado da acurácia da previsão. + +```python +from sklearn.metrics import confusion_matrix, classification_report, accuracy_score + + +# Iniciando a classe. +airs = AIRS(seed=1234) +# Efetuando o treinamento: +airs.fit(X=train_x, y=train_y) +# Efetuando a previsão:: +prev = airs.predict(X=test_x) +# Mostrando a acurácia das previsões para os dados. +print(f"A acurácia é {accuracy_score(prev, test_y)}") +print(classification_report(test_y, prev)) +``` + +Output: + +```bash +✔ Set of memory cells for classes (0, 1) successfully generated: ┇██████████┇ 400/400 memory cells for each aᵢ +A acurácia é 1.0 + precision recall f1-score support + + 0 1.00 1.00 1.00 48 + 1 1.00 1.00 1.00 52 + + accuracy 1.00 100 + macro avg 1.00 1.00 1.00 100 +weighted avg 1.00 1.00 1.00 100 +``` + +--- + +## Célula de memória e plotagem de amostra + +![Célula de memória e plotagem de amostra](../../assets/exemple_airs_plot.png) diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/getting-started/basic-use/AiNet.mdx b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/getting-started/basic-use/AiNet.mdx new file mode 100644 index 00000000..48544600 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/getting-started/basic-use/AiNet.mdx @@ -0,0 +1,263 @@ +--- +sidebar_label: Usando o AiNet +lastUpdatedAt: 2025/08/02 +author: João Paulo +showLastUpdateAuthor: true +showLastUpdateTime: true +last_update: + date: 2025/08/02 + author: João Paulo +keywords: + - Rede Imune Artificial + - AiNet + - algoritmos inspirados no sistema imune + - agrupamento + - aprendizado de máquina + - detecção de anomalias + - make_blobs + - make_moons + - make_circles + - visualização de dados + - networkx +--- + +# Usando o AiNet +Acesse o Jupyter Notebook com o código disponível [aqui](https://github.com/AIS-Package/aisp/blob/main/examples/pt-br/clustering/AiNet/example_with_randomly_generated_dataset.ipynb)! + +Execute o notebook online via Binder: [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/AIS-Package/aisp/HEAD?labpath=%2Fexamples%2Fpt-br%2Fclustering%2FAiNet%2Fexample_with_randomly_generated_dataset.ipynb) +## Introdução + +A clusterização é uma tarefa de aprendizado de máquina não supervisionado que visa agrupar um conjunto de dados no mesmo grupo (chamado de cluster). + +Neste notebook, exploraremos o AiNet (Artificial Immune Network). O AiNet utiliza conceitos como afinidade de anticorpos e supressão de clones para identificar os centros dos clusters nos dados. + +Objetivo: O objetivo é demonstrar a eficácia do AiNet na clusterização dos conjuntos de dados random: + +* **Blobs:** Clusters bem definidos e esféricos. +* **Moons:** Clusters com uma forma não linear. +* **Circles:** Clusters dispostos em dois círculos concêntricos, apresentando separação não linear. + +**Estrutura do Notebook:** + +* **Configuração:** Instalação e importação das bibliotecas necessárias. +* **Função de Visualização:** Definição de uma função para plotar os resultados. +* **Demonstração 1** - Dataset Blobs: Aplicação do AiNet ao blobs. +* **Demonstração 2** - Dataset Moons: Aplicação do AiNet ao moons. +* **Demonstração 3** - Dataset Circles: Aplicação do AiNet ao circles. + +--- + +## Importando a Rede Imune Artificial +```python +from aisp.ina import AiNet +``` + +--- + +## Função de Visualização + +
+Função de Visualização do AiNet (plota agrupamentos e a rede imune) + +```python +def plot_immune_network(train_x, predict_y, model, title_prefix=""): + """ + Plota os resultados da clusterização da AiNet. + + Paramentos: + train_x (np.array): Os dados de entrada. + predict_y (np.array): As previsões de cluster do modelo. + model (AiNet): O modelo AiNet treinado. + title_prefix (str, optional): Um prefixo para os títulos dos gráficos. + """ + clusters = list(model._memory_network.values()) + network = np.array(model._population_antibodies) + + _, axs = plt.subplots(2, 2, figsize=(12, 12)) + colors = colormaps.get_cmap('Accent') + + # Dados originais + axs[0][0].scatter(train_x[:, 0], train_x[:, 1], color='dodgerblue', alpha=0.9, s=50, marker='o', edgecolors='k') + axs[0][0].set_title(f'{title_prefix}Dados Originais', fontsize=16) + axs[0][0].set_xlabel('X', fontsize=14) + axs[0][0].set_ylabel('Y', fontsize=14) + axs[0][0].grid(True, linestyle='--', alpha=0.5) + + # População de anticorpos + axs[0][1].scatter(network[:, 0], network[:, 1], color='crimson', alpha=0.9, s=70, marker='.', edgecolors='k') + axs[0][1].set_title(f'{title_prefix}População de Anticorpos', fontsize=16) + axs[0][1].set_xlabel('X', fontsize=14) + axs[0][1].set_ylabel('Y', fontsize=14) + axs[0][1].grid(True, linestyle='--', alpha=0.5) + + # Previsões dos clusters + scatter = axs[1][0].scatter(train_x[:, 0], train_x[:, 1], c=predict_y, cmap='Accent', s=50, edgecolors='k', alpha=0.9) + axs[1][0].set_title(f'{title_prefix}Previsões dos Clusters (AiNet)', fontsize=16) + axs[1][0].set_xlabel('X', fontsize=14) + axs[1][0].set_ylabel('Y', fontsize=14) + axs[1][0].grid(True, linestyle='--', alpha=0.5) + legend1 = axs[1][0].legend(*scatter.legend_elements(), title="Clusters") + axs[1][0].add_artist(legend1) + + # Grafo da Rede Imune + G = nx.Graph() + positions = {} + for i, cluster in enumerate(clusters): + cluster_nodes = [f'{i}_{j}' for j in range(len(cluster))] + G.add_nodes_from(cluster_nodes) + for node, point in zip(cluster_nodes, cluster): + positions[node] = tuple(point) + dist_matrix = squareform(pdist(cluster)) + mst_local = minimum_spanning_tree(dist_matrix).toarray() + for row_idx, row in enumerate(mst_local): + for col_idx, weight in enumerate(row): + if weight > 0: + G.add_edge(cluster_nodes[row_idx], cluster_nodes[col_idx], weight=weight) + for i, cluster in enumerate(clusters): + cluster_nodes = [f'{i}_{j}' for j in range(len(cluster))] + nx.draw_networkx_nodes(G, positions, nodelist=cluster_nodes, ax=axs[1][1], + node_color=[colors(i)], node_size=70, edgecolors='k', label=f'Cluster {i}') + nx.draw_networkx_edges(G, positions, ax=axs[1][1], alpha=0.6) + axs[1][1].set_title(f'{title_prefix}Rede Imune Grafo', fontsize=16) + axs[1][1].set_xlabel('X', fontsize=14) + axs[1][1].set_ylabel('Y', fontsize=14) + axs[1][1].grid(True, linestyle='--', alpha=0.5) + axs[1][1].legend() + plt.tight_layout() + plt.show() +``` + +
+ +--- + +## Demonstração 1 - Dataset Blobs + +### Gerando bolhas de dados + +```python +samples, output = make_blobs( + n_samples=1000, + cluster_std=0.07, + center_box=(0.0, 1.0), + centers=[[0.25, 0.75], [0.75, 0.25]], + random_state=1234, +) +``` + +### Treinando o modelo AiNet + +```python +model = AiNet(suppression_threshold=0.96, affinity_threshold=0.95, mst_inconsistency_factor=3, seed=123) +predict_y = model.fit_predict(samples) +``` + +Output: +```bash +✔ Set of memory antibodies for classes (0, 1) successfully generated | Clusters: 2 | Population of antibodies size: 119: ┇██████████┇ 10/10 total training interactions +``` + +### Silhouette score + +```python +silhouette = silhouette_score(samples, predict_y) +print(f"Coeficiente de Silhueta: {silhouette:.3f}") +``` + +Output: +```bash +Coeficiente de Silhueta: 0.826 +``` + +### Visualizando os resultados + +```python +plot_immune_network(samples, predict_y, model, title_prefix="Blobs - ") +``` + +![Blobs](../../assets/ainet_blob.png) + +--- + +## Demonstração 2 - Moons Dataset + +### Gerando dados em formato de "moons" (luas) + +```python +samples, output = make_moons(n_samples=1000, noise=0.05, random_state=42) +samples = MinMaxScaler().fit_transform(samples) +``` + +### Treinando o AiNet + +```python +model = AiNet(suppression_threshold=0.95, affinity_threshold=0.97, mst_inconsistency_factor=2.5, seed=123) +predict_y = model.fit_predict(samples) +``` + +Output: +```bash +✔ Set of memory antibodies for classes (0, 1) successfully generated | Clusters: 2 | Population of antibodies size: 69: ┇██████████┇ 10/10 total training interactions +``` + +### Silhouette score + +```python +silhouette = silhouette_score(samples, predict_y) +print(f"Coeficiente de Silhueta: {silhouette:.3f}") +``` + +Output: +```bash +Coeficiente de Silhueta: 0.398 +``` + +### Visualizando + +```python +plot_immune_network(samples, predict_y, model, title_prefix="Moons - ") +``` + +![Moons](../../assets/ainet_moon.png) + +--- + +## Demonstração 3 - Circles Dataset + +### Gerando dados em formato de círculos concêntricos + +```python +samples, output = make_circles(n_samples=1000, noise=0.05, factor=0.5, random_state=42) +samples = MinMaxScaler().fit_transform(samples) +``` + +### Training AiNet + +```python +model = AiNet(suppression_threshold=0.97, affinity_threshold=0.98, mst_inconsistency_factor=3.8, seed=123) +predict_y = model.fit_predict(samples) +``` + +Output: +```bash +✔ Set of memory antibodies for classes (0, 1) successfully generated | Clusters: 2 | Population of antibodies size: 169: ┇██████████┇ 10/10 total training interactions +``` + +### Silhouette score + +```python +silhouette = silhouette_score(samples, predict_y) +print(f"Coeficiente de Silhueta: {silhouette:.3f}") +``` + +Output: +```bash +Coeficiente de Silhueta: 0.112 +``` +### Visualizando o AiNet nos dados de círculos + +```python +plot_immune_network(samples, predict_y, model, title_prefix="Circles - ") +``` + +![Visualização da rede imunológica AiNet gerada a partir do conjunto de dados Circles](../../assets/ainet_circler.png) diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/getting-started/basic-use/BNSA.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/getting-started/basic-use/BNSA.md new file mode 100644 index 00000000..8ceda585 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/getting-started/basic-use/BNSA.md @@ -0,0 +1,127 @@ +--- +sidebar_label: Usando o BNSA +lastUpdatedAt: 2025/08/22 +author: João Paulo +showLastUpdateAuthor: true +showLastUpdateTime: true +last_update: + date: 2025/08/22 + author: João Paulo +keywords: + - Binário + - classificação + - anomalias + - not self + - affinity threshold + - Algoritmo de Seleção Negativa + - Sistema Imunológico Artificial (AIS) + - Próprio e não-próprio + - Imune + - Computação Natural +--- + +# Usando o BNSA + +O presente exemplo, disponível aqui, visa demonstrar a aplicação do algoritmo de seleção negativa binária. Esse algoritmo é empregado na classificação de amostras com características discretas. + +Acesse o notebook Jupyter disponível [aqui](https://github.com/AIS-Package/aisp/blob/main/examples/pt-br/classification/BNSA/example_with_randomly_generated_dataset-pt.ipynb)! + +Executar o notebook online via Binder: [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/AIS-Package/aisp/HEAD?labpath=%2Fexamples%2Fpt-br%2Fclassification%2FBNSA%2Fexample_with_randomly_generated_dataset-pt.ipynb) + +## Importando o algoritmo BNSA + +```python +from aisp.nsa import BNSA +``` + +## Gerando amostras + +O treinamento e teste do algoritmo precisa de amostras de dados. Assim, para a demonstração, foram geradas duas classes aleatórias, empregando a função a seguir: + +```python +import numpy as np +from scipy.spatial.distance import cdist +# Essa função gera amostras com similaridades acima de um limiar de semelhança. +def generate_samples(n_samples: int, n_features: int, s: float, x: None): + classe_samples = [] + while len(classe_samples) < n_samples: + similarity = 0 + sample_rand = np.random.randint(0, 2, size=(n_features)) + if(len(classe_samples) > max(int(n_samples * 0.1), 1)): + similarity = cdist(classe_samples, np.expand_dims(sample_rand, axis=0), metric='hamming')[0, :] + if x is not None: + if similarity[0] <= s and not np.any(np.all(sample_rand == x, axis=1)): + classe_samples.append(sample_rand) + elif similarity[0] <= s: + classe_samples.append(sample_rand) + else: + classe_samples.append(sample_rand) + return np.array(classe_samples) +``` + +--- + +Cada classe contará com 500 amostras, sendo a similaridade mínima entre amostras de 80% (s = 0.2). Essas classes serão separadas em conjunto de treinamento (800 amostras) e de teste (200 amostras). + +```python +# Configurando a seed para 121 para garantir a reprodutibilidade dos dados gerados. +np.random.seed(121) +# Gerando amostras para a classe "x". +x = generate_samples(500, 20, 0.2, None) +# Gerando amostras exclusivas para a classe "y", diferentes das amostras presentes na classe "x". +y = generate_samples(500, 20, 0.2, x) +# Adicionando colunas contendo as saídas (rótulos) das classes "x" e "y". +x = np.hstack((x, np.full((x.shape[0], 1), 'x'))) +y = np.hstack((y, np.full((y.shape[0], 1), 'y'))) +# Juntando os dois vetores (classes "x" e "y") e randomizando a ordem das amostras. +index = np.random.permutation(x.shape[0]*2) +dataset = np.vstack((x, y))[index] + +# Separando as características (inputs) e as classes de saída (rótulos). +samples = dataset[:, :-1].astype(int) +output = dataset[:, -1] +# Separando as amostras de treinamento e teste +train_x, test_x, train_y, test_y = train_test_split(samples, output, test_size=0.2, random_state=1234321) + +``` + +--- + +## Treinamento + +O modelo é ajustado através dos padrões de treinamento. Nessa aplicação, a seleção negativa distribuirá, com taxa de diferenciação de 30%, 250 detectores pelo espaço de entradas. + +```python +# Iniciando p modelo. +nsa = BNSA(N=250, aff_thresh=0.30, seed=1234321, max_discards=10000) +# Efetuando o treinamento: +nsa.fit(X=train_x, y=train_y) +# Efetuando a previsão:: +prev = nsa.predict(X=test_x) +# Mostrando a acurácia das previsões para os dados reais. +print(f"A acurácia é {accuracy_score(prev, test_y)}") +print(classification_report(test_y, prev)) +``` + +Output: + +```bash +✔ Non-self detectors for classes (x, y) successfully generated: ┇██████████┇ 500/500 detectors +A acurácia é 0.93 + precision recall f1-score support + + x 0.93 0.91 0.92 90 + y 0.93 0.95 0.94 110 + + accuracy 0.93 200 + macro avg 0.93 0.93 0.93 200 +weighted avg 0.93 0.93 0.93 200 +``` + +--- + +## Avaliação + +O modelo obteve 0,93 de acurácia para o conjunto teste. A precisão na classificação, tanto para x quanto para y, também foi de 0,93. Isso pode ser observado pela matriz de confusão na Figura 1. + +![Matriz de confusão](../../assets/matrizBNSA.png) diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/getting-started/basic-use/Clonalg.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/getting-started/basic-use/Clonalg.md new file mode 100644 index 00000000..3f10be4a --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/getting-started/basic-use/Clonalg.md @@ -0,0 +1,223 @@ +--- +title: Usando o Clonalg +sidebar_label: Usando o Clonalg +author: João Paulo +showLastUpdateAuthor: true +showLastUpdateTime: true +last_update: + date: 2025/09/17 + author: João Paulo +keywords: + - clonalg + - algoritmo clonal + - otimização + - função de Rastrigin + - inteligência artificial + - algoritmo imunológico + - benchmark de otimização + - aprendizado de máquina + - meta-heurísticas +--- + +Acesse o notebook Jupyter com o código disponível [here](https://github.com/AIS-Package/aisp/blob/main/examples/pt-br/optimization/clonalg/rastrigin_function_example.ipynb)! + +Executar o notebook online via Binder: [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/AIS-Package/aisp/HEAD?urlpath=%2Fdoc%2Ftree%2F%2Fexamples%2Fpt-br%2Foptimization%2Fclonalg%2Frastrigin_function_example.ipynb) + +### Aplicamos o Clonalg à Função Rastrigin + +A função Rastrigin é uma função multimodal não-convexa que possui muitos mínimos locais, +tornando-a um excelente teste para algoritmos de otimização, [saiba mais](https://en.wikipedia.org/wiki/Rastrigin_function). A função é definida como: + +$$ f(x) = 10n + \sum_{i=1}^{n} (x_i^{2} - 10\cos(2\pi x_i)) $$ + +Onde: + +* **n** é a dimensão do problema +* **x_i** ∈ [-5.12, 5.12] para cada dimensão +* **Mínimo global**: f(0,0) = 0 + +### Importação das bibliotecas necessárias + +```python +# Importando o Algoritmo de Seleção Clonal (CLONALG) +from aisp.csa import Clonalg + +# Bibliotecas para manipulação de dados e cálculos numéricos +import numpy as np + +# Visualização de dados +import matplotlib.pyplot as plt +``` + +### Definição do problema + +```python +problem_size = 2 +bounds = {'low': -5.12, 'high': 5.12} + +def rastrigin_fitness(x: np.ndarray) -> float: + x = np.clip(x, bounds['low'], bounds['high']) + + n = len(x) + result = 10 * n + for i in range(n): + result += x[i]**2 - 10 * np.cos(2 * np.pi * x[i]) + return result +``` + +### Configuração do algoritmo + +```python +# Configuração otimizada do Clonalg para função Rastrigin +clonalg = Clonalg( + problem_size=problem_size, + N=50, + selection_size=15, + rate_clonal=10, + rate_hypermutation=0.3, + n_diversity_injection=15, + bounds=bounds, + seed=1234 +) + +# Registrar a função de fitness +clonalg.register('affinity_function', rastrigin_fitness) +``` + +### Execução da otimização + +```python +clonalg.optimize(100, 20) + +if clonalg.best_cost is not None: + print('Best cost:', abs(clonalg.best_cost)) +``` + +Output: + +```bash +┌───────────┬─────────────────────────┬────────────────────┬─────────────────┐ +│ Iteration │ Best Affinity (min) │ Worse Affinity │ Stagnation │ +├───────────┼─────────────────────────┼────────────────────┼─────────────────┤ +│ 1 │ 7.153385│ 76.021342│ 0 │ +│ 2 │ 2.344533│ 33.315827│ 0 │ +│ 3 │ 2.140116│ 30.948129│ 0 │ +│ 4 │ 2.140116│ 31.998642│ 1 │ +│ 5 │ 0.484366│ 56.071764│ 0 │ +│ 6 │ 0.185833│ 36.260411│ 0 │ +│ 7 │ 0.185833│ 27.861454│ 1 │ +│ 8 │ 0.185833│ 29.599095│ 2 │ +│ 9 │ 0.185833│ 17.182111│ 3 │ +│ 10 │ 0.185833│ 18.465362│ 4 │ +│ 11 │ 0.185833│ 56.496717│ 5 │ +│ 12 │ 0.161393│ 33.675148│ 0 │ +│ 13 │ 0.161393│ 22.855341│ 1 │ +│ 14 │ 0.161393│ 71.552278│ 2 │ +│ 15 │ 0.161393│ 43.872058│ 3 │ +│ 16 │ 0.161393│ 28.045742│ 4 │ +│ 17 │ 0.161393│ 46.444268│ 5 │ +│ 18 │ 0.161393│ 28.197926│ 6 │ +│ 19 │ 0.030122│ 32.764169│ 0 │ +│ 20 │ 0.030122│ 27.485715│ 1 │ +│ 21 │ 0.030122│ 17.547005│ 2 │ +│ 22 │ 0.030122│ 43.293872│ 3 │ +│ 23 │ 0.030122│ 43.366562│ 4 │ +│ 24 │ 0.030122│ 42.037080│ 5 │ +│ 25 │ 0.030122│ 28.196466│ 6 │ +│ 26 │ 0.020278│ 37.645191│ 0 │ +│ 27 │ 0.020278│ 28.413549│ 1 │ +│ 28 │ 0.020278│ 32.007209│ 2 │ +│ 29 │ 0.020278│ 45.392869│ 3 │ +│ 30 │ 0.020278│ 15.223606│ 4 │ +│ 31 │ 0.020278│ 46.298146│ 5 │ +│ 32 │ 0.020278│ 21.641321│ 6 │ +│ 33 │ 0.020278│ 47.343886│ 7 │ +│ 34 │ 0.020278│ 20.720949│ 8 │ +│ 35 │ 0.020278│ 31.158014│ 9 │ +│ 36 │ 0.020278│ 42.655313│ 10 │ +│ 37 │ 0.020278│ 28.978964│ 11 │ +│ 38 │ 0.020278│ 27.926847│ 12 │ +│ 39 │ 0.020278│ 22.639969│ 13 │ +│ 40 │ 0.020278│ 43.618425│ 14 │ +│ 41 │ 0.020278│ 28.637045│ 15 │ +│ 42 │ 0.020278│ 36.324186│ 16 │ +│ 43 │ 0.020278│ 58.068571│ 17 │ +│ 44 │ 0.020278│ 61.189833│ 18 │ +│ 45 │ 0.020278│ 26.157713│ 19 │ +│ 46 │ 0.020278│ 49.301933│ 20 │ +└───────────┴─────────────────────────┴────────────────────┴─────────────────┘ +Total time: 0.107499 seconds +Best cost: 0.020278270044883584 +``` + +### Resultado + +```python +print(clonalg.get_report()) +``` + +Output: + +```python +============================================= + Optimization Summary +============================================= +Best cost : 0.020278270044883584 +Best solution : [ 0.0088594 -0.00487301] +Cost History per Iteration: + +┌────────────┬────────────────────────────┐ +│ Iteration │ Cost │ +├────────────┼────────────────────────────┤ +│ 1 │ 7.153385 │ +│ 2 │ 2.344533 │ +│ 3 │ 2.140116 │ +│ 4 │ 2.140116 │ +│ 5 │ 0.484366 │ +│ 6 │ 0.185833 │ +│ 7 │ 0.185833 │ +│ 8 │ 0.185833 │ +│ 9 │ 0.185833 │ +│ 10 │ 0.185833 │ +│ 11 │ 0.185833 │ +│ 12 │ 0.161393 │ +│ 13 │ 0.161393 │ +│ 14 │ 0.161393 │ +│ 15 │ 0.161393 │ +│ 16 │ 0.161393 │ +│ 17 │ 0.161393 │ +│ 18 │ 0.161393 │ +│ 19 │ 0.030122 │ +│ 20 │ 0.030122 │ +│ 21 │ 0.030122 │ +│ 22 │ 0.030122 │ +│ 23 │ 0.030122 │ +│ 24 │ 0.030122 │ +│ 25 │ 0.030122 │ +│ 26 │ 0.020278 │ +│ 27 │ 0.020278 │ +│ 28 │ 0.020278 │ +│ 29 │ 0.020278 │ +│ 30 │ 0.020278 │ +│ 31 │ 0.020278 │ +│ 32 │ 0.020278 │ +│ 33 │ 0.020278 │ +│ 34 │ 0.020278 │ +│ 35 │ 0.020278 │ +│ 36 │ 0.020278 │ +│ 37 │ 0.020278 │ +│ 38 │ 0.020278 │ +│ 39 │ 0.020278 │ +│ 40 │ 0.020278 │ +│ 41 │ 0.020278 │ +│ 42 │ 0.020278 │ +│ 43 │ 0.020278 │ +│ 44 │ 0.020278 │ +│ 45 │ 0.020278 │ +│ 46 │ 0.020278 │ +└────────────┴────────────────────────────┘ +``` + +### Evolução do melhor ao longo das gerações + +![Evolução do melhor ao longo das gerações](../../assets/clonalg.png) diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/getting-started/basic-use/RNSA.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/getting-started/basic-use/RNSA.md new file mode 100644 index 00000000..27a5fba4 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/getting-started/basic-use/RNSA.md @@ -0,0 +1,129 @@ +--- +sidebar_label: Usando o RNSA +lastUpdatedAt: 2025/08/22 +author: João Paulo +showLastUpdateAuthor: true +showLastUpdateTime: true +last_update: + date: 2025/08/22 + author: João Paulo +keywords: + - Valor Real + - classificação + - anomalias + - not self + - V-detector + - Algoritmo de Seleção Negativa + - Sistema Imunológico Artificial (AIS) + - Próprio e não-próprio + - Imune + - Computação Natural +--- + +# Usando o RNSA + +Acesse o notebook Jupyter com o código disponível [aqui](https://github.com/AIS-Package/aisp/blob/main/examples/pt-br/classification/RNSA/example_with_randomly_generated_dataset-pt.ipynb)! + +Executar o notebook online via Binder: [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/AIS-Package/aisp/HEAD?labpath=%2Fexamples%2Fpt-br%2Fclassification%2FRNSA%2Fexample_with_randomly_generated_dataset-pt.ipynb) + +## Importando o Algoritmo de seleção negativa de valor real + +```python +from aisp.nsa import RNSA +``` + +## Gerando bolhas de dados para as classe aleatoriamente + +Utilizando a função make_blobs, são gerados dois conjuntos de dados em forma de bolhas, no intervalo entre 0 e 1, representando cada classe x e y. Em seguida, esses dados são separados em conjuntos de teste e treinamento. + +```python +from sklearn.datasets import make_blobs +from sklearn.model_selection import train_test_split + +# Gerando as amostras e saídas para o treinamento. +samples, output = make_blobs(n_samples=500 , n_features=2, cluster_std=0.07, center_box=([0.0, 1.0]), centers=[[0.25, 0.75], [0.75, 0.25]], random_state=1234) +# Separando dados para treinamento e teste. +train_x, test_x, train_y, test_y = train_test_split(samples, output, test_size=0.2) +``` + +--- + +## Testando o modelo `default-NSA` + +Inicia o modelo com 500 detectores, cada um com um raio de 0.06. Em seguida, apresenta o resultado da acurácia da previsão. + +```python +from sklearn.metrics import confusion_matrix, classification_report, accuracy_score + +# Iniciando a classe. +model = RNSA(N=500, r=0.05, r_s=0.03, seed=1234) +# Efetuando o treinamento: +model.fit(X=train_x, y=train_y) +# Efetuando a previsão: +prev_y = model.predict(test_x) +# Mostrando a acurácia das previsões para os dados reais. +print(f"The accuracy is {accuracy_score(prev_y, test_y)}") +print(classification_report(test_y, prev_y)) +``` + +Output: + +```bash +✔ Non-self detectors for classes (0, 1) successfully generated: ┇██████████┇ 1000/1000 detectors +The accuracy is 1.0 + precision recall f1-score support + + 0 1.00 1.00 1.00 55 + 1 1.00 1.00 1.00 45 + + accuracy 1.00 100 + macro avg 1.00 1.00 1.00 100 +weighted avg 1.00 1.00 1.00 100 +``` + +--- + +## Plotagem dos detector e amostras + +![Plotagem dos detector e amostras](../../assets/exemple_pt_d.png) + +--- + +## Testando o modelo `V-detector` + +Inicia o modelo com 50 detectores, onde o raio mínimo é de 0.05 e o raio próprio das amostras é de 0.04. Em seguida, mostra o resultado da acurácia da previsão. + +```python +from sklearn.metrics import confusion_matrix, classification_report, accuracy_score + +# Iniciando a classe. +model = RNSA(N=50, r=0.05, algorithm="V-detector", r_s=0.03, seed=1234) +# Efetuando o treinamento: +model.fit(X=train_x, y=train_y) +# Efetuando a previsão: +prev_y = model.predict(test_x) +# Mostrando a acurácia das previsões para os dados reais. +print(f"A acuracia é {accuracy_score(prev, test_y)}") +print(classification_report(test_y, prev)) +``` + +Output: + +```bash +✔ Non-self detectors for classes (0, 1) successfully generated: ┇██████████┇ 100/100 detectors +A acuracia é 1.0 + precision recall f1-score support + + 0 1.00 1.00 1.00 48 + 1 1.00 1.00 1.00 52 + + accuracy 1.00 100 + macro avg 1.00 1.00 1.00 100 +weighted avg 1.00 1.00 1.00 100 +``` + +--- + +## Plotagem dos v-detector e amostras + +![Plotagem dos v-detector e amostras](../../assets/exemple_pt_d.png) diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/getting-started/basic-use/_category_.json b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/getting-started/basic-use/_category_.json new file mode 100644 index 00000000..04368434 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/getting-started/basic-use/_category_.json @@ -0,0 +1,5 @@ +{ + "label": "Basic usage", + "position": 2, + "collapsible": false +} diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/getting-started/instalation.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/getting-started/instalation.md new file mode 100644 index 00000000..d9c6a2d7 --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/getting-started/instalation.md @@ -0,0 +1,65 @@ +--- +sidebar_position: 1 +title: Instalação +sidebar_label: Instalação +lastUpdatedAt: 2025/05/17 +author: João Paulo +showLastUpdateAuthor: true +showLastUpdateTime: true +last_update: + date: 2025/05/17 + author: João Paulo +--- + +Esta página contém informações sobre as dependências do pacote, como instalá-lo e como importar os módulos. + +## Dependências + +O módulo requer [python 3.10](https://www.python.org/downloads/) ou superior. + +
+ +| Pacotes | Versão | +|:-------------:|:-------------:| +| numpy | ≥ 1.23.0 | +| scipy | ≥ 1.8.1 | +| tqdm | ≥ 4.64.1 | +| numba | ≥ 0.59.0 | + +
+ +## Procedimento de instalação + +A maneira mais simples de instalação é através do ``pip``: + +```bash +pip install aisp +``` + +## Importando módulos + +### Algoritmos de Seleção Negativa + +```python +from aisp.nsa import RNSA, BNSA + +r_nsa = RNSA(N=300, r=0.05) +b_nsa = BNSA(N=300, aff_thresh=0.30) +``` + +### Algoritmos de Seleção Clonal + +```python +from aisp.csa import AIRS, Clonalg + +airs = AIRS() +clonalg = Clonalg(problem_size=problem_size) +``` + +### Algoritmo de Rede Imunológica + +```python +from aisp.ina import AiNet + +ai_net = AiNet(suppression_threshold=0.96, affinity_threshold=0.95) +``` diff --git a/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/intro.md b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/intro.md new file mode 100644 index 00000000..faccfdbc --- /dev/null +++ b/i18n/pt-br/docusaurus-plugin-content-docs/version-0.5.x/intro.md @@ -0,0 +1,46 @@ +--- +sidebar_position: 1 +lastUpdatedAt: 2023/05/30 +author: João Paulo +showLastUpdateAuthor: true +showLastUpdateTime: true +last_update: + date: 2025/05/17 + author: João Paulo +keywords: + - AISP + - Inteligência Artificial + - Sistemas Imunológicos Artificiais + - Computação Natural + - Algoritmos Imunoinspirados + - Otimização + - Reconhecimento de Padrões + - Python + - Código Aberto + - LGPLv3 + - Pesquisa + - Bioinspiração + - Artificial Immune System + - Immune-inspired Algorithms +--- + +# Pacote de Sistemas Imunológicos Artificiais + +
+ +![Pacote de Sistemas Imunológicos Artificiais](./assets/logo.svg) + +
+ +--- + +## Introdução + +**AISP** é um pacote Python de técnicas imunoinspiradas, as quais aplicam metáforas do sistema imunológico dos vertebrados ao reconhecimento de padrões e à tarefas de otimização. Concebido como um pacote de sistemas imunológicos artificiais de código aberto, o AISP é resultado de um projeto de pesquisa iniciado em **2022** no Instituto Federal do Norte de Minas Gerais - Campus Salinas (**IFNMG - Salinas**). Sua distribuição é regida pela GNU Lesser General Public License v3.0 (LGPLv3). + +### Algoritmos implementados + +> - [x] [**Seleção Negativa.**](./aisp-techniques/negative-selection/) +> - [x] [**Algoritmos de Seleção Clonal.**](./aisp-techniques/clonal-selection-algorithms/) +> - [x] [**Teoria da Rede Imune.**](./aisp-techniques/immune-network-theory/) +> - [ ] *Teoria do Perigo.* diff --git a/versioned_docs/version-0.1.x/advanced-guides/Utils/Distance.md b/versioned_docs/version-0.1.x/advanced-guides/Utils/Distance.md index a3d758f8..1ac5aba8 100644 --- a/versioned_docs/version-0.1.x/advanced-guides/Utils/Distance.md +++ b/versioned_docs/version-0.1.x/advanced-guides/Utils/Distance.md @@ -16,7 +16,9 @@ def hamming(u: npt.NDArray, v: npt.NDArray) -> np.float64: The function to calculate the normalized Hamming distance between two points. -$$\frac{(x_1 \neq y_1) + (x_2 \neq y_2) + \cdots + (x_n \neq y_n)}{n}$$ +$$ +\frac{(x_1 \neq y_1) + (x_2 \neq y_2) + \cdots + (x_n \neq y_n)}{n} +$$ **Parameters:** @@ -37,7 +39,9 @@ def euclidean(u: npt.NDArray[np.float64], v: npt.NDArray[np.float64]) -> np.floa Function to calculate the normalized Euclidean distance between two points. -$$\sqrt{(X_{1} - X_{1})^2 + (Y_{2} - Y_{2})^2 + \cdots + (Y_{n} - Y_{n})^2}$$ +$$ +\sqrt{(X_{1} - X_{1})^2 + (Y_{2} - Y_{2})^2 + \cdots + (Y_{n} - Y_{n})^2} +$$ **Parameters:** @@ -58,7 +62,9 @@ def cityblock(u: npt.NDArray[np.float64], v: npt.NDArray[np.float64]) -> np.floa Function to calculate the normalized Manhattan distance between two points. -$$\frac{(|X_{1} - X_{1}| + |Y_{2} - Y_{2}| + \cdots + |Y_{n} - Y_{n}|)}{n}$$ +$$ +\frac{(|X_{1} - X_{1}| + |Y_{2} - Y_{2}| + \cdots + |Y_{n} - Y_{n}|)}{n} +$$ **Parameters:** @@ -79,7 +85,9 @@ def minkowski(u: npt.NDArray[np.float64], v: npt.NDArray[np.float64], p: float = Function to calculate the normalized Minkowski distance between two points. -$$\frac{((|X_{1} - Y_{1}|^p + |X_{2} - Y_{2}|^p + \cdots + |X_{n} - Y_{n}|^p)^\frac{1}{p})}{n}$$ +$$ +\frac{((|X_{1} - Y_{1}|^p + |X_{2} - Y_{2}|^p + \cdots + |X_{n} - Y_{n}|^p)^\frac{1}{p})}{n} +$$ **Parameters:** diff --git a/versioned_docs/version-0.2.x/advanced-guides/Utils/Distance.md b/versioned_docs/version-0.2.x/advanced-guides/Utils/Distance.md index a3d758f8..1ac5aba8 100644 --- a/versioned_docs/version-0.2.x/advanced-guides/Utils/Distance.md +++ b/versioned_docs/version-0.2.x/advanced-guides/Utils/Distance.md @@ -16,7 +16,9 @@ def hamming(u: npt.NDArray, v: npt.NDArray) -> np.float64: The function to calculate the normalized Hamming distance between two points. -$$\frac{(x_1 \neq y_1) + (x_2 \neq y_2) + \cdots + (x_n \neq y_n)}{n}$$ +$$ +\frac{(x_1 \neq y_1) + (x_2 \neq y_2) + \cdots + (x_n \neq y_n)}{n} +$$ **Parameters:** @@ -37,7 +39,9 @@ def euclidean(u: npt.NDArray[np.float64], v: npt.NDArray[np.float64]) -> np.floa Function to calculate the normalized Euclidean distance between two points. -$$\sqrt{(X_{1} - X_{1})^2 + (Y_{2} - Y_{2})^2 + \cdots + (Y_{n} - Y_{n})^2}$$ +$$ +\sqrt{(X_{1} - X_{1})^2 + (Y_{2} - Y_{2})^2 + \cdots + (Y_{n} - Y_{n})^2} +$$ **Parameters:** @@ -58,7 +62,9 @@ def cityblock(u: npt.NDArray[np.float64], v: npt.NDArray[np.float64]) -> np.floa Function to calculate the normalized Manhattan distance between two points. -$$\frac{(|X_{1} - X_{1}| + |Y_{2} - Y_{2}| + \cdots + |Y_{n} - Y_{n}|)}{n}$$ +$$ +\frac{(|X_{1} - X_{1}| + |Y_{2} - Y_{2}| + \cdots + |Y_{n} - Y_{n}|)}{n} +$$ **Parameters:** @@ -79,7 +85,9 @@ def minkowski(u: npt.NDArray[np.float64], v: npt.NDArray[np.float64], p: float = Function to calculate the normalized Minkowski distance between two points. -$$\frac{((|X_{1} - Y_{1}|^p + |X_{2} - Y_{2}|^p + \cdots + |X_{n} - Y_{n}|^p)^\frac{1}{p})}{n}$$ +$$ +\frac{((|X_{1} - Y_{1}|^p + |X_{2} - Y_{2}|^p + \cdots + |X_{n} - Y_{n}|^p)^\frac{1}{p})}{n} +$$ **Parameters:** diff --git a/versioned_docs/version-0.3.x/advanced-guides/Utils/Distance.md b/versioned_docs/version-0.3.x/advanced-guides/Utils/Distance.md index a3d758f8..1ac5aba8 100644 --- a/versioned_docs/version-0.3.x/advanced-guides/Utils/Distance.md +++ b/versioned_docs/version-0.3.x/advanced-guides/Utils/Distance.md @@ -16,7 +16,9 @@ def hamming(u: npt.NDArray, v: npt.NDArray) -> np.float64: The function to calculate the normalized Hamming distance between two points. -$$\frac{(x_1 \neq y_1) + (x_2 \neq y_2) + \cdots + (x_n \neq y_n)}{n}$$ +$$ +\frac{(x_1 \neq y_1) + (x_2 \neq y_2) + \cdots + (x_n \neq y_n)}{n} +$$ **Parameters:** @@ -37,7 +39,9 @@ def euclidean(u: npt.NDArray[np.float64], v: npt.NDArray[np.float64]) -> np.floa Function to calculate the normalized Euclidean distance between two points. -$$\sqrt{(X_{1} - X_{1})^2 + (Y_{2} - Y_{2})^2 + \cdots + (Y_{n} - Y_{n})^2}$$ +$$ +\sqrt{(X_{1} - X_{1})^2 + (Y_{2} - Y_{2})^2 + \cdots + (Y_{n} - Y_{n})^2} +$$ **Parameters:** @@ -58,7 +62,9 @@ def cityblock(u: npt.NDArray[np.float64], v: npt.NDArray[np.float64]) -> np.floa Function to calculate the normalized Manhattan distance between two points. -$$\frac{(|X_{1} - X_{1}| + |Y_{2} - Y_{2}| + \cdots + |Y_{n} - Y_{n}|)}{n}$$ +$$ +\frac{(|X_{1} - X_{1}| + |Y_{2} - Y_{2}| + \cdots + |Y_{n} - Y_{n}|)}{n} +$$ **Parameters:** @@ -79,7 +85,9 @@ def minkowski(u: npt.NDArray[np.float64], v: npt.NDArray[np.float64], p: float = Function to calculate the normalized Minkowski distance between two points. -$$\frac{((|X_{1} - Y_{1}|^p + |X_{2} - Y_{2}|^p + \cdots + |X_{n} - Y_{n}|^p)^\frac{1}{p})}{n}$$ +$$ +\frac{((|X_{1} - Y_{1}|^p + |X_{2} - Y_{2}|^p + \cdots + |X_{n} - Y_{n}|^p)^\frac{1}{p})}{n} +$$ **Parameters:** diff --git a/versioned_docs/version-0.4.x/advanced-guides/Utils/Distance.md b/versioned_docs/version-0.4.x/advanced-guides/Utils/Distance.md index a3d758f8..1ac5aba8 100644 --- a/versioned_docs/version-0.4.x/advanced-guides/Utils/Distance.md +++ b/versioned_docs/version-0.4.x/advanced-guides/Utils/Distance.md @@ -16,7 +16,9 @@ def hamming(u: npt.NDArray, v: npt.NDArray) -> np.float64: The function to calculate the normalized Hamming distance between two points. -$$\frac{(x_1 \neq y_1) + (x_2 \neq y_2) + \cdots + (x_n \neq y_n)}{n}$$ +$$ +\frac{(x_1 \neq y_1) + (x_2 \neq y_2) + \cdots + (x_n \neq y_n)}{n} +$$ **Parameters:** @@ -37,7 +39,9 @@ def euclidean(u: npt.NDArray[np.float64], v: npt.NDArray[np.float64]) -> np.floa Function to calculate the normalized Euclidean distance between two points. -$$\sqrt{(X_{1} - X_{1})^2 + (Y_{2} - Y_{2})^2 + \cdots + (Y_{n} - Y_{n})^2}$$ +$$ +\sqrt{(X_{1} - X_{1})^2 + (Y_{2} - Y_{2})^2 + \cdots + (Y_{n} - Y_{n})^2} +$$ **Parameters:** @@ -58,7 +62,9 @@ def cityblock(u: npt.NDArray[np.float64], v: npt.NDArray[np.float64]) -> np.floa Function to calculate the normalized Manhattan distance between two points. -$$\frac{(|X_{1} - X_{1}| + |Y_{2} - Y_{2}| + \cdots + |Y_{n} - Y_{n}|)}{n}$$ +$$ +\frac{(|X_{1} - X_{1}| + |Y_{2} - Y_{2}| + \cdots + |Y_{n} - Y_{n}|)}{n} +$$ **Parameters:** @@ -79,7 +85,9 @@ def minkowski(u: npt.NDArray[np.float64], v: npt.NDArray[np.float64], p: float = Function to calculate the normalized Minkowski distance between two points. -$$\frac{((|X_{1} - Y_{1}|^p + |X_{2} - Y_{2}|^p + \cdots + |X_{n} - Y_{n}|^p)^\frac{1}{p})}{n}$$ +$$ +\frac{((|X_{1} - Y_{1}|^p + |X_{2} - Y_{2}|^p + \cdots + |X_{n} - Y_{n}|^p)^\frac{1}{p})}{n} +$$ **Parameters:** diff --git a/versioned_docs/version-0.5.x/about-us.mdx b/versioned_docs/version-0.5.x/about-us.mdx new file mode 100644 index 00000000..0d837149 --- /dev/null +++ b/versioned_docs/version-0.5.x/about-us.mdx @@ -0,0 +1,50 @@ +--- +sidebar_position: 3 +pagination_prev: null +lastUpdatedAt: 2023/05/30 +author: João Paulo +last_update: + date: 2023/05/30 + author: João Paulo +--- + +import TeamUser from '@site/src/components/TeamUser'; + +# About us + +## History + +The AISP, or Artificial Immune Systems Package, had its origins in a research project at the IFNMG (Federal Institute of Northern Minas Gerais) on the Salinas campus. Starting on May 2, 2022, with the aim of starting the creation of an open software package that allows the application, study and popularization of techniques belonging to the area of artificial immune systems. + +--- + +## Team of collaborators + +### Coordinator + +
+ + + +
+ +--- + +### Students + +
+ + + +
\ No newline at end of file diff --git a/versioned_docs/version-0.5.x/advanced-guides/Core/_category_.json b/versioned_docs/version-0.5.x/advanced-guides/Core/_category_.json new file mode 100644 index 00000000..650683c4 --- /dev/null +++ b/versioned_docs/version-0.5.x/advanced-guides/Core/_category_.json @@ -0,0 +1,3 @@ +{ + "description": "The functions perform detector checks and utilize Numba decorators for Just-In-Time compilation" +} \ No newline at end of file diff --git a/versioned_docs/version-0.5.x/advanced-guides/Core/negative-selection.md b/versioned_docs/version-0.5.x/advanced-guides/Core/negative-selection.md new file mode 100644 index 00000000..a85f9771 --- /dev/null +++ b/versioned_docs/version-0.5.x/advanced-guides/Core/negative-selection.md @@ -0,0 +1,86 @@ +--- +last_update: + date: 2025/05/17 + author: João Paulo +--- + +# Negative Selection + +The functions perform detector checks and utilize Numba decorators for Just-In-Time compilation + +## Function check_detector_bnsa_validity(...) + +```python +def check_detector_bnsa_validity( + x_class: npt.NDArray, + vector_x: npt.NDArray, + aff_thresh: float +) -> bool: +``` + +Checks the validity of a candidate detector (vector_x) against samples from a class (x_class) using the Hamming distance. A detector is considered INVALID if its distance to any sample in ``x_class`` is less than or equal to ``aff_thresh``. + +**Parameters**: + +* x_class (``npt.NDArray``): Array containing the class samples. Expected shape: (n_samples, n_features). +* vector_x (``npt.NDArray``): Array representing the detector. Expected shape: (n_features,). +* aff_thresh (``float``): Affinity threshold. + +**returns**: + +* True if the detector is valid, False otherwise. + +--- + +## Function bnsa_class_prediction(...) + +```python +def bnsa_class_prediction( + features: npt.NDArray, + class_detectors: npt.NDArray, + aff_thresh: float +) -> int: +``` + +Defines the class of a sample from the non-self detectors. + +**Parameters**: + +* features (``npt.NDArray``): binary sample to be classified (shape: [n_features]). +* class_detectors (``npt.NDArray``): Array containing the detectors of all classes +(shape: [n_classes, n_detectors, n_features]). +* aff_thresh (``float``): Affinity threshold that determines whether a detector recognizes the sample as non-self. + +**returns**: + +* int: Index of the predicted class. Returns -1 if it is non-self for all classes. + +--- + +## Function check_detector_rnsa_validity(...) + +```python +def check_detector_rnsa_validity( + x_class: npt.NDArray, + vector_x: npt.NDArray, + threshold: float, + metric: int, + p: float +) -> bool: +``` + +Checks the validity of a candidate detector (vector_x) against samples from a class (x_class) using the Hamming distance. A detector is considered INVALID if its distance to any sample in ``x_class`` is less than or equal to ``aff_thresh``. + +**Parameters**: + +* x_class (``npt.NDArray``): Array containing the class samples. Expected shape: (n_samples, n_features). +* vector_x (``npt.NDArray``): Array representing the detector. Expected shape: (n_features,). +* threshold (``float``): threshold. +* metric (``int``): Distance metric to be used. Available options: [0 (Euclidean), 1 (Manhattan), 2 (Minkowski)] +* p (``float``): Parameter for the Minkowski distance (used only if `metric` is "minkowski"). + +**returns**: + +* int: Index of the predicted class. Returns -1 if it is non-self for all classes. + +--- diff --git a/versioned_docs/version-0.5.x/advanced-guides/Utils/Display.md b/versioned_docs/version-0.5.x/advanced-guides/Utils/Display.md new file mode 100644 index 00000000..51c3bbdb --- /dev/null +++ b/versioned_docs/version-0.5.x/advanced-guides/Utils/Display.md @@ -0,0 +1,152 @@ +# Display + +Utility Functions for Displaying Algorithm Information + +## def _supports_box_drawing() + +```python +def _supports_box_drawing() -> bool +``` + +Function to check if the terminal supports boxed characters. + +**Returns**: + +* ***bool*** (`bool`): True if the terminal likely supports boxed characters, False otherwise. + +--- + +## class TableFormatter + +Class to format tabular data into strings for display in the console. + +**Parameters**: + +* ***headers*** (`Mapping[str, int]`): Mapping of column names to their respective widths, in the format `{column_name: column_width}`. + +**Raises**: + +* `ValueError`: If `headers` is empty or not a valid mapping. + +--- + +### def _border(left, middle, right, line, new_line=True) + +```python +def _border(self, left: str, middle: str, right: str, line: str, new_line: bool = True) -> str +``` + +Create a horizontal border for the table. + +**Parameters**: + +* ***left*** (`str`): Character on the left side of the border. +* ***middle*** (`str`): Character separator between columns. +* ***right*** (`str`): Character on the right side of the border. +* ***line*** (`str`): Character used to fill the border. +* ***new_line*** (`bool`, optional): If True, adds a line break before the border (default is True). + +**Returns**: + +* ***border*** (`str`): String representing the horizontal border. + +--- + +### def get_header() + +```python +def get_header(self) -> str +``` + +Generate the table header, including the top border, column headings, and separator line. + +**Returns**: + +* ***header*** (`str`): Formatted string of the table header. + +--- + +### def get_row(values) + +```python +def get_row(self, values: Mapping[str, Union[str, int, float]]) -> str +``` + +Generate a formatted row for the table data. + +**Parameters**: + +* ***values*** (`Mapping[str, Union[str, int, float]]`): Dictionary with values for each column, in the format `{column_name: value}`. + +**Returns**: + +* ***row*** (`str`): Formatted string of the table row. + +--- + +### def get_bottom(new_line=False) + +```python +def get_bottom(self, new_line: bool = False) -> str +``` + +Generate the table's bottom border. + +**Parameters**: + +* ***new_line*** (`bool`, optional): If True, adds a line break before the border (default is False). + +**Returns**: + +* ***bottom*** (`str`): Formatted string for the bottom border. + +--- + +## class ProgressTable(TableFormatter) + +Class to display a formatted table in the console to track the algorithm's progress. + +**Parameters**: + +* ***headers*** (`Mapping[str, int]`): Mapping `{column_name: column_width}`. +* ***verbose*** (`bool`): If False, prints nothing to the terminal. + +**Raises**: + +* `ValueError`: If `headers` is empty or not a valid mapping. + +--- + +### def _print_header() + +```python +def _print_header(self) -> None +``` + +Print the table header. + +--- + +### def update(values) + +```python +def update(self, values: Mapping[str, Union[str, int, float]]) -> None +``` + +Add a new row of values to the table. + +**Parameters**: + +* ***values*** (`Mapping[str, Union[str, int, float]]`): Keys must match the columns defined in headers. + +--- + +### def finish() + +```python +def finish(self) -> None +``` + +End the table display, printing the bottom border and total time. + +--- diff --git a/versioned_docs/version-0.5.x/advanced-guides/Utils/Distance.md b/versioned_docs/version-0.5.x/advanced-guides/Utils/Distance.md new file mode 100644 index 00000000..1ac5aba8 --- /dev/null +++ b/versioned_docs/version-0.5.x/advanced-guides/Utils/Distance.md @@ -0,0 +1,180 @@ +--- +last_update: + date: 2025/08/28 + author: João Paulo +--- + +# Distance + +Utility functions for normalized distance between arrays with numba decorators. + +## def hamming(...) + +```python +def hamming(u: npt.NDArray, v: npt.NDArray) -> np.float64: +``` + +The function to calculate the normalized Hamming distance between two points. + +$$ +\frac{(x_1 \neq y_1) + (x_2 \neq y_2) + \cdots + (x_n \neq y_n)}{n} +$$ + +**Parameters:** + +* u (``npt.NDArray``): Coordinates of the first point. +* v (``npt.NDArray``): Coordinates of the second point. + +**Returns:** + +* Distance (``float``) between the two points. + +--- + +## def euclidean(...) + +```python +def euclidean(u: npt.NDArray[np.float64], v: npt.NDArray[np.float64]) -> np.float64: +``` + +Function to calculate the normalized Euclidean distance between two points. + +$$ +\sqrt{(X_{1} - X_{1})^2 + (Y_{2} - Y_{2})^2 + \cdots + (Y_{n} - Y_{n})^2} +$$ + +**Parameters:** + +* u (``npt.NDArray``): Coordinates of the first point. +* v (``npt.NDArray``): Coordinates of the second point. + +**Returns:** + +* Distance (``float``) between the two points. + +--- + +## def cityblock(...) + +```python +def cityblock(u: npt.NDArray[np.float64], v: npt.NDArray[np.float64]) -> np.float64: +``` + +Function to calculate the normalized Manhattan distance between two points. + +$$ +\frac{(|X_{1} - X_{1}| + |Y_{2} - Y_{2}| + \cdots + |Y_{n} - Y_{n}|)}{n} +$$ + +**Parameters:** + +* u (``npt.NDArray``): Coordinates of the first point. +* v (``npt.NDArray``): Coordinates of the second point. + +**Returns:** + +* Distance (``float``) between the two points. + +--- + +## def minkowski(...) + +```python +def minkowski(u: npt.NDArray[np.float64], v: npt.NDArray[np.float64], p: float = 2.0): +``` + +Function to calculate the normalized Minkowski distance between two points. + +$$ +\frac{((|X_{1} - Y_{1}|^p + |X_{2} - Y_{2}|^p + \cdots + |X_{n} - Y_{n}|^p)^\frac{1}{p})}{n} +$$ + +**Parameters:** + +* u (``npt.NDArray``): Coordinates of the first point. +* v (``npt.NDArray``): Coordinates of the second point. +* p float: The p parameter defines the type of distance to be calculated: + * p = 1: **Manhattan** distance — sum of absolute differences. + * p = 2: **Euclidean** distance — sum of squared differences (square root). + * p > 2: **Minkowski** distance with an increasing penalty as p increases. + +**Returns:** + +* Distance (``float``) between the two points. + +--- + +## def compute_metric_distance(...) + +```python +def compute_metric_distance( + u: npt.NDArray[np.float64], + v: npt.NDArray[np.float64], + metric: int, + p: np.float64 = 2.0 +) -> np.float64: +``` + +Function to calculate the distance between two points by the chosen ``metric``. + +**Parameters:** + +* u (``npt.NDArray``): Coordinates of the first point. +* v (``npt.NDArray``): Coordinates of the second point. +* metric (``int``): Distance metric to be used. Available options: [0 (Euclidean), 1 (Manhattan), 2 (Minkowski)] +* p (``float``): Parameter for the Minkowski distance (used only if `metric` is "minkowski"). + +**Returns:** + +* Distance (``double``) between the two points with the selected metric. + +--- + +## def min_distance_to_class_vectors(...) + +```python +def min_distance_to_class_vectors( + x_class: npt.NDArray, + vector_x: npt.NDArray, + metric: int, + p: float = 2.0 +) -> float: +``` + +Calculates the minimum distance between an input vector and the vectors of a class. + +**Parameters:** + +* x_class (``npt.NDArray``): Array containing the class vectors to be compared with the input vector. Expected shape: (n_samples, n_features). +* vector_x (``npt.NDArray``): Vector to be compared with the class vectors. Expected shape: (n_features,). +* metric (``int``): Distance metric to be used. Available options: [0 (Euclidean), 1 (Manhattan), 2 (Minkowski)] +* p (``float``): Parameter for the Minkowski distance (used only if `metric` is "minkowski"). + +**Returns:** + +* float: The minimum distance calculated between the input vector and the class vectors. +* Returns -1.0 if the input dimensions are incompatible. + +--- + +## def get_metric_code(...) + +```python +def get_metric_code(metric: str) -> int: +``` + +Returns the numeric code associated with a distance metric. + +**Parameters:** + +* metric (str): Name of the metric. Can be "euclidean", "manhattan", "minkowski" or "hamming". + +**Raises** + +* ``ValueError``: If the metric provided is not supported + +**Returns:** + +* ``int``: Numeric code corresponding to the metric. + +--- diff --git a/versioned_docs/version-0.5.x/advanced-guides/Utils/Metrics.md b/versioned_docs/version-0.5.x/advanced-guides/Utils/Metrics.md new file mode 100644 index 00000000..d65da92c --- /dev/null +++ b/versioned_docs/version-0.5.x/advanced-guides/Utils/Metrics.md @@ -0,0 +1,39 @@ +--- +sidebar_position: 1 +title: Metrics +sidebar_label: Metrics +lastUpdatedAt: 2025/04/04 +author: João Paulo +--- + +The metrics file provides utilities to measure, analyze, and compare the performance of the package's algorithms in a standardized way. + +#### def accuracy_score(...) + +```python +def accuracy_score( + y_true: Union[npt.NDArray, list], + y_pred: Union[npt.NDArray, list] +) -> float +``` + +Function to calculate precision accuracy based on lists of true labels and +predicted labels. + +**Parameters**: + +* **_y_true_** (``Union[npt.NDArray, list]``): Ground truth (correct) labels. + Expected to be of the same length as `y_pred`. +* **_y_pred_** (``Union[npt.NDArray, list]``): Predicted labels. Expected to + be of the same length as `y_true`. + +Returns: + +* **_Accuracy_** (``float``): The ratio of correct predictions to the total +number of predictions. + +**Raises**: + +* `ValueError`: If `y_true` or `y_pred` are empty or if they do not have the same length. + +--- diff --git a/versioned_docs/version-0.5.x/advanced-guides/Utils/Multiclass.md b/versioned_docs/version-0.5.x/advanced-guides/Utils/Multiclass.md new file mode 100644 index 00000000..dc919f82 --- /dev/null +++ b/versioned_docs/version-0.5.x/advanced-guides/Utils/Multiclass.md @@ -0,0 +1,54 @@ +--- +sidebar_position: 1 +title: Multiclass +sidebar_label: Multiclass +lastUpdatedAt: 2025/04/04 +author: João Paulo +--- + +This file contains internal utility functions designed to simplify data manipulation and processing in multiclass classification scenarios within the AISP package. + +## def slice_index_list_by_class(...) + +```python +def slice_index_list_by_class(classes: Union[npt.NDArray, list], y: npt.NDArray) -> dict +``` + +The function ``slice_index_list_by_class(...)``, separates the indices of the lines \ +according to the output class, to loop through the sample array, only in positions where \ +the output is the class being trained. + +**Parameters**: + +* ***classes*** (``list or npt.NDArray``): list with unique classes. +* ***y*** (npt.NDArray): Receives a ``y``[``N sample``] array with the output classes of the ``X`` sample array. + +**returns**: + +* dict: A dictionary with the list of array positions(``y``), with the classes as key. + +--- + +## def predict_knn_affinity(...) + +```python +def predict_knn_affinity( + X: npt.NDArray, + k: int, + all_cell_vectors: List[Tuple[Union[str, int], npt.NDArray]], + affinity_func: Callable[[npt.NDArray, npt.NDArray], float] +) -> npt.NDArray +``` + +Function to predict classes using k-nearest neighbors and trained cells. + +**Parameters:** + +* ***X*** (`npt.NDArray`): Input data to be classified. +* ***k*** (`int`): Number of nearest neighbors to consider for prediction. +* ***all_cell_vectors*** (`List[Tuple[Union[str, int], npt.NDArray]]`): List of tuples containing (class_name, cell vector) pairs. +* ***affinity_func*** (`Callable[[npt.NDArray, npt.NDArray], float]`): Function that takes two vectors and returns an affinity value. + +**Returns:** + +* `npt.NDArray`: Array of predicted labels for each sample in X, based on the k nearest neighbors. diff --git a/versioned_docs/version-0.5.x/advanced-guides/Utils/Random.md b/versioned_docs/version-0.5.x/advanced-guides/Utils/Random.md new file mode 100644 index 00000000..8bcd0393 --- /dev/null +++ b/versioned_docs/version-0.5.x/advanced-guides/Utils/Random.md @@ -0,0 +1,17 @@ +# Random + +Utility functions for random number generation and reproducibility. + +## Function set_seed_numba(...) + +```python +@njit(cache=True) +def set_seed_numba(seed: int) +``` + +Set the seed for random numbers used by functions compiled with Numba. + +**Parameters**: + +* **seed**: `int` + Integer value used to initialize Numba's random number generator. diff --git a/versioned_docs/version-0.5.x/advanced-guides/Utils/Sanitizers.md b/versioned_docs/version-0.5.x/advanced-guides/Utils/Sanitizers.md new file mode 100644 index 00000000..b57a8053 --- /dev/null +++ b/versioned_docs/version-0.5.x/advanced-guides/Utils/Sanitizers.md @@ -0,0 +1,85 @@ +--- +last_update: + date: 2025/05/17 + author: João Paulo +--- + +# Sanitizers + +## def sanitize_choice(...) + +```python +def sanitize_choice(value: T, valid_choices: Iterable[T], default: T) -> T +``` + +The function ``sanitize_choice(...)``, returns the value if it is present in the set of valid choices; otherwise, returns the default value. + +**Parameters:** + +* ***value*** (``T``): The value to be checked. +* ***valid_choices*** (``Iterable[T]``): A collection of valid choices. +* ***default***: The default value to be returned if ``value`` is not in ``valid_choices``. + +**Returns:** + +* `T`: The original value if valid, or the default value if not. + +--- + +## def sanitize_param(...) + +```python +def sanitize_param(value: T, default: T, condition: Callable[[T], bool]) -> T: +``` + +The function ``sanitize_param(...)``, returns the value if it satisfies the specified condition; otherwise, returns the default value. + +**Parameters:** + +* value (``T``): The value to be checked. +* default (``T``): The default value to be returned if the condition is not satisfied. +* condition (``Callable[[T], bool]``): A function that takes a value and returns a boolean, determining if the value is valid. + +**Returns:** + +* `T`: The original value if the condition is satisfied, or the default value if not. + +--- + +## def sanitize_seed(...) + +```python +def sanitize_seed(seed: Any) -> Optional[int]: +``` + +The function ``sanitize_param(...)``, returns the seed if it is a non-negative integer; otherwise, returns None. + +**Parameters:** + +* seed (``Any``): The seed value to be validated. + +**Returns:** + +* ``Optional[int]``: The original seed if it is a non-negative integer, or ``None`` if it is invalid. + +--- + +## def sanitize_bounds(...) + +```python +def sanitize_bounds( + bounds: Any, + problem_size: int +) -> Dict[str, npt.NDArray[np.float64]] +``` + +The function ``sanitize_bounds(...)``, validate and normalize feature bounds. + +**Parameters:** + +* ***bounds*** (``Any``): he input bounds, which must be either None or a dictionary with 'low' and 'high' keys. +* ***problem_size*** (``int``): The expected length for the normalized bounds lists, corresponding to the number of features in the problem. + +**Returns:** + +* `Dict[str, list]`: Dictionary ``{'low': [low_1, ..., low_N], 'high': [high_1, ..., high_N]}``. diff --git a/versioned_docs/version-0.5.x/advanced-guides/Utils/Validation.md b/versioned_docs/version-0.5.x/advanced-guides/Utils/Validation.md new file mode 100644 index 00000000..c0d5bba6 --- /dev/null +++ b/versioned_docs/version-0.5.x/advanced-guides/Utils/Validation.md @@ -0,0 +1,104 @@ +# Validation + +## def detect_vector_data_type(...) + +```python +def detect_vector_data_type( + vector: npt.NDArray +) -> FeatureType: +``` + +Detects the type of data in a given vector. + +This function analyzes the input vector and classifies its data as one of the supported types: + +* **binary**: Boolean values (`True`/`False`) or integer `0`/`1`. +* **continuous**: Float values within the normalized range `[0.0, 1.0]`. +* **ranged**: Float values outside the normalized range. + +### Parameters + +* `vector` (`npt.NDArray`): An array containing the data to be classified. + +### Returns + +* `FeatureType` (`Literal["binary-features", "continuous-features", "ranged-features"]`): The detected type of data in the vector. + +### Raises + +* `UnsupportedDataTypeError`: Raised if the vector contains an unsupported data type. + +--- + +## def check_array_type(...) + +```python +def check_array_type(x, name: str = "X") -> npt.NDArray: +``` + +Ensure X is a numpy array. Convert from list if needed. + +### Parameters + +* `x` (`Any`): Array, containing the samples and their characteristics, \[`N samples` (rows)\]\[`N features` (columns)\]. +* `name` (`str`, default='X'): Variable name used in error messages. + +### Returns + +* `npt.NDArray`: The converted or validated array. + +### Raises + +* `TypeError`: If X or y are not ndarrays or have incompatible shapes. + +--- + +## def check_shape_match(...) + +```python +def check_shape_match(x: npt.NDArray, y: npt.NDArray): +``` + +Ensure X and y have compatible first dimensions. + +### Parameters + +* `x` (`npt.NDArray`): Array, containing the samples and their characteristics, \[`N samples` (rows)\]\[`N features` (columns)\]. +* `y` (`npt.NDArray`): Array of target classes of `x` with [`N samples` (lines)]. + +### Raises + +* `TypeError`: If x or y are not ndarrays or have incompatible shapes. + +--- + +## def check_feature_dimension(...) + +```python +def check_feature_dimension(x: npt.NDArray, expected: int): +``` + +Ensure X has the expected number of features. + +### Parameters + +* `x` (`npt.NDArray`): Input array for prediction, containing the samples and their characteristics, \[`N samples` (rows)\]\[`N features` (columns)\]. +* `expected` (`int`): Expected number of features per sample (columns in X). + +### Raises + +* `FeatureDimensionMismatch`: If the number of features in X does not match the expected number. + +--- + +## def check_binary_array(...) + +```python +def check_binary_array(x: npt.NDArray): +``` + +Ensure X contains only 0 and 1. + +### Raises + +* `ValueError`: If feature_type is binary-features and X contains values that are not composed only of 0 and 1. diff --git a/versioned_docs/version-0.5.x/advanced-guides/Utils/_category_.json b/versioned_docs/version-0.5.x/advanced-guides/Utils/_category_.json new file mode 100644 index 00000000..c57d4b80 --- /dev/null +++ b/versioned_docs/version-0.5.x/advanced-guides/Utils/_category_.json @@ -0,0 +1,4 @@ +{ + "label": "Utils", + "description": "Utility functions and helpers for development." +} \ No newline at end of file diff --git a/versioned_docs/version-0.5.x/advanced-guides/_category_.json b/versioned_docs/version-0.5.x/advanced-guides/_category_.json new file mode 100644 index 00000000..020788b9 --- /dev/null +++ b/versioned_docs/version-0.5.x/advanced-guides/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Advanced Guides", + "position": 2.6, + "link": { + "type": "generated-index", + "description": "Explore the advanced documentation of the library, covering the base classes and the utility functions in utils for metrics and multiclass classification handling." + } +} \ No newline at end of file diff --git a/versioned_docs/version-0.5.x/advanced-guides/base-module/_category_.json b/versioned_docs/version-0.5.x/advanced-guides/base-module/_category_.json new file mode 100644 index 00000000..d6566b36 --- /dev/null +++ b/versioned_docs/version-0.5.x/advanced-guides/base-module/_category_.json @@ -0,0 +1,5 @@ +{ + "label": "Base module", + "position": 1, + "description": "Base class for classification algorithm." +} \ No newline at end of file diff --git a/versioned_docs/version-0.5.x/advanced-guides/base-module/core/Base.md b/versioned_docs/version-0.5.x/advanced-guides/base-module/core/Base.md new file mode 100644 index 00000000..2d458c1b --- /dev/null +++ b/versioned_docs/version-0.5.x/advanced-guides/base-module/core/Base.md @@ -0,0 +1,57 @@ +--- +sidebar_position: 1 +title: Base class +sidebar_label: Base +lastUpdatedAt: 2025/08/19 +author: João Paulo +keywords: + - Base Class + - Model Base + - Scikit-learn Compatibility + - get_params + - set_params + - Random Seed + - Python Classes +--- + +Base class for scikit-learn API compatibility. + +Provides the `get_params` and `set_params` methods for compatibility with the scikit-learn API, allowing access to the model's public parameters. + +### Function set_params(...) + +```python +def set_params(self, **params) +``` + +Set the parameters of the instance. Ensures compatibility with scikit-learn functions. + +**Parameters**: + +* **params**: ``dict`` + Dictionary of parameters to set as attributes on the instance. Only public attributes (not starting with "_") are modified. + +**Returns**: + +* self: `Base` + Returns the instance itself after setting the parameters. + +--- + +### Function get_params(...) + +```python +def get_params(self, deep: bool = True) -> dict +``` + +Return a dictionary with the object's main parameters. Ensures compatibility with scikit-learn functions. + +**Parameters**: + +* **deep**: `bool` + Ignored in this implementation but included for scikit-learn compatibility. + +**Returns**: + +* params: `dict` + Dictionary containing the object's attributes that do not start with "_". diff --git a/versioned_docs/version-0.5.x/advanced-guides/base-module/core/Classifier.md b/versioned_docs/version-0.5.x/advanced-guides/base-module/core/Classifier.md new file mode 100644 index 00000000..86baa60f --- /dev/null +++ b/versioned_docs/version-0.5.x/advanced-guides/base-module/core/Classifier.md @@ -0,0 +1,92 @@ +--- +sidebar_position: 2 +title: Base class for classification algorithm. +sidebar_label: BaseClassifier +lastUpdatedAt: 2025/08/19 +author: João Paulo +keywords: + - Base Classifier + - Classification + - Abstract Base Class + - BaseClassifier + - Machine Learning + - Supervised Learning + - fit Method + - predict Method + - score Method + - Model Evaluation + - Accuracy + - Python ML Classes + - RNSA + - BNSA +--- + +## ``class BaseClassifier(ABC, Base)`` + +Base class for classification algorithms, defining the abstract methods ``fit`` and ``predict``, and implementing the ``get_params`` method. + +## Abstract methods + +### def fit(...) + +```python +def fit(self, X: npt.NDArray, y: npt.NDArray, verbose: bool = True) +``` + +Fit the model to the training data. + +Implementation: + +- [RNSA](../../../aisp-techniques/negative-selection/RNSA.md#Function-fit) +- [BNSA](../../../aisp-techniques/negative-selection/BNSA.md#Function-fit) +- [AIRS](../../../aisp-techniques/clonal-selection-algorithms/airs/#Function-fit) + +### def predict(...) + +```python +def predict(self, X) -> Optional[npt.NDArray]: +``` + +Performs label prediction for the given data. + +Implementation: + +- [RNSA](../../../aisp-techniques/negative-selection/RNSA.md#Function-predict) +- [BNSA](../../../aisp-techniques/negative-selection/BNSA.md#Function-predict) +- [AIRS](../../../aisp-techniques/clonal-selection-algorithms/airs/#Function-predict) + +--- + +## Methods + +### def score(...) + +```python +def score(self, X: npt.NDArray, y: list) -> float +``` + +Score function calculates forecast accuracy. + +This function performs the prediction of X and checks how many elements are equal between vector y and y_predicted. +This function was added for compatibility with some scikit-learn functions. + +**Parameters**: + +- ***X***: ``np.ndarray`` + Feature set with shape (n_samples, n_features). +- ***y***: ``np.ndarray`` + True values with shape (n_samples,). + +**Returns**: + +- accuracy: ``float`` The accuracy of the model. + +### Function _slice_index_list_by_class(...) + +The function ``__slice_index_list_by_class(...)``, separates the indices of the lines according to the output class, to go through the sample array, only in the positions that the output is the class that is being trained: + +```python +def __slice_index_list_by_class(self, y: npt.NDArray) -> dict: +``` + +Returns a dictionary with the classes as key and the indices in ``X`` of the samples. diff --git a/versioned_docs/version-0.5.x/advanced-guides/base-module/core/Clusterer.md b/versioned_docs/version-0.5.x/advanced-guides/base-module/core/Clusterer.md new file mode 100644 index 00000000..559c3049 --- /dev/null +++ b/versioned_docs/version-0.5.x/advanced-guides/base-module/core/Clusterer.md @@ -0,0 +1,102 @@ +--- +sidebar_position: 3 +title: Base class for clustering algorithm. +sidebar_label: BaseClusterer +lastUpdatedAt: 2025/08/19 +author: João Paulo +keywords: + - Base Clusterer + - Clustering + - Unsupervised Learning + - BaseClusterer + - Abstract Base Class + - fit Method + - predict Method + - fit_predict Method + - AiNet + - Cluster Prediction + - Python ML Classes +--- + + +## ``BaseClusterer(ABC, Base)`` + +Abstract base class for clustering algorithms. + +This class defines the core interface for clustering models. It enforces +the implementation of the **`fit`** and **`predict`** methods in all derived classes, +and provides a default implementation for **`fit_predict`** and **`get_params`**. + +--- + +### Function fit(...) + +```python +def fit(self, X: npt.NDArray, verbose: bool = True) -> BaseClusterer +``` + +Fit the model to the training data. +This abstract method must be implemented by subclasses. + +**Parameters**: + +* ***X***: `npt.NDArray` + Input data used for training the model. +* ***verbose***: `bool`, default=True + Flag to enable or disable detailed output during training. + +**Returns**: + +* ***self***: + Instance of the class that implements this method. + +**Implementation**: + +* [AiNet](../../../aisp-techniques/immune-network-theory/AiNet.md#Function-fit) + +--- + +### Function predict(...) + +```python +def predict(self, X: npt.NDArray) -> Optional[npt.NDArray] +``` + +Generate predictions based on the input data. +This abstract method must be implemented by subclasses. + +**Parameters**: + +* ***X***: `npt.NDArray` + Input data for which predictions will be generated. + +**Returns**: + +* ***predictions***: `Optional[npt.NDArray]` + Predicted cluster labels for each input sample, or `None` if prediction is not possible. + +**Implementation**: + +* [AiNet](../../../aisp-techniques/immune-network-theory/AiNet.md#Function-predict) + +--- + +### Function fit_predict(...) + +```python +def fit_predict(self, X: npt.NDArray, verbose: bool = True) -> Optional[npt.NDArray] +``` + +Convenience method that combines `fit` and `predict` in a single call. + +**Parameters**: + +* ***X***: `npt.NDArray` + Input data for which predictions will be generated. +* ***verbose***: `bool`, default=True + Flag to enable or disable detailed output during training. + +**Returns**: + +* ***predictions***: `Optional[npt.NDArray]` + Predicted cluster labels for each input sample, or `None` if prediction is not possible. diff --git a/versioned_docs/version-0.5.x/advanced-guides/base-module/core/Optimizer.md b/versioned_docs/version-0.5.x/advanced-guides/base-module/core/Optimizer.md new file mode 100644 index 00000000..aa33b86c --- /dev/null +++ b/versioned_docs/version-0.5.x/advanced-guides/base-module/core/Optimizer.md @@ -0,0 +1,173 @@ +--- +sidebar_position: 4 +title: Base class for optimization algorithms. +sidebar_label: BaseOptimizer +lastUpdatedAt: 2025/08/19 +author: João Paulo +keywords: + - BaseOptimizer + - base class + - optimization algorithms + - abstract base class + - machine learning optimization + - supervised learning + - optimize method + - objective function + - model evaluation + - Python ML classes + - Clonalg + - metaheuristics +--- + + +This class defines the core interface for optimization strategies and +keeps track of the cost history, evaluated solutions, and the best solution found. Subclasses must implement +``optimize`` and ``objective_function``. + +--- + +### Properties + +#### `cost_history` + +```python +@property +def cost_history(self) -> List[float] +``` + +Returns the history of costs during optimization. + +--- + +#### `solution_history` + +```python +@property +def solution_history(self) -> List +``` + +Returns the history of evaluated solutions. + +--- + +#### `best_solution` + +```python +@property +def best_solution(self) -> Optional[Any] +``` + +Returns the best solution found so far, or `None` if unavailable. + +--- + +#### `best_cost` + +```python +@property +def best_cost(self) -> Optional[float] +``` + +Returns the cost of the best solution found so far, or `None` if unavailable. + +--- + +## Functions + +### Function _record_best(...) + +```python +def _record_best(self, cost: float, best_solution: Any) -> None +``` + +Record a new cost value and update the best solution if improved. + +**Parameters**: + +* ***cost***: `float` - Cost value to be added to the history. + +--- + +### Function get_report() + +```python +def get_report(self) -> str +``` + +Generate a formatted summary report of the optimization process. The report includes the best solution, +its associated cost, and the evolution of cost values per iteration. + +**Returns**: + +* **report**: `str` - A formatted string containing the optimization summary. + +--- + +### Function register(...) + +```python +def register(self, alias: str, function: Callable[..., Any]) -> None +``` + +Register a function dynamically in the optimizer instance. + +**Parameters**: + +* ***alias***: `str` - Name used to access the function as an attribute. +* ***function***: `Callable[..., Any]` - Callable to be registered. + +**Raises**: + +* **TypeError**: If `function` is not callable. +* **AttributeError**: If `alias` is protected and cannot be modified, or if `alias` does not exist in the + optimizer class. + +--- + +### Function reset() + +```python +def reset(self) +``` + +Reset the object's internal state, clearing history and resetting values. + +--- + +### Abstract methods + +#### Function optimize(...) + +```python +def optimize(self, max_iters: int = 50, n_iter_no_change=10, verbose: bool = True) -> Any +``` + +Execute the optimization process. This method must be implemented by the subclass to define how the optimization strategy explores the search space. + +**Parameters**: + +* ***max_iters***: `int` - Maximum number of iterations. +* ***n_iter_no_change***: `int`, default=10 - The maximum number of iterations without updating the best solution. +* ***verbose***: `bool`, default=True - Flag to enable or disable detailed output during optimization. + +**Implementation**: + +* [Clonalg](../../../aisp-techniques/clonal-selection-algorithms/clonalg.md#Function-optimize) + +--- + +#### Function affinity_function(...) + +```python +def affinity_function(self, solution: Any) -> float +``` + +Evaluate the affinity of a candidate solution. This method must be implemented by the subclass to define the problem-specific. + +**Parameters**: + +* ***solution***: `Any` - Candidate solution to be evaluated. + +**Returns**: + +* **cost**: `float` - Cost value associated with the given solution. diff --git a/versioned_docs/version-0.5.x/advanced-guides/base-module/immune/cell.md b/versioned_docs/version-0.5.x/advanced-guides/base-module/immune/cell.md new file mode 100644 index 00000000..1ceacb91 --- /dev/null +++ b/versioned_docs/version-0.5.x/advanced-guides/base-module/immune/cell.md @@ -0,0 +1,116 @@ +--- +title: Cell Classes +sidebar_label: Cell Classes +keywords: + - Binary + - classifying + - affinity threshold + - Real-Valued + - classifying + - anomalies + - K-Nearest Neighbors + - memory B-cell +lastUpdatedAt: 2025/05/25 +author: João Paulo +--- + +Representation of immune system cells. + +## Cell + +Represents a basic immune cell. + +```python +@dataclass(slots=True) +class Cell: + vector: np.ndarray +``` + +### Attributes + +* **vector** (`np.ndarray`): A vector of cell features. + +### Methods + +* `__eq__(other)`: Check if two cells are equal based on their vectors. +* `__array__()`: Array interface to NumPy, allows the instance to be treated as a `np.ndarray`. +* `__getitem__(item)`: Get elements from the feature vector using indexing. + +--- + +## BCell + +Represents a memory B-cell. + +```python +@dataclass(slots=True, eq=False) +class BCell(Cell): + vector: np.ndarray +``` + +### Methods + +#### hyper_clonal_mutate(...) + +```python +def hyper_clonal_mutate( + self, + n: int, + feature_type: FeatureType = "continuous-features", + bounds: Optional[npt.NDArray[np.float64]] = None +) -> np.ndarray +``` + +Clones N features from a cell's features, generating a set of mutated vectors. + +##### Parameters + +* **n** (`int`): Number of clones to be generated from mutations of the original cell. +* **feature_type** (`Literal["binary-features", "continuous-features", "ranged-features"]`): + Specifies the type of feature_type to use based on the nature of the input features +* **bounds** (`Optional[npt.NDArray[np.float64]]`): Array (n_features, 2) with min and max per dimension. + +##### Returns + +* **npt.NDArray**: An array containing N mutated vectors from the original cell. + +--- + +## Antibody + +Represent an antibody. + +```python +@dataclass(slots=True) +class Antibody(Cell): + vector: np.ndarray + affinity: float +``` + +### Attributes + +* **vector** (`npt.NDArray`): A vector of cell features. +* **affinity** (`float`): Affinity value for the antibody. + +### Methods + +* `__lt__(other)`: Compare this cell with another Antibody cell based on affinity. +* `__eq__(other)`: Check if this cell has the same affinity as another cell. + +--- + +## Detector + +Represents a non-self detector of the RNSA class. + +```python +@dataclass(slots=True) +class Detector: + position: npt.NDArray[np.float64] + radius: Optional[float] = None +``` + +### Attributes + +* **position** (`npt.NDArray[np.float64]`): Detector feature vector. +* **radius** (`Optional[float]`): Detector radius, used in the V-detector algorithm. diff --git a/versioned_docs/version-0.5.x/advanced-guides/base-module/immune/mutation.md b/versioned_docs/version-0.5.x/advanced-guides/base-module/immune/mutation.md new file mode 100644 index 00000000..d6c3082c --- /dev/null +++ b/versioned_docs/version-0.5.x/advanced-guides/base-module/immune/mutation.md @@ -0,0 +1,121 @@ +--- +title: Mutation +sidebar_label: Mutation +lastUpdatedAt: 2025/04/04 +author: João Paulo +keywords: + - Mutation + - Clonal Expansion + - Immune System + - clone_and_mutate + - clone_and_mutate_continuous + - clone_and_mutate_binary + - clone_and_mutate_ranged + - Artificial Immune Systems + - Python Numba Functions + - Vector Mutation +--- + +Contains functions that generate sets of mutated clones from continuous or binary vectors, simulating the clonal expansion process in artificial immune systems. + +## clone_and_mutate_continuous + +```python +@njit([(types.float64[:], types.int64)], cache=True) +def clone_and_mutate_continuous( + vector: npt.NDArray[np.float64], + n: int +) -> npt.NDArray[np.float64]: +``` + +Generates a set of mutated clones from a continuous vector. + +This function creates `n` clones of the input vector and applies random mutations to each one, simulating the clonal expansion process in artificial immune systems. Each clone receives a random number of mutations at distinct positions of the original vector. + +### Parameters + +* `vector` (`npt.NDArray[np.float64]`): The original immune cell with continuous values to be cloned and mutated. +* `n` (`int`): Number of mutated clones to be generated. + +### Returns + +* `clone_set` (`npt.NDArray[np.float64]`): Array with shape `(n, len(vector))` containing the `n` mutated clones of the original vector. + +--- + +## clone_and_mutate_binary + +```python +@njit([(types.boolean[:], types.int64)], cache=True) +def clone_and_mutate_binary( + vector: npt.NDArray[np.bool_], + n: int +) -> npt.NDArray[np.bool_]: +``` + +Generates a set of mutated clones from a binary vector. + +This function creates `n` clones of the input binary vector and applies random mutations to some bits, simulating clonal expansion in artificial immune systems with discrete representations. + +### Parameters + +* `vector` (`npt.NDArray[np.bool_]`): The original immune cell with binary values to be cloned and mutated. +* `n` (`int`): Number of mutated clones to be generated. + +### Returns + +* `clone_set` (`npt.NDArray[np.bool_]`): Array with shape `(n, len(vector))` containing the `n` mutated clones of the original vector. + +--- + +## clone_and_mutate_ranged + +```python +@njit([(types.float64[:], types.int64, types.float64[:, :])], cache=True) +def clone_and_mutate_ranged( + vector: npt.NDArray[np.float64], + n: int, + bounds: npt.NDArray[np.float64] +) -> npt.NDArray[np.float64]: +``` + +Generates a set of mutated clones from a continuous vector using custom bounds per dimension. + +This function creates `n` clones of the input vector and applies random mutations to each of them, simulating the process of clonal expansion in artificial immune systems. Each clone will have a random number of mutations applied to distinct positions of the original vector, respecting the mutation bounds defined per dimension. + +### Parameters + +* `vector` (`npt.NDArray[np.float64]`): The original immune cell with continuous values to be cloned and mutated. +* `n` (`int`): Number of mutated clones to be generated. +* `bounds` (`npt.NDArray[np.float64]`): A 2D array with shape `(len(vector), 2)` containing the minimum and maximum values for each dimension. + +### Returns + +* `clone_set` (`npt.NDArray[np.float64]`): Array with shape `(n, len(vector))` containing the `n` mutated clones of the original vector. + +--- + +## clone_and_mutate_permutation + +```python +@njit([(types.int64[:], types.int64, types.float64)], cache=True) +def clone___and_mutate_permutation( + vector: npt.NDArray[np.int64], + n: int, + mutation_rate: float +) -> npt.NDArray[np.int64]: +``` + +Generates a set of mutated clones from a permutation vector. + +This function creates `n` clones of the input permutation vector and applies random mutations to each one, simulating clonal expansion in artificial immune systems with discrete permutations. Each clone receives a random number of swaps according to the mutation rate. + +### Parameters + +* `vector` (`npt.NDArray[np.int64]`): The original immune cell with permutation values to be cloned and mutated. +* `n` (`int`): Number of mutated clones to be generated. +* `mutation_rate` (`float`): Probability of mutating each component ($$0 <= mutation\_rate < 1$$). + +### Returns + +* `clone_set` (`npt.NDArray[np.int64]`): Array with shape `(n, len(vector))` containing the `n` mutated clones of the original vector. diff --git a/versioned_docs/version-0.5.x/advanced-guides/base-module/immune/populations.md b/versioned_docs/version-0.5.x/advanced-guides/base-module/immune/populations.md new file mode 100644 index 00000000..3944371f --- /dev/null +++ b/versioned_docs/version-0.5.x/advanced-guides/base-module/immune/populations.md @@ -0,0 +1,49 @@ +--- +title: Populations Module +sidebar_label: Populations +pagination_next: null +keywords: + - Binary + - classifying + - affinity threshold + - Real-Valued + - classifying + - anomalies + - K-Nearest Neighbors + - memory B-cell + - Clonal Expansion + - Immune System + - Artificial Immune Systems +lastUpdatedAt: 2025/11/21 +author: João Paulo +--- + +Utility functions for generating antibody populations in immunological algorithms. + +## generate_random_antibodies(...) + +```python +def generate_random_antibodies( + n_samples: int, + n_features: int, + feature_type: FeatureTypeAll = "continuous-features", + bounds: Optional[npt.NDArray[np.float64]] = None +) -> npt.NDArray +``` + +Generate a random antibody population. + +### Parameters + +* **n_samples** (`int`): Number of antibodies (samples) to generate. +* **n_features** (`int`): Number of features (dimensions) for each antibody. +* **feature_type** (`FeatureTypeAll`, default="continuous-features"): Specifies the type of features: "continuous-features", "binary-features", "ranged-features", or "permutation-features". +* **bounds** (`Optional[npt.NDArray[np.float64]]`): Array (n_features, 2) with min and max per dimension. + +### Returns + +* **npt.NDArray**: Array of shape (n_samples, n_features) containing the generated antibodies. + +### Raises + +* **ValueError**: If the number of features is less than or equal to zero. \ No newline at end of file diff --git a/versioned_docs/version-0.5.x/aisp-techniques/README.mdx b/versioned_docs/version-0.5.x/aisp-techniques/README.mdx new file mode 100644 index 00000000..30f5273d --- /dev/null +++ b/versioned_docs/version-0.5.x/aisp-techniques/README.mdx @@ -0,0 +1,18 @@ +--- +sidebar_position: 2 +--- + +import DocCardList from '@theme/DocCardList'; + +# Implemented techniques + +## AISP Classes + +Classes implemented using the metaphors of artificial immune systems. + +--- + +### Class module: + + +--- \ No newline at end of file diff --git a/versioned_docs/version-0.5.x/aisp-techniques/clonal-selection-algorithms/README.mdx b/versioned_docs/version-0.5.x/aisp-techniques/clonal-selection-algorithms/README.mdx new file mode 100644 index 00000000..79e83816 --- /dev/null +++ b/versioned_docs/version-0.5.x/aisp-techniques/clonal-selection-algorithms/README.mdx @@ -0,0 +1,16 @@ +--- +sidebar_position: 2 +lastUpdatedAt: 2025/05/25 +author: João Paulo +--- +import DocCardList from '@theme/DocCardList'; + +# Clonal Selection Algorithm. + + +Clonal Selection Algorithms are inspired by the process of antibody proliferation upon detecting an antigen, during which +the generated antibodies undergo mutations in an attempt to enhance pathogen recognition. + +## Classes: + + \ No newline at end of file diff --git a/versioned_docs/version-0.5.x/aisp-techniques/clonal-selection-algorithms/airs/README.md b/versioned_docs/version-0.5.x/aisp-techniques/clonal-selection-algorithms/airs/README.md new file mode 100644 index 00000000..9e523121 --- /dev/null +++ b/versioned_docs/version-0.5.x/aisp-techniques/clonal-selection-algorithms/airs/README.md @@ -0,0 +1,210 @@ +--- +id: airs +sidebar_label: AIRS - Artificial Immune Recognition System +keywords: + - Binary + - classifying + - affinity threshold + - Real-Valued + - anomalies + - K-Nearest Neighbors +lastUpdatedAt: 2025/05/25 +author: João Paulo +--- + +# AIRS - Artificial Immune Recognition System + +The ``AIRS`` class aims to perform classification using metaphors of selection and clonal expansion. + +This implementation is inspired by AIRS2, a simplified version of the original AIRS algorithm. +Introducing adaptations to handle continuous and binary datasets. + +Based on Algorithm 16.5 from Brabazon et al. [1](#1). + +:::tip Related and noteworthy works: + +- [Artificial Immune Recognition System V2 - AZZOUG Aghiles](https://github.com/AghilesAzzoug/Artificial-Immune-System) + +::: + +:::info + +**``AIRS``** extends the **[``BaseClassifier`` class](../../../advanced-guides/base-module/core/Classifier.md)**, inheriting its base functionality. + +::: + +## AIRS Constructor + +**Attributes:** + +- **n_resources** (``float``): Total amount of available resources. Defaults to 10. +- **rate_clonal** (``float``): Maximum number of possible clones of a class. This quantity is multiplied by (cell stimulus * rate_hypermutation) to define the number of clones. Defaults to 10. +- **rate_hypermutation** (``int``): The rate of mutated clones derived from rate_clonal as a scalar factor. Defaults to 0.75. +- **affinity_threshold_scalar** (``float``): Normalized affinity threshold. Defaults to 0.75. +- **k** (``int``): The number of K nearest neighbors that will be used to choose a label in the prediction. Defaults to 10. +- **max_iters** (``int``): Maximum number of interactions in the refinement process of the ARB set exposed to aᵢ. Defaults to 100. +- **resource_amplified** (``float``): Resource consumption amplifier is multiplied with the incentive to subtract resources. Defaults to 1.0 without amplification. +- **metric** (Literal["manhattan", "minkowski", "euclidean"]): Way to calculate the distance between the detector and the sample: + - ``'Euclidean'`` ➜ The calculation of the distance is given by the expression: + $$ + \sqrt{(X_{1} - X_{1})^2 + (Y_{2} - Y_{2})^2 + \cdots + (Y_{n} - Y_{n})^2} + $$ + - ``'minkowski'`` ➜ The calculation of the distance is given by the expression: + $$ + \frac{((|X_{1} - Y_{1}|^p + |X_{2} - Y_{2}|^p + \cdots + |X_{n} - Y_{n}|^p)^\frac{1}{p})}{n} + $$ + - ``'manhattan'`` ➜ The calculation of the distance is given by the expression: + $$ + \frac{(|X_{1} - X_{1}| + |Y_{2} - Y_{2}| + \cdots + |Y_{n} - Y_{n}|)}{n} + $$ + + Defaults to **"Euclidean"**. + +- **seed** (``Optional[int]``): Seed for the random generation of detector values. Defaults to None. + +- ``**kwargs``: + - **p** (``float``): This parameter stores the value of ``p`` used in the Minkowski distance. + The default is ``2``, which means normalized Euclidean distance. Different values of p lead to different variants of the Minkowski distance. [Learn more](https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.minkowski.html). + +**Other initialized variables:** + +- **cells_memory** (``dict``): This variable stores a list of memory cells by class. +- **affinity_threshold** (``dict``): Defines the affinity threshold between antigens. +- **classes** (``npt.NDArray``): List of output classes. + +--- + +## Public Methods + +### Function fit(...) + +The ``fit(...)`` function generates detectors for the non-owners relative to the samples: + +```python +def fit(self, X: npt.NDArray, y: npt.NDArray, verbose: bool = True) -> AIRS: +``` + +It performs the training according to ``X`` and ``y``, using the method Artificial Immune Recognition System (``AIRS``). + +**Input parameters:** + +- **X**: Array with sample features, with **N** samples (rows) and **N** features (columns), normalized to values between [0, 1]. +- **y**: Array with output classes corresponding to **N** samples related to ``X``. +- **verbose**: Boolean, default ``True``, determines if the feedback from the detector generation will be printed. + +*Returns the class instance.* + +--- + +### Function predict(...) + +The ``predict(...)`` function performs class prediction using the generated detectors: + +```python +def predict(self, X: npt.NDArray) -> npt.NDArray: +``` + +**Input parameter:** + +- **X**: Array with the features for prediction, with **N** samples (rows) and **N** columns. + +**Returns:** + +- **C**: An array of predictions with the output classes for the given features. +- **None**: If there are no detectors. + +--- + +### Function score(...) + +The ``score(...)`` function calculates the accuracy of the trained model by making predictions and calculating the accuracy. + +```python +def score(self, X: npt.NDArray, y: list) -> float: +``` + +Returns accuracy as a ``float``. + +--- + +## Private Methods + +### Function _refinement_arb(...) + +The function "_refinement_arb(...)" refines the ARB set until the average stimulation value exceeds the defined threshold (``affinity_threshold_scalar``). + +```python +def _refinement_arb(self, ai: npt.NDArray, c_match: Cell, arb_list: List[_ARB]) -> _ARB: +``` + +Parameters: + +- **c_match** (``Cell``): Cell with the highest stimulation relative to aᵢ. +- **arb_list** (``List[_ARB]``): ARB set. + +Returns the cell (_ARB) with the highest ARB stimulation. + +--- + +### Function _cells_affinity_threshold(...) + +The function "_cells_affinity_threshold(...)" calculates the affinity threshold based on the average affinity between training instances, where aᵢ and aⱼ are a pair of antigens, and affinity is measured by distance (Euclidean, Manhattan, Minkowski, Hamming). +**Following the formula:** + +$$ +\text{affinity}_{\text{threshold}} = \frac{ +\sum_{i=1}^{n-1} \sum_{j=i+1}^{n} \text{affinity}(a_i, a_j)}{n(n-1)/2} +$$ + +Parameters: + +- **antigens_list** (``NDArray``): List of training antigens. + +```python +def _cells_affinity_threshold(self, antigens_list: npt.NDArray): +``` + +--- + +### Function _affinity(...) + +The function "_affinity(...)" calculates the stimulus between two vectors using metrics. + +```python +def _affinity(self, u: npt.NDArray, v: npt.NDArray) -> float: +``` + +Parameters: + +- **u** (``npt.NDArray``): Coordinates of the first point. +- **v** (``npt.NDArray``): Coordinates of the second point. + +Returns the stimulus rate between the vectors. + +--- + +### Function _init_memory_c(...) + +The function "_init_memory_c(...)" initializes memory cells by randomly selecting `n_antigens_selected` from the list of training antigens. + +```python +def _init_memory_c(self, antigens_list: npt.NDArray) -> List[BCell]: +``` + +Parameters: + +- **antigens_list** (``NDArray``): List of training antigens. + +Returns + +- ``List[BCell]``: List of initialized memories. + +--- + +## References + +--- + +### 1 +> +> BRABAZON, Anthony; O'NEILL, Michael; MCGARRAGHY, Seán. Natural Computing Algorithms. [S. l.]: Springer Berlin Heidelberg, 2015. DOI 10.1007/978-3-662-43631-8. Disponível em: [https://dx.doi.org/10.1007/978-3-662-43631-8](https://dx.doi.org/10.1007/978-3-662-43631-8). diff --git a/versioned_docs/version-0.5.x/aisp-techniques/clonal-selection-algorithms/airs/abr.md b/versioned_docs/version-0.5.x/aisp-techniques/clonal-selection-algorithms/airs/abr.md new file mode 100644 index 00000000..bf2bcf61 --- /dev/null +++ b/versioned_docs/version-0.5.x/aisp-techniques/clonal-selection-algorithms/airs/abr.md @@ -0,0 +1,47 @@ +--- +id: abr +title: ABR +sidebar_label: ABR - Artificial Recognition Ball +sidebar_position: 2 +keywords: + - Binary + - classifying + - affinity threshold + - Real-Valued + - classifying + - anomalies + - K-Nearest Neighbors +lastUpdatedAt: 2025/05/25 +author: João Paulo +--- + +## ABR (Artificial Recognition Ball) + +Individual from the set of recognizing cells (ABR), inherits characteristics from a B-cell, adding resource consumption + +:::info + +**``ABR``** extends the **[``BCell`` class](../../../advanced-guides/base-module/immune/cell.md#BCell)**, inheriting its base functionality. + +::: + +### Constructor + +Parameters: + +* vector (``npt.NDArray``): A feature vector of the cell. Defaults to None. + +--- + +### Function consume_resource(...) + +Parameters: + +* n_resource (```float```) : The initial amount of resources. +* amplified (``float``): Amplifier for resource consumption by the cell. It is multiplied by the cell's stimulus. The default value is 1. + +```python +def consume_resource(self, n_resource: float, amplified: float = 1) -> float: +``` + +Returns the remaining amount of resources after consumption. diff --git a/versioned_docs/version-0.5.x/aisp-techniques/clonal-selection-algorithms/clonalg.md b/versioned_docs/version-0.5.x/aisp-techniques/clonal-selection-algorithms/clonalg.md new file mode 100644 index 00000000..7ee8a2da --- /dev/null +++ b/versioned_docs/version-0.5.x/aisp-techniques/clonal-selection-algorithms/clonalg.md @@ -0,0 +1,198 @@ +--- +id: clonalg +sidebar_label: CLONALG - Clonal Selection Algorithm +keywords: + - CLONALG + - clonal selection algorithm + - optimization + - binary optimization + - real-valued optimization + - ranged-value problems + - permutation problems + - metaheuristics + - bio-inspired algorithms + - machine learning optimization +lastUpdatedAt: 2025/09/21 +author: João Paulo +--- + +# CLONALG - Clonal Selection Algorithm + +The `Clonalg` class is an **optimization algorithm** inspired by the biological process of clonal selection in the immune system. This implementation is designed for minimizing or maximizing cost functions in various problem types, including binary, continuous, ranged-value, and permutation problems. + +:::tip +The CLONALG implementation was inspired by the description presented in [1](#1). +::: + +:::info +This CLONALG implementation contains some changes based on the AISP context, for general +application to various problems, which may produce results different from the standard or +specific implementation. This adaptation aims to generalize CLONALG to minimization and +maximization tasks, in addition to supporting continuous, discrete, and permutation problems. +::: + +:::info + +**``Clonalg``** extends the **[``BaseOptimizer`` class](../../advanced-guides/base-module/core/Optimizer.md)**, inheriting its base functionality. + +::: + +--- + +## CLONALG Constructor + +The constructor initializes the CLONALG instance with key parameters that define the optimization process. + +**Attributes:** + +* **problem_size**: `int` - The dimension of the problem to be optimized. +* **N**: `int`, default=50 - The number of memory cells (antibodies) in the population. +* **rate_clonal**: `float`, default=10 - The maximum number of possible clones of a cell. This value is multiplied by the cell's affinity to determine the number of clones. +* **rate_hypermutation**: `float`, default=0.75 - The rate of mutated clones, used as a scalar factor. +* **n_diversity_injection**: `int`, default=5 - The number of new random memory cells injected to maintain diversity. +* **selection_size**: `int`, default=5 - The number of best antibodies selected for cloning. +* **affinity_function**: `Optional[Callable[..., npt.NDArray]]`, default=None - The objective function used to evaluate candidate solutions. +* **feature_type**: `FeatureTypeAll`, default='ranged-features' - The type of problem samples, which can be `'continuous-features'`, `'binary-features'`, `'ranged-features'`, or `'permutation-features'`. +* **bounds**: `Optional[Dict]`, default=None - A dictionary defining the search limits for `'ranged-features'` problems. Can be a single fixed range or a list of ranges for each dimension. +* **mode**: `Literal["min", "max"]`, default="min" - Specifies whether the algorithm minimizes or maximizes the cost function. +* **seed**: `Optional[int]`, default=None - A seed for random number generation. + +--- + +## Public Methods + +### Function `optimize(...)` + +```python +def optimize( + self, + max_iters: int = 50, + n_iter_no_change=10, + verbose: bool = True +) -> List[Antibody]: +``` + +This method execute the optimization process and return the population. + +**Input parameters:** + +* **max_iters**: `int`, default=50 - The maximum number of interactions. +* **n_iter_no_change**: `int`, default=10 - The maximum number of iterations without an improvement in the best solution. +* **verbose**: `bool`, default=True - A flag to enable or disable detailed output during the optimization process. + +**Returns:** + +* population : ``List[Antibody]``, [Antibody](../../advanced-guides/base-module/immune/cell.md#Antibody) population after clonal expansion. + +--- + +### Function `affinity_function(...)` + +```python +def affinity_function(self, solution: npt.NDArray) -> np.float64: +``` + +This method evaluates the affinity of a candidate solution. It raises a `NotImplementedError` if no affinity function has been provided to the class instance. + +**Input parameters:** + +* **solution**: `npt.NDArray` - The candidate solution to be evaluated. + +**Returns:** + +* `np.float64`: The affinity value associated with the solution. + +--- + +## Private Methods + +### Function `_select_top_antibodies(...)` + +```python +def _select_top_antibodies(self, n: int, antibodies: list[tuple]) -> list[tuple]: +``` + +This method selects the top `n` antibodies based on their affinity scores, according to the `mode` (`'min'` or `'max'`). + +**Input parameters:** + +* **n**: `int` - The number of antibodies to select. +* **antibodies**: `list[tuple]` - A list of tuples, where each tuple represents an antibody and its associated score. + +**Returns:** + +* `list[tuple]`: A list containing the `n` selected antibodies. + +--- + +### Function `_init_population_antibodies(...)` + +```python +def _init_population_antibodies(self) -> npt.NDArray: +``` + +This method initializes the initial population of antibodies randomly. + +**Returns:** + +* `npt.NDArray`: A list of the initialized antibodies. + +--- + +### Function `_diversity_introduction(...)` + +```python +def _diversity_introduction(self): +``` + +This method introduces new random antibodies into the population to maintain genetic diversity and help prevent premature convergence. + +**Returns:** + +* `npt.NDArray`: An array of new random antibodies. + +--- + +### Function `_clone_and_mutate(...)` + +```python +def _clone_and_mutate(self, antibody: npt.NDArray, n_clone: int, rate_hypermutation: float) -> npt.NDArray: +``` + +This method generates mutated clones from a single antibody. The mutation strategy depends on the `feature_type` specified during initialization (`'binary-features'`, `'continuous-features'`, `'ranged-features'`, or `'permutation-features'`). + +**Input parameters:** + +* **antibody**: `npt.NDArray` - The original antibody vector to be cloned and mutated. +* **n_clone**: `int` - The number of clones to generate. +* **rate_hypermutation**: `float` - The hypermutation rate. + +**Returns:** + +* `npt.NDArray`: An array containing the mutated clones. + +--- + +### Function `_clone_and_hypermutation(...)` + +```python +def _clone_and_hypermutation(self, population: list[tuple]) -> list: +``` + +This method clones and hypermutates a population of antibodies. It returns a list of all clones and their affinities with respect to the cost function. + +**Input parameters:** + +* **population**: `list[tuple]` - The list of antibodies to be evaluated and cloned. + +**Returns:** + +* `list`: A list of mutated clones. + +--- + +## References + +### 1 +> +> BROWNLEE, Jason. Clonal Selection Algorithm. Clever Algorithms: Nature-inspired Programming Recipes., 2011. Available at: [https://cleveralgorithms.com/nature-inspired/immune/clonal_selection_algorithm.html](https://cleveralgorithms.com/nature-inspired/immune/clonal_selection_algorithm.html) diff --git a/versioned_docs/version-0.5.x/aisp-techniques/immune-network-theory/AiNet.md b/versioned_docs/version-0.5.x/aisp-techniques/immune-network-theory/AiNet.md new file mode 100644 index 00000000..5f6807b9 --- /dev/null +++ b/versioned_docs/version-0.5.x/aisp-techniques/immune-network-theory/AiNet.md @@ -0,0 +1,322 @@ +--- +id: ainet +sidebar_label: AiNet - Clustering and Compression +sidebar_position: 1 +pagination_next: null +keywords: + - Artificial Immune Network + - AiNet + - Clustering + - Data Compression + - Immune Algorithms + - Bioinspired Computing + - Memory Cells + - Affinity Threshold + - Suppression Threshold + - Clonal Selection + - Clonal Expansion + - Diversity Introduction + - Pattern Recognition + - Anomaly Detection + - MST Clustering + - Minimum Spanning Tree + - Unsupervised Learning + - Bioinspired Algorithms + - Antibody Network +lastUpdatedAt: 2025/08/19 +author: João Paulo +--- + +# AiNet - Artificial Immune Network para Clustering and Compression + +The AiNet class aims to perform clustering using metaphors inspired by immune network theory. + +This class implements the aiNet algorithm, an artificial immune network model designed for +clustering and data compression tasks. The aiNet algorithm uses principles from immune +network theory, clonal selection, and affinity maturation to compress high-dimensional +datasets [1](#1). +For clustering, the class uses SciPy's implementation of the [**Minimum Spanning Tree** +(MST)](#2) to remove the most distant nodes and separate the groups + +:::info + +**``AiNet``** extends the **[``BaseClusterer`` class](../../advanced-guides/base-module/core/Clusterer.md)**, inheriting its base functionality. + +::: + +## Constructor + +```python +class AiNet( + self, + N: int = 50, + n_clone: int = 10, + top_clonal_memory_size: int = 5, + n_diversity_injection: int = 5, + affinity_threshold: float = 0.5, + suppression_threshold: float = 0.5, + mst_inconsistency_factor: float = 2.0, + max_iterations: int = 10, + k: int = 3, + metric: MetricType = "euclidean", + seed: Optional[int] = None, + use_mst_clustering: bool = True, + **kwargs +) +``` + +**Attributes:** + +* **N** (``int``): Number of memory cells (antibodies) in the population. Defaults to 50. +* **n_clone** (``int``): Number of clones generated per selected memory cell. Defaults to 10. +* **top_clonal_memory_size** (``Optional[int]``): Number of highest-affinity antibodies selected for cloning. Defaults to 5. +* **n_diversity_injection** (``int``): Number of new random antibodies injected to maintain diversity. Defaults to 5. +* **affinity_threshold** (``float``): Threshold for cell selection/suppression. Defaults to 0.5. +* **suppression_threshold** (``float``): Threshold for removing similar memory cells. Defaults to 0.5. +* **mst_inconsistency_factor** (``float``): Factor to determine inconsistent MST edges. Defaults to 2.0. +* **max_iterations** (``int``): Maximum number of training iterations. Defaults to 10. +* **k** (``int``): Number of nearest neighbors used for label prediction. Defaults to 3. +* **metric** (Literal["manhattan", "minkowski", "euclidean"]): Way to calculate the distance between the detector and the sample: + * ``'Euclidean'`` ➜ The calculation of the distance is given by the expression: + $$ + \sqrt{(X_{1} - X_{1})^2 + (Y_{2} - Y_{2})^2 + \cdots + (Y_{n} - Y_{n})^2} + $$ + * ``'minkowski'`` ➜ The calculation of the distance is given by the expression: + $$ + \frac{((|X_{1} - Y_{1}|^p + |X_{2} - Y_{2}|^p + \cdots + |X_{n} - Y_{n}|^p)^\frac{1}{p})}{n} + $$ + * ``'manhattan'`` ➜ The calculation of the distance is given by the expression: + $$ + \frac{(|X_{1} - X_{1}| + |Y_{2} - Y_{2}| + \cdots + |Y_{n} - Y_{n}|)}{n} + $$ + + Defaults to **"Euclidean"**. + +* **seed** (``Optional[int]``): Seed for random number generation. Defaults to None. +* **use_mst_clustering** (``bool``): Whether to perform MST-based clustering. Defaults to True. +* **kwargs**: + * **p** (``float``): Parameter for Minkowski distance. Defaults to 2. + +**Other initialized variables:** + +* **_population_antibodies** (``npt.NDArray``): Stores the current set of antibodies. +* **_memory_network** (``dict``): Dictionary mapping clusters to antibodies. +* **_mst_structure** (``scipy.sparse.csr_matrix``): MST adjacency structure. +* **_mst_mean_distance** (``float``): Mean of MST edge distances. +* **_mst_std_distance** (``float``): Standard deviation of MST edge distances. +* **classes** (``list``): List of cluster labels. + +--- + +## Public Methods + +### Function fit(...) + +Trains the AiNet model on input data: + +```python +def fit(self, X: npt.NDArray, verbose: bool = True) -> AiNet: +``` + +**Input parameters:** + +* **X**: Array with input samples (rows) and features (columns). +* **verbose**: Boolean, default True, enables progress feedback. + +*Returns the class instance.* + +--- + +### Function predict(...) + +Predicts cluster labels for new samples: + +```python +def predict(self, X) -> Optional[npt.NDArray]: +``` + +**Input parameters:** + +* **X**: Array of input features. + +**Returns:** + +* **Predictions**: Array of cluster labels, or None if clustering is disabled. + +--- + +### Function update_clusters(...) + +Partitions clusters using the MST: + +```python +def update_clusters(self, mst_inconsistency_factor: Optional[float] = None): +``` + +**Input parameters:** + +* **mst_inconsistency_factor**: Optional float to override the MST inconsistency factor. + +**Updates:** + +* **_memory_network**: Dictionary of cluster labels to antibody arrays. +* **classes**: List of cluster labels. + +--- + +## Private Methods + +### Function _init_population_antibodies(...) + +Initializes antibody population randomly. + +```python +def _init_population_antibodies(self) -> npt.NDArray: +``` + +**Returns:** Initialized antibodies (`npt.NDArray`). + +--- + +### Function _select_and_clone_population(...) + +Selects top antibodies and generates mutated clones: + +```python +def _select_and_clone_population(self, antigen: npt.NDArray, population: npt.NDArray) -> list: +``` + +**Input parameters:** + +* **antigen**: Array representing the antigen to which affinities will be computed. +* **population**: Array of antibodies to be evaluated and cloned. + +**Returns:** List of mutated clones. + +--- + +### Function _clonal_suppression(...) + +Suppresses redundant clones based on thresholds: + +```python +def _clonal_suppression(self, antigen: npt.NDArray, clones: list): +``` + +**Input parameters:** + +* **antigen**: Array representing the antigen. +* **clones**: List of candidate clones to be suppressed. + +**Returns:** List of non-redundant, high-affinity clones. + +--- + +### Function _memory_suppression(...) + +Removes redundant antibodies from memory pool: + +```python +def _memory_suppression(self, pool_memory: list) -> list: +``` + +**Input parameters:** + +* **pool_memory**: List of antibodies currently in memory. + +**Returns:** Cleaned memory pool (`list`). + +--- + +### Function _diversity_introduction(...) + +Introduces new random antibodies: + +```python +def _diversity_introduction(self) -> npt.NDArray: +``` + +**Returns:** Array of new antibodies (`npt.NDArray`). + +--- + +### Function _affinity(...) + +Calculates stimulus between two vectors: + +```python +def _affinity(self, u: npt.NDArray, v: npt.NDArray) -> float: +``` + +**Input parameters:** + +* **u**: Array representing the first point. +* **v**: Array representing the second point. + +**Returns:** Affinity score (`float`) in [0,1]. + +--- + +### Function _calculate_affinities(...) + +Calculates affinity matrix between reference and target vectors: + +```python +def _calculate_affinities(self, u: npt.NDArray, v: npt.NDArray) -> npt.NDArray: +``` + +**Input parameters:** + +* **u**: Reference vector (`npt.NDArray`) of shape `(n_features,)`. +* **v**: Target vectors (`npt.NDArray`) of shape `(n_samples, n_features)`. + +**Returns:** Array of affinities (`npt.NDArray`) with shape `(n_samples,)`. + +--- + +### Function _clone_and_mutate(...) + +Generates mutated clones: + +```python +def _clone_and_mutate(self, antibody: npt.NDArray, n_clone: int) -> npt.NDArray: +``` + +**Input parameters:** + +* **antibody**: Original antibody vector to clone and mutate. +* **n_clone**: Number of clones to generate. + +**Returns:** Array of mutated clones (`npt.NDArray`) of shape `(n_clone, len(antibody))`. + +--- + +### Function _build_mst(...) + +Constructs the MST and stores statistics. + +```python +def _build_mst(self): +``` + +**Raises:** ValueError if antibody population is empty. + +**Updates internal variables:** + +* **_mst_structure**: MST adjacency structure. +* **_mst_mean_distance**: Mean edge distance. +* **_mst_std_distance**: Standard deviation of MST edge distances. + +--- + +## References + +### 1 +> +> De Castro, Leandro & José, Fernando & von Zuben, Antonio Augusto. (2001). aiNet: An Artificial Immune Network for Data Analysis. +> Available at: [https://www.researchgate.net/publication/228378350_aiNet_An_Artificial_Immune_Network_for_Data_Analysis](https://www.researchgate.net/publication/228378350_aiNet_An_Artificial_Immune_Network_for_Data_Analysis) + +### 2 +> +> SciPy Documentation. *Minimum Spanning Tree*. +> Available at: [https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csgraph.minimum_spanning_tree](https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csgraph.minimum_spanning_tree) diff --git a/versioned_docs/version-0.5.x/aisp-techniques/immune-network-theory/README.mdx b/versioned_docs/version-0.5.x/aisp-techniques/immune-network-theory/README.mdx new file mode 100644 index 00000000..148e0fbe --- /dev/null +++ b/versioned_docs/version-0.5.x/aisp-techniques/immune-network-theory/README.mdx @@ -0,0 +1,39 @@ +--- +sidebar_position: 3 +lastUpdatedAt: 2025/08/19 +author: João Paulo +keywords: + - Immune Network Theory + - AiNet + - Artificial Immune Systems + - Clustering + - Optimization + - Classification + - Machine Learning + - Immune Algorithms +--- + +import DocCardList from '@theme/DocCardList'; + +# Immune Network Theory + +This technique was introduced by **Niels Jerne (1974)** and models the immune system as a dynamic network, +in which cells and molecules are capable of recognizing each other. [1](#1) + +--- + +The Artificial Immune Network can be applied in different contexts, such as: +- **Clustering** +- **Optimization** +- **Classification** + +## Classes: + + + +## References + +--- + +### 1 +> BRABAZON, Anthony; O'NEILL, Michael; MCGARRAGHY, Seán. Natural Computing Algorithms. [S. l.]: Springer Berlin Heidelberg, 2015. DOI 10.1007/978-3-662-43631-8. Disponível em: [https://dx.doi.org/10.1007/978-3-662-43631-8](https://dx.doi.org/10.1007/978-3-662-43631-8). diff --git a/versioned_docs/version-0.5.x/aisp-techniques/negative-selection/BNSA.md b/versioned_docs/version-0.5.x/aisp-techniques/negative-selection/BNSA.md new file mode 100644 index 00000000..a8f7cd82 --- /dev/null +++ b/versioned_docs/version-0.5.x/aisp-techniques/negative-selection/BNSA.md @@ -0,0 +1,143 @@ +--- +id: bnsa +sidebar_label: BNSA - Binary Negative Selection Algorithm +sidebar_position: 2 +pagination_next: null +keywords: + - Binary + - classifying + - anomalies + - not self + - affinity threshold + - Negative Selection Algorithm + - Artificial Immune System (AIS) + - Self and non-self + - Immune + - Computação Natural + - Real-Valued + - V-detector +last_update: + date: 2025/05/17 + author: João Paulo +--- + +# BNSA (Binary Negative Selection Algorithm) + +:::info + +**``BNSA``** extends the **[``BaseClassifier`` class](../../advanced-guides/base-module/core/Classifier.md)**, inheriting its base functionality. + +::: + +## Constructor RNSA + +The ``BNSA`` (Binary Negative Selection Algorithm) class has the purpose of classifying and identifying anomalies through the self and not self methods. + +``` python +class BNSA( + self, + N: int = 100, + aff_thresh: float = 0.1, + max_discards: int = 1000, + seed: int = None, + no_label_sample_selection: Literal[ + "max_average_difference", "max_nearest_difference" + ] = "max_average_difference", +) +``` + +**Attributes:** + +* *N* (``int``): Number of detectors. Defaults to ``100``. +* *aff_thresh* (``float``): The variable ('affinity threshold') represents the percentage of dissimilarity between the T cell and the own samples. The default value is 10% (0.1), while a value of 1.0 represents 100% dissimilarity. + + :::note + Setting the difference percentage too high can result in the inability to generate detectors for non-self. + ::: + +* *max_discards* (``int``): This parameter indicates the maximum number of detector discards in sequence, which aims to avoid a +possible infinite loop if a radius is defined that it is not possible to generate non-self detectors. Defaults to ``1000``. +* *seed* (``int``): Seed for the random generation of values in the detectors. Defaults to ``None``. +* no_label_sample_selection (``str``): Method for selecting labels for samples designated as non-members by all non-member detectors. **Available method types:** + * (``max_average_difference``): Selects the class with the highest average difference among the detectors. + * (``max_nearest_difference``): Selects the class with the highest difference between the nearest and farthest detector from the sample. + +**Other variables initiated:** + +* *detectors* (``dict``): This variable stores a list of detectors by class. + +* *classes* (``npt.NDArray``): list of output classes. + +--- + +### Function fit(...) + +The ``fit(...)`` function generates the detectors for non-fits with respect to the samples: + +```python +def fit(self, X: npt.NDArray, y: npt.NDArray, verbose: bool = True) +``` + +In it, training is performed according to ``X`` and ``y``, using the negative selection method(``NegativeSelect``). + +**The input parameters are:** + +* ``X``: array with the characteristics of the samples with **N** samples (rows) and **N** characteristics (columns). + +* ``y``: array with the output classes arranged in **N** samples that are related to ``X``. + +* ``verbose``: boolean with default value ``True``, determines if the feedback from the detector generation will be printed. + +*Returns the instance of the class.* + +--- + +### Function predict(...) + +The ``predict(...)`` function performs class prediction using the generated detectors: + +```python +def predict(self, X: npt.NDArray) -> npt.NDArray: +``` + +**The input parameter is:** + +* ``X``: array with the characteristics for the prediction, with **N** samples (Rows) and **N** columns. + +**Returns:** + +* ``C``: prediction array, with the output classes for the given characteristics. +* ``None``: if there are no detectors. + +--- + +### Function score(...) + +The function ``score(...)`` calculates the accuracy of the trained model by making predictions and computing accuracy. + +```python +def score(self, X: npt.NDArray, y: list) -> float: +``` + +It returns the accuracy as a float type. + +--- + +## Private Methods + +--- + +### Function __assign_class_to_non_self_sample(...) + +The function ``__assign_class_to_non_self_sample(...)``, determines the class of a sample when all detectors classify it as "non-self". Classification is performed using the ``max_average_difference`` and ``max_nearest_difference`` methods. + +```python +def __assign_class_to_non_self_sample(self, line: npt.NDArray, c: list): +``` + +**The input parameter is:** + +* ***line*** (``npt.NDArray``): Sample to be classified. +* ***c*** (``list``): List of predictions to be updated with the new classification. + +--- diff --git a/versioned_docs/version-0.5.x/aisp-techniques/negative-selection/README.md b/versioned_docs/version-0.5.x/aisp-techniques/negative-selection/README.md new file mode 100644 index 00000000..be74a482 --- /dev/null +++ b/versioned_docs/version-0.5.x/aisp-techniques/negative-selection/README.md @@ -0,0 +1,42 @@ +--- +sidebar_position: 1 +--- + +# Negative selection + +**Negative selection** is the process in which the immune system maturates T-cells, also known as T-lymphocytes, which make them capable of detecting non-self. Thus, the Negative Selection Algorithm (NSA) uses hyperspheres symbolizing the detectors in an N-dimensional data space. [[1]](#1) + +## classes + +> 1. **[Binary version:](BNSA.md)** +> +>> The binary algorithm adapted for multiple classes in this project is based on the version proposed by [Forrest et al. (1994)](#2), originally developed for computer security. +>>> **Example:** +>>> +>>> + [Mushrooms Database](https://github.com/AIS-Package/aisp/blob/main/examples/en/classification/BNSA/mushrooms_dataBase_example_en.ipynb) + +> 2. **[Real-Valued version:](RNSA.md)** +> +>>This algorithm has two different versions: one based on the canonical version [[1]](#1) and another with variable radius detectors [[3]](#3). Both are adapted to work with multiple classes and have methods for predicting data present in the non-self region of all detectors and classes. +>>> **Examples:** +>>> +>>> + [Iris Database](https://github.com/AIS-Package/aisp/blob/main/examples/en/classification/RNSA/iris_dataBase_example_en.ipynb) +>>> + [Geyser Database](https://github.com/AIS-Package/aisp/blob/main/examples/en/classification/RNSA/geyser_dataBase_example_en.ipynb) + +## References + +--- + +### 1 +> +> BRABAZON, Anthony; O'NEILL, Michael; MCGARRAGHY, Seán. Natural Computing Algorithms. [S. l.]: Springer Berlin Heidelberg, 2015. DOI 10.1007/978-3-662-43631-8. Disponível em: [https://dx.doi.org/10.1007/978-3-662-43631-8](https://dx.doi.org/10.1007/978-3-662-43631-8). + +### 2 +> +> S. Forrest, A. S. Perelson, L. Allen and R. Cherukuri, "Self-nonself discrimination in a computer," Proceedings of 1994 IEEE Computer Society Symposium on Research in Security and Privacy, Oakland, CA, USA, 1994, pp. 202-212, doi: [https://dx.doi.org/10.1109/RISP.1994.296580](https://dx.doi.org/10.1109/RISP.1994.296580). + +### 3 +> +> JI, Zhou; DASGUPTA, Dipankar. Real-Valued Negative Selection Algorithm with Variable-Sized Detectors. Genetic and Evolutionary Computation - GECCO 2004. [S. l.]: Springer Berlin Heidelberg, 2004. DOI 10.1007/978-3-540-24854-5_30. Disponível em: [https://dx.doi.org/10.1007/978-3-540-24854-5_30](https://dx.doi.org/10.1007/978-3-540-24854-5_30). + +--- diff --git a/versioned_docs/version-0.5.x/aisp-techniques/negative-selection/RNSA.md b/versioned_docs/version-0.5.x/aisp-techniques/negative-selection/RNSA.md new file mode 100644 index 00000000..3c102d26 --- /dev/null +++ b/versioned_docs/version-0.5.x/aisp-techniques/negative-selection/RNSA.md @@ -0,0 +1,241 @@ +--- +id: rnsa +sidebar_label: RNSA - Real-Valued Negative Selection Algorithm +sidebar_position: 1 +keywords: + - Real-Valued + - classifying + - anomalies + - not self + - V-detector + - Negative Selection Algorithm + - Artificial Immune System (AIS) + - Self and non-self + - Immune + - Computação Natural +last_update: + date: 2025/05/17 + author: João Paulo +--- + +# RNSA (Real-Valued Negative Selection Algorithm) + +:::info + +**``RNSA``** extends the **[``BaseClassifier`` class](../../advanced-guides/base-module/core/Classifier.md)**, inheriting its base functionality. + +::: + +## Constructor RNSA + +The ``RNSA`` (Real-Valued Negative Selection Algorithm) class has the purpose of classifying and identifying anomalies through the self and not self methods. + +```python +class RNSA( + self, + N: int = 100, + r: float = 0.05, + r_s: float = 0.0001, + k: int = 1, + metric: Literal["manhattan", "minkowski", "euclidean"] = "euclidean", + max_discards: int = 1000, + seed: int = None, + algorithm: Literal["default-NSA", "V-detector"] = "default-NSA", + **kwargs: Dict[str, Union[bool, str, float]], +) +``` + +**Attributes:** + +* *N* (``int``): Number of detectors. Defaults to ``100``. +* *r* (``float``): Radius of the detector. Defaults to ``0.05``. + + :::note + it is important to consider that setting a very low radius for the detector can significantly reduce the detection rate. On the other hand, a very large radius can make it impossible to incorporate the detector into the search space, which can also compromise detection performance. It is essential to find a balance between the radius size and detection efficiency to achieve the best possible results. + ::: + +* *k* (``int``): Number of neighbors near the randomly generated detectors to perform the distance average calculation. Defaults to ``1``. +* *metric* (``str``): Way to calculate the distance between the detector and the sample: + + * ``'Euclidean'`` ➜ The calculation of the distance is given by the expression: + $$ + \sqrt{(X_{1} - X_{1})^2 + (Y_{2} - Y_{2})^2 + \cdots + (Y_{n} - Y_{n})^2} + $$ + + * ``'minkowski'`` ➜ The calculation of the distance is given by the expression: + $$ + \frac{((|X_{1} - Y_{1}|^p + |X_{2} - Y_{2}|^p + \cdots + |X_{n} - Y_{n}|^p)^\frac{1}{p})}{n} + $$ + * ``'manhattan'`` ➜ The calculation of the distance is given by the expression: + $$ + \frac{(|X_{1} - X_{1}| + |Y_{2} - Y_{2}| + \cdots + |Y_{n} - Y_{n}|)}{n} + $$ + + Defaults to ``'euclidean'``. + +* *max_discards* (``int``): This parameter indicates the maximum number of consecutive detector discards, aimed at preventing a possible infinite loop in case a radius is defined that cannot generate non-self detectors. Defaults to ``1000``. +* *seed* (``int``): Seed for the random generation of values in the detectors. Defaults to ``None``. + +* *algorithm* (``str``), Set the algorithm version: + + * ``'default-NSA'``: Default algorithm with fixed radius. + * ``'V-detector'``: This algorithm is based on the article "[Real-Valued Negative Selection Algorithm with Variable-Sized Detectors](https://doi.org/10.1007/978-3-540-24854-5_30)", by Ji, Z., Dasgupta, D. (2004), and uses a variable radius for anomaly detection in feature spaces. + + Defaults to ``'default-NSA'``. + +* *r_s* (``float``): rₛ Radius of the ``X`` own samples. + +* ``**kwargs``: + * *non_self_label* (``str``): This variable stores the label that will be assigned when the data has only one + output class, and the sample is classified as not belonging to that class. Defaults to ``'non-self'``. + * *cell_bounds* (``bool``): If set to ``True``, this option limits the generation of detectors to the space within the plane between 0 and 1. This means that any detector whose radius exceeds this limit is discarded, this variable is only used in the ``V-detector`` algorithm. + * p (``float``): This parameter stores the value of ``p`` used in the Minkowski distance. The default is ``2``, which represents normalized Euclidean distance. Different values of p lead to different variants of the Minkowski + distance [learn more](https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.minkowski.html). + +**Other variables initiated:** + +* *detectors* (``dict``): This variable stores a list of detectors by class. + +* *classes* (``npt.NDArray``): list of output classes. + +--- + +### Function fit(...) + +The ``fit(...)`` function generates the detectors for non-fits with respect to the samples: + +```python +def fit(self, X: npt.NDArray, y: npt.NDArray, verbose: bool = True) +``` + +In it, training is performed according to ``X`` and ``y``, using the negative selection method(``NegativeSelect``). + +The input parameters are: + +* ``X``: array with the characteristics of the samples with **N** samples (rows) and **N** characteristics (columns). + +* ``y``: array with the output classes arranged in **N** samples that are related to ``X``. + +* ``verbose``: boolean with default value ``True``, determines if the feedback from the detector generation will be printed. + +*Returns the instance of the class.* + +--- + +### Function predict(...) + +The ``predict(...)`` function performs class prediction using the generated detectors: + +```python +def predict(self, X: npt.NDArray) -> npt.NDArray: +``` + +**The input parameter is:** + +* ``X``: array with the characteristics for the prediction, with **N** samples (Rows) and **N** columns. + +**Returns:** + +* ``C``: prediction array, with the output classes for the given characteristics. +* ``None``: if there are no detectors. + +--- + +### Function score(...) + +The function ``score(...)`` calculates the accuracy of the trained model by making predictions and computing accuracy. + +```python +def score(self, X: npt.NDArray, y: list) -> float: +``` + +It returns the accuracy as a float type. + +--- + +## Private Methods + +--- + +### Function __checks_valid_detector(...) + +The ``def __checks_valid_detector(...)`` function checks if the detector has a valid ``r`` radius for the non-self of the class: + +```python +def __checks_valid_detector(self, X: npt.NDArray, vector_x: npt.NDArray, samplesIndexClass: npt.NDArray) -> bool: +``` + +**The input parameters are:** + +* ``X``: array with sample characteristics with **N** samples (rows) and **N** characteristics (columns), normalized to values between [0, 1]. + +* ``vector_x``: Randomly generated candidate detector. + +* ``samplesIndexClass``: Array with the indexes of a class. + +**Returns:** ``True`` for detectors that do not have samples inside or ``False`` if they do. + +--- + +### Function __compare_KnearestNeighbors_List(...) + +The ``def __compare_KnearestNeighbors_List(...)`` function compares the distance of the k-nearest neighbors, so if the distance of the new sample is smaller, replaces ``k-1`` and sorts in ascending order: + +```python +def __compare_KnearestNeighbors_List(self, knn: npt.NDArray, distance: float) -> npt.NDArray: +``` + +Returns a list of k-nearest neighbor distances. + +--- + +### Function __compare_sample_to_detectors(...) + +Function to compare a sample with the detectors, verifying if the sample is proper. +In this function, when there is class ambiguity, it returns the class that has the greatest average distance between the detectors. + +```python +def __compare_sample_to_detectors(self, line): +``` + +**The input parameters are:** + +* line: vector with N-features + +**Returns:** The predicted class with the detectors or None if the sample does not qualify for any class. + +--- + +### Function __detector_is_valid_to_Vdetector(...) + +Check if the distance between the detector and the samples, minus the radius of the samples, is greater than the minimum radius. + +```python +def __detector_is_valid_to_Vdetector(self, distance, vector_x): +``` + +**The input parameters are:** + +* distance (``float``): minimum distance calculated between all samples. +* vector_x (``numpy.ndarray``): randomly generated candidate detector vector x with values between 0 and 1. + +**Returns:** + +* ``False``: if the calculated radius is smaller than the minimum distance or exceeds the edge of the space, if this option is enabled. +* ``True`` and the distance minus the radius of the samples, if the radius is valid.` + +--- + +### Function __distance(...) + +The function ``def __distance(...)`` calculates the distance between two points using the technique defined in ``metric``, which are: ``'euclidean', 'norm_euclidean', or 'manhattan'`` + +```python +def __distance(self, u: npt.NDArray, v: npt.NDArray): +``` + +The input parameters are ``u`` and ``v`` NDArrays, with the coordinates for the points. + +**Returns:** the distance (``double``) between the two points. + +--- diff --git a/versioned_docs/version-0.5.x/assets/ainet_blob.png b/versioned_docs/version-0.5.x/assets/ainet_blob.png new file mode 100644 index 00000000..b3749d53 Binary files /dev/null and b/versioned_docs/version-0.5.x/assets/ainet_blob.png differ diff --git a/versioned_docs/version-0.5.x/assets/ainet_circler.png b/versioned_docs/version-0.5.x/assets/ainet_circler.png new file mode 100644 index 00000000..b0f2c397 Binary files /dev/null and b/versioned_docs/version-0.5.x/assets/ainet_circler.png differ diff --git a/versioned_docs/version-0.5.x/assets/ainet_moon.png b/versioned_docs/version-0.5.x/assets/ainet_moon.png new file mode 100644 index 00000000..75c14fcc Binary files /dev/null and b/versioned_docs/version-0.5.x/assets/ainet_moon.png differ diff --git a/versioned_docs/version-0.5.x/assets/clonalg.png b/versioned_docs/version-0.5.x/assets/clonalg.png new file mode 100644 index 00000000..2fc76c79 Binary files /dev/null and b/versioned_docs/version-0.5.x/assets/clonalg.png differ diff --git a/versioned_docs/version-0.5.x/assets/exemple_airs_plot.png b/versioned_docs/version-0.5.x/assets/exemple_airs_plot.png new file mode 100644 index 00000000..fd4cbbbd Binary files /dev/null and b/versioned_docs/version-0.5.x/assets/exemple_airs_plot.png differ diff --git a/versioned_docs/version-0.5.x/assets/exemple_en_d.png b/versioned_docs/version-0.5.x/assets/exemple_en_d.png new file mode 100644 index 00000000..4e54d076 Binary files /dev/null and b/versioned_docs/version-0.5.x/assets/exemple_en_d.png differ diff --git a/versioned_docs/version-0.5.x/assets/exemple_en_v.png b/versioned_docs/version-0.5.x/assets/exemple_en_v.png new file mode 100644 index 00000000..077e32b2 Binary files /dev/null and b/versioned_docs/version-0.5.x/assets/exemple_en_v.png differ diff --git a/versioned_docs/version-0.5.x/assets/logo.svg b/versioned_docs/version-0.5.x/assets/logo.svg new file mode 100644 index 00000000..868c42c5 --- /dev/null +++ b/versioned_docs/version-0.5.x/assets/logo.svg @@ -0,0 +1,2190 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/versioned_docs/version-0.5.x/assets/matrixBNSA.png b/versioned_docs/version-0.5.x/assets/matrixBNSA.png new file mode 100644 index 00000000..ed20f41d Binary files /dev/null and b/versioned_docs/version-0.5.x/assets/matrixBNSA.png differ diff --git a/versioned_docs/version-0.5.x/examples/Classification/README.mdx b/versioned_docs/version-0.5.x/examples/Classification/README.mdx new file mode 100644 index 00000000..07fbe438 --- /dev/null +++ b/versioned_docs/version-0.5.x/examples/Classification/README.mdx @@ -0,0 +1,46 @@ +--- +sidebar_position: 1 +lastUpdatedAt: 2025/05/25 +author: João Paulo +showLastUpdateAuthor: true +showLastUpdateTime: true +keywords: + - Binary + - classifying + - anomalies + - not self + - affinity threshold + - Negative Selection Algorithm + - Artificial Immune System (AIS) + - Self and non-self + - Immune + - Computação Natural + - mushrooms dataset + - iris dataset + - geyser dataset +--- + +import DocCardList from '@theme/DocCardList'; + +# Classification + +Access the notebooks with the option to run them online using Binder: [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/AIS-Package/aisp/HEAD?labpath=%2Fexamples%2Fen%2Fclassification) + +--- + +## The examples are organized below: + +### Data Normalization: +> Shows how to normalize data using negative selection classes. In the real-valued version, the data is normalized between 0 and 1. In the binary version, it is normalized into a bit vector. + +### K-fold Cross Validation with 50 Interactions: +> In this example, the data is divided into training and test sets and model performance is evaluated by cross-validation. So with dividing the training data into k parts. In each iteration, 10% of the training data is reserved for testing. + +### Training: +> The trained model is tested in this example with all available training data. + +The examples below show various functionality of negative selection classes so that you know how to use them in your project. Feel free to explore these examples and adapt them as needed to meet your specific needs. + +## Examples: + + \ No newline at end of file diff --git a/versioned_docs/version-0.5.x/examples/Classification/csa.md b/versioned_docs/version-0.5.x/examples/Classification/csa.md new file mode 100644 index 00000000..aba99717 --- /dev/null +++ b/versioned_docs/version-0.5.x/examples/Classification/csa.md @@ -0,0 +1,60 @@ +--- +title: Clonal Selection Algorithm +sidebar_position: 2 +lastUpdatedAt: 2025/05/25 +author: João Paulo +showLastUpdateAuthor: true +showLastUpdateTime: true +last_update: + date: 2025/05/25 + author: João Paulo +keywords: + - Clonal Selection Algorithm + - CSA + - Artificial Immune System + - AIS + - AIRS + - Binary Algorithm + - NSA + - immune-inspired algorithms + - machine learning + - classification + - anomaly detection + - mushrooms dataset + - iris dataset + - geyser dataset + - real-valued detectors + - immune recognition +--- + +This page presents a collection of practical examples showcasing how to use the Clonal Selection Algorithm. + +## AIRS (Artificial Immune Recognition System) + +Run notebooks online via Binder: [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/AIS-Package/aisp/HEAD?labpath=%2Fexamples%2Fen%2Fclassification%2FAIRS) + +--- + +### Binary Algorithm + ++ [Example with random samples](https://github.com/AIS-Package/aisp/blob/main/examples/en/classification/AIRS/example_with_randomly_generated_dataset-en.ipynb) + +> In the example present in this notebook 1000 random samples were generated, arranged in two groups, one for each class. + ++ [mushrooms_dataBase_example](https://github.com/AIS-Package/aisp/blob/main/examples/en/classification/AIRS/mushrooms_dataBase_example_en.ipynb) + +> It uses the [mushrooms database](https://archive.ics.uci.edu/dataset/73/mushroom), which contains information about edible and poisonous mushrooms. + +### Real-Valued Algorithm + ++ [Example with random samples](https://github.com/AIS-Package/aisp/blob/main/examples/en/classification/AIRS/example_with_randomly_generated_dataset-en.ipynb) + +> In the example present in this notebook 500 random samples were generated, arranged in two groups, one for each class, we can see the non-self detectors generated below + ++ [iris_dataBase_example](https://github.com/AIS-Package/aisp/blob/main/examples/en/classification/AIRS/iris_dataBase_example_en.ipynb) + +> Example using the NSA [iris database](https://archive.ics.uci.edu/ml/datasets/iris), which contains four-dimensional samples and three output classes (Setosa, Versicolor and Virginica). + ++ [geyser_dataBase_example](https://github.com/AIS-Package/aisp/blob/main/examples/en/classification/AIRS/geyser_dataBase_example_en.ipynb) + +> To classify geyser eruptions in Yellowstone National Park, this notebook uses the [Old Faithful database](https://github.com/mwaskom/seaborn-data/blob/master/geyser.csv). diff --git a/versioned_docs/version-0.5.x/examples/Classification/nsa.md b/versioned_docs/version-0.5.x/examples/Classification/nsa.md new file mode 100644 index 00000000..89981dd5 --- /dev/null +++ b/versioned_docs/version-0.5.x/examples/Classification/nsa.md @@ -0,0 +1,60 @@ +--- +sidebar_position: 1 +lastUpdatedAt: 2023/05/30 +author: João Paulo +showLastUpdateAuthor: true +showLastUpdateTime: true +last_update: + date: 2023/05/30 + author: João Paulo +keywords: + - Binary + - classifying + - anomalies + - not self + - affinity threshold + - Negative Selection Algorithm + - Artificial Immune System (AIS) + - Self and non-self + - Immune + - Computação Natural + - mushrooms dataset + - iris dataset + - geyser dataset +--- + +# Negative Selection Algorithm + +On this page, you will find a collection of practical examples that demonstrate how to use the negative selection classes implemented in our package. + +## BNSA (Binary Negative Selection Algorithm) + +Run notebooks online via Binder: [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/AIS-Package/aisp/HEAD?labpath=%2Fexamples%2Fen%2Fclassification%2FBNSA) + +--- + ++ [Example with random samples](https://github.com/AIS-Package/aisp/blob/main/examples/en/classification/BNSA/example_with_randomly_generated_dataset-en.ipynb) + +> In the example present in this notebook 1000 random samples were generated, arranged in two groups, one for each class. + ++ [mushrooms_dataBase_example](https://github.com/AIS-Package/aisp/blob/main/examples/en/classification/BNSA/mushrooms_dataBase_example_en.ipynb) + +> It uses the [mushrooms database](https://archive.ics.uci.edu/dataset/73/mushroom), which contains information about edible and poisonous mushrooms. + +## RNSA (Real-Valued Negative Selection Algorithm) + +Run notebooks online via Binder: [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/AIS-Package/aisp/HEAD?labpath=%2Fexamples%2Fen%2Fclassification%2FRNSA) + +--- + ++ [Example with random samples](https://github.com/AIS-Package/aisp/blob/main/examples/en/classification/RNSA/example_with_randomly_generated_dataset-en.ipynb) + +> In the example present in this notebook 500 random samples were generated, arranged in two groups, one for each class, we can see the non-self detectors generated below + ++ [iris_dataBase_example](https://github.com/AIS-Package/aisp/blob/main/examples/en/classification/RNSA/iris_dataBase_example_en.ipynb) + +> Example using the NSA [iris database](https://archive.ics.uci.edu/ml/datasets/iris), which contains four-dimensional samples and three output classes (Setosa, Versicolor and Virginica). + ++ [geyser_dataBase_example](https://github.com/AIS-Package/aisp/blob/main/examples/en/classification/RNSA/geyser_dataBase_example_en.ipynb) + +> To classify geyser eruptions in Yellowstone National Park, this notebook uses the [Old Faithful database](https://github.com/mwaskom/seaborn-data/blob/master/geyser.csv). diff --git a/versioned_docs/version-0.5.x/examples/Clustering/README.mdx b/versioned_docs/version-0.5.x/examples/Clustering/README.mdx new file mode 100644 index 00000000..dec56264 --- /dev/null +++ b/versioned_docs/version-0.5.x/examples/Clustering/README.mdx @@ -0,0 +1,50 @@ +--- +sidebar_position: 1 +lastUpdatedAt: 2025/05/25 +author: João Paulo +showLastUpdateAuthor: true +showLastUpdateTime: true +keywords: + - Binary + - Clustering + - anomalies + - not self + - affinity threshold + - Artificial Immune System (AIS) + - Self and non-self + - Immune + - Computação Natural + - mushrooms dataset + - iris dataset + - geyser dataset + - Silhouette score + - Adjusted Rand Index +--- + +import DocCardList from '@theme/DocCardList'; + +# Clustering + +Access the notebooks with the option to run them online using Binder: [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/AIS-Package/aisp/HEAD?labpath=%2Fexamples%2Fen%2Fclustering) + + +--- + +## The examples are organized below: + +### Data Normalization +> It presents the use of the original (non-normalized) data and demonstrates how to normalize it between 0 and 1 +> using MinMaxScaler, preparing the dataset for training and enhancing clustering performance. + +### Training Model +> Initializes and trains the model, identifies clusters, and evaluates clustering quality using metrics such as +> Silhouette Score and Adjusted Rand Index (ARI). + +### Visualizing Clusters +> Visualizes the formed clusters, the antibody population, and the immune network. + +--- + +## Examples: + + \ No newline at end of file diff --git a/versioned_docs/version-0.5.x/examples/Clustering/ina.md b/versioned_docs/version-0.5.x/examples/Clustering/ina.md new file mode 100644 index 00000000..26ef03c8 --- /dev/null +++ b/versioned_docs/version-0.5.x/examples/Clustering/ina.md @@ -0,0 +1,39 @@ +--- +title: Immune Network Algorithms +sidebar_position: 2 +lastUpdatedAt: 2025/05/25 +author: João Paulo +showLastUpdateAuthor: true +showLastUpdateTime: true +last_update: + date: 2025/05/25 + author: João Paulo +keywords: + - Immune Network Algorithm + - Artificial Immune System + - AIS + - immune-inspired algorithms + - machine learning + - iris dataset + - geyser dataset +--- + +On this page, you will find a collection of practical examples that demonstrate how to use the Immune Network Algorithm classes implemented in our package. + +Run notebooks online via Binder: [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/AIS-Package/aisp/HEAD?labpath=%2Fexamples%2Fen%2Fclustering%2FAiNet) + +## AiNet (Artificial Immune Network) + +--- + ++ [Random datasets](https://github.com/AIS-Package/aisp/blob/main/examples/en/clustering/AiNet/example_with_randomly_generated_dataset.ipynb) + +> In this notebook AiNet is demonstrated on three synthetic datasets: +> +> + **Blobs:** well-defined spherical clusters, easy to separate. +> + **Moons:** non-linear clusters, illustrating more complex decision boundaries. +> + **Circles:** two concentric circles, showing the capability of handling non-linear separation. + ++ [geyser_dataBase_example](https://github.com/AIS-Package/aisp/blob/main/examples/en/clustering/AiNet/geyser_dataBase_example.ipynb) + +> To classify geyser eruptions in Yellowstone National Park, this notebook uses the [Old Faithful database](https://github.com/mwaskom/seaborn-data/blob/master/geyser.csv). diff --git a/versioned_docs/version-0.5.x/examples/Optimization/README.mdx b/versioned_docs/version-0.5.x/examples/Optimization/README.mdx new file mode 100644 index 00000000..a0a554f2 --- /dev/null +++ b/versioned_docs/version-0.5.x/examples/Optimization/README.mdx @@ -0,0 +1,31 @@ +--- +sidebar_position: 3 +lastUpdatedAt: 2025/09/20 +author: João Paulo +showLastUpdateAuthor: true +showLastUpdateTime: true +keywords: + - optimization + - artificial immune system + - affinity threshold + - natural computation + - heuristic algorithms + - function optimization + - benchmark datasets + - evolutionary computation + - tsp + - rastrigin + - knapsack +--- + +import DocCardList from '@theme/DocCardList'; + +# Optimization + +Access the notebooks with the option to run them online using Binder: [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/AIS-Package/aisp/HEAD?labpath=%2Fexamples%2Fen%2Foptimization) + +--- + +## Examples: + + \ No newline at end of file diff --git a/versioned_docs/version-0.5.x/examples/Optimization/csa.md b/versioned_docs/version-0.5.x/examples/Optimization/csa.md new file mode 100644 index 00000000..21176f04 --- /dev/null +++ b/versioned_docs/version-0.5.x/examples/Optimization/csa.md @@ -0,0 +1,40 @@ +--- +title: Clonal Selection Algorithms +sidebar_position: 3 +showLastUpdateAuthor: true +showLastUpdateTime: true +keywords: + - clonalg + - clonal selection algorithm + - artificial immune system + - AIS + - immune-inspired algorithms + - optimization + - tsp + - Traveling Salesman Problem + - knapsack + - rastrigin + - machine learning +--- + +On this page, you will find a collection of practical examples that demonstrate how to use the Clonal Selection Algorithms classes implemented in our package. + +Run notebooks online via Binder: [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/AIS-Package/aisp/HEAD?labpath=%2Fexamples%2Fen%2Foptimization%2Fclonalg) + +--- + +## Clonalg (Clonal Selection Algorithm) + ++ [Traveling Salesman Problem](https://github.com/AIS-Package/aisp/blob/main/examples/en/optimization/clonalg/tsp_problem_example.ipynb) + +> In this notebook, apply **Clonalg** to the Knapsack Problem using optimization algorithms from the AISP package. + ++ [Rastrigin Function](https://github.com/AIS-Package/aisp/blob/main/examples/en/optimization/clonalg/rastrigin_function_example.ipynb) + +> In this notebook, we apply **Clonalg** to the **Rastrigin Function**, a classic continuous optimization problem using optimization algorithms from the **AISP** package. + ++ [Knapsack Problem](https://github.com/AIS-Package/aisp/blob/main/examples/en/optimization/clonalg/knapsack_problem_example.ipynb) + +> In this notebook, apply **Clonalg** to the Knapsack Problem using optimization algorithms from the AISP package. + +--- diff --git a/versioned_docs/version-0.5.x/examples/README.mdx b/versioned_docs/version-0.5.x/examples/README.mdx new file mode 100644 index 00000000..08d6de7e --- /dev/null +++ b/versioned_docs/version-0.5.x/examples/README.mdx @@ -0,0 +1,11 @@ +--- +sidebar_position: 2.5 +--- + +import DocCardList from '@theme/DocCardList'; + +# Examples + +Below are some examples that use the package with the Jupyter Notebook tool. + + \ No newline at end of file diff --git a/versioned_docs/version-0.5.x/getting-started/_category_.json b/versioned_docs/version-0.5.x/getting-started/_category_.json new file mode 100644 index 00000000..560390a4 --- /dev/null +++ b/versioned_docs/version-0.5.x/getting-started/_category_.json @@ -0,0 +1,5 @@ +{ + "label": "Getting Started", + "position": 1.5 +} + diff --git a/versioned_docs/version-0.5.x/getting-started/basic-use/AIRS.md b/versioned_docs/version-0.5.x/getting-started/basic-use/AIRS.md new file mode 100644 index 00000000..12e618b9 --- /dev/null +++ b/versioned_docs/version-0.5.x/getting-started/basic-use/AIRS.md @@ -0,0 +1,93 @@ +--- +title: Using the AIRS +sidebar_label: Using the AIRS +lastUpdatedAt: 2025/05/17 +author: João Paulo +showLastUpdateAuthor: true +showLastUpdateTime: true +last_update: + date: 2025/05/17 + author: João Paulo +keywords: + - Clonal Selection Algorithm + - CSA + - Artificial Immune System + - AIS + - AIRS + - Binary Algorithm + - NSA + - immune-inspired algorithms + - machine learning + - classification + - anomaly detection + - mushrooms dataset + - iris dataset + - geyser dataset + - real-valued detectors + - immune recognition +--- + +Access the Jupyter notebook with the code available [here](https://github.com/AIS-Package/aisp/blob/main/examples/en/classification/AIRS/example_with_randomly_generated_dataset-en.ipynb)! + +Run notebook online via Binder: [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/AIS-Package/aisp/HEAD?labpath=%2Fexamples%2Fen%2Fclassification%2FAIRS%2Fexample_with_randomly_generated_dataset-en.ipynb) + +### Importing the Artificial Immune Recognition System + +```python +from aisp.csa import AIRS +``` + +### Generating dice bubbles for classes randomly + +Using the `make_blobs` function, two sets of data are generated in the form of bubbles, in the range between 0 and 1, representing each class x and y. Then this data is separated into test and training sets. + +```python +from sklearn.datasets import make_blobs +from sklearn.model_selection import train_test_split + +# Generating the samples and outputs for the training. +samples, output = make_blobs(n_samples=500 , n_features=2, cluster_std=0.07, center_box=([0.0, 1.0]), centers=[[0.25, 0.75], [0.75, 0.25]], random_state=1234) +# Separating data for training and testing. +train_x, test_x, train_y, test_y = train_test_split(samples, output, test_size=0.2) +``` + +--- + +### Testing the model AIRS + +Then, it presents the result of the forecast accuracy. + +```python +from sklearn.metrics import confusion_matrix, classification_report, accuracy_score + +# Starting the class. +airs = AIRS(seed=1234) +# Carrying out the training: +airs.fit(X=train_x, y=train_y) +# Previewing classes with test samples. +prev_y = airs.predict(test_x) +# Showing the accuracy of predictions for data. +print(f"The accuracy is {accuracy_score(prev_y, test_y)}") +print(classification_report(test_y, prev_y)) +``` + +Output: + +```bash +✔ Set of memory cells for classes (0, 1) successfully generated: ┇██████████┇ 400/400 memory cells for each aᵢ +The accuracy is 1.0 + precision recall f1-score support + + 0 1.00 1.00 1.00 51 + 1 1.00 1.00 1.00 49 + + accuracy 1.00 100 + macro avg 1.00 1.00 1.00 100 +weighted avg 1.00 1.00 1.00 100 +``` + +--- + +### Memory cell and sample plotting + +![Memory cell and sample plotting](../../assets/exemple_airs_plot.png) diff --git a/versioned_docs/version-0.5.x/getting-started/basic-use/AiNet.mdx b/versioned_docs/version-0.5.x/getting-started/basic-use/AiNet.mdx new file mode 100644 index 00000000..b770c3ea --- /dev/null +++ b/versioned_docs/version-0.5.x/getting-started/basic-use/AiNet.mdx @@ -0,0 +1,266 @@ +--- +title: Using the AiNet +sidebar_label: Using the AiNet +lastUpdatedAt: 2025/08/02 +author: João Paulo +showLastUpdateAuthor: true +showLastUpdateTime: true +last_update: + date: 2025/08/02 + author: João Paulo +keywords: + - Artificial Immune Network + - AiNet + - immune-inspired algorithms + - clustering + - machine learning + - anomaly detection + - make_blobs + - make_moons + - make_circles + - data visualization + - networkx +--- + +# Using the AiNet + +Access the Jupyter notebook with the code available [here](https://github.com/AIS-Package/aisp/blob/main/examples/en/clustering/AiNet/example_with_randomly_generated_dataset.ipynb)! + +Run notebook online via Binder: [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/AIS-Package/aisp/HEAD?labpath=%2Fexamples%2Fen%2Fclustering%2FAiNet%2Fexample_with_randomly_generated_dataset.ipynb) + +## Introduction + +Clustering is an unsupervised machine learning task that groups data into clusters. + +In this notebook, we explore **AiNet (Artificial Immune Network)**. AiNet uses concepts such as antibody affinity and clone suppression to identify cluster centers. + +**Objective:** Demonstrate AiNet on random datasets: + +* **Blobs:** Well-defined spherical clusters. +* **Moons:** Non-linear clusters. +* **Circles:** Two concentric circles, showing non-linear separation. + +**Notebook Structure:** + +* Setup: Install and import libraries. +* Visualization Function: Plot AiNet results. +* Demonstration 1 - Blobs +* Demonstration 2 - Moons +* Demonstration 3 - Circles + +--- + +## Importing the Artificial Immune Network +```python +from aisp.ina import AiNet +``` + +--- + +## Visualization Function + +
+AiNet Visualization Function (plots clusters and immune network) + +```python +def plot_immune_network(train_x, predict_y, model, title_prefix=""): + """ + Plots the clustering results of AiNet. + + Parameters: + train_x (np.array): Input data. + predict_y (np.array): Cluster predictions from the model. + model (AiNet): The trained AiNet model. + title_prefix (str, optional): A prefix for the plot titles. + """ + clusters = list(model._memory_network.values()) + network = np.array(model._population_antibodies) + + fig, axs = plt.subplots(2, 2, figsize=(15, 15)) + colors = colormaps.get_cmap('Accent') + + # Original data + axs[0][0].scatter(train_x[:, 0], train_x[:, 1], color='dodgerblue', alpha=0.9, s=50, marker='o', edgecolors='k') + axs[0][0].set_title(f'{title_prefix}Original Data', fontsize=16) + axs[0][0].set_xlabel('X', fontsize=14) + axs[0][0].set_ylabel('Y', fontsize=14) + axs[0][0].grid(True, linestyle='--', alpha=0.5) + + # Antibody population + axs[0][1].scatter(network[:, 0], network[:, 1], color='crimson', alpha=0.9, s=70, marker='.', edgecolors='k') + axs[0][1].set_title(f'{title_prefix}Antibody Population', fontsize=16) + axs[0][1].set_xlabel('X', fontsize=14) + axs[0][1].set_ylabel('Y', fontsize=14) + axs[0][1].grid(True, linestyle='--', alpha=0.5) + + # Cluster predictions + scatter = axs[1][0].scatter(train_x[:, 0], train_x[:, 1], c=predict_y, cmap='Accent', s=50, edgecolors='k', alpha=0.9) + axs[1][0].set_title(f'{title_prefix}Cluster Predictions (AiNet)', fontsize=16) + axs[1][0].set_xlabel('X', fontsize=14) + axs[1][0].set_ylabel('Y', fontsize=14) + axs[1][0].grid(True, linestyle='--', alpha=0.5) + legend1 = axs[1][0].legend(*scatter.legend_elements(), title="Clusters") + axs[1][0].add_artist(legend1) + + # Immune Network Graph + G = nx.Graph() + positions = {} + for i, cluster in enumerate(clusters): + cluster_nodes = [f'{i}_{j}' for j in range(len(cluster))] + G.add_nodes_from(cluster_nodes) + for node, point in zip(cluster_nodes, cluster): + positions[node] = tuple(point) + dist_matrix = squareform(pdist(cluster)) + mst_local = minimum_spanning_tree(dist_matrix).toarray() + for row_idx, row in enumerate(mst_local): + for col_idx, weight in enumerate(row): + if weight > 0: + G.add_edge(cluster_nodes[row_idx], cluster_nodes[col_idx], weight=weight) + for i, cluster in enumerate(clusters): + cluster_nodes = [f'{i}_{j}' for j in range(len(cluster))] + nx.draw_networkx_nodes(G, positions, nodelist=cluster_nodes, ax=axs[1][1], + node_color=[colors(i)], node_size=70, edgecolors='k', label=f'Cluster {i}') + nx.draw_networkx_edges(G, positions, ax=axs[1][1], alpha=0.6) + axs[1][1].set_title(f'{title_prefix}Graph Immune Network', fontsize=16) + axs[1][1].set_xlabel('X', fontsize=14) + axs[1][1].set_ylabel('Y', fontsize=14) + axs[1][1].grid(True, linestyle='--', alpha=0.5) + axs[1][1].legend() + plt.tight_layout() + plt.show() +``` + +
+ +--- + +## Demonstration 1 - Blobs Dataset + +### Generating data + +```python +samples, output = make_blobs( + n_samples=1000, + cluster_std=0.07, + center_box=(0.0, 1.0), + centers=[[0.25, 0.75], [0.75, 0.25]], + random_state=1234, +) +``` + +### Training AiNet + +```python +model = AiNet(suppression_threshold=0.96, affinity_threshold=0.95, mst_inconsistency_factor=3, seed=123) +predict_y = model.fit_predict(samples) +``` + +Output: +```bash +✔ Set of memory antibodies for classes (0, 1) successfully generated | Clusters: 2 | Population of antibodies size: 104: ┇██████████┇ 10/10 total training interactions +``` + +### Silhouette score + +```python +silhouette = silhouette_score(samples, predict_y) +print(f"Silhouette Coefficient: {silhouette:.3f}") +``` + +Output: +```bash +Silhouette Coefficient: 0.826 +``` + +### Visualization + +```python +plot_immune_network(samples, predict_y, model, title_prefix="Blobs - ") +``` + +![Blobs](../../assets/ainet_blob.png) + +--- + +## Demonstration 2 - Moons Dataset + +### Generating data + +```python +samples, output = make_moons(n_samples=1000, noise=0.05, random_state=42) +samples = MinMaxScaler().fit_transform(samples) +``` + +### Training AiNet + +```python +model = AiNet(suppression_threshold=0.95, affinity_threshold=0.97, mst_inconsistency_factor=2.5, seed=123) +predict_y = model.fit_predict(samples) +``` + +Output: +```bash +✔ Set of memory antibodies for classes (0, 1) successfully generated | Clusters: 2 | Population of antibodies size: 69: ┇██████████┇ 10/10 total training interactions +``` + +### Silhouette score + +```python +silhouette = silhouette_score(samples, predict_y) +print(f"Silhouette Coefficient: {silhouette:.3f}") +``` + +Output: +```bash +Silhouette Coefficient: 0.398 +``` + +### Visualization + +```python +plot_immune_network(samples, predict_y, model, title_prefix="Moons - ") +``` + +![Moons](../../assets/ainet_moon.png) + +--- + +## Demonstration 3 - Circles Dataset + +### Generating data + +```python +samples, output = make_circles(n_samples=1000, noise=0.05, factor=0.5, random_state=42) +samples = MinMaxScaler().fit_transform(samples) +``` + +### Training AiNet + +```python +model = AiNet(suppression_threshold=0.97, affinity_threshold=0.98, mst_inconsistency_factor=3.8, seed=123) +predict_y = model.fit_predict(samples) +``` + +Output: +```bash +✔ Set of memory antibodies for classes (0, 1) successfully generated | Clusters: 2 | Population of antibodies size: 169: ┇██████████┇ 10/10 total training interactions +``` + +### Silhouette score + +```python +silhouette = silhouette_score(samples, predict_y) +print(f"Silhouette Coefficient: {silhouette:.3f}") +``` + +Output: +```bash +Silhouette Coefficient: 0.112 +``` +### Visualization + +```python +plot_immune_network(samples, predict_y, model, title_prefix="Circles - ") +``` + +![AiNet immune network visualization generated from the Circles Dataset](../../assets/ainet_circler.png) diff --git a/versioned_docs/version-0.5.x/getting-started/basic-use/BNSA.md b/versioned_docs/version-0.5.x/getting-started/basic-use/BNSA.md new file mode 100644 index 00000000..4b58e8f7 --- /dev/null +++ b/versioned_docs/version-0.5.x/getting-started/basic-use/BNSA.md @@ -0,0 +1,136 @@ +--- +title: Using the BNSA +sidebar_label: Using the BNSA +lastUpdatedAt: 2025/05/17 +author: João Paulo +showLastUpdateAuthor: true +showLastUpdateTime: true +last_update: + date: 2025/05/17 + author: João Paulo +keywords: + - Binary + - classifying + - anomalies + - not self + - affinity threshold + - Negative Selection Algorithm + - Artificial Immune System (AIS) + - Self and non-self + - Immune + - Computação Natural +--- + +The present example, available here, aims to demonstrate the application of the binary negative selection algorithm. This algorithm is used to classify samples with discrete characteristics. + +Access the Jupyter notebook with the code available [here](https://github.com/AIS-Package/aisp/blob/main/examples/en/classification/BNSA/example_with_randomly_generated_dataset-en.ipynb)! + +Run notebook online via Binder: [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/AIS-Package/aisp/HEAD?labpath=%2Fexamples%2Fen%2Fclassification%2FBNSA%2Fexample_with_randomly_generated_dataset-en.ipynb) + +## Importing the BNSA algorithm + +```python +from aisp.nsa import BNSA +``` + +## Generating samples + +Algorithm training and testing needs data samples. Thus, for the demonstration, two random classes were generated, using the following function: + +```python +import numpy as np +from scipy.spatial.distance import cdist + +def generate_samples(n_samples: int, n_features: int, s: float, x: None): + class_samples = [] + while len(class_samples) < n_samples: + similarity = 0 + sample_rand = np.random.randint(0, 2, size=(n_features)) + if(len(class_samples) > max(int(n_samples * 0.1), 1)): + similarity = cdist(class_samples, np.expand_dims(sample_rand, axis=0), metric='hamming')[0, :] + if x is not None: + if similarity[0] <= s and not np.any(np.all(sample_rand == x, axis=1)): + class_samples.append(sample_rand) + elif similarity[0] <= s: + class_samples.append(sample_rand) + else: + class_samples.append(sample_rand) + return np.array(class_samples) +``` + +--- + +Each class will have 500 samples, with the minimum similarity between samples being 80% (s = 0.2). These classes will be separated into training (800 samples) and testing (200 samples) sets. + +```python +from sklearn.model_selection import train_test_split +# Setting the seed to 121 to ensure the reproducibility of the generated data. +np.random.seed(121) +# Generating samples for class "x". +x = generate_samples(500, 20, 0.2, None) +# Generating unique samples for class "y", different from samples present in class "x". +y = generate_samples(500, 20, 0.2, x) +# Adding columns containing the outputs (labels) of classes "x" and "y". +x = np.hstack((x, np.full((x.shape[0], 1), 'x'))) +y = np.hstack((y, np.full((y.shape[0], 1), 'y'))) +# Merging the two vectors (classes "x" and "y") and randomizing the order of the samples. +index = np.random.permutation(x.shape[0]*2) +dataset = np.vstack((x, y))[index] +# Separating the characteristics (inputs) and the output classes (labels). +samples = dataset[:, :-1].astype(int) +output = dataset[:, -1] +# Data separation for training and testing. +train_x, test_x, train_y, test_y = train_test_split(samples, output, test_size=0.2, random_state=1234321) + +``` + +--- + +## Training + +The model is tuned through training patterns. In this application, negative selection will distribute, with a differentiation rate of 30%, 250 detectors across the input space. + +```python +from sklearn.metrics import confusion_matrix, classification_report, accuracy_score +# Starting the model. +nsa = BNSA(N=250, aff_thresh=0.30, seed=1234321, max_discards=10000) +# Conducting the training: +nsa.fit(X=train_x, y=train_y) +# Visualization of classes with test samples. +prev_y = nsa.predict(test_x) +# Showing the accuracy of predictions for real data. +print(f"The accuracy is {accuracy_score(prev_y, test_y)}") +print(classification_report(test_y, prev_y)) +``` + +Output: + +``` +✔ Non-self detectors for classes (x, y) successfully generated: ┇██████████┇ 500/500 detectors +The accuracy is 0.93 + precision recall f1-score support + + x 0.93 0.91 0.92 90 + y 0.93 0.95 0.94 110 + + accuracy 0.93 200 + macro avg 0.93 0.93 0.93 200 +weighted avg 0.93 0.93 0.93 200 +``` + +--- + +## Evaluation + +The model obtained an accuracy of 0.93 for the test set. The precision in each class, for both x and y, was also 0.93. This can be seen in the confusion matrix in Figure 1. + +```python +# Generating the confusion matrix and plotting it graphically. +mat = confusion_matrix(y_true=test_y, y_pred=prev_y) +sns.heatmap(mat.T, square=True, annot=True, fmt='d', cbar=False, xticklabels=nsa.classes, yticklabels=nsa.classes) +plt.xlabel('Real') +plt.ylabel('Estimated') +plt.show() +``` + +![BNSA confusion Matrix](../../assets/matrixBNSA.png) diff --git a/versioned_docs/version-0.5.x/getting-started/basic-use/Clonalg.md b/versioned_docs/version-0.5.x/getting-started/basic-use/Clonalg.md new file mode 100644 index 00000000..df75714e --- /dev/null +++ b/versioned_docs/version-0.5.x/getting-started/basic-use/Clonalg.md @@ -0,0 +1,222 @@ +--- +title: Using the Clonalg +sidebar_label: Using the Clonalg +author: João Paulo +showLastUpdateAuthor: true +showLastUpdateTime: true +last_update: + date: 2025/09/17 + author: João Paulo +keywords: + - clonalg + - clonal algorithm + - optimization + - rastrigin function + - artificial intelligence + - immune algorithm + - optimization benchmark + - machine learning + - metaheuristics +--- + +Access the Jupyter notebook with the code available [here](https://github.com/AIS-Package/aisp/blob/main/examples/en/optimization/clonalg/rastrigin_function_example.ipynb)! + +Run notebook online via Binder: [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/AIS-Package/aisp/HEAD?urlpath=%2Fdoc%2Ftree%2F%2Fexamples%2Fen%2Foptimization%2Fclonalg%2Frastrigin_function_example.ipynb) + +### Clonalg to the Rastrigin Function + +The Rastrigin function is a multimodal, non-convex function with many local minima, making it an excellent benchmark for optimization algorithms, [learn more](https://en.wikipedia.org/wiki/Rastrigin_function). The function is defined as: + +$$ f(x) = 10n + \sum_{i=1}^{n} (x_i^{2} - 10\cos(2\pi x_i)) $$ + +Where: + +* **n** is the problem dimension +* **xᵢ** ∈ \[−5.12, 5.12] for each dimension +* **Global minimum**: f(0,0) = 0 + +### Import of the required libraries + +```python +# Importing the Clonal Selection Algorithm (CLONALG) +from aisp.csa import Clonalg + +# Libraries for data manipulation and numerical calculations +import numpy as np + +# Data visualization +import matplotlib.pyplot as plt +``` + +### Problem Definition + +```python +problem_size = 2 +bounds = {'low': -5.12, 'high': 5.12} + +def rastrigin_fitness(x: np.ndarray) -> float: + x = np.clip(x, bounds['low'], bounds['high']) + + n = len(x) + result = 10 * n + for i in range(n): + result += x[i]**2 - 10 * np.cos(2 * np.pi * x[i]) + return result +``` + +### Algorithm configuration + +```python +# Optimized Clonalg configuration for Rastrigin function +clonalg = Clonalg( + problem_size=problem_size, + N=50, + selection_size=15, + rate_clonal=10, + rate_hypermutation=0.3, + n_diversity_injection=15, + bounds=bounds, + seed=1234 +) + +# Register the fitness function +clonalg.register('affinity_function', rastrigin_fitness) +``` + +### Running the optimization + +```python +clonalg.optimize(100, 20) + +if clonalg.best_cost is not None: + print('Best cost:', abs(clonalg.best_cost)) +``` + +Output: + +```bash +┌───────────┬─────────────────────────┬────────────────────┬─────────────────┐ +│ Iteration │ Best Affinity (min) │ Worse Affinity │ Stagnation │ +├───────────┼─────────────────────────┼────────────────────┼─────────────────┤ +│ 1 │ 7.153385│ 76.021342│ 0 │ +│ 2 │ 2.344533│ 33.315827│ 0 │ +│ 3 │ 2.140116│ 30.948129│ 0 │ +│ 4 │ 2.140116│ 31.998642│ 1 │ +│ 5 │ 0.484366│ 56.071764│ 0 │ +│ 6 │ 0.185833│ 36.260411│ 0 │ +│ 7 │ 0.185833│ 27.861454│ 1 │ +│ 8 │ 0.185833│ 29.599095│ 2 │ +│ 9 │ 0.185833│ 17.182111│ 3 │ +│ 10 │ 0.185833│ 18.465362│ 4 │ +│ 11 │ 0.185833│ 56.496717│ 5 │ +│ 12 │ 0.161393│ 33.675148│ 0 │ +│ 13 │ 0.161393│ 22.855341│ 1 │ +│ 14 │ 0.161393│ 71.552278│ 2 │ +│ 15 │ 0.161393│ 43.872058│ 3 │ +│ 16 │ 0.161393│ 28.045742│ 4 │ +│ 17 │ 0.161393│ 46.444268│ 5 │ +│ 18 │ 0.161393│ 28.197926│ 6 │ +│ 19 │ 0.030122│ 32.764169│ 0 │ +│ 20 │ 0.030122│ 27.485715│ 1 │ +│ 21 │ 0.030122│ 17.547005│ 2 │ +│ 22 │ 0.030122│ 43.293872│ 3 │ +│ 23 │ 0.030122│ 43.366562│ 4 │ +│ 24 │ 0.030122│ 42.037080│ 5 │ +│ 25 │ 0.030122│ 28.196466│ 6 │ +│ 26 │ 0.020278│ 37.645191│ 0 │ +│ 27 │ 0.020278│ 28.413549│ 1 │ +│ 28 │ 0.020278│ 32.007209│ 2 │ +│ 29 │ 0.020278│ 45.392869│ 3 │ +│ 30 │ 0.020278│ 15.223606│ 4 │ +│ 31 │ 0.020278│ 46.298146│ 5 │ +│ 32 │ 0.020278│ 21.641321│ 6 │ +│ 33 │ 0.020278│ 47.343886│ 7 │ +│ 34 │ 0.020278│ 20.720949│ 8 │ +│ 35 │ 0.020278│ 31.158014│ 9 │ +│ 36 │ 0.020278│ 42.655313│ 10 │ +│ 37 │ 0.020278│ 28.978964│ 11 │ +│ 38 │ 0.020278│ 27.926847│ 12 │ +│ 39 │ 0.020278│ 22.639969│ 13 │ +│ 40 │ 0.020278│ 43.618425│ 14 │ +│ 41 │ 0.020278│ 28.637045│ 15 │ +│ 42 │ 0.020278│ 36.324186│ 16 │ +│ 43 │ 0.020278│ 58.068571│ 17 │ +│ 44 │ 0.020278│ 61.189833│ 18 │ +│ 45 │ 0.020278│ 26.157713│ 19 │ +│ 46 │ 0.020278│ 49.301933│ 20 │ +└───────────┴─────────────────────────┴────────────────────┴─────────────────┘ +Total time: 0.079153 seconds +Best cost: 0.020278270044883584 +``` + +### Result + +```python +print(clonalg.get_report()) +``` + +Output: + +```python +============================================= + Optimization Summary +============================================= +Best cost : 0.020278270044883584 +Best solution : [ 0.0088594 -0.00487301] +Cost History per Iteration: + +┌────────────┬────────────────────────────┐ +│ Iteration │ Cost │ +├────────────┼────────────────────────────┤ +│ 1 │ 7.153385 │ +│ 2 │ 2.344533 │ +│ 3 │ 2.140116 │ +│ 4 │ 2.140116 │ +│ 5 │ 0.484366 │ +│ 6 │ 0.185833 │ +│ 7 │ 0.185833 │ +│ 8 │ 0.185833 │ +│ 9 │ 0.185833 │ +│ 10 │ 0.185833 │ +│ 11 │ 0.185833 │ +│ 12 │ 0.161393 │ +│ 13 │ 0.161393 │ +│ 14 │ 0.161393 │ +│ 15 │ 0.161393 │ +│ 16 │ 0.161393 │ +│ 17 │ 0.161393 │ +│ 18 │ 0.161393 │ +│ 19 │ 0.030122 │ +│ 20 │ 0.030122 │ +│ 21 │ 0.030122 │ +│ 22 │ 0.030122 │ +│ 23 │ 0.030122 │ +│ 24 │ 0.030122 │ +│ 25 │ 0.030122 │ +│ 26 │ 0.020278 │ +│ 27 │ 0.020278 │ +│ 28 │ 0.020278 │ +│ 29 │ 0.020278 │ +│ 30 │ 0.020278 │ +│ 31 │ 0.020278 │ +│ 32 │ 0.020278 │ +│ 33 │ 0.020278 │ +│ 34 │ 0.020278 │ +│ 35 │ 0.020278 │ +│ 36 │ 0.020278 │ +│ 37 │ 0.020278 │ +│ 38 │ 0.020278 │ +│ 39 │ 0.020278 │ +│ 40 │ 0.020278 │ +│ 41 │ 0.020278 │ +│ 42 │ 0.020278 │ +│ 43 │ 0.020278 │ +│ 44 │ 0.020278 │ +│ 45 │ 0.020278 │ +│ 46 │ 0.020278 │ +└────────────┴────────────────────────────┘ +``` + +### Evolution of the best over generations + +![Evolution of the best over generations](../../assets/clonalg.png) diff --git a/versioned_docs/version-0.5.x/getting-started/basic-use/RNSA.md b/versioned_docs/version-0.5.x/getting-started/basic-use/RNSA.md new file mode 100644 index 00000000..3b3d6fe6 --- /dev/null +++ b/versioned_docs/version-0.5.x/getting-started/basic-use/RNSA.md @@ -0,0 +1,128 @@ +--- +title: Using the RNSA +sidebar_label: Using the RNSA +lastUpdatedAt: 2025/05/17 +author: João Paulo +showLastUpdateAuthor: true +showLastUpdateTime: true +last_update: + date: 2025/05/17 + author: João Paulo +keywords: + - Real-Valued + - classifying + - anomalies + - not self + - V-detector + - Negative Selection Algorithm + - Artificial Immune System (AIS) + - Self and non-self + - Immune + - Computação Natural +--- + +Access the Jupyter notebook with the code available [here](https://github.com/AIS-Package/aisp/blob/main/examples/en/classification/RNSA/example_with_randomly_generated_dataset-en.ipynb)! + +Run notebook online via Binder: [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/AIS-Package/aisp/HEAD?labpath=%2Fexamples%2Fen%2Fclassification%2FRNSA%2Fexample_with_randomly_generated_dataset-en.ipynb) + +### Importing the Real-Valued Negative Selection Algorithm + +```python +from aisp.nsa import RNSA +``` + +### Generating dice bubbles for classes randomly + +Using the `make_blobs` function, two sets of data are generated in the form of bubbles, in the range between 0 and 1, representing each class x and y. Then this data is separated into test and training sets. + +```python +from sklearn.datasets import make_blobs +from sklearn.model_selection import train_test_split + +# Generating the samples and outputs for the training. +samples, output = make_blobs(n_samples=500 , n_features=2, cluster_std=0.07, center_box=([0.0, 1.0]), centers=[[0.25, 0.75], [0.75, 0.25]], random_state=1234) +# Separating data for training and testing. +train_x, test_x, train_y, test_y = train_test_split(samples, output, test_size=0.2) +``` + +--- + +### Testing the model `default-NSA` + +Start the model with 500 detectors, each with a radius of 0.06. Then, it presents the result of the forecast accuracy. + +```python +from sklearn.metrics import confusion_matrix, classification_report, accuracy_score + +# Starting the class. +model = RNSA(N=500, r=0.05, seed=1234) +# Carrying out the training: +model.fit(X=train_x, y=train_y) +# Previewing classes with test samples. +prev_y = model.predict(test_x) +# Showing the accuracy of predictions for actual data. +print(f"The accuracy is {accuracy_score(prev_y, test_y)}") +print(classification_report(test_y, prev_y)) +``` + +Output: + +```bash +✔ Non-self detectors for classes (0, 1) successfully generated: ┇██████████┇ 1000/1000 detectors +The accuracy is 1.0 + precision recall f1-score support + + 0 1.00 1.00 1.00 55 + 1 1.00 1.00 1.00 45 + + accuracy 1.00 100 + macro avg 1.00 1.00 1.00 100 +weighted avg 1.00 1.00 1.00 100 +``` + +--- + +### Detector and sample plotting + +![Detector and sample plotting](../../assets/exemple_en_d.png) + +--- + +### Testing the model `V-detector` + +Start the model with 50 detectors, where the minimum radius is 0.05 and the sample's own radius is 0.04. It then shows the forecast accuracy result. + +```python +from sklearn.metrics import confusion_matrix, classification_report, accuracy_score + +# Starting the class. +model = RNSA(N=20, r=0.02, algorithm='V-detector', r_s=0.04, seed=123) +# Carrying out the training: +model.fit(X=train_x, y=train_y) +# Previewing classes with test samples. +prev_y = model.predict(test_x) +# Showing the accuracy of predictions for actual data. +print(f"The accuracy is {accuracy_score(prev_y, test_y)}") +print(classification_report(test_y, prev_y)) +``` + +Output: + +```bash +✔ Non-self detectors for classes (0, 1) successfully generated: ┇██████████┇ 40/40 detectors +The accuracy is 1.0 + precision recall f1-score support + + 0 1.00 1.00 1.00 55 + 1 1.00 1.00 1.00 45 + + accuracy 1.00 100 + macro avg 1.00 1.00 1.00 100 +weighted avg 1.00 1.00 1.00 100 +``` + +--- + +### V-Detector and sample plotting + +![V-Detector and sample plotting](../../assets/exemple_en_v.png) diff --git a/versioned_docs/version-0.5.x/getting-started/basic-use/_category_.json b/versioned_docs/version-0.5.x/getting-started/basic-use/_category_.json new file mode 100644 index 00000000..04368434 --- /dev/null +++ b/versioned_docs/version-0.5.x/getting-started/basic-use/_category_.json @@ -0,0 +1,5 @@ +{ + "label": "Basic usage", + "position": 2, + "collapsible": false +} diff --git a/versioned_docs/version-0.5.x/getting-started/instalation.md b/versioned_docs/version-0.5.x/getting-started/instalation.md new file mode 100644 index 00000000..7ae233da --- /dev/null +++ b/versioned_docs/version-0.5.x/getting-started/instalation.md @@ -0,0 +1,65 @@ +--- +sidebar_position: 1 +title: Installation +sidebar_label: Installation +lastUpdatedAt: 2025/05/17 +author: João Paulo +showLastUpdateAuthor: true +showLastUpdateTime: true +last_update: + date: 2025/05/17 + author: João Paulo +--- + +This page contains information about dependencies, how to install and how to import modules. + +## **Dependencies:** + +The package requires [python 3.10](https://www.python.org/downloads/) or higher. + +
+ +| Packages | Version | +|:-------------:|:-------------:| +| numpy | ≥ 1.23.0 | +| scipy | ≥ 1.8.1 | +| tqdm | ≥ 4.64.1 | +| numba | ≥ 0.59.0 | + +
+ +## Installation procedure + +The simplest way to install is via ``pip``: + +```bash +pip install aisp +``` + +## **Importing modules** + +### Negative selection Algorithms + +```python +from aisp.nsa import RNSA, BNSA + +r_nsa = RNSA(N=300, r=0.05) +b_nsa = BNSA(N=300, aff_thresh=0.30) +``` + +### Clonal Selection Algorithms + +```python +from aisp.csa import AIRS, Clonalg + +airs = AIRS() +clonalg = Clonalg(problem_size=problem_size) +``` + +### Immune Network Algorithms + +```python +from aisp.ina import AiNet + +ai_net = AiNet(suppression_threshold=0.96, affinity_threshold=0.95) +``` diff --git a/versioned_docs/version-0.5.x/intro.md b/versioned_docs/version-0.5.x/intro.md new file mode 100644 index 00000000..178a8f7d --- /dev/null +++ b/versioned_docs/version-0.5.x/intro.md @@ -0,0 +1,42 @@ +--- +sidebar_position: 1 +lastUpdatedAt: 2023/05/30 +author: João Paulo +last_update: + date: 2025/05/17 + author: João Paulo +keywords: + - AISP + - Artificial Intelligence + - Artificial Immune Systems + - Natural Computing + - Immune-inspired Algorithms + - Optimization + - Pattern Recognition + - Python + - Open Source + - LGPLv3 + - Research + - Bioinspiration + - Immune Metaphors +--- +# Artificial Immune Systems Package + +
+ +![Artificial Immune Systems Package](./assets/logo.svg) + +
+ +--- + +## Introduction + +**AISP** is a Python package of immunoinspired techniques that apply metaphors from the vertebrate immune system to pattern recognition and optimization tasks. Conceived as an open-source package of artificial immune systems, AISP emerged from a research project initiated in **2022** at the Instituto Federal do Norte de Minas Gerais - Campus Salinas (**IFNMG - Salinas**). Its distribution is governed by the GNU Lesser General Public License v3.0 (LGPLv3). + +### Algorithms implemented + +> - [x] [**Negative Selection.**](./aisp-techniques/negative-selection/) +> - [x] [**Clonal Selection Algorithms.**](./aisp-techniques/clonal-selection-algorithms/) +> - [x] [**Immune Network Theory.**](./aisp-techniques/immune-network-theory/) +> - [ ] *Danger Theory* diff --git a/versioned_sidebars/version-0.5.x-sidebars.json b/versioned_sidebars/version-0.5.x-sidebars.json new file mode 100644 index 00000000..1fd014a2 --- /dev/null +++ b/versioned_sidebars/version-0.5.x-sidebars.json @@ -0,0 +1,8 @@ +{ + "docs": [ + { + "type": "autogenerated", + "dirName": "." + } + ] +} diff --git a/versions.json b/versions.json index 98e248f0..1a0684da 100644 --- a/versions.json +++ b/versions.json @@ -1,4 +1,5 @@ [ + "0.5.x", "0.4.x", "0.3.x", "0.2.x",