diff --git a/aisp/__init__.py b/aisp/__init__.py index fad8f7e..61142f0 100644 --- a/aisp/__init__.py +++ b/aisp/__init__.py @@ -31,5 +31,5 @@ from . import nsa __author__ = "AISP Development Team" -__version__ = "0.5.1" +__version__ = "0.5.4" __all__ = ["csa", "nsa", "ina"] diff --git a/aisp/base/core/_classifier.py b/aisp/base/core/_classifier.py index c5ab681..3ff2bca 100644 --- a/aisp/base/core/_classifier.py +++ b/aisp/base/core/_classifier.py @@ -67,7 +67,7 @@ def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: Parameters ---------- X : Union[npt.NDArray, list] - Input data for which predictions will be generated. + Data for which predictions will be generated. Returns ------- @@ -83,8 +83,8 @@ def score( """ Score function calculates forecast accuracy. - Details - ------- + Notes + ----- 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. @@ -116,11 +116,11 @@ def _slice_index_list_by_class(self, y: npt.NDArray) -> dict: Parameters ---------- y : npt.NDArray - Receives a y ``n_samples`` array with the output classes of the ``X`` sample array. + Receives a y `n_samples` array with the output classes of the `X` sample array. Returns ------- indices_by_class : dict - A dictionary with the list of array positions(``y``), with the classes as key. + A dictionary with the list of array positions(`y`), with the classes as key. """ return slice_index_list_by_class(self.classes, y) diff --git a/aisp/base/core/_clusterer.py b/aisp/base/core/_clusterer.py index ce376a7..00948f4 100644 --- a/aisp/base/core/_clusterer.py +++ b/aisp/base/core/_clusterer.py @@ -70,7 +70,7 @@ def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: Parameters ---------- X : Union[npt.NDArray, list] - Input data for which predictions will be generated. + Data for which predictions will be generated. Returns ------- @@ -87,7 +87,7 @@ def fit_predict(self, X: Union[npt.NDArray, list], verbose: bool = True) -> npt. Parameters ---------- X : Union[npt.NDArray, list] - Input data for which predictions will be generated. + Data for which predictions will be generated. verbose : bool, default=True Flag to enable or disable detailed output during training. diff --git a/aisp/base/core/_optimizer.py b/aisp/base/core/_optimizer.py index 2e23825..c65590a 100644 --- a/aisp/base/core/_optimizer.py +++ b/aisp/base/core/_optimizer.py @@ -160,7 +160,9 @@ def optimize( def affinity_function(self, solution: Any) -> float: """Evaluate the affinity of a candidate solution. - This abstract method must be implemented by the subclass to define the problem-specific. + This method must be implemented according to the specific optimization problem, defining + how the solution will be evaluated. The returned value should represent the quality of + the evaluated solution. Parameters ---------- @@ -186,10 +188,10 @@ def register(self, alias: str, function: Callable[..., Any]) -> None: Raises ------ TypeError - If `function` is not callable. + If the provided `function` is not callable. AttributeError - If `alias` is protected and cannot be modified. Or if `alias` does not exist in the - optimizer class. + If `alias` is protected and cannot be modified, or does not exist in the + class. """ if not callable(function): raise TypeError(f"Expected a function for '{alias}', got {type(function).__name__}") @@ -202,7 +204,10 @@ def register(self, alias: str, function: Callable[..., Any]) -> None: setattr(self, alias, function) def reset(self): - """Reset the object's internal state, clearing history and resetting values.""" + """Reset the object's internal state. + + Clears the optimization history and resetting values. + """ self._cost_history = [] self._solution_history = [] self._best_solution = None diff --git a/aisp/base/immune/cell.py b/aisp/base/immune/cell.py index a085e3d..e991c1c 100644 --- a/aisp/base/immune/cell.py +++ b/aisp/base/immune/cell.py @@ -72,14 +72,14 @@ def hyper_clonal_mutate( bounds: Optional[npt.NDArray[np.float64]] = None ) -> npt.NDArray: """ - Clones N features from a cell's features, generating a set of mutated vectors. + Generate N clones of the current cell and apply hypermutation to the clones. Parameters ---------- n : int - Number of clones to be generated from mutations of the original cell. + Number of clones to generate from the original b-cell. feature_type : { "binary-features", "continuous-features", "ranged-features" } - Specifies the type of feature_type to use based on the nature of the input features + Specifies the type of features of the cell. bounds : npt.NDArray[np.float64], optional Array (n_features, 2) with min and max per dimension. diff --git a/aisp/base/immune/mutation.py b/aisp/base/immune/mutation.py index 2450f56..b6faac9 100644 --- a/aisp/base/immune/mutation.py +++ b/aisp/base/immune/mutation.py @@ -19,9 +19,8 @@ def clone_and_mutate_continuous( """ Generate a set of mutated clones from a cell represented by a continuous vector. - 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 in distinct positions of the original vector. + This function creates `n` clones of the input vector and applies mutations to each of + them, simulating the process of clonal expansion in artificial immune systems. Parameters ---------- @@ -30,9 +29,8 @@ def clone_and_mutate_continuous( n : int The number of mutated clones to be generated. mutation_rate : float, default=1 - If 0 <= mutation_rate < 1: probability of mutating each component. - If mutation_rate >= 1 or mutation_rate <= 0: the mutation randomizes - a number of components between 1 and len(vector). + If 0 ≤ mutation_rate < 1, mutation probability per feature. + Otherwise, a random number of features is mutated. Returns ------- @@ -67,9 +65,8 @@ def clone_and_mutate_binary( """ Generate a set of mutated clones from a cell represented by a binary vector. - This function creates `n` clones of the input vector and applies random mutations to each of - them, changing some bits randomly. The process simulates clonal expansion in artificial - immune systems with discrete representations. + This function creates `n` clones of the input binary vector and applies mutations to the + bits, simulating clonal expansion in artificial immune systems with discrete representations. Parameters ---------- @@ -78,9 +75,8 @@ def clone_and_mutate_binary( n : int The number of mutated clones to be generated. mutation_rate : float, default=1 - If 0 <= mutation_rate < 1: probability of mutating each component. - If mutation_rate >= 1 or mutation_rate <= 0: the mutation randomizes - a number of components between 1 and len(vector). + If 0 ≤ mutation_rate < 1, mutation probability per feature. + Otherwise, a random number of features is mutated. Returns ------- @@ -116,9 +112,8 @@ def clone_and_mutate_ranged( """ Generate a set of mutated clones from a cell represented by custom ranges 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 in distinct positions of the original vector. + This function creates `n` clones of the input vector and applies mutations to each of + them, simulating the process of clonal expansion in artificial immune systems. Parameters ---------- @@ -129,9 +124,8 @@ def clone_and_mutate_ranged( bounds : np.ndarray Array (n_features, 2) with min and max per dimension. mutation_rate : float, default=1 - If 0 <= mutation_rate < 1: probability of mutating each component. - If mutation_rate >= 1 or mutation_rate <= 0: the mutation randomizes - a number of components between 1 and len(vector). + If 0 ≤ mutation_rate < 1, mutation probability per feature. + Otherwise, a random number of features is mutated. Returns ------- @@ -166,7 +160,7 @@ def clone_and_mutate_permutation( n: int, mutation_rate: float ) -> npt.NDArray[np.int64]: - """Generate a set of mutated clones by random permutation. + """Generate a set of mutated clones by permutation. Parameters ---------- @@ -175,7 +169,7 @@ def clone_and_mutate_permutation( n : int The number of mutated clones to be generated. mutation_rate : float - Probability of mutating each component 0 <= mutation_rate < 1. + Probability of mutating each feature 0 ≤ mutation_rate < 1. Returns ------- diff --git a/aisp/base/immune/populations.py b/aisp/base/immune/populations.py index d9a1ccd..0f3948b 100644 --- a/aisp/base/immune/populations.py +++ b/aisp/base/immune/populations.py @@ -23,21 +23,21 @@ def generate_random_antibodies( Number of antibodies (samples) to generate. n_features : int Number of features (dimensions) for each antibody. - feature_type : FeatureType, default="continuous-features" + feature_type : FeatureTypeAll, default="continuous-features" Specifies the type of features: "continuous-features", "binary-features", "ranged-features", or "permutation-features". bounds : npt.NDArray[np.float64], optional Array (n_features, 2) with min and max per dimension. - Raises - ------ - ValueError - If number of features must be greater than zero. - 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. """ if n_features <= 0: raise ValueError("Number of features must be greater than zero.") diff --git a/aisp/csa/_ai_recognition_sys.py b/aisp/csa/_ai_recognition_sys.py index b5e82ca..67af792 100644 --- a/aisp/csa/_ai_recognition_sys.py +++ b/aisp/csa/_ai_recognition_sys.py @@ -53,18 +53,17 @@ class AIRS(BaseClassifier): k : int, default=3 The number of K nearest neighbors that will be used to choose a label in the prediction. max_iters : int, default=100 - Maximum number of interactions in the refinement process of the ARB set exposed to aᵢ. + Maximum number of iterations in the refinement process of the ARB set exposed to aᵢ. resource_amplified : float, default=1.0 Resource consumption amplifier is multiplied with the incentive to subtract resources. - Defaults to 1.0 without amplification. metric : {"euclidean", "minkowski", "manhattan"}, default="euclidean" Distance metric used to compute affinity between cells and samples. seed : int - Seed for the random generation of detector values. Defaults to None. + Seed for random generation. **kwargs p : float - This parameter stores the value of ``p`` used in the Minkowski distance. The default + 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. @@ -107,7 +106,7 @@ class AIRS(BaseClassifier): >>> airs = airs.fit(x_train, y_train, verbose=False) >>> x_test = [ ... [0.15, 0.45], # Expected: Class 0 - ... [0.85, 0.65], # Esperado: Classe 1 + ... [0.85, 0.65], # Esperado: Class 1 ... ] >>> y_pred = airs.predict(x_test) >>> print(y_pred) @@ -175,7 +174,7 @@ def fit( """ Fit the model to the training data using the AIRS. - The function ``fit(...)``, performs the training according to ``X`` and ``y``, using the + The function ``fit(...)``, performs the training according to `X` and `y`, using the method AIRS. Parameters @@ -184,7 +183,7 @@ def fit( Training array, containing the samples and their characteristics, Shape: (n_samples, n_features). y : Union[npt.NDArray, list] - Array of target classes of ``X`` with (``n_samples``). + Array of target classes of `X` with (`n_samples`). verbose : bool Feedback on which sample aᵢ the memory cells are being generated. @@ -192,6 +191,11 @@ def fit( ------- AIRS Returns the instance itself. + + Raises + ------ + TypeError + If X or y are not ndarrays or have incompatible shapes. """ X = self._prepare_features(X) y = check_array_type(y, "y") @@ -258,7 +262,13 @@ def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: Parameters ---------- X : Union[npt.NDArray, list] - Array with input samples with Shape: (``n_samples, n_features``) + Array with input samples with Shape: (`n_samples, n_features`) + + Returns + ------- + C : npt.NDArray + An ndarray of the form `C` (`n_samples`), containing the predicted classes for + `X`. Raises ------ @@ -269,12 +279,6 @@ def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: ModelNotFittedError If the mode has not yet been adjusted and does not have defined memory cells, it is not able to predictions - - Returns - ------- - C : npt.NDArray - An ndarray of the form ``C`` (``n_samples``), containing the predicted classes for - ``X``. """ if self._all_class_cell_vectors is None: raise ModelNotFittedError("AIRS") @@ -524,6 +528,13 @@ def _prepare_features(self, X: Union[npt.NDArray, list]) -> npt.NDArray: ------- X : npt.NDArray The processed input data. + + Raises + ------ + TypeError: + If X is not a ndarray or a list. + UnsupportedTypeError + If the data type of the vector is not supported. """ X = check_array_type(X) self._feature_type = detect_vector_data_type(X) diff --git a/aisp/csa/_clonalg.py b/aisp/csa/_clonalg.py index f54284d..921fdaa 100644 --- a/aisp/csa/_clonalg.py +++ b/aisp/csa/_clonalg.py @@ -38,7 +38,7 @@ class Clonalg(BaseOptimizer): Dimension of the problem to be minimized. N : int, default=50 Number of memory cells (antibodies) in the population. - rate_clonal : float, default=10 + rate_clonal : int, default=10 Maximum number of possible clones of a cell. This value is multiplied by cell_affinity to determine the number of clones. rate_hypermutation : float, default=1.0 @@ -182,19 +182,19 @@ def optimize( max_iters : int, default=50 Maximum number of iterations when searching for the best solution using clonalg. n_iter_no_change: int, default=10 - The maximum number of iterations without updating the best cell + The maximum number of iterations without updating the best cell. verbose : bool, default=True Feedback on iterations, indicating the best antibody. - Raises - ------ - NotImplementedError - If no affinity function has been provided to model. - Returns ------- population : List[Antibody] Antibody population after clonal expansion. + + Raises + ------ + NotImplementedError + If no affinity function has been provided to evaluate candidate solutions. """ self.reset() diff --git a/aisp/exceptions.py b/aisp/exceptions.py index 4994ff2..24dcc45 100644 --- a/aisp/exceptions.py +++ b/aisp/exceptions.py @@ -4,13 +4,21 @@ class MaxDiscardsReachedError(Exception): - """Exception thrown when the maximum number of detector discards is reached.""" + """Exception thrown when the maximum number of detector discards is reached. + + Parameters + ---------- + object_name : str + The name of the instantiated class that throws the exceptions. + message : Optional[str] + Custom message to display. + """ - def __init__(self, _class_, message=None): + def __init__(self, object_name: str, message: Optional[str] = None): if message is None: message = ( "An error has been identified:\n" - f"the maximum number of discards of detectors for the {_class_} class " + f"the maximum number of discards of detectors for the {object_name} class " "has been reached.\nIt is recommended to check the defined radius and " "consider reducing its value." ) @@ -23,6 +31,15 @@ class FeatureDimensionMismatch(Exception): Exception raised when the number of input features does not match the expected number. This exception is triggered during prediction if the input features' dimension is incorrect. + + Parameters + ---------- + expected : int + The expected number of features + received : int + The actual number of features received. + variable_name : Optional[str] + The name of the variable that caused this mismatch. """ def __init__( @@ -47,9 +64,14 @@ class UnsupportedTypeError(Exception): Exception raised when the input vector type is not supported. This exception is thrown when the vector data type does not match any of the supported. + + Parameters + ---------- + message : Optional[str] + Custom message to display. """ - def __init__(self, message=None): + def __init__(self, message: Optional[str] = None): if message is None: message = ( "Type is not supported. Provide a binary, normalized, or bounded " @@ -64,6 +86,13 @@ class ModelNotFittedError(Exception): This exception is thrown when the model instance is being used without first training it via the `fit` method. + + Parameters + ---------- + object_name : str + The name of the instantiated class that throws the exceptions. + message : Optional[str] + Custom message to display. """ def __init__(self, object_name: str, message: Optional[str] = None): diff --git a/aisp/ina/_ai_network.py b/aisp/ina/_ai_network.py index fb4f09f..0f04715 100644 --- a/aisp/ina/_ai_network.py +++ b/aisp/ina/_ai_network.py @@ -39,7 +39,7 @@ class AiNet(BaseClusterer): 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]_ - For clustering, the class uses SciPy's implementation of the **Minimum Spanning Tree** + For clustering, the class uses SciPy implementation of the **Minimum Spanning Tree** (MST) to remove the most distant nodes and separate the groups. [2]_ Parameters @@ -67,13 +67,13 @@ class AiNet(BaseClusterer): metric : {"euclidean", "minkowski", "manhattan"}, default="euclidean" Distance metric used to compute similarity between memory cells seed : Optional[int] - Seed for the random generation of detector values. Defaults to None. + Seed for random generation. use_mst_clustering : bool, default=True If ``True``, performs clustering with **Minimum Spanning Tree** (MST). If ``False``, does not perform clustering and predict returns None. **kwargs p : float - This parameter stores the value of ``p`` used in the Minkowski distance. The default + 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. @@ -222,17 +222,17 @@ def fit(self, X: Union[npt.NDArray, list], verbose: bool = True) -> AiNet: verbose : bool, default=True Feedback from the progress bar showing current training interaction details. + Returns + ------- + self : AiNet + Returns the instance itself. + Raises ------ TypeError If X is not a ndarray or list. UnsupportedTypeError - If the data type of the vector is not supported. - - Returns - ------- - self : AiNet - Returns the instance of the class that implements this method. + If the data type of the feature on X is not supported. """ X = self._prepare_features(X) @@ -240,7 +240,7 @@ def fit(self, X: Union[npt.NDArray, list], verbose: bool = True) -> AiNet: total=self.max_iterations, postfix="\n", disable=not verbose, - bar_format="{desc} ┇{bar}┇ {n}/{total} total training interactions", + bar_format="{desc} ┇{bar}┇ {n}/{total} total training iterations", ) population_p = self._init_population_antibodies() @@ -287,6 +287,11 @@ def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: X : Union[npt.NDArray, list] Data to predict. + Returns + ------- + predictions : npt.NDArray + Predicted cluster labels, or None if clustering is disabled. + Raises ------ TypeError @@ -294,15 +299,10 @@ def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: ValueError If the array contains values other than 0 and 1. FeatureDimensionMismatch - If the number of features in X does not match the expected number. + If the number of features (columns) in X does not match the expected number. ModelNotFittedError If the mode has not yet been adjusted and does not have defined memory cells, it is not able to predictions - - Returns - ------- - predictions : npt.NDArray - Predicted cluster labels, or None if clustering is disabled. """ if ( not self.use_mst_clustering @@ -478,7 +478,6 @@ def _calculate_affinities(self, u: npt.NDArray, v: npt.NDArray) -> npt.NDArray: v : npt.NDArray An array of vectors with shape (n_samples, n_features). - Returns ------- affinities : npt.NDArray @@ -617,7 +616,7 @@ def _prepare_features(self, X: Union[npt.NDArray, list]) -> npt.NDArray: """ Check the samples, specifying the type, quantity of characteristics, and other parameters. - * This method updates the following attributes: + This method updates the following attributes: * ``self._feature_type`` * ``self.metric`` (only for binary features) * ``self._bounds`` (only for ranged features) @@ -629,15 +628,17 @@ def _prepare_features(self, X: Union[npt.NDArray, list]) -> npt.NDArray: Training array, containing the samples and their characteristics, Shape: (n_samples, n_features). - Raises - ------ - UnsupportedTypeError - If the data type of the vector is not supported. - Returns ------- X : npt.NDArray The processed input data. + + Raises + ------ + TypeError: + If X is not a ndarray or a list. + UnsupportedTypeError + If the data type of the vector is not supported. """ X = check_array_type(X) self._feature_type = detect_vector_data_type(X) diff --git a/aisp/nsa/_binary_negative_selection.py b/aisp/nsa/_binary_negative_selection.py index 65b28bd..965d158 100644 --- a/aisp/nsa/_binary_negative_selection.py +++ b/aisp/nsa/_binary_negative_selection.py @@ -142,26 +142,26 @@ def fit( ---------- X : Union[npt.NDArray, list] Training array, containing the samples and their characteristics. - Shape: (``n_samples, n_features``) + Shape: (`n_samples, n_features`) y : Union[npt.NDArray, list] - Array of target classes of ``X`` with ``n_samples`` (lines). + Array of target classes of `X` with `n_samples` (lines). verbose : bool, default=True Feedback from detector generation to the user. + Returns + ------- + self : BNSA + Returns the instance itself. + Raises ------ TypeError If X or y are not ndarrays or have incompatible shapes. ValueError - If the array contains values other than 0 and 1. + If the array X contains any values other than (0 and 1) or (True and False). MaxDiscardsReachedError - The maximum number of detector discards was reached during maturation. Check the + If the maximum number of detector discards was reached during maturation. Check the defined radius value and consider reducing it. - - Returns - ------- - self : BNSA - Returns the instance itself. """ X = check_array_type(X) y = check_array_type(y, "y") @@ -223,7 +223,13 @@ def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: Parameters ---------- X : Union[npt.NDArray, list] - Array with input samples with Shape: (``n_samples, n_features``) + Array with input samples with Shape: (`n_samples, n_features`) + + Returns + ------- + c : npt.NDArray + A ndarray of the form `C` (`n_samples`), containing the predicted classes for + `X`. Raises ------ @@ -232,16 +238,10 @@ def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: ValueError If the array contains values other than 0 and 1. FeatureDimensionMismatch - If the number of features in X does not match the expected number. + If the number of features (columns) in X does not match the expected number. ModelNotFittedError If the mode has not yet been adjusted and does not have defined detectors or classes, it is not able to predictions - - Returns - ------- - c : npt.NDArray - A ndarray of the form ``C`` (``n_samples``), containing the predicted classes for - ``X``. """ if ( self._detectors is None diff --git a/aisp/nsa/_negative_selection.py b/aisp/nsa/_negative_selection.py index babb4bd..a54eca3 100644 --- a/aisp/nsa/_negative_selection.py +++ b/aisp/nsa/_negative_selection.py @@ -40,7 +40,7 @@ class RNSA(BaseClassifier): r : float, default=0.05 Radius of the detector. r_s : float, default=0.0001 - rₛ Radius of the ``X`` own samples. + rₛ Radius of the `X` own samples. k : int, default=1 Number of neighbors near the randomly generated detectors to perform the distance average calculation. @@ -68,7 +68,7 @@ class RNSA(BaseClassifier): 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, default=2 - This parameter stores the value of ``p`` used in the Minkowski distance. The default + This parameter stores the value of `p` used in the Minkowski distance. The default is ``2``, which represents Euclidean distance. Different values of p lead to different variants of the Minkowski Distance. @@ -187,24 +187,24 @@ def fit( Training array, containing the samples and their characteristics. Shape: ``(n_samples, n_features)`` y : Union[npt.NDArray, list] - Array of target classes of ``X`` with ``n_samples`` (lines). + Array of target classes of `X` with `n_samples` (lines). verbose: bool, default=True Feedback from detector generation to the user. + Returns + ------- + self : RNSA + Returns the instance itself. + Raises ------ TypeError If X or y are not ndarrays or have incompatible shapes. + ValueError + If the array X fall outside the interval (0.0, 1.0). MaxDiscardsReachedError The maximum number of detector discards was reached during maturation. Check the defined radius value and consider reducing it. - ValueError - If the array X fall outside the interval (0, 1). - - Returns - ------- - self : RNSA - Returns the instance itself. """ X = check_array_type(X) y = check_array_type(y, "y") @@ -270,23 +270,23 @@ def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: X : Union[npt.NDArray, list] Array with input samples with Shape: (n_samples, n_features) + Returns + ------- + C : npt.NDArray + A ndarray of the form `C` (n_samples), containing the predicted classes + for `X`. + Raises ------ TypeError If X is not a ndarray or list. + ValueError + If the array X fall outside the interval (0.0, 1.0). FeatureDimensionMismatch If the number of features in X does not match the expected number. ModelNotFittedError If the mode has not yet been adjusted and does not have defined detectors or classes, it is not able to predictions - ValueError - If the array X fall outside the interval (0, 1). - - Returns - ------- - C : npt.NDArray - A ndarray of the form ``C`` (n_samples), containing the predicted classes - for ``X``. """ if self._detectors is None or self.classes is None: raise ModelNotFittedError("RNSA") diff --git a/aisp/utils/display.py b/aisp/utils/display.py index 0c6885e..d72f39a 100644 --- a/aisp/utils/display.py +++ b/aisp/utils/display.py @@ -35,7 +35,7 @@ class TableFormatter: ---------- headers : Mapping[str, int] Mapping of column names to their respective widths, in the format - {column_name: column_width}. + `{column_name: column_width}`. """ def __init__(self, headers: Mapping[str, int]) -> None: @@ -108,7 +108,7 @@ def get_row(self, values: Mapping[str, Union[str, int, float]]): ---------- values : Mapping[str, Union[str, int, float]] Dictionary with values for each column, in the format - {column_name: value}. + `{column_name: value}`. Returns ------- @@ -154,7 +154,7 @@ class ProgressTable(TableFormatter): Parameters ---------- headers : Mapping[str, int] - Mapping {column_name: column_width}. + Mapping `{column_name: column_width}`. verbose : bool, default=True If False, prints nothing to the terminal. """ diff --git a/aisp/utils/distance.py b/aisp/utils/distance.py index 078eae2..6d01dbf 100644 --- a/aisp/utils/distance.py +++ b/aisp/utils/distance.py @@ -145,7 +145,7 @@ def compute_metric_distance( Returns ------- float64 - Distance (``float``) between the two points with the selected metric. + Distance between the two points with the selected metric. """ if metric == MANHATTAN: return cityblock(u, v) @@ -203,15 +203,15 @@ def get_metric_code(metric: str) -> int: 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. + + Raises + ------ + ValueError + If the metric provided is not supported. """ metric_map = { "euclidean": EUCLIDEAN, diff --git a/aisp/utils/metrics.py b/aisp/utils/metrics.py index 91504f5..f3df463 100644 --- a/aisp/utils/metrics.py +++ b/aisp/utils/metrics.py @@ -28,6 +28,15 @@ def accuracy_score( ------ ValueError If `y_true` or `y_pred` are empty or if they do not have the same length. + + Examples + -------- + >>> import numpy as np + >>> from aisp.utils.metrics import accuracy_score + >>> y_true = [1, 1, 1, 1, 1] + >>> y_pred = [1, 1, 1, 0, 0] + >>> print(accuracy_score(y_true, y_pred)) + 0.6 """ n = len(y_true) if n == 0: diff --git a/aisp/utils/multiclass.py b/aisp/utils/multiclass.py index badf4fe..e382c99 100644 --- a/aisp/utils/multiclass.py +++ b/aisp/utils/multiclass.py @@ -16,12 +16,12 @@ def slice_index_list_by_class(classes: Optional[Union[npt.NDArray, list]], y: np classes: list or npt.NDArray list with unique classes. y : npt.NDArray - Receives a ``y`` (``n_samples``) array with the output classes of the ``X`` sample array. + Receives a `y` (`n_samples`) array with the output classes of the `X` sample array. Returns ------- position_samples : dict - A dictionary with the list of array positions(``y``), with the classes as key. + A dictionary with the list of array positions(`y`), with the classes as key. Examples -------- @@ -59,7 +59,7 @@ def predict_knn_affinity( k: int Number of nearest neighbors to consider for prediction. all_cell_vectors: List[Tuple[Union[str, int], npt.NDArray]] - List of tuples (class_name, cell[np.ndarray]). + List of tuples (class_name, cell(np.ndarray)). affinity_func: Callable[[npt.NDArray, npt.NDArray], float] Function that takes two vectors and returns an affinity value. diff --git a/aisp/utils/types.py b/aisp/utils/types.py index 7f092f7..6603c3c 100644 --- a/aisp/utils/types.py +++ b/aisp/utils/types.py @@ -8,7 +8,7 @@ - "ranged-features": values defined by intervals. FeatureTypeAll: - Same as ``FeatureType``, plus: + Same as `FeatureType`, plus: - "permutation-features": values represented as permutation. MetricType: diff --git a/aisp/utils/validation.py b/aisp/utils/validation.py index bd044c4..4b1dc01 100644 --- a/aisp/utils/validation.py +++ b/aisp/utils/validation.py @@ -82,7 +82,7 @@ def check_shape_match(x: npt.NDArray, y: npt.NDArray): Array, containing the samples and their characteristics, Shape: (n_samples, n_features). y : npt.NDArray - Array of target classes of ``x`` with (``n_samples``). + Array of target classes of `x` with (`n_samples`). Raises ------ diff --git a/docs/assets/template-docs-class.md b/docs/assets/template-docs-class.md new file mode 100644 index 0000000..00deb70 --- /dev/null +++ b/docs/assets/template-docs-class.md @@ -0,0 +1,106 @@ +--- +id: class-name +sidebar_label: ClassName +keywords: + - key +tags: + - tag +--- + +# ClassName + +{{ Brief description of the class }} + +:::tip[Inheritance] + +This class extends {{ class }} + +::: + + +> **Module:** `aisp.[module]` +> **Import:** `from aisp.[module] import [class]` + +--- + +## Overview + +{{ Explain what the class. }} + +Use cases: + +- {{ Use case 1 }} + +--- + +## Example + +```python +from aisp.module import ClassName + +model = ClassName() +model.method_name() +``` + +--- + +## Constructor Parameters + +| Name | Type | Default | Description | +|-----------|--------|:-------:|---------------------------| +| `param_1` | `Type` | - | Description of the param. | +| `param_2` | `Type` | - | Description of the param. | + +## Attributes + +| Name | Type | Default | Description | +|---------------|--------|:-------:|-------------------------------| +| `attribute_1` | `Type` | - | Description of the attribute. | +| `attribute_2` | `Type` | - | Description of the attribute. | + +--- + +## Public Methods + +### method_name + +```python +def method_name( + param_1: type, +) -> type: + ... +``` + +Description. + +**Parameters** + +| Name | Type | Default | Description | +|-----------|--------|:-------:|---------------------------| +| `param_1` | `Type` | - | Description of the param. | + +**Returns** + +| Type | Description | +|--------------|----------------------------| +| `ReturnType` | Description of the return. | + +**Raises** + +| Exception | Description | +|-----------|---------------------------| +| `Error` | Description of the raise. | + +--- + +## Extended Example + +Complete usage examples are available in the Jupyter Notebooks: + +- [example](#link) + +--- + +## References + +[^1]: {{ Reference }} diff --git a/docs/assets/template-docs-functions.md b/docs/assets/template-docs-functions.md new file mode 100644 index 0000000..34e7aee --- /dev/null +++ b/docs/assets/template-docs-functions.md @@ -0,0 +1,52 @@ +--- +id: module +sidebar_label: module +keywords: + - key +tags: + - tag +--- + +# module + +{{ Brief description of the submodule }} + +> **Module:** `aisp.[module]` +> **Import:** `from aisp import [module]` + +## Functions + +### function_name + +```python +def function_name( + param_1: type, +) -> type: + ... +``` + +{{ description }} + +**Parameters** + +| Name | Type | Default | Description | +|-----------|--------|:-------:|---------------------------| +| `param_1` | `Type` | - | Description of the param. | + +**Returns** + +| Type | Description | +|--------------|----------------------------| +| `ReturnType` | Description of the return. | + +**Raises** + +| Exception | Description | +|-----------|------------------------| +| `Error` | When and why it raised | + +--- + +## References + +[^1]: {{ Reference }} \ No newline at end of file diff --git a/docs/assets/template-docs-module.md b/docs/assets/template-docs-module.md new file mode 100644 index 0000000..b5df15e --- /dev/null +++ b/docs/assets/template-docs-module.md @@ -0,0 +1,51 @@ +--- +id: module-name +sidebar_label: ModuleName +keywords: + - key +tags: + - tag +--- + +# ModuleName + +{{ Brief description of the module }} + +> **Module:** `aisp.[module]` +> **Import:** `from aisp import [module]` + +--- + +## Overview + +{{ Explain what the module }} + +--- + +## Classes + +| Class | Description | +|-------------|--------------| +| `ClassName` | Description. | + +--- + +## Functions + +| Function | Description | +|-----------------|--------------| +| `function_name` | Description. | + +--- + +## Submodules + +| Module | Description | +|-------------|--------------| +| `submodule` | Description. | + +--- + +## References + +[^1]: {{ Reference }} diff --git a/docs/en/advanced-guides/Core/Negative Selection.md b/docs/en/advanced-guides/Core/Negative Selection.md deleted file mode 100644 index 95ab3b8..0000000 --- a/docs/en/advanced-guides/Core/Negative Selection.md +++ /dev/null @@ -1,94 +0,0 @@ -**Negative Selection** - -The functions perform detector checks and utilize Numba decorators for Just-In-Time compilation - -### Function check_detector_bnsa_validity(...) - -```python -@njit([(types.boolean[:, :], types.boolean[:], types.float64)], cache=True) -def check_detector_bnsa_validity( - x_class: npt.NDArray[np.bool_], - vector_x: npt.NDArray[np.bool_], - 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[np.bool_]``): Array containing the class samples. Expected shape: (n_samples, n_features). -* **vector_x** (``npt.NDArray[np.bool_]``): 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 -@njit([(types.boolean[:], types.boolean[:, :, :], types.float64)], cache=True) -def bnsa_class_prediction( - features: npt.NDArray[np.bool_], - class_detectors: npt.NDArray[np.bool_], - aff_thresh: float, -) -> int: -``` - -Defines the class of a sample from the non-self detectors. - -**Parameters:** - -* **features** (``npt.NDArray[np.bool_]``): binary sample to be classified (shape: [n_features]). -* **class_detectors** (``npt.NDArray[np.bool_]``): 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 -@njit( - [ - ( - types.float64[:, :], - types.float64[:], - types.float64, - types.int32, - types.float64, - ) - ], - cache=True, -) -def check_detector_rnsa_validity( - x_class: npt.NDArray[np.float64], - vector_x: npt.NDArray[np.float64], - 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[np.float64]``): Array containing the class samples. Expected shape: (n_samples, n_features). -* **vector_x** (``npt.NDArray[np.float64]``): 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/docs/en/advanced-guides/base/base.md b/docs/en/advanced-guides/base/base.md deleted file mode 100644 index bbe5b2d..0000000 --- a/docs/en/advanced-guides/base/base.md +++ /dev/null @@ -1,43 +0,0 @@ -# Base Class - -Base class for parameter introspection compatible with the scikit-learn API. - -## Base - -Generic base class for models with a common interface. - -Provides the `get_params` and `set_params` methods for compatibility with the scikit-learn API, allowing access to the model's public parameters. - -### Method `set_params(...)` - -```python -def set_params(self, **params) -> Base: -``` - -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. - ---- - -### Method `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`, default=True)): 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/docs/en/advanced-guides/base/classifier.md b/docs/en/advanced-guides/base/classifier.md deleted file mode 100644 index 3043940..0000000 --- a/docs/en/advanced-guides/base/classifier.md +++ /dev/null @@ -1,80 +0,0 @@ -Base class for classification algorithm. - -# BaseClassifier - -Base class for classification algorithms, defining the abstract methods ``fit`` and ``predict``, and implementing the ``get_params`` method. - -### Method `score(...)` - -```python -def score( - self, - X: Union[npt.NDArray, list], - y: Union[npt.NDArray, 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** (`Union[npt.NDArray, list]`): Feature set with shape (n_samples, n_features). -* **y** (`Union[npt.NDArray, list]`): True values with shape (n_samples,). - -**Returns**: - -* accuracy: ``float`` The accuracy of the model. - ---- - -### Method `_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. - ---- - -## Abstract methods - -### Method `fit(...)` - -```python -@abstractmethod -def fit( - self, - X: Union[npt.NDArray, list], - y: Union[npt.NDArray, list], - verbose: bool = True -) -> BaseClassifier: -``` - -Fit the model to the training data. - -Implementation: - -* [RNSA](../../classes/Negative%20Selection/RNSA.md#method-fit) -* [BNSA](../../classes/Negative%20Selection/BNSA.md#method-fit) -* [AIRS](../../classes/Clonal%20Selection%20Algorithms/AIRS.md#method-fit) - -### Method `predict(...)` - -```python -@abstractmethod -def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: -``` - -Performs label prediction for the given data. - -Implementation: - -* [RNSA](../../classes/Negative%20Selection/RNSA.md#method-predict) -* [BNSA](../../classes/Negative%20Selection/BNSA.md#method-predict) -* [AIRS](../../classes/Clonal%20Selection%20Algorithms/AIRS.md#method-predict) diff --git a/docs/en/advanced-guides/base/clusterer.md b/docs/en/advanced-guides/base/clusterer.md deleted file mode 100644 index 486d442..0000000 --- a/docs/en/advanced-guides/base/clusterer.md +++ /dev/null @@ -1,74 +0,0 @@ -# BaseClusterer - -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. - ---- - -### Method `fit(...)` - -```python -@abstractmethod -def fit(self, X: Union[npt.NDArray, list], verbose: bool = True) -> BaseClusterer: -``` - -Fit the model to the training data. -This abstract method must be implemented by subclasses. - -**Parameters**: - -* **X** (`Union[npt.NDArray, list]`): Input data used for training the model. -* **verbose** (`bool`, default=True): Flag to enable or disable detailed output during training. - -**Returns**: - -* **self** (`BaseClusterer`): Instance of the class that implements this method. - -**Implementation**: - -* [AiNet](../../classes/Network%20Theory%20Algorithms/AiNet.md#method-fit) - ---- - -### Method `predict(...)` - -```python -@abstractmethod -def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: -``` - -Generate predictions based on the input data. -This abstract method must be implemented by subclasses. - -**Parameters**: - -* **X** (`Union[npt.NDArray, list]`): Input data for which predictions will be generated. - -**Returns**: - -* **predictions** (`npt.NDArray`): Predicted cluster labels for each input sample. - -**Implementation**: - -* [AiNet](../../classes/Network%20Theory%20Algorithms/AiNet.md#method-predict) - ---- - -### Method `fit_predict(...)` - -```python -def fit_predict(self, X: Union[npt.NDArray, list], verbose: bool = True) -> npt.NDArray: -``` - -Convenience method that combines `fit` and `predict` in a single call. - -**Parameters**: - -* **X** (`Union[npt.NDArray, list]`): Input data for which predictions will be generated. -* **verbose** (`bool`, default=True): Flag to enable or disable detailed output during training. - -**Returns**: - -* **predictions**: `npt.NDArray` - Predicted cluster labels for each input sample. diff --git a/docs/en/advanced-guides/base/immune/cell.md b/docs/en/advanced-guides/base/immune/cell.md deleted file mode 100644 index eff26fd..0000000 --- a/docs/en/advanced-guides/base/immune/cell.md +++ /dev/null @@ -1,102 +0,0 @@ -# Cell Classes - -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/en/advanced-guides/base/immune/mutation.md b/docs/en/advanced-guides/base/immune/mutation.md deleted file mode 100644 index 730ba85..0000000 --- a/docs/en/advanced-guides/base/immune/mutation.md +++ /dev/null @@ -1,116 +0,0 @@ -# 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, types.float64)], cache=True) -def clone_and_mutate_continuous( - vector: npt.NDArray[np.float64], - n: int, - mutation_rate: float -) -> 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. -* ``mutation_rate`` : (``float``) If 0 <= mutation_rate < 1: probability of mutating each component. - If mutation_rate >= 1 or mutation_rate <= 0: the mutation randomizes - number of components between 1 and len(vector). - -### 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, types.float64)], cache=True) -def clone_and_mutate_binary( - vector: npt.NDArray[np.bool_], - n: int, - mutation_rate: float -) -> 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[:, :], types.float64)], cache=True) -def clone_and_mutate_ranged( - vector: npt.NDArray[np.float64], - n: int, - bounds: npt.NDArray[np.float64], - mutation_rate: float, -) -> 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. -* ``mutation_rate`` : (``float``) If 0 <= mutation_rate < 1: probability of mutating each component. - If mutation_rate >= 1 or mutation_rate <= 0: the mutation randomizes - number of components between 1 and len(vector). - -### 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/docs/en/advanced-guides/base/immune/populations.md b/docs/en/advanced-guides/base/immune/populations.md deleted file mode 100644 index cef96a2..0000000 --- a/docs/en/advanced-guides/base/immune/populations.md +++ /dev/null @@ -1,31 +0,0 @@ -# Populations Module - -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/en/advanced-guides/base/optimizer.md b/docs/en/advanced-guides/base/optimizer.md deleted file mode 100644 index e464942..0000000 --- a/docs/en/advanced-guides/base/optimizer.md +++ /dev/null @@ -1,161 +0,0 @@ -Base class for optimization algorithms. - -# BaseOptimizer - -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 ``affinity_function``. - ---- - -## Properties - -### Property `cost_history` - -```python -@property -def cost_history(self) -> List[float] -``` - -Returns the history of costs during optimization. - ---- - -### Property `solution_history` - -```python -@property -def solution_history(self) -> List -``` - -Returns the history of evaluated solutions. - ---- - -### Property `best_solution` - -```python -@property -def best_solution(self) -> Optional[Any] -``` - -Returns the best solution found so far, or `None` if unavailable. - ---- - -### Property `best_cost` - -```python -@property -def best_cost(self) -> Optional[float] -``` - -Returns the cost of the best solution found so far, or `None` if unavailable. - ---- - -## Methods - -### Method `_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. - ---- - -### Method `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. - ---- - -### Method `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. - ---- - -### Method `reset()` - -```python -def reset(self) -``` - -Reset the object's internal state, clearing history and resetting values. - ---- - -### Abstract methods - -#### Method `optimize(...)` - -```python -@abstractmethod -def optimize( - self, - max_iters: int = 50, - n_iter_no_change: int = 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. - -**Returns**: - -* **best_solution**: `Any` - The best solution found by the optimization algorithm. - ---- - -#### Method `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/docs/en/advanced-guides/utils.md b/docs/en/advanced-guides/utils.md deleted file mode 100644 index 0bd63dd..0000000 --- a/docs/en/advanced-guides/utils.md +++ /dev/null @@ -1,618 +0,0 @@ -# Utils - -Utility functions and helpers for development. - -## Metrics - -### Function `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. - ---- - -## Multiclass - -## Function `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. - ---- - -## Function `slice_index_list_by_class(...)` - -```python -def slice_index_list_by_class(classes: Optional[Union[npt.NDArray, list]], y: npt.NDArray) -> dict: -``` - -The function ``slice_index_list_by_class(...)``, separates the indices of the samples -according to their output class, to iterate through the sample array only at positions where -the output matches the class being trained. - -**Parameters:** - -* **classes** (`Optional[Union[npt.NDArray, list]]`): List with unique classes. If None, returns an empty dictionary. -* **y** (`npt.NDArray`): Array with output classes of the ``X`` sample array. - -**Returns:** - -* `dict`: A dictionary with the list of array positions keyed by class. - -**Examples:** - -```python ->>> import numpy as np ->>> labels = ['a', 'b', 'c'] ->>> y = np.array(['a', 'c', 'b', 'a', 'c', 'b']) ->>> slice_index_list_by_class(labels, y) -{'a': [0, 3], 'b': [2, 5], 'c': [1, 4]} -``` - ---- - -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:** - -* **y** (npt.NDArray): Receives a ``y`` (``n_samples``) 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. - ---- - -## Sanitizers - -### Function `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. - ---- - -### Function `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. - ---- - -### Function `sanitize_seed(...)` - -```python -def sanitize_seed(seed: Any) -> Optional[int]: -``` - -The function ``sanitize_seed(...)``, 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. - -### Function `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, npt.NDArray[np.float64]]`: Dictionary {'low': [low_1, ..., low_N], 'high': [high_1, ..., high_N]}. - -## Distance - -Utility functions for normalized distance between arrays with numba decorators. - -### Function `hamming(...)` - -```python -def hamming(u: npt.NDArray[np.bool_], v: npt.NDArray[np.bool_]) -> float64: -``` - -The function to calculate the normalized Hamming distance between two points. - -$((x₁ ≠ x₂) + (y₁ ≠ y₂) + ... + (yn ≠ yn)) / n$ - -**Parameters:** - -* **u** (``npt.NDArray[np.bool_]``): Coordinates of the first point. -* **v** (``npt.NDArray[np.bool_]``): Coordinates of the second point. - -**Returns:** - -* Distance (``float64``) between the two points. - ---- - -### Function `euclidean(...)` - -```python -def euclidean(u: npt.NDArray[np.float64], v: npt.NDArray[np.float64]) -> float64: -``` - -Function to calculate the normalized Euclidean distance between two points. - -$√( (x₁ - x₂)² + (y₁ - y₂)² + ... + (yn - yn)²)$ - -**Parameters:** - -* **u** (``npt.NDArray[float64]``): Coordinates of the first point. -* **v** (``npt.NDArray[float64]``): Coordinates of the second point. - -**Returns:** - -* Distance (``float64``) between the two points. - ---- - -### Function `cityblock(...)` - -```python -def cityblock(u: npt.NDArray[float64], v: npt.NDArray[float64]) -> float64: -``` - -Function to calculate the normalized Manhattan distance between two points. - -$(|x₁ - x₂| + |y₁ - y₂| + ... + |yn - yn|) / n$ - -**Parameters:** - -* **u** (``npt.NDArray[float64]``): Coordinates of the first point. -* **v** (``npt.NDArray[float64]``): Coordinates of the second point. - -**Returns:** - -* Distance (``float64``) between the two points. - ---- - -### Function `minkowski(...)` - -```python -def minkowski( - u: npt.NDArray[float64], - v: npt.NDArray[float64], - p: float = 2.0 -) -> float64: -``` - -Function to calculate the normalized Minkowski distance between two points. - -$(( |X₁ - Y₁|p + |X₂ - Y₂|p + ... + |Xn - Yn|p) ¹/ₚ) / n$ - -**Parameters:** - -* **u** (``npt.NDArray[float64]``): Coordinates of the first point. -* **v** (``npt.NDArray[float64]``): 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 (``float64``) between the two points. - ---- - -### Function `compute_metric_distance(...)` - -```python -def compute_metric_distance( - u: npt.NDArray[float64], - v: npt.NDArray[float64], - metric: int, - p: float = 2.0 -) -> float64: -``` - -Function to calculate the distance between two points by the chosen ``metric``. - -**Parameters:** - -* **u** (``npt.NDArray[float64]``): Coordinates of the first point. -* **v** (``npt.NDArray[float64]``): 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 (``float64``) between the two points with the selected metric. - ---- - -### Function `min_distance_to_class_vectors(...)` - -```python -def min_distance_to_class_vectors( - x_class: npt.NDArray[float64], - vector_x: npt.NDArray[float64], - 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[float64]``): Array containing the class vectors to be compared with the input vector. Expected shape: (n_samples, n_features). -* **vector_x** (``npt.NDArray[float64]``): 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), 3 (hamming)] -* **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. - ---- - -### Function `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. - ---- - -## Validation - -### Function `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. - ---- - -### Function `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. Shape: (``n_samples, n_features``). -* **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. - ---- - -### Function `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. Shape: (``n_samples, n_features``). -* **y** (`npt.NDArray`): Array of target classes of `x` with (``n_samples``). - -**Raises:** - -* `TypeError`: If x or y are not ndarrays or have incompatible shapes. - ---- - -### Function `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. Shape: (``n_samples, n_features``). -* `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. - ---- - -### Function `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. - ---- - -## Display - -Utility Functions for Displaying Algorithm Information - -### Function `_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. - ---- - -#### Function `_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. - ---- - -#### Function `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. - ---- - -#### Function `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. - ---- - -#### Function `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`, default=True): If False, prints nothing to the terminal. - -**Raises**: - -* `ValueError`: If `headers` is empty or not a valid mapping. - ---- - -#### Function `_print_header()` - -```python -def _print_header(self) -> None: -``` - -Print the table header. - ---- - -#### Function `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. - ---- - -#### Function `finish()` - -```python -def finish(self) -> None: -``` - -End the table display, printing the bottom border and total time. - ---- diff --git a/docs/en/api/README.md b/docs/en/api/README.md new file mode 100644 index 0000000..7619fbc --- /dev/null +++ b/docs/en/api/README.md @@ -0,0 +1,84 @@ +--- +id: api +sidebar_label: api +keywords: + - api + - aisp + - Artificial Immune System Package + - classification + - optimization + - clustering +--- + +# AISP - API + +Welcome to the **AISP** (Artificial Immune System Package) api. This documentation demonstrates the package public API. + +## Core Modules ([`aisp.base`](./base/README.md)) + +Fundamental abstractions and base classes that define core interfaces of package. + +| Class | Description | +|-----------------------------------------------|----------------------------------------------------| +| [`BaseClassifier`](./base/base-classifier.md) | Abstract base class for classification algorithms. | +| [`BaseClusterer`](./base/base-clusterer.md) | Abstract base class for clustering algorithms. | +| [`BaseOptimizer`](./base/base-optimizer.md) | Abstract base class for optimization algorithms. | + +### Immune Domain components ([`aisp.base.immune`](./base/immune/README.md)) + +Core structures and support utilities for implementations immune. + +| Module | Description | +|-----------------------------------------------|--------------------------------------------------------------------------------------------| +| [`cell`](./base/immune/cell/README.md) | Representation of immune system cells. | +| [`mutation`](./base/immune/mutation.md) | Functions to generate mutated clones and simulate clonal expansion. | +| [`populations`](./base/immune/populations.md) | Provide utility functions for generating antibody populations in immunological algorithms. | + +--- + +## Algorithms + +### Negative Selection Algorithms ([`aisp.nsa`](./nsa/README.md)) + +supervised learning algorithms based on negative selection, the immune systems process of distinguishing self from +not-self. + +| Class | Description | +|-------------------------|-------------------------------------------------------------------------------------| +| [`RNSA`](./nsa/rnsa.md) | A supervised learning algorithm for classification that uses real-valued detectors. | +| [`BNSA`](./nsa/bnsa.md) | A supervised learning algorithm for classification that uses binary detectors. | + +### Clonal Selection Algorithms ([`aisp.csa`](./csa/README.md)) + +Algorithms inspired by the process of antibody proliferation to detecting an antigen. + +| Class | Description | +|-------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| [`AIRS`](./csa/airs.md) | A supervised learning algorithm for classification tasks based on the clonal selection principle. | +| [`Clonalg`](./csa/clonalg.md) | Implementation of the clonal selection algorithm for optimization, adapted for both minimization and maximization of cost functions in binary, continuous, and permutation problems. | + +### Immune Network Algorithms ([`aisp.ina`](./ina/README.md)) + +Algorithms based on Network Theory Algorithms proposed by Jerne. + +| Class | Description | +|----------------------------|--------------------------------------------------------------------------------------------| +| [`AiNet`](./ina/ai-net.md) | An unsupervised learning algorithm for clustering, based on the theory of immune networks. | + +## Utils ([`aisp.utils`](./utils/README.md)) + +Utility functions and helpers for development. + +| Module | Description | +|----------------------------------------|--------------------------------------------------------------------------| +| [`display`](./utils/display/README.md) | Utility functions for displaying algorithm information. | +| [`distance`](./utils/distance.md) | Utility functions for distance between arrays with numba decorators. | +| [`metrics`](./utils/metrics.md) | Utility functions for measuring accuracy and performance. | +| [`multiclass`](./utils/multiclass.md) | Utility functions for handling classes with multiple categories. | +| [`sanitizers`](./utils/sanitizers.md) | Utility functions for validation and treatment of parameters. | +| [`types`](./utils/types.md) | Defines type aliases used throughout the project to improve readability. | +| [`validation`](./utils/validation.md) | Contains functions responsible for validating data types. | + +## Exceptions ([`aisp.exceptions`](./exceptions.md)) + +Custom warnings and errors. diff --git a/docs/en/api/base/README.md b/docs/en/api/base/README.md new file mode 100644 index 0000000..631dcb4 --- /dev/null +++ b/docs/en/api/base/README.md @@ -0,0 +1,33 @@ +--- +id: base +sidebar_label: aisp.base +keywords: + - base + - immune + - abstract +--- + +# aisp.base + +Base Classes and Core Utilities. + +> **Module:** `aisp.base` + +## Overview + +This module provides the fundamental classes and utilities that serve as the basis for all +Artificial Immune Systems algorithms implemented in the AISP package. + +## Classes + +| Class | Description | +|------------------------------------------|----------------------------------------------------| +| [`BaseClassifier`](./base-classifier.md) | Abstract base class for classification algorithms. | +| [`BaseClusterer`](./base-clusterer.md) | Abstract base class for clustering algorithms. | +| [`BaseOptimizer`](./base-optimizer.md) | Abstract base class for optimization algorithms. | + +## Submodules + +| Module | Description | +|--------------------------------|-----------------------------------------------| +| [`immune`](./immune/README.md) | Support Module for Artificial Immune Systems. | \ No newline at end of file diff --git a/docs/en/api/base/base-classifier.md b/docs/en/api/base/base-classifier.md new file mode 100644 index 0000000..51b4986 --- /dev/null +++ b/docs/en/api/base/base-classifier.md @@ -0,0 +1,133 @@ +--- +id: base-classifier +sidebar_label: BaseClassifier +keywords: + - base + - classifier + - classifier interface + - accuracy score + - fit + - predict +tags: + - classifier + - classification +--- + +# BaseClassifier + +Abstract base class for classification algorithms. + +> **Module:** `aisp.base` +> **Import:** `from aisp.base import BaseClassifier` + +--- + +## Overview + +This class defines the core interface for classification models. It enforces the implementation of the `fit` +and `predict` methods in all derived classes, and provides a default implementation of the `score` method. + +Use cases: + +- Abstract base class for extending classification algorithm classes. + +--- + +## Attributes + +| Name | Type | Default | Description | +|-----------|-------------------------|:-------:|------------------------------------------| +| `classes` | `Optional[npt.NDArray]` | `None` | Class labels identified during training. | + +--- + +## Abstract Methods + +### fit + +```python +@abstractmethod +def fit( + self, + X: Union[npt.NDArray, list], + y: Union[npt.NDArray, list], + verbose: bool = True +) -> BaseClassifier: + ... +``` + +Train the model using the input data X and corresponding labels y. +This abstract method is implemented by the class that inherits it. + +**Parameters** + +| Name | Type | Default | Description | +|-----------|----------------------------|:-------:|------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Input data used for training the model. | +| `y` | `Union[npt.NDArray, list]` | - | Corresponding labels or target values for the input data. | +| `verbose` | `bool` | `True` | Flag to enable or disable detailed output during training. | + +**Returns** + +| Type | Description | +|--------|----------------------------------------------------------------| +| `Self` | Returns the instance of the class that implements this method. | + +--- + +### predict + +```python +@abstractmethod +def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: + ... +``` + +Generate predictions based on the input data X. +This abstract method is implemented by the class that inherits it. + +**Parameters** + +| Name | Type | Default | Description | +|------|----------------------------|:-------:|-----------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Data for which predictions will be generated. | + +**Returns** + +| Type | Description | +|---------------|-----------------------------------------| +| `npt.NDArray` | Predicted values for each input sample. | + +--- + +## Public Methods + +### score + +```python +def score( + self, + X: Union[npt.NDArray, list], + y: Union[npt.NDArray, 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** + +| Name | Type | Default | Description | +|------|----------------------------|:-------:|-------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Feature set with shape (n_samples, n_features). | +| `y` | `Union[npt.NDArray, list]` | - | True values with shape (n_samples,). | + +**Returns** + +| Type | Description | +|---------|----------------------------| +| `float` | The accuracy of the model. | + diff --git a/docs/en/api/base/base-clusterer.md b/docs/en/api/base/base-clusterer.md new file mode 100644 index 0000000..ac139d5 --- /dev/null +++ b/docs/en/api/base/base-clusterer.md @@ -0,0 +1,122 @@ +--- +id: base-clusterer +sidebar_label: BaseClusterer +keywords: + - base + - clusterer + - clusterer interface + - cluster labels + - fit + - predict + - fit_predict +tags: + - clusterer + - clustering +--- + +# BaseClusterer + +Abstract base class for clustering algorithms. + +> **Module:** `aisp.base` +> **Import:** `from aisp.base import BaseClusterer` + +--- + +## Overview + +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`. + +Use cases: + +- Abstract base class for extending clustering algorithm classes. + +--- + +## Attributes + +| Name | Type | Default | Description | +|----------|-------------------------|:-------:|---------------------------------------------------------| +| `labels` | `Optional[npt.NDArray]` | `None` | Labels for the clusters generated during model fitting. | + +--- + +## Abstract Methods + +### fit + +```python +@abstractmethod +def fit(self, X: Union[npt.NDArray, list], verbose: bool = True) -> BaseClusterer: + ... +``` + +Train the model using the input data X. +This abstract method is implemented by the class that inherits it. + +**Parameters** + +| Name | Type | Default | Description | +|-----------|----------------------------|:-------:|------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Input data used for training the model. | +| `verbose` | `bool` | `True` | Flag to enable or disable detailed output during training. | + +**Returns** + +| Type | Description | +|--------|----------------------------------------------------------------| +| `Self` | Returns the instance of the class that implements this method. | + +--- + +### predict + +```python +@abstractmethod +def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: + ... +``` + +Generate predictions based on the input data X. +This abstract method is implemented by the class that inherits it. + +**Parameters** + +| Name | Type | Default | Description | +|------|----------------------------|:-------:|-----------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Data for which predictions will be generated. | + +**Returns** + +| Type | Description | +|---------------|-------------------------------------------------| +| `npt.NDArray` | Predicted cluster labels for each input sample. | + +--- + +## Public Methods + +### fit_predict + +```python +def fit_predict(self, X: Union[npt.NDArray, list], verbose: bool = True) -> npt.NDArray: + ... +``` + +Fit the clustering model to the data and return cluster labels. + +This is a convenience method that combines `fit` and `predict` into a single call. + +**Parameters** + +| Name | Type | Default | Description | +|-----------|----------------------------|:-------:|------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Feature set with shape (n_samples, n_features). | +| `verbose` | `bool` | `True` | Flag to enable or disable detailed output during training. | + +**Returns** + +| Type | Description | +|---------------|-------------------------------------------------| +| `npt.NDArray` | Predicted cluster labels for each input sample. | diff --git a/docs/en/api/base/base-optimizer.md b/docs/en/api/base/base-optimizer.md new file mode 100644 index 0000000..f3bde23 --- /dev/null +++ b/docs/en/api/base/base-optimizer.md @@ -0,0 +1,165 @@ +--- +id: base-optimizer +sidebar_label: BaseOptimizer +keywords: + - base + - optimizer + - optimization + - optimizer interface + - objective function + - minimization + - maximization +tags: + - optimizer + - optimization +--- + +# BaseOptimizer + +Abstract base class for optimization algorithms. + +> **Module:** `aisp.base` +> **Import:** `from aisp.base import BaseOptimizer` + +--- + +## Overview + +This class defines the core interface for optimization strategies. It keeps track of cost history, evaluated +solutions, and the best solution found during the optimization process. Subclasses must implement ``optimize`` +and ``affinity_function``. + +Use cases: + +- Abstract base class for extending optimization algorithm classes. + +--- + +## Attributes + +| Name | Type | Default | Description | +|--------------------|-------------------|:-------:|-------------------------------------------------------------------------| +| `cost_history` | `List[float]` | `[]` | History of best costs found at each iteration. | +| `solution_history` | `List` | `[]` | History of the best solution found at each iteration. | +| `best_solution` | `Any` | `None` | The best solution found. | +| `best_cost` | `Optional[float]` | `None` | Cost of the best solution found. | +| `mode` | `{"min", "max"}` | `'min'` | Defines whether the algorithm minimizes or maximizes the cost function. | + +--- + +## Abstract Methods + +### optimize + +```python +@abstractmethod +def optimize( + self, + max_iters: int = 50, + n_iter_no_change: int = 10, + verbose: bool = True +) -> Any: + ... +``` + +Execute the optimization process. +This abstract method must be implemented by the subclass, defining how the optimization strategy explores the search +space. + +**Parameters** + +| Name | Type | Default | Description | +|--------------------|--------|:-------:|------------------------------------------------------------| +| `max_iters` | `int` | `50` | Maximum number of iterations | +| `n_iter_no_change` | `int` | `10` | the maximum number of iterations without updating the best | +| `verbose` | `bool` | `True` | Flag to enable or disable detailed output during training. | + +**Returns** + +| Type | Description | +|--------|----------------------------------------------------------------| +| `Self` | Returns the instance of the class that implements this method. | + +--- + +### affinity_function + +```python +@abstractmethod +def affinity_function(self, solution: Any) -> float: + ... +``` + +Evaluate the affinity of a candidate solution. + +This method must be implemented according to the specific optimization problem, defining how the solution will be +evaluated. +The returned value should represent the quality of the evaluated solution. + +**Parameters** + +| Name | Type | Default | Description | +|------------|-------|:-------:|-------------------------------------| +| `solution` | `Any` | - | Candidate solution to be evaluated. | + +**Returns** + +| Type | Description | +|---------|------------------------------------------------| +| `float` | Cost value associated with the given solution. | + +--- + +## Public Methods + +### 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** + +| Type | Description | +|-------|---------------------------------------------------------| +| `str` | A formatted string containing the optimization summary. | + +--- + +### register + +```python +def register(self, alias: str, function: Callable[..., Any]) -> None: + ... +``` + +Register a function dynamically in the optimizer instance. + +**Parameters** + +| Name | Type | Default | Description | +|------------|----------------------|:-------:|---------------------------------------------------| +| `alias` | `str` | - | Name used to access the function as an attribute. | +| `function` | `Callable[..., Any]` | - | Callable to be registered. | + +**Raises** + +| Exception | Description | +|------------------|---------------------------------------------------------------------------------| +| `TypeError` | If the provided `function` is not callable. | +| `AttributeError` | If `alias` is protected and cannot be modified, or does not exist in the class. | + +--- + +### reset + +```python +def reset(self): + ... +``` + +Reset the object's internal state, clearing history and resetting values. diff --git a/docs/en/api/base/immune/README.md b/docs/en/api/base/immune/README.md new file mode 100644 index 0000000..5e196cb --- /dev/null +++ b/docs/en/api/base/immune/README.md @@ -0,0 +1,22 @@ +--- +id: immune +sidebar_label: immune +keywords: + - cell + - mutation + - population +--- + +# aisp.base.immune + +Support Module for Artificial Immune Systems. + +> **Module:** `aisp.base.immune` + +## Submodules + +| Module | Description | +|-----------------------------------|--------------------------------------------------------------------------------------------| +| [`cell`](./cell/README.md) | Representation of immune system cells. | +| [`mutation`](./mutation.md) | Functions to generate mutated clones and simulate clonal expansion. | +| [`populations`](./populations.md) | Provide utility functions for generating antibody populations in immunological algorithms. | \ No newline at end of file diff --git a/docs/en/api/base/immune/cell/README.md b/docs/en/api/base/immune/cell/README.md new file mode 100644 index 0000000..e35cc09 --- /dev/null +++ b/docs/en/api/base/immune/cell/README.md @@ -0,0 +1,33 @@ +--- +id: immune-cell +sidebar_label: cell +keywords: + - vector representation + - cell + - immune + - immune cell + - base class + - bcell + - antibody + - dataclass +--- + +# aisp.base.immune.cell + +Representation of immune system cells. + +> **Module:** `aisp.base.immune.cell` + +## Overview + +This module defines the representation of cells in artificial immune systems, +implements as dataclass. + +## Classes + +| Class | Description | +|-----------------------------|---------------------------------------------------| +| [`Cell`](./cell.md) | Represents a basic immune cell. | +| [`BCell`](./b-cell.md) | Represents a memory B-cell. | +| [`Antibody`](./antibody.md) | Represent an antibody. | +| [`Detector`](./detector.md) | Represents a non-self detector of the RNSA class. | \ No newline at end of file diff --git a/docs/en/api/base/immune/cell/antibody.md b/docs/en/api/base/immune/cell/antibody.md new file mode 100644 index 0000000..2a6aa20 --- /dev/null +++ b/docs/en/api/base/immune/cell/antibody.md @@ -0,0 +1,39 @@ +--- +id: antibody +sidebar_label: Antibody +keywords: + - antibody + - affinity + - cell + - immune + - dataclass +--- + +# Antibody + +Represent an antibody. + +:::tip[Inheritance] + +This class extends [Cell](./cell.md) + +::: + +> **Module:** `aisp.base.immune.cell` +> **Import:** `from aisp.base.immune.cell import Antibody` + +--- + +## Attributes + +| Name | Type | Default | Description | +|------------|---------------|:-------:|----------------------------------| +| `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. diff --git a/docs/en/api/base/immune/cell/b-cell.md b/docs/en/api/base/immune/cell/b-cell.md new file mode 100644 index 0000000..cd96493 --- /dev/null +++ b/docs/en/api/base/immune/cell/b-cell.md @@ -0,0 +1,63 @@ +--- +id: b-cell +sidebar_label: BCell +keywords: + - B-cell + - immune memory + - dataclass + - clonal mutation + - clonal expansion +--- + +# BCell + +Represents a memory B-cell. + +:::tip[Inheritance] + +This class extends [Cell](./cell.md) + +::: + +> **Module:** `aisp.base.immune.cell` +> **Import:** `from aisp.base.immune.cell import BCell` + +--- + +## Attributes + +| Name | Type | Default | Description | +|----------|--------------|:-------:|----------------------------| +| `vector` | `np.ndarray` | - | A vector of cell features. | + +--- + +## Public Methods + +### hyper_clonal_mutate + +```python +def hyper_clonal_mutate( + self, + n: int, + feature_type: FeatureType = "continuous-features", + bounds: Optional[npt.NDArray[np.float64]] = None +) -> npt.NDArray: + ... +``` + +Generate **N** clones of the current cell and apply hypermutation to the clones. + +**Parameters** + +| Name | Type | Default | Description | +|----------------|------------------------------------------------------|:-----------------------:|--------------------------------------------------------| +| `n` | `int` | - | Number of clones to generate from the original b-cell. | +| `feature_type` | [`FeatureType`](../../../utils/types.md#featuretype) | `"continuous-features"` | Specifies the type of features of the cell. | +| `bounds` | `Optional[npt.NDArray[np.float64]]` | `None` | Array (n_features, 2) with min and max per dimension. | + +**Returns** + +| Type | Description | +|---------------|---------------------------------------------------------------| +| `npt.NDArray` | An array containing N mutated vectors from the original cell. | diff --git a/docs/en/api/base/immune/cell/cell.md b/docs/en/api/base/immune/cell/cell.md new file mode 100644 index 0000000..ff94da9 --- /dev/null +++ b/docs/en/api/base/immune/cell/cell.md @@ -0,0 +1,35 @@ +--- +id: cell +sidebar_label: Cell +keywords: + - vector representation + - cell + - immune + - immune cell + - base class + - dataclass +--- + +# Cell + +Represents a basic immune cell. + +> **Module:** `aisp.base.immune.cell` +> **Import:** `from aisp.base.immune.cell import Cell` + +--- + +## Attributes + +| Name | Type | Default | Description | +|----------|--------------|:-------:|----------------------------| +| `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. + diff --git a/docs/en/api/base/immune/cell/detector.md b/docs/en/api/base/immune/cell/detector.md new file mode 100644 index 0000000..520294d --- /dev/null +++ b/docs/en/api/base/immune/cell/detector.md @@ -0,0 +1,28 @@ +--- +id: detector +sidebar_label: Detector +keywords: + - detector + - cell + - immune + - radius + - non-self + - nsa + - dataclass +--- + +# Detector + +Represents a non-self detector of the RNSA class. + +> **Module:** `aisp.base.immune.cell` +> **Import:** `from aisp.base.immune.cell import Detector` + +--- + +## Attributes + +| Name | Type | Default | Description | +|------------|---------------------------|:-------:|----------------------------------------------------| +| `position` | `npt.NDArray[np.float64]` | - | Detector feature vector. | +| `radius` | `float, optional` | - | Detector radius, used in the V-detector algorithm. | diff --git a/docs/en/api/base/immune/mutation.md b/docs/en/api/base/immune/mutation.md new file mode 100644 index 0000000..c0d34a9 --- /dev/null +++ b/docs/en/api/base/immune/mutation.md @@ -0,0 +1,145 @@ +--- +id: mutation +sidebar_label: mutation +keywords: + - mutation + - clonal expansion + - immune system + - python numba functions + - vector mutation +--- + +# mutation + +The functions perform utilize Numba decorators for Just-In-Time compilation. + +Contains functions that generate sets of mutated clones from continuous or binary vectors, +simulating the clonal expansion process in artificial immune systems. + +> **Module:** `aisp.base.immune` +> **Import:** `from aisp.base.immune import mutation` + +## Functions + +### clone_and_mutate_continuous + +```python +@njit([(types.float64[:], types.int64, types.float64)], cache=True) +def clone_and_mutate_continuous( + vector: npt.NDArray[np.float64], + n: int, + mutation_rate: float +) -> npt.NDArray[np.float64]: + ... +``` + +Generate a set of mutated clones from a cell represented by a continuous vector. + +This function creates `n` clones of the input vector and applies mutations to each of +them, simulating the process of clonal expansion in artificial immune systems. + +**Parameters** + +| Name | Type | Default | Description | +|-----------------|---------------------------|:-------:|------------------------------------------------------------------------------------------------------------------| +| `vector` | `npt.NDArray[np.float64]` | - | The original immune cell with continuous values to be cloned and mutated. | +| `n` | `int` | - | The number of mutated clones to be generated. | +| `mutation_rate` | `float` | - | If `0 ≤ mutation_rate < 1`, mutation probability per feature. Otherwise, a random number of features is mutated. | + +**Returns** + +| Type | Description | +|---------------------------|------------------------------------------------------------------------------------| +| `npt.NDArray[np.float64]` | An Array(n, len(vector)) containing the `n` mutated clones of the original vector. | + +### clone_and_mutate_binary + +```python +@njit([(types.boolean[:], types.int64, types.float64)], cache=True) +def clone_and_mutate_binary( + vector: npt.NDArray[np.bool_], + n: int, + mutation_rate: float +) -> npt.NDArray[np.bool_]: + ... +``` + +Generate a set of mutated clones from a cell represented by a binary vector. + +This function creates `n` clones of the input binary vector and applies mutations to the +bits, simulating clonal expansion in artificial immune systems with discrete representations. + +**Parameters** + +| Name | Type | Default | Description | +|-----------------|---------------------------|:-------:|------------------------------------------------------------------------------------------------------------------| +| `vector` | `npt.NDArray[np.float64]` | - | The original immune cell with binary values to be cloned and mutated. | +| `n` | `int` | - | The number of mutated clones to be generated. | +| `mutation_rate` | `float` | - | If `0 ≤ mutation_rate < 1`, mutation probability per feature. Otherwise, a random number of features is mutated. | + +**Returns** + +| Type | Description | +|-------------------------|------------------------------------------------------------------------------------| +| `npt.NDArray[np.bool_]` | An Array(n, len(vector)) containing the `n` mutated clones of the original vector. | + +### clone_and_mutate_ranged + +```python +@njit([(types.float64[:], types.int64, types.float64[:, :], types.float64)], cache=True) +def clone_and_mutate_ranged( + vector: npt.NDArray[np.float64], + n: int, + bounds: npt.NDArray[np.float64], + mutation_rate: float, +) -> npt.NDArray[np.float64]: + ... +``` + +Generate a set of mutated clones from a cell represented by custom ranges per dimension. + +This function creates `n` clones of the input vector and applies mutations to each of +them, simulating the process of clonal expansion in artificial immune systems. + +**Parameters** + +| Name | Type | Default | Description | +|-----------------|---------------------------|:-------:|------------------------------------------------------------------------------------------------------------------| +| `vector` | `npt.NDArray[np.float64]` | - | The original immune cell with continuous values to be cloned and mutated. | +| `n` | `int` | - | The number of mutated clones to be generated. | +| `bounds` | `np.ndarray` | - | Array (n_features, 2) with min and max per dimension. | +| `mutation_rate` | `float` | - | If `0 ≤ mutation_rate < 1`, mutation probability per feature. Otherwise, a random number of features is mutated. | + +**Returns** + +| Type | Description | +|---------------------------|------------------------------------------------------------------------------------| +| `npt.NDArray[np.float64]` | An Array(n, len(vector)) containing the `n` mutated clones of the original vector. | + +### clone_and_mutate_continuous + +```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]: + ... +``` + +Generate a set of mutated clones by permutation. + +**Parameters** + +| Name | Type | Default | Description | +|-----------------|-------------------------|:-------:|----------------------------------------------------------------------------| +| `vector` | `npt.NDArray[np.int64]` | - | The original immune cell with permutation values to be cloned and mutated. | +| `n` | `int` | - | The number of mutated clones to be generated. | +| `mutation_rate` | `float` | - | Probability of mutating each feature 0 ≤ mutation_rate < 1. | + +**Returns** + +| Type | Description | +|---------------------------|------------------------------------------------------------------------------------| +| `npt.NDArray[np.float64]` | An Array(n, len(vector)) containing the `n` mutated clones of the original vector. | diff --git a/docs/en/api/base/immune/populations.md b/docs/en/api/base/immune/populations.md new file mode 100644 index 0000000..0126de2 --- /dev/null +++ b/docs/en/api/base/immune/populations.md @@ -0,0 +1,56 @@ +--- +id: populations +sidebar_label: populations +keywords: + - binary + - classifying + - affinity threshold + - real-Valued + - memory B-cell + - clonal Expansion + - populations +--- + +# populations + +Provide utility functions for generating antibody populations in immunological algorithms. + +> **Module:** `aisp.base.immune` +> **Import:** `from aisp.base.immune import populations` + +## Functions + +### 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** + +| Name | Type | Default | Description | +|----------------|---------------------------------------------------------|:-----------------------:|-------------------------------------------------------------------------------------------------------------------------| +| `n_samples` | `int` | - | Number of antibodies (samples) to generate. | +| `n_features` | `int` | - | Number of features (dimensions) for each antibody. | +| `feature_type` | [`FeatureTypeAll`](../../utils/types.md#featuretypeall) | `"continuous-features"` | Specifies the type of features: "continuous-features", "binary-features", "ranged-features", or "permutation-features". | +| `bounds` | `npt.NDArray[np.float64]` | `None` | Array (n_features, 2) with min and max per dimension. | + +**Returns** + +| Type | Description | +|---------------|-----------------------------------------------------------------------------| +| `npt.NDArray` | Array of shape (n_samples, n_features) containing the generated antibodies. | + +**Raises** + +| Exception | Description | +|--------------|----------------------------------------------------------| +| `ValueError` | If the number of features is less than or equal to zero. | diff --git a/docs/en/api/csa/README.md b/docs/en/api/csa/README.md new file mode 100644 index 0000000..e2872ed --- /dev/null +++ b/docs/en/api/csa/README.md @@ -0,0 +1,33 @@ +--- +id: csa +sidebar_label: aisp.csa +keywords: + - immune + - clonal selection + - clonalg + - airsv2 + - antibody proliferation + - mutations + - clonal selection algorithm + - artificial immune systems + - classification + - optimization +--- + +# aisp.csa + +Module (CSA) Clonal Selection Algorithm. + +> **Module:** `aisp.csa` + +## Overview + +CSAs 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 + +| Class | Description | +|---------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| [`AIRS`](./airs.md) | A supervised learning algorithm for classification tasks based on the clonal selection principle. | +| [`Clonalg`](./clonalg.md) | Implementation of the clonal selection algorithm for optimization, adapted for both minimization and maximization of cost functions in binary, continuous, and permutation problems. | diff --git a/docs/en/api/csa/airs.md b/docs/en/api/csa/airs.md new file mode 100644 index 0000000..8517b45 --- /dev/null +++ b/docs/en/api/csa/airs.md @@ -0,0 +1,200 @@ +--- +id: airs +sidebar_label: AIRS +keywords: + - classification + - artificial immune recognition system + - memory cells + - k-nn + - supervised learning + - AIRS2 +tags: + - classification + - supervised + - clonal selection +--- + +# AIRS + +Artificial Immune Recognition System (AIRS) + +:::tip[Inheritance] + +This class extends [BaseClassifier](../base/base-classifier.md) + +::: + + +> **Module:** `aisp.csa` +> **Import:** `from aisp.csa import AIRS` + +--- + +## Overview + +The Artificial Immune Recognition System (AIRS) is a classification algorithm inspired by the +clonal selection process of the biological immune system. This implementation is based on the +simplified AIRS2 version described in [^1]. The algorithm has been adapted to support both +real-valued (continuous) and binary feature datasets. + +:::note + +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] + +Related and noteworthy works: access here [^2]. + +::: + +--- + +## Example + +```python +import numpy as np +from aisp.csa import AIRS + +np.random.seed(1) +# Generating training data +a = np.random.uniform(high=0.5, size=(50, 2)) +b = np.random.uniform(low=0.51, size=(50, 2)) +x_train = np.vstack((a, b)) +y_train = [0] * 50 + [1] * 50 +# AIRS Instance +airs = AIRS(n_resources=5, rate_clonal=5, rate_hypermutation=0.65, seed=1) +airs = airs.fit(x_train, y_train, verbose=False) +x_test = [ + [0.15, 0.45], # Expected: Class 0 + [0.85, 0.65], # Esperado: Classe 1 +] +y_pred = airs.predict(x_test) +print(y_pred) +``` + +Output: + +```bash +[0 1] +``` + +--- + +## Constructor Parameters + +| Name | Type | Default | Description | +|-----------------------------|---------|:-------------:|---------------------------------------------------------------------------------------------------------------------------------------------------| +| `n_resources` | `float` | `10` | Total amount of available resources. | +| `rate_clonal` | `float` | `10` | Maximum number of possible clones of a class. This quantity is multiplied by (cell_stimulus * rate_hypermutation) to define the number of clones. | +| `rate_mc_init` | `float` | `0.2` | Percentage of samples used to initialize memory cells. | +| `rate_hypermutation` | `float` | `0.75` | The rate of mutated clones derived from rate_clonal as a scalar factor. | +| `affinity_threshold_scalar` | `float` | `0.75` | Normalized affinity threshold. | +| `k` | `int` | `3` | The number of K nearest neighbors that will be used to choose a label in the prediction. | +| `max_iters` | `int` | `100` | Maximum number of iterations in the refinement process of the ARB set exposed to aᵢ. | +| `resource_amplified` | `float` | `1.0` | Resource consumption amplifier is multiplied with the incentive to subtract resources. | +| `metric` | `str` | `"euclidean"` | Distance metric used to compute affinity between cells and samples. | +| `seed` | `int` | `None` | Seed for random generation. | +| `p` | `float` | `2` | This parameter stores the value of `p` used in the Minkowski distance. | + +## Attributes + +| Name | Type | Default | Description | +|----------------|-------------------------------------------|:-------:|---------------------------------------------------------| +| `cells_memory` | `Optional[Dict[str \| int, list[BCell]]]` | - | Dictionary of trained memory cells, organized by class. | + +--- + +## Public Methods + +### fit + +```python +def fit( + self, + X: Union[npt.NDArray, list], + y: Union[npt.NDArray, list], + verbose: bool = True, +) -> AIRS: + ... +``` + +Fit the model to the training data using the AIRS. + +The function ``fit(...)``, performs the training according to `X` and `y`, using the +method AIRS. + +**Parameters** + +| Name | Type | Default | Description | +|-----------|----------------------------|:-------:|---------------------------------------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Training array, containing the samples and their characteristics, Shape: (n_samples, n_features). | +| `y` | `Union[npt.NDArray, list]` | - | Array of target classes of `X` with (`n_samples`). | +| `verbose` | `bool` | `True` | Feedback on which sample aᵢ the memory cells are being generated. | + +**Returns** + +| Type | Description | +|--------|------------------------------| +| `Self` | Returns the instance itself. | + +**Raises** + +| Exception | Description | +|-------------|---------------------------------------------------------| +| `TypeError` | If X or y are not ndarrays or have incompatible shapes. | + +--- + +### predict + +```python +def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: + ... +``` + +Predict class labels based on the memory cells created during training. + +This method uses the trained memory cells to perform classification of the input data +using the k-nearest neighbors approach. + +**Parameters** + +| Name | Type | Default | Description | +|------|----------------------------|:-------:|-----------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Array with input samples with Shape: (`n_samples, n_features`) | + +**Returns** + +| Type | Description | +|---------------|-------------------------------------------------------------------------------------| +| `npt.NDArray` | An ndarray of the form `C` (`n_samples`), containing the predicted classes for `X`. | + +**Raises** + +| Exception | Description | +|-------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------| +| `TypeError` | If X is not a ndarray or list. | +| [`FeatureDimensionMismatch`](../exceptions.md#featuredimensionmismatch) | If the number of features in X does not match the expected number. | +| [`ModelNotFittedError`](../exceptions.md#modelnotfittederror) | If the mode has not yet been adjusted and does not have defined memory cells, it is not able to predictions | + +--- + +## Extended Example + +Complete usage examples are available in the Jupyter Notebooks: + +- [**Iris Dataset Example**](../../../../examples/en/classification/AIRS/iris_dataBase_example_en.ipynb) +- [**Geyser Dataset Example**](../../../../examples/en/classification/AIRS/geyser_dataBase_example_en.ipynb) +- [**Mushrooms Dataset Example**](../../../../examples/en/classification/AIRS/mushrooms_dataBase_example_en.ipynb) +- [**Random Dataset Example**](../../../../examples/en/classification/AIRS/example_with_randomly_generated_dataset-en.ipynb) + +--- + +## References + +[^1]: Brabazon, A., O'Neill, M., & McGarraghy, S. (2015). Natural Computing Algorithms. In Natural Computing Series. + Springer Berlin Heidelberg. [https://doi.org/10.1007/978-3-662-43631-8](https://doi.org/10.1007/978-3-662-43631-8) + +[^2]: AZZOUG, Aghiles. Artificial Immune Recognition System V2. Available at: + [https://github.com/AghilesAzzoug/Artificial-Immune-System](https://github.com/AghilesAzzoug/Artificial-Immune-System) diff --git a/docs/en/api/csa/clonalg.md b/docs/en/api/csa/clonalg.md new file mode 100644 index 0000000..863e94e --- /dev/null +++ b/docs/en/api/csa/clonalg.md @@ -0,0 +1,185 @@ +--- +id: clonalg +sidebar_label: Clonalg +keywords: + - optimization + - clonal selection + - clonalg + - antibody population + - objective function +tags: + - optimization + - clonal selection + - minimization + - maximization + - binary + - continuous + - permutation + - ranged +--- + +# Clonalg + +Clonal Selection Algorithm (CLONALG). + +:::tip[Inheritance] + +This class extends [BaseOptimizer](../base/base-optimizer.md) + +::: + + +> **Module:** `aisp.csa` +> **Import:** `from aisp.csa import Clonalg` + +--- + +## Overview + +The Clonal Selection Algorithm (CSA) is an optimization algorithm inspired by the biological +process of clonal selection and expansion of antibodies in the immune system [^1]. This +implementation of CLONALG has been adapted for the minimization or maximization of cost +functions in binary, continuous, ranged-value, and permutation problems. + +:::note + +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. + +::: + +--- + +## Example + +```python +import numpy as np +from aisp.csa import Clonalg +# Search space limits +bounds = {'low': -5.12, 'high': 5.12} +# Objective function +def rastrigin_fitness(x): + x = np.clip(x, bounds['low'], bounds['high']) + return 10 * len(x) + np.sum(x**2 - 10 * np.cos(2 * np.pi * x)) +# CLONALG Instance +clonalg = Clonalg(problem_size=2, bounds=bounds, seed=1) +clonalg.register('affinity_function', rastrigin_fitness) +population = clonalg.optimize(100, 50, False) +print('Best cost:', abs(clonalg.best_cost)) +``` + +**Output:** + +```bash +Best cost: 0.02623036956750724 +``` + +--- + +## Constructor Parameters + +| Name | Type | Default | Description | +|-------------------------|------------------------------------------------------|:-------------------:|------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `problem_size` | `int` | - | Dimension of the problem to be minimized. | +| `N` | `int` | `50` | Number of memory cells (antibodies) in the population. | +| `rate_clonal` | `int` | `10` | Maximum number of possible clones of a cell. This value is multiplied by cell_affinity to determine the number of clones. | +| `rate_hypermutation` | `float` | `1.0` | Hypermutation rate controls the intensity of mutations during clonal expansion. Higher values decrease mutation intensity, while lower values increase it. | +| `n_diversity_injection` | `int` | `5` | Number of new random memory cells injected to maintain diversity. | +| `selection_size` | `int` | `5` | Number of the best antibodies selected for cloning. | +| `affinity_function` | `Optional[Callable[..., npt.NDArray]]` | `None` | Objective function to evaluate candidate solutions in minimizing the problem. | +| `feature_type` | [`FeatureTypeAll`](../utils/types.md#featuretypeall) | `'ranged-features'` | Type of problem samples: binary, continuous, or based on value ranges. | +| `bounds` | `Optional[Dict]` | `None` | Definition of search limits when ``feature_type='ranged-features'``. | +| `mode` | `{"min", "max"}` | `'min'` | Defines whether the algorithm minimizes or maximizes the cost function. | +| `seed` | `int` | `None` | Seed for random generation of detector values. If None, the value is random. | + +## Attributes + +| Name | Type | Default | Description | +|--------------|----------------------------|:-------:|--------------------------| +| `population` | `Optional[List[Antibody]]` | `None` | Population of antibodies | + +--- + +## Public Methods + +### optimize + +```python +def optimize( + self, max_iters: int = 50, n_iter_no_change=10, verbose: bool = True +) -> List[Antibody]: + ... +``` + +Execute the optimization process and return the population. + +**Parameters** + +| Name | Type | Default | Description | +|--------------------|--------|:-------:|----------------------------------------------------------------------------------| +| `max_iters` | `int` | `50` | Maximum number of iterations when searching for the best solution using clonalg. | +| `n_iter_no_change` | `int` | `10` | The maximum number of iterations without updating the best cell. | +| `verbose` | `bool` | `True` | Feedback on iterations, indicating the best antibody. | + +**Returns** + +| Type | Description | +|------------------|---------------------------------------------| +| `List[Antibody]` | Antibody population after clonal expansion. | + + +**Raises** + +| Exception | Description | +|-----------------------|----------------------------------------------------------------------------| +| `NotImplementedError` | If no affinity function has been provided to evaluate candidate solutions. | + +--- + +### affinity_function + +```python +def affinity_function(self, solution: npt.NDArray) -> np.float64: + ... +``` + +Evaluate the affinity of a candidate cell. + +**Parameters** + +| Name | Type | Default | Description | +|------------|---------------|:-------:|---------------------------------| +| `solution` | `npt.NDArray` | - | Candidate solution to evaluate. | + +**Returns** + +| Type | Description | +|--------------|------------------------------------------------| +| `np.float64` | Affinity value associated with the given cell. | + + +**Raises** + +| Exception | Description | +|-----------------------|--------------------------------------------| +| `NotImplementedError` | If no affinity function has been provided. | + +--- + +## Extended Example + +Complete usage examples are available in the Jupyter Notebooks: + +- [**Knapsack Problem Example**](../../../../examples/en/optimization/clonalg/knapsack_problem_example.ipynb) +- [**Rastrigin Function Example**](../../../../examples/en/optimization/clonalg/rastrigin_function_example.ipynb) +- [**Tsp Problem Example**](../../../../examples/en/optimization/clonalg/tsp_problem_example.ipynb) + +--- + +## 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 diff --git a/docs/en/api/exceptions.md b/docs/en/api/exceptions.md new file mode 100644 index 0000000..688c12e --- /dev/null +++ b/docs/en/api/exceptions.md @@ -0,0 +1,91 @@ +--- +id: exceptions +sidebar_label: aisp.exceptions +keywords: + - exceptions + - raises + - warnings +--- + +# aisp.exceptions + +Custom warnings and errors. + +> **Module:** `aisp.exceptions` +> **Import:** `from aisp import exceptions` + +## Exception classes + +### MaxDiscardsReachedError + +```python +class MaxDiscardsReachedError(Exception): + ... +``` + +Exception thrown when the maximum number of detector discards is reached. + +**Parameters** + +| Name | Type | Default | Description | +|---------------|-----------------|:-------:|----------------------------------------------------------------| +| `object_name` | `str` | - | The name of the instantiated class that throws the exceptions. | +| `message` | `Optional[str]` | `None` | Custom message to display. | + +--- + +### FeatureDimensionMismatch + +```python +class FeatureDimensionMismatch(Exception): + ... +``` + +Exception raised when the number of input features does not match the expected number. +This exception is triggered during prediction if the input features' dimension is incorrect. + +**Parameters** + +| Name | Type | Default | Description | +|-----------------|-----------------|:-------:|-----------------------------------------------------| +| `expected` | `int` | - | The expected number of features | +| `received` | `int` | - | The actual number of features received. | +| `variable_name` | `Optional[str]` | `None` | The name of the variable that caused this mismatch. | + +--- + +### UnsupportedTypeError + +```python +class UnsupportedTypeError(Exception): + ... +``` + +Exception raised when the input vector type is not supported. +This exception is thrown when the vector data type does not match any of the supported. + +**Parameters** + +| Name | Type | Default | Description | +|-----------|-----------------|:-------:|----------------------------| +| `message` | `Optional[str]` | `None` | Custom message to display. | + +--- + +### ModelNotFittedError + +```python +class ModelNotFittedError(Exception): + ... +``` + +Exception raised when a method is called before the model has been fit. +This exception is thrown when the model instance is being used without first training +it via the `fit` method. + +**Parameters** + +| Name | Type | Default | Description | +|---------------|-----------------|:-------:|----------------------------------------------------------------| +| `object_name` | `str` | - | The name of the instantiated class that throws the exceptions. | +| `message` | `Optional[str]` | `None` | Custom message to display. | diff --git a/docs/en/api/ina/README.md b/docs/en/api/ina/README.md new file mode 100644 index 0000000..59c20b7 --- /dev/null +++ b/docs/en/api/ina/README.md @@ -0,0 +1,31 @@ +--- +id: ina +sidebar_label: aisp.ina +keywords: + - immune + - clonal selection + - immune networks + - ainet + - opt-ainet + - mutations + - clonal selection + - artificial immune systems + - clustering + - optimization +--- + +# aisp.ina + +Module (ina) Immune Network Algorithm. + +> **Module:** `aisp.ina` + +## Overview + +This module implements algorithms based on Network Theory Algorithms proposed by Jerne. + +## Classes + +| Class | Description | +|------------------------|--------------------------------------------------------------------------------------------| +| [`AiNet`](./ai-net.md) | An unsupervised learning algorithm for clustering, based on the theory of immune networks. | diff --git a/docs/en/api/ina/ai-net.md b/docs/en/api/ina/ai-net.md new file mode 100644 index 0000000..46d2d78 --- /dev/null +++ b/docs/en/api/ina/ai-net.md @@ -0,0 +1,228 @@ +--- +id: ai-net +sidebar_label: AiNet +keywords: + - immune network + - clustering + - data compression + - unsupervised learning + - Minimum Spanning Tree +tags: + - clustering + - unsupervised + - immune network + - data compression +--- + +# AiNet + +Artificial Immune Network (AiNet) for Compression and Clustering. + +:::tip[Inheritance] + +This class extends [BaseClusterer](../base/base-clusterer.md). + +::: + + +> **Module:** `aisp.ina` +> **Import:** `from aisp.ina import AiNet` + +--- + +## Overview + +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]. +For clustering, the class uses SciPy implementation of the **Minimum Spanning Tree** +(MST) to remove the most distant nodes and separate the groups [^2]. + +--- + +## Example + +```python +import numpy as np +from aisp.ina import AiNet + +np.random.seed(1) +# Generating training data +a = np.random.uniform(high=0.4, size=(50, 2)) +b = np.random.uniform(low=0.6, size=(50, 2)) +x_train = np.vstack((a, b)) +# AiNet Instance +ai_net = AiNet( + N=150, + mst_inconsistency_factor=1, + seed=1, + affinity_threshold=0.85, + suppression_threshold=0.7 +) +ai_net = ai_net.fit(x_train, verbose=True) +x_test = [ + [0.15, 0.45], # Expected: label 0 + [0.85, 0.65], # Esperado: label 1 +] +y_pred = ai_net.predict(x_test) +print(y_pred) +``` + +**Output** + +```bash +[0 1] +``` + +--- + +## Constructor Parameters + +| Name | Type | Default | Description | +|----------------------------|----------------------------------------------|:-------------:|--------------------------------------------------------------------------------------------------------------------------------------------| +| `N` | `int` | `50` | Number of memory cells (antibodies) in the population. | +| `n_clone` | `int` | `10` | Number of clones generated for each selected memory cell. | +| `top_clonal_memory_size` | `int` | `5` | Number of highest-affinity antibodies selected per antigen for cloning and mutation. | +| `n_diversity_injection` | `int` | `5` | Number of new random memory cells injected to maintain diversity. | +| `affinity_threshold` | `float` | `0.5` | Threshold for affinity (similarity) to determine cell suppression or selection. | +| `suppression_threshold` | `float` | `0.5` | Threshold for suppressing similar memory cells | +| `mst_inconsistency_factor` | `float` | `2.0` | Factor used to determine which edges in the **Minimum Spanning Tree (MST)** are considered inconsistent. | +| `max_iterations` | `int` | `10` | Maximum number of training iterations. | +| `k` | `int` | `3` | The number of K nearest neighbors that will be used to choose a label in the prediction. | +| `metric` | [`MetricType`](../utils/types.md#metrictype) | `"euclidean"` | Distance metric used to compute similarity between memory cells | +| `seed` | `Optional[int]` | `None` | Seed for random generation. | +| `use_mst_clustering` | `bool` | `True` | If ``True``, performs clustering with **Minimum Spanning Tree** (MST). If ``False``, does not perform clustering and predict returns None. | +| `p` | `float` | `2.0` | This parameter stores the value of `p` used in the Minkowski distance. | + +## Attributes + +| Name | Type | Default | Description | +|-------------------------|-------------------------|:-------:|------------------------------------------------------------------------------------| +| `memory_network` | `Dict[int, List[Cell]]` | - | The immune network representing clusters. | +| `population_antibodies` | `Optional[npt.NDArray]` | - | The set of memory antibodies. | +| `mst` | `dict` | - | The Minimum Spanning Tree and its statistics (graph, mean_distance, std_distance). | + +--- + +## Public Methods + +### fit + +```python +def fit(self, X: Union[npt.NDArray, list], verbose: bool = True) -> AiNet: + ... +``` + +Train the AiNet model on input data. + +**Parameters** + +| Name | Type | Default | Description | +|-----------|----------------------------|:-------:|------------------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Input data used for training the model. | +| `verbose` | `bool` | `True` | Feedback from the progress bar showing current training interaction details. | + +**Returns** + +| Type | Description | +|--------|------------------------------| +| `Self` | Returns the instance itself. | + + +**Raises** + +| Exception | Description | +|-----------------------------------------------------------------|--------------------------------------------------------| +| `TypeError` | If X is not a ndarray or list. | +| [`UnsupportedTypeError`](../exceptions.md#unsupportedtypeerror) | If the data type of the feature on X is not supported. | + +--- + +### predict + +```python +def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: + ... +``` + +Predict cluster labels for input data. + +**Parameters** + +| Name | Type | Default | Description | +|------|----------------------------|:-------:|------------------| +| `X` | `Union[npt.NDArray, list]` | - | Data to predict. | + +**Returns** + +| Type | Description | +|---------------|--------------------------------------------------------------| +| `npt.NDArray` | Predicted cluster labels, or None if clustering is disabled. | + + +**Raises** + +| Exception | Description | +|-------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------| +| `TypeError` | If X is not a ndarray or list. | +| `ValueError` | If the array contains values other than 0 and 1. | +| [`FeatureDimensionMismatch`](../exceptions.md#featuredimensionmismatch) | If the number of features (columns) in X does not match the expected number. | +| [`ModelNotFittedError`](../exceptions.md#modelnotfittederror) | If the mode has not yet been adjusted and does not have defined memory cells, it is not able to predictions | + +--- + +### update_clusters + +```python +def update_clusters(self, mst_inconsistency_factor: Optional[float] = None): + ... +``` + +Partition the clusters based on the MST inconsistency factor. + +Uses the precomputed Minimum Spanning Tree (MST) of the antibody population +to redefine clusters. Edges whose weights exceed the mean plus the +`mst_inconsistency_factor` multiplied by the standard deviation of MST edge +weights are removed. Each connected component after pruning is treated as a +distinct cluster. + +**Parameters** + +| Name | Type | Default | Description | +|----------------------------|---------|:-------:|----------------------------------------------------------| +| `mst_inconsistency_factor` | `float` | `None` | If provided, overrides the current inconsistency factor. | + +**Raises** + +| Exception | Description | +|--------------|-------------------------------------------------------------| +| `ValueError` | If the Minimum Spanning Tree (MST) has not yet been created | +| `ValueError` | If Population of antibodies is empty | +| `ValueError` | If MST statistics (mean or std) are not available. | + +**Updates** + +| Name | Type | Description | +|------------------|--------------------------|-------------------------------------------------------| +| `memory_network` | `dict[int, npt.NDArray]` | Dictionary mapping cluster labels to antibody arrays. | +| `labels` | `list` | List of cluster labels. | + +--- + +## Extended Example + +Complete usage examples are available in the Jupyter Notebooks: + +- [**Random Example**](../../../../examples/en/clustering/AiNet/example_with_randomly_generated_dataset.ipynb) +- [**Geyser Dataset Example**](../../../../examples/en/clustering/AiNet/geyser_dataBase_example.ipynb) + +--- + +## 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 + +[^2]: SciPy Documentation. *Minimum Spanning Tree*. + https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csgraph.minimum_spanning_tree diff --git a/docs/en/api/nsa/README.md b/docs/en/api/nsa/README.md new file mode 100644 index 0000000..0b354be --- /dev/null +++ b/docs/en/api/nsa/README.md @@ -0,0 +1,35 @@ +--- +id: nsa +sidebar_label: aisp.nsa +keywords: + - immune + - artificial immune systems + - classification + - negative selection + - binary features + - anomaly detection + - non-self recognition + - pattern recognition + - multiclass + - real-valued + - v-detector +--- + +# aisp.nsa + +Module (NSA) Negative Selection Algorithm. + +> **Module:** `aisp.nsa` + +## Overview + +NSAs simulate the maturation process of T-cells in the immune system, where these cells learn to +distinguish between self and non-self. Only T-cells capable of recognizing non-self elements are +preserved. + +## Classes + +| Class | Description | +|---------------------|-------------------------------------------------------------------------------------| +| [`RNSA`](./rnsa.md) | A supervised learning algorithm for classification that uses real-valued detectors. | +| [`BNSA`](./bnsa.md) | A supervised learning algorithm for classification that uses binary detectors. | diff --git a/docs/en/api/nsa/bnsa.md b/docs/en/api/nsa/bnsa.md new file mode 100644 index 0000000..228ac23 --- /dev/null +++ b/docs/en/api/nsa/bnsa.md @@ -0,0 +1,195 @@ +--- +id: bnsa +sidebar_label: BNSA +keywords: + - negative selection + - binary features + - anomaly detection + - non-self recognition + - pattern recognition + - classification + - multiclass +tags: + - classification + - supervised + - negative selection + - binary-features + - anomaly detection +--- + +# BNSA + +Binary Negative Selection Algorithm (BNSA). + +:::tip[Inheritance] +This class extends [BaseClassifier](../base/base-classifier.md) +::: + + +> **Module:** `aisp.nsa` +> **Import:** `from aisp.nsa import BNSA` + +--- + +## Overview + +Algorithm for classification and anomaly detection Based on self or not self +discrimination, inspired by Negative Selection Algorithm. + +:::note + +The **Binary Negative Selection Algorithm (BNSA)** is based on the original proposal by +Forrest et al. (1994) [^1], originally developed for computer security. In the adaptation, the +algorithm use bits arrays, and it has support for multiclass classification. + +::: + +:::warning + +High `aff_thresh` values may prevent the generation of valid non-self detectors + +::: + +--- + +## Example + +```python +from aisp.nsa import BNSA +# Binary 'self' samples +x_train = [ + [0, 0, 1, 0, 1], + [0, 1, 1, 0, 1], + [0, 1, 0, 1, 0], + [0, 0, 1, 0, 1], + [0, 1, 1, 0, 1], + [0, 1, 0, 1, 0] +] +y_train = ['self', 'self', 'self', 'self', 'self', 'self'] +bnsa = BNSA(aff_thresh=0.55, seed=1) +bnsa = bnsa.fit(x_train, y_train, verbose=False) +# samples for testing +x_test = [ +... [1, 1, 1, 1, 1], # Sample of Anomaly +... [0, 1, 0, 1, 0], # self sample +... ] +y_prev = bnsa.predict(X=x_test) +print(y_prev) +``` + +**Output** + +```bash +['non-self' 'self'] +``` + +--- + +## Constructor Parameters + +| Name | Type | Default | Description | +|-----------------------------|-----------------|:--------------------------:|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `N` | `int` | `100` | Number of detectors. | +| `aff_thresh` | `float` | `0.1` | The variable represents the percentage of similarity between the T cell and the own samples. The default value is 10% (0.1), while a value of 1.0 represents 100% similarity. | +| `max_discards` | `int` | `1000` | 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. | +| `seed` | `Optional[int]` | `None` | Seed for the random generation of values in the detectors. | +| `no_label_sample_selection` | `str` | `'max_average_difference'` | Method for selecting labels for samples designated as non-self by all detectors. | + +## Attributes + +| Name | Type | Default | Description | +|-------------|-----------------------------------------------------|:-------:|--------------------------------------------| +| `detectors` | `Optional[Dict[str \| int, npt.NDArray[np.bool_]]]` | - | The trained detectors, organized by class. | + +--- + +## Public Methods + +### fit + +```python +def fit( + self, + X: Union[npt.NDArray, list], + y: Union[npt.NDArray, list], + verbose: bool = True, +) -> BNSA: + ... +``` + +Training according to X and y, using the method negative selection method. + +**Parameters** + +| Name | Type | Default | Description | +|-----------|----------------------------|:-------:|---------------------------------------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Training array, containing the samples and their characteristics, Shape: (n_samples, n_features). | +| `y` | `Union[npt.NDArray, list]` | - | Array of target classes of `X` with (`n_samples`). | +| `verbose` | `bool` | `True` | Feedback from detector generation to the user. | + +**Returns** + +| Type | Description | +|--------|------------------------------| +| `Self` | Returns the instance itself. | + + +**Raises** + +| Exception | Description | +|-----------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------| +| `TypeError` | If X or y are not ndarrays or have incompatible shapes. | +| `ValueError` | If the array X contains any values other than (0 and 1) or (True and False). | +| [`MaxDiscardsReachedError`](../exceptions.md#maxdiscardsreachederror) | If the maximum number of detector discards was reached during maturation. Check the defined radius value and consider reducing it. | + +--- + +### predict + +```python +def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: + ... +``` + +Prediction of classes based on detectors created after training. + +**Parameters** + +| Name | Type | Default | Description | +|------|----------------------------|:-------:|-----------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Array with input samples with Shape: (`n_samples, n_features`) | + +**Returns** + +| Type | Description | +|---------------|-------------------------------------------------------------------------------------| +| `npt.NDArray` | An ndarray of the form `C` (`n_samples`), containing the predicted classes for `X`. | + + +**Raises** + +| Exception | Description | +|-------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------| +| `TypeError` | If X is not a ndarray or list. | +| `ValueError` | If the array contains values other than 0 and 1. | +| [`FeatureDimensionMismatch`](../exceptions.md#featuredimensionmismatch) | If the number of features (columns) in X does not match the expected number. | +| [`ModelNotFittedError`](../exceptions.md#modelnotfittederror) | If the mode has not yet been adjusted and does not have defined detectors or classes, it is not able to predictions | + +--- + +## Extended Example + +Complete usage examples are available in the Jupyter Notebooks: + +- [**Mushrooms Dataset Example**](../../../../examples/en/classification/BNSA/mushrooms_dataBase_example_en.ipynb) +- [**Random Dataset Example + **](../../../../examples/en/classification/BNSA/example_with_randomly_generated_dataset-en.ipynb) + +--- + +## References + +[^1]: 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. diff --git a/docs/en/api/nsa/rnsa.md b/docs/en/api/nsa/rnsa.md new file mode 100644 index 0000000..fd4e6c8 --- /dev/null +++ b/docs/en/api/nsa/rnsa.md @@ -0,0 +1,225 @@ +--- +id: rnsa +sidebar_label: RNSA +keywords: + - negative selection + - anomaly detection + - non-self recognition + - pattern recognition + - classification + - real-valued + - v-detector + - multiclass +tags: + - classification + - supervised + - negative selection + - real-valued + - anomaly detection +--- + +# RNSA + +Real-Valued Negative Selection Algorithm (RNSA). + +:::tip[Inheritance] + +This class extends [BaseClassifier](../base/base-classifier.md) + +::: + + +> **Module:** `aisp.nsa` +> **Import:** `from aisp.nsa import RNSA` + +--- + +## Overview + +Algorithm for classification and anomaly detection Based on self or not self +discrimination, inspired by Negative Selection Algorithm. + +:::note + +This algorithm has two different versions: one based on the canonical version [^1] and another +with variable radius detectors [^2]. 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. + +::: + +:::warning + +The parameters `r` and `r_s` can prevent the generation of valid detectors. A very small `r` +value can limit coverage, while a very high one can hinder the generation of valid detectors. +Similarly, a high r_s can restrict detector creation. Thus, proper adjustment of `r` and `r_s` +is essential to ensure good model performance. + +::: + +--- + +## Example + +```python +import numpy as np +from aisp.nsa import RNSA + +np.random.seed(1) +class_a = np.random.uniform(high=0.5, size=(50, 2)) +class_b = np.random.uniform(low=0.51, size=(50, 2)) +``` + +**Example 1:** Multiclass classification (RNSA supports two or more classes) + +```python +x_train = np.vstack((class_a, class_b)) +y_train = ['a'] * 50 + ['b'] * 50 +rnsa = RNSA(N=150, r=0.3, seed=1) +rnsa = rnsa.fit(x_train, y_train, verbose=False) +x_test = [ + [0.15, 0.45], # Expected: Class 'a' + [0.85, 0.65], # Expected: Class 'b' +] +y_pred = rnsa.predict(x_test) +print(y_pred) +``` + +**Output** + +```bash +['a' 'b'] +``` + +**Example 2:** Anomaly Detection (self/non-self) + +```python +rnsa = RNSA(N=150, r=0.3, seed=1) +rnsa = rnsa.fit(X=class_a, y=np.array(['self'] * 50), verbose=False) +y_pred = rnsa.predict(class_b[:5]) +print(y_pred) +``` + +**Output** + +```bash +['non-self' 'non-self' 'non-self' 'non-self' 'non-self'] +``` + +--- + +## Constructor Parameters + +| Name | Type | Default | Description | +|------------------|-------------------------------------------|:---------------:|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `N` | `int` | `100` | Number of detectors. | +| `r` | `float` | `0.05` | Radius of the detector. | +| `r_s` | `float` | `0.0001` | rₛ Radius of the `X` own samples. | +| `k` | `int` | `1` | Number of neighbors near the randomly generated detectors to perform the distance average calculation. | +| `metric` | `{"euclidean", "minkowski", "manhattan"}` | `'euclidean'` | Distance metric used to compute the distance between the detector and the sample. | +| `max_discards` | `int` | `1000` | 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. | +| `seed` | `Optional[int]` | `None` | Seed for the random generation of values in the detectors. | +| `algorithm` | `{"default-NSA", "V-detector"}` | `'default-NSA'` | Set the algorithm version | +| `non_self_label` | `str` | `'non-self'` | 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. | +| `cell_bounds` | `bool` | `False` | 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` | `bool` | `2.0` | This parameter stores the value of `p` used in the Minkowski distance. | + +## Attributes + +| Name | Type | Default | Description | +|-------------|----------------------------------------------|:-------:|--------------------------------------------| +| `detectors` | `Optional[Dict[str \| int, list[Detector]]]` | - | The trained detectors, organized by class. | + +--- + +## Public Methods + +### fit + +```python +def fit( + self, + X: Union[npt.NDArray, list], + y: Union[npt.NDArray, list], + verbose: bool = True, +) -> BNSA: + ... +``` + +Perform training according to X and y, using the negative selection method (NegativeSelect). + +**Parameters** + +| Name | Type | Default | Description | +|-----------|----------------------------|:-------:|---------------------------------------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Training array, containing the samples and their characteristics, Shape: (n_samples, n_features). | +| `y` | `Union[npt.NDArray, list]` | - | Array of target classes of `X` with (`n_samples`). | +| `verbose` | `bool` | `True` | Feedback from detector generation to the user. | + +**Returns** + +| Type | Description | +|--------|------------------------------| +| `Self` | Returns the instance itself. | + + +**Raises** + +| Exception | Description | +|-----------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------| +| `TypeError` | If X or y are not ndarrays or have incompatible shapes. | +| `ValueError` | If the array X fall outside the interval (0.0, 1.0). | +| [`MaxDiscardsReachedError`](../exceptions.md#maxdiscardsreachederror) | The maximum number of detector discards was reached during maturation. Check the defined radius value and consider reducing it. | + +--- + +### predict + +```python +def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: + ... +``` + +Prediction of classes based on detectors created after training. + +**Parameters** + +| Name | Type | Default | Description | +|------|----------------------------|:-------:|-----------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Array with input samples with Shape: (`n_samples, n_features`) | + +**Returns** + +| Type | Description | +|---------------|-------------------------------------------------------------------------------------| +| `npt.NDArray` | An ndarray of the form `C` (`n_samples`), containing the predicted classes for `X`. | + +**Raises** + +| Exception | Description | +|-------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------| +| `TypeError` | If X is not a ndarray or list. | +| `ValueError` | If the array X fall outside the interval (0.0, 1.0). | +| [`FeatureDimensionMismatch`](../exceptions.md#featuredimensionmismatch) | If the number of features in X does not match the expected number. | +| [`ModelNotFittedError`](../exceptions.md#modelnotfittederror) | If the mode has not yet been adjusted and does not have defined detectors or classes, it is not able to predictions | + +--- + +## Extended Example + +Complete usage examples are available in the Jupyter Notebooks: + +- [**Iris Dataset Example**](../../../../examples/en/classification/RNSA/iris_dataBase_example_en.ipynb) +- [**Geyser Dataset Example**](../../../../examples/en/classification/RNSA/geyser_dataBase_example_en.ipynb) +- [**Random Dataset Example + **](../../../../examples/en/classification/RNSA/example_with_randomly_generated_dataset-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. + +[^2] Ji, Z.; Dasgupta, D. (2004). Real-Valued Negative Selection Algorithm with Variable-Sized Detectors. + In *Lecture Notes in Computer Science*, vol. 3025. https://doi.org/10.1007/978-3-540-24854-5_30 diff --git a/docs/en/api/utils/README.md b/docs/en/api/utils/README.md new file mode 100644 index 0000000..a0467fa --- /dev/null +++ b/docs/en/api/utils/README.md @@ -0,0 +1,28 @@ +--- +id: utils +sidebar_label: aisp.utils +keywords: + - functions + - helpers + - utils +--- + +# aisp.utils + +Utility functions and helpers for development. + +> **Module:** `aisp.utils` +> **Import:** `from aisp import utils` + +## Submodules + +| Module | Description | +|----------------------------------|--------------------------------------------------------------------------| +| [`display`](./display/README.md) | Utility functions for displaying algorithm information. | +| [`distance`](./distance.md) | Utility functions for distance between arrays with numba decorators. | +| [`metrics`](./metrics.md) | Utility functions for measuring accuracy and performance. | +| [`multiclass`](./multiclass.md) | Utility functions for handling classes with multiple categories. | +| [`sanitizers`](./sanitizers.md) | Utility functions for validation and treatment of parameters. | +| [`types`](./types.md) | Defines type aliases used throughout the project to improve readability. | +| [`validation`](./validation.md) | Contains functions responsible for validating data types. | + diff --git a/docs/en/api/utils/display/README.md b/docs/en/api/utils/display/README.md new file mode 100644 index 0000000..6625dc7 --- /dev/null +++ b/docs/en/api/utils/display/README.md @@ -0,0 +1,23 @@ +--- +id: display +sidebar_label: display +keywords: + - table + - progress +--- + +# display + +Utility functions for displaying algorithm information. + +> **Module:** `aisp.utils.display` +> **Import:** `from aisp.utils import display` + +--- + +## Classes + +| Class | Description | +|------------------------------------------|-----------------------------------------------------------------------------| +| [`TableFormatter`](./table-formatter.md) | Format tabular data into strings for display in the console. | +| [`ProgressTable`](./progress-table.md) | Display a formatted table in the console to track the algorithm's progress. | diff --git a/docs/en/api/utils/display/progress-table.md b/docs/en/api/utils/display/progress-table.md new file mode 100644 index 0000000..7823ef2 --- /dev/null +++ b/docs/en/api/utils/display/progress-table.md @@ -0,0 +1,57 @@ +--- +id: progress-table +sidebar_label: ProgressTable +--- + +# ProgressTable + +Display a formatted table in the console to track the algorithm's progress. + +:::tip[Inheritance] + +This class extends [TableFormatter](./table-formatter.md). + +::: + + +> **Module:** `aisp.utils.display` +> **Import:** `from aisp.utils.display import ProgressTable` + +--- + +## Constructor Parameters + +| Name | Type | Default | Description | +|-----------|---------------------|:-------:|-------------------------------------------| +| `headers` | `Mapping[str, int]` | - | Mapping `{column_name: column_width}`. | +| `verbose` | `bool` | `True` | If False, prints nothing to the terminal. | + +--- + +## Public Methods + +### update + +```python +def update(self, values: Mapping[str, Union[str, int, float]]) -> None: + ... +``` + +Add a new row of values to the table. + +**Parameters** + +| Name | Type | Default | Description | +|----------|----------------------------------------|:-------:|-------------------------------------------------| +| `values` | `Mapping[str, Union[str, int, float]]` | - | Keys must match the columns defined in headers. | + +--- + +### finish + +```python +def finish(self) -> None: + ... +``` + +End the table display, printing the bottom border and total time. diff --git a/docs/en/api/utils/display/table-formatter.md b/docs/en/api/utils/display/table-formatter.md new file mode 100644 index 0000000..c1c8931 --- /dev/null +++ b/docs/en/api/utils/display/table-formatter.md @@ -0,0 +1,85 @@ +--- +id: table-formatter +sidebar_label: TableFormatter +--- + +# TableFormatter + +Format tabular data into strings for display in the console. + +> **Module:** `aisp.utils.display` +> **Import:** `from aisp.utils.display import TableFormatter` + +--- + +## Constructor Parameters + +| Name | Type | Default | Description | +|-----------|---------------------|:-------:|--------------------------------------------------------------------------------------------------| +| `headers` | `Mapping[str, int]` | - | Mapping of column names to their respective widths, in the format `{column_name: column_width}`. | + +--- + +## Public Methods + +### get_header + +```python +def get_header(self): + ... +``` + +Generate the table header, including the top border, column headings, and separator line. + +**Returns** + +| Type | Description | +|-------|---------------------------------------| +| `str` | Formatted string of the table header. | + + +--- + +### get_row + +```python +def get_row(self, values: Mapping[str, Union[str, int, float]]): + ... +``` + +Generate a formatted row for the table data. + +**Parameters** + +| Name | Type | Default | Description | +|----------|----------------------------------------|:-------:|-------------------------------------------------------------------------------| +| `values` | `Mapping[str, Union[str, int, float]]` | - | Dictionary with values for each column, in the format `{column_name: value}`. | + +**Returns** + +| Type | Description | +|-------|------------------------------------| +| `str` | Formatted string of the table row. | + +--- + +### get_bottom + +```python +def get_bottom(self, new_line: bool = False): + ... +``` + +Generate the table's bottom border. + +**Parameters** + +| Name | Type | Default | Description | +|------------|--------|:-------:|------------------------------------------------------------------| +| `new_line` | `bool` | `False` | If True, adds a line break before the border (default is False). | + +**Returns** + +| Type | Description | +|-------|-----------------------------------------| +| `str` | Formatted string for the bottom border. | diff --git a/docs/en/api/utils/distance.md b/docs/en/api/utils/distance.md new file mode 100644 index 0000000..fc827f6 --- /dev/null +++ b/docs/en/api/utils/distance.md @@ -0,0 +1,243 @@ +--- +id: distance +sidebar_label: distance +keywords: + - hamming + - euclidean + - cityblock + - Manhattan + - minkowski + - distance +--- + +# distance + +Utility functions for distance between arrays with numba decorators. + +> **Module:** `aisp.utils.distance` +> **Import:** `from aisp.utils import distance` + +## Functions + +### hamming + +```python +@njit([(types.boolean[:], types.boolean[:])], cache=True) +def hamming(u: npt.NDArray[np.bool_], v: npt.NDArray[np.bool_]) -> float64: + ... +``` + +Calculate the Hamming distance between two points. + +$$ +\frac{(x_1 \neq y_1) + (x_2 \neq y_2) + \cdots + (x_n \neq y_n)}{n} +$$ + +**Parameters** + +| Name | Type | Default | Description | +|------|-------------------------|:-------:|----------------------------------| +| `u` | `npt.NDArray[np.bool_]` | - | Coordinates of the first point. | +| `v` | `npt.NDArray[np.bool_]` | - | Coordinates of the second point. | + + +**Returns** + +| Type | Description | +|-----------|--------------------------------------| +| `float64` | Hamming distance between two points. | + +--- + +### euclidean + +```python +@njit() +def euclidean(u: npt.NDArray[np.float64], v: npt.NDArray[np.float64]) -> float64: + ... +``` + +Calculate the Euclidean distance between two points. + +$$ +\sqrt{(X_{1} - X_{1})^2 + (Y_{2} - Y_{2})^2 + \cdots + (Y_{n} - Y_{n})^2} +$$ + +**Parameters** + +| Name | Type | Default | Description | +|------|------------------------|:-------:|----------------------------------| +| `u` | `npt.NDArray[float64]` | - | Coordinates of the first point. | +| `v` | `npt.NDArray[float64]` | - | Coordinates of the second point. | + +**Returns** + +| Type | Description | +|-----------|----------------------------------------| +| `float64` | Euclidean distance between two points. | + +--- + +### cityblock + +```python +@njit() +def cityblock(u: npt.NDArray[float64], v: npt.NDArray[float64]) -> float64: + ... +``` + +Calculate the Manhattan distance between two points. + +$$ +|X_{1} - Y_{1}| + |X_{2} - Y_{2}| + \cdots + |X_{n} - Y_{n}| +$$ + +**Parameters** + +| Name | Type | Default | Description | +|------|------------------------|:-------:|----------------------------------| +| `u` | `npt.NDArray[float64]` | - | Coordinates of the first point. | +| `v` | `npt.NDArray[float64]` | - | Coordinates of the second point. | + +**Returns** + +| Type | Description | +|-----------|----------------------------------------| +| `float64` | Manhattan distance between two points. | + +--- + +### minkowski + +```python +@njit() +def minkowski( + u: npt.NDArray[float64], + v: npt.NDArray[float64], + p: float = 2.0 +) -> float64: + ... +``` + +Calculate the Minkowski distance between two points. + +$$ +(|X_{1} - Y_{1}|^p + |X_{2} - Y_{2}|^p + \cdots + |X_{n} - Y_{n}|^p)^\frac{1}{p}| +$$ + +**Parameters** + +| Name | Type | Default | Description | +|------|------------------------|:-------:|----------------------------------------------------------------| +| `u` | `npt.NDArray[float64]` | - | Coordinates of the first point. | +| `v` | `npt.NDArray[float64]` | - | Coordinates of the second point. | +| `p` | `float` | `2.0` | The p parameter defines the type of distance to be calculated. | + +:::note[Parameter `p`] + +- 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** + +| Type | Description | +|-----------|----------------------------------------| +| `float64` | Minkowski distance between two points. | + +--- + +### compute_metric_distance + +```python +@njit([(types.float64[:], types.float64[:], types.int32, types.float64)], cache=True) +def compute_metric_distance( + u: npt.NDArray[float64], + v: npt.NDArray[float64], + metric: int, + p: float = 2.0 +) -> float64: + ... +``` + +Calculate the distance between two points by the chosen metric. + +**Parameters** + +| Name | Type | Default | Description | +|----------|------------------------|:-------:|--------------------------------------------------------------------------------------------| +| `u` | `npt.NDArray[float64]` | - | Coordinates of the first point. | +| `v` | `npt.NDArray[float64]` | - | Coordinates of the second point. | +| `metric` | `int` | - | Distance metric to be used. Available options: 0 (Euclidean), 1 (Manhattan), 2 (Minkowski) | +| `p` | `float` | `2.0` | The p parameter defines the type of distance to be calculated. | + +**Returns** + +| Type | Description | +|-----------|-----------------------------------------------------------| +| `float64` | Distance between the two points with the selected metric. | + +--- + +### min_distance_to_class_vectors + +```python +@njit([(types.float64[:, :], types.float64[:], types.int32, types.float64)], cache=True) +def min_distance_to_class_vectors( + x_class: npt.NDArray[float64], + vector_x: npt.NDArray[float64], + metric: int, + p: float = 2.0, +) -> float: + ... +``` + +Calculate the minimum distance between an input vector and the vectors of a class. + +**Parameters** + +| Name | Type | Default | Description | +|------------|------------------------|:-------:|-------------------------------------------------------------------------------------------------------------------| +| `x_class` | `npt.NDArray[float64]` | - | Array containing the class vectors to be compared with the input vector. Expected shape: (n_samples, n_features). | +| `vector_x` | `npt.NDArray[float64]` | - | 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") or ("hamming") | +| `p` | `float` | `2.0` | Parameter for the Minkowski distance (used only if `metric` is "minkowski"). | + +**Returns** + +| Type | Description | +|---------|----------------------------------------------------------------------------------------------------------------------------------------| +| `float` | The minimum distance calculated between the input vector and the class vectors. Returns -1.0 if the input dimensions are incompatible. | + +--- + +### get_metric_code + +```python +def get_metric_code(metric: str) -> int: + ... +``` + +Get the numeric code associated with a distance metric. + +**Parameters** + +| Name | Type | Default | Description | +|----------|-------|:-------:|----------------------------------------------------------------------------------------| +| `metric` | `str` | - | Name of the metric. Can be `"euclidean"`, `"manhattan"`, `"minkowski"` or `"hamming"`. | + +**Returns** + +| Type | Description | +|-------|-------------------------------------------| +| `int` | Numeric code corresponding to the metric. | + + +**Raises** + +| Exception | Description | +|--------------|------------------------------------------| +| `ValueError` | If the metric provided is not supported. | + diff --git a/docs/en/api/utils/metrics.md b/docs/en/api/utils/metrics.md new file mode 100644 index 0000000..14e8ff3 --- /dev/null +++ b/docs/en/api/utils/metrics.md @@ -0,0 +1,47 @@ +--- +id: metrics +sidebar_label: metrics +keywords: + - accuracy + - score +--- + +# metrics + +Utility functions for measuring accuracy and performance. + +> **Module:** `aisp.utils.metrics` +> **Import:** `from aisp.utils import metrics` + +## Functions + +### accuracy_score + +```python +def accuracy_score( + y_true: Union[npt.NDArray, list], + y_pred: Union[npt.NDArray, list] +) -> float: + ... +``` + +Calculate the accuracy score based on true and predicted labels. + +**Parameters** + +| Name | Type | Default | Description | +|----------|----------------------------|:-------:|-------------------------------------------------------------------------------| +| `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** + +| Type | Description | +|---------|----------------------------------------------------------------------| +| `float` | The ratio of correct predictions to the total number of predictions. | + +**Raises** + +| Exception | Description | +|--------------|---------------------------------------------------------------------------| +| `ValueError` | If `y_true` or `y_pred` are empty or if they do not have the same length. | diff --git a/docs/en/api/utils/multiclass.md b/docs/en/api/utils/multiclass.md new file mode 100644 index 0000000..367c641 --- /dev/null +++ b/docs/en/api/utils/multiclass.md @@ -0,0 +1,82 @@ +--- +id: multiclass +sidebar_label: multiclass +keywords: + - k-nearest neighbors + - samples + - slice + - multiclass +--- + +# multiclass + +Utility functions for handling classes with multiple categories. + +> **Module:** `aisp.utils.multiclass` +> **Import:** `from aisp.utils import multiclass` + +## Functions + +### slice_index_list_by_class + +```python +def slice_index_list_by_class(classes: Optional[Union[npt.NDArray, list]], y: npt.NDArray) -> dict: + ... +``` + +Separate indices of samples by class for targeted iteration. + +**Parameters** + +| Name | Type | Default | Description | +|-----------|--------------------------------------|:-------:|-------------------------------------------------------------------------------------| +| `classes` | `Optional[Union[npt.NDArray, list]]` | - | list with unique classes. | +| `y` | `npt.NDArray` | - | Receives a `y` (`n_samples`) array with the output classes of the `X` sample array. | + +**Returns** + +| Type | Description | +|--------|------------------------------------------------------------------------------| +| `dict` | A dictionary with the list of array positions(`y`), with the classes as key. | + +**Example** + +```python +import numpy as np +from aisp.utils.multiclass import slice_index_list_by_class + +labels = ['a', 'b', 'c'] +y = np.array(['a', 'c', 'b', 'a', 'c', 'b']) +slice_index_list_by_class(labels, y) +``` + +--- + +### 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: + ... +``` + +Predict classes using k-nearest neighbors and trained cells. + +**Parameters** + +| Name | Type | Default | Description | +|--------------------|-----------------------------------------------|:-------:|----------------------------------------------------------------| +| `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 (class_name, cell(np.ndarray)). | +| `affinity_func` | `Callable[[npt.NDArray, npt.NDArray], float]` | - | Function that takes two vectors and returns an affinity value. | + +**Returns** + +| Type | Description | +|---------------|-----------------------------------------------------------------------------------| +| `npt.NDArray` | Array of predicted labels for each sample in X, based on the k nearest neighbors. | diff --git a/docs/en/api/utils/sanitizers.md b/docs/en/api/utils/sanitizers.md new file mode 100644 index 0000000..9a189a4 --- /dev/null +++ b/docs/en/api/utils/sanitizers.md @@ -0,0 +1,122 @@ +--- +id: sanitizers +sidebar_label: sanitizers +keywords: + - sanitize +--- + +# sanitizers + +Utility functions for validation and treatment of parameters. + +> **Module:** `aisp.utils.sanitizers` +> **Import:** `from aisp.utils import sanitizers` + +## Functions + +### sanitize_choice + +```python +def sanitize_choice(value: T, valid_choices: Iterable[T], default: T) -> T: + ... +``` + +Value if present in the set of valid choices; otherwise, the default value. + +**Parameters** + +| Name | Type | Default | Description | +|-----------------|---------------|:-------:|------------------------------------------------------------------------| +| `value` | `T` | - | The value to be checked. | +| `valid_choices` | `Iterable[T]` | - | A collection of valid choices. | +| `default` | `T` | - | The default value to be returned if 'value' is not in 'valid_choices'. | + +**Returns** + +| Type | Description | +|------|-----------------------------------------------------------| +| `T` | The original value if valid, or the default value if not. | + +--- + +### sanitize_param + +```python +def sanitize_param(value: T, default: T, condition: Callable[[T], bool]) -> T: + ... +``` + +Value if it satisfies the specified condition; otherwise, the default value. + +**Parameters** + +| Name | Type | Default | Description | +|-------------|-----------------------|:-------:|-----------------------------------------------------------------------------------------| +| `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** + +| Type | Description | +|------|--------------------------------------------------------------------------------| +| `T` | The original value if the condition is satisfied, or the default value if not. | + +--- + +### sanitize_seed + +```python +def sanitize_seed(seed: Any) -> Optional[int]: + ... +``` + +Seed if it is a non-negative integer; otherwise, None. + +**Parameters** + +| Name | Type | Default | Description | +|--------|-------|:-------:|---------------------------------| +| `seed` | `Any` | - | The seed value to be validated. | + +**Returns** + +| Type | Description | +|-----------------|------------------------------------------------------------------------------| +| `Optional[int]` | The original seed if it is a non-negative integer, or None if it is invalid. | + + +**seed**: `Optional[int]` - The original seed if it is a non-negative integer, or None if it is invalid. + +--- + +### sanitize_bounds + +```python +def sanitize_bounds( + bounds: Any, problem_size: int +) -> Dict[str, npt.NDArray[np.float64]]: + ... +``` + +Validate and normalize feature bounds. + +**Parameters** + +| Name | Type | Default | Description | +|----------------|-------|:-------:|--------------------------------------------------------------------------------------------------------------| +| `bounds` | `Any` | - | The 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** + +| Type | Description | +|-------------------|---------------------------------------------------------------------------| +| `Dict[str, list]` | Dictionary `{'low': [low_1, ..., low_N], 'high': [high_1, ..., high_N]}`. | + +**Raises** + +| Exception | Description | +|--------------|----------------------------------------------------------------------------------------| +| `TypeError` | If `bounds` is not None and not a dict with 'low'/'high', or if items are non-numeric. | +| `ValueError` | If provided iterables have the wrong length. | diff --git a/docs/en/api/utils/types.md b/docs/en/api/utils/types.md new file mode 100644 index 0000000..3df5066 --- /dev/null +++ b/docs/en/api/utils/types.md @@ -0,0 +1,60 @@ +--- +id: types +sidebar_label: types +keywords: + - types + - typing + - aliases + - type hints +--- + +# types + +Defines type aliases used throughout the project to improve readability. + +> **Module:** `aisp.utils.types` +> **Import:** `from aisp.utils import types` + +## Type aliases + +### FeatureType + +```python +FeatureType: TypeAlias = Literal[ + "binary-features", "continuous-features", "ranged-features" +] +``` + +Type of input features: + +- `"binary-features"`: values like 0 or 1. +- `"continuous-features"`: numeric continuous values. +- `"ranged-features"`: values defined by intervals. + +--- + +### FeatureTypeAll + +```python +FeatureTypeAll: TypeAlias = Union[FeatureType, Literal["permutation-features"]] +``` + +Same as ``FeatureType``, plus: + +- `"permutation-features"`: values represented as permutation. + +--- + +### MetricType + +```python +MetricType: TypeAlias = Literal["manhattan", "minkowski", "euclidean"] +``` + +Distance metric used in calculations: + +- `"manhattan"`: the Manhattan distance between two points +- `"minkowski"`: the Minkowski distance between two points. +- `"euclidean"`: the Euclidean distance between two points. + +--- \ No newline at end of file diff --git a/docs/en/api/utils/validation.md b/docs/en/api/utils/validation.md new file mode 100644 index 0000000..d148ede --- /dev/null +++ b/docs/en/api/utils/validation.md @@ -0,0 +1,180 @@ +--- +id: validation +sidebar_label: validation +keywords: + - validation +--- + +# module + +Contains functions responsible for validating data types. + +> **Module:** `aisp.utils.validation` +> **Import:** `from aisp.utils import validation` + +## Functions + +### detect_vector_data_type + +```python +def detect_vector_data_type(vector: npt.NDArray) -> FeatureType: + ... +``` + +Detect the type of data in a vector. + +The function detects if the vector contains data of type: + +- Binary features: boolean values or integers restricted to 0 and 1. +- Continuous features: floating-point values in the normalized range [0.0, 1.0]. +- Ranged features: floating-point values outside the normalized range. + +**Parameters** + +| Name | Type | Default | Description | +|----------|---------------|:-------:|------------------------------------------------| +| `vector` | `npt.NDArray` | - | An array containing the data to be classified. | + +**Returns** + +| Type | Description | +|-----------------------------------------|-----------------------------------------------------------------------------------------------| +| [`FeatureType`](./types.md#featuretype) | The data type of the vector: "binary-features", "continuous-features", or " ranged-features". | + +**Raises** + +| Exception | Description | +|------------------------|------------------------------------------------------------------| +| `UnsupportedTypeError` | If the data type of the vector is not supported by the function. | + +--- + +### 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** + +| Name | Type | Default | Description | +|--------|-------|:-------:|------------------------------------------------------------------------------------------| +| `x` | `Any` | - | Array, containing the samples and their characteristics, Shape: (n_samples, n_features). | +| `name` | `str` | `'X'` | Variable name used in error messages. | + +**Returns** + +| Type | Description | +|---------------|----------------------------------| +| `npt.NDArray` | The converted or validated array | + +**Raises** + +| Exception | Description | +|-------------|---------------------------------------| +| `TypeError` | If X or y are not ndarrays or a list. | + +--- + +### check_shape_match + +```python +def check_shape_match(x: npt.NDArray, y: npt.NDArray): + ... +``` + +Ensure X and y have compatible first dimensions. + +**Parameters** + +| Name | Type | Default | Description | +|------|---------------|:-------:|------------------------------------------------------------------------------------------| +| `x` | `npt.NDArray` | - | Array, containing the samples and their characteristics, Shape: (n_samples, n_features). | +| `y` | `npt.NDArray` | - | Array of target classes of `x` with (`n_samples`). | + +**Raises** + +| Exception | Description | +|-------------|-------------------------------------| +| `TypeError` | If x or y have incompatible shapes. | + +--- + +### check_feature_dimension + +```python +def check_feature_dimension(x: npt.NDArray, expected: int): + ... +``` + +Ensure X has the expected number of features. + +**Parameters** + +| Name | Type | Default | Description | +|------------|---------------|:-------:|---------------------------------------------------------------------------------------------------------------| +| `x` | `npt.NDArray` | - | Input array for prediction, containing the samples and their characteristics, Shape: (n_samples, n_features). | +| `expected` | `int` | - | Expected number of features per sample (columns in X). | + +**Raises** + +| Exception | Description | +|-------------------------------------------------------------------------|--------------------------------------------------------------------| +| [`FeatureDimensionMismatch`](../exceptions.md#featuredimensionmismatch) | If the number of features in X does not match the expected number. | + +--- + +### check_binary_array + +```python +def check_binary_array(x: npt.NDArray): + ... +``` + +Ensure X contains only 0 and 1. + +**Parameters** + +| Name | Type | Default | Description | +|------|---------------|:-------:|--------------------------------| +| `x` | `npt.NDArray` | - | Array, containing the samples. | + +**Raises** + +| Exception | Description | +|--------------|--------------------------------------------------| +| `ValueError` | If the array contains values other than 0 and 1. | + +--- + +### check_value_range + +```python +def check_value_range( + x: npt.NDArray, + name: str = 'X', + min_value: float = 0.0, + max_value: float = 1.0 +) -> None: + ... +``` + +Ensure all values in the x array fall within a range. + +**Parameters** + +| Name | Type | Default | Description | +|-------------|---------------|:-------:|---------------------------------| +| `x` | `npt.NDArray` | - | Array, containing the samples. | +| `name` | `str` | `'X'` | Name used in the error message. | +| `min_value` | `float` | `0.0` | Minimum allowed value. | +| `max_value` | `float` | `1.0` | Maximum allowed value. | + +**Raises** + +| Exception | Description | +|--------------|----------------------------------------------------------------| +| `ValueError` | If the array fall outside the interval (min_value, max_value). | diff --git a/docs/en/classes/Clonal Selection Algorithms/AIRS.md b/docs/en/classes/Clonal Selection Algorithms/AIRS.md deleted file mode 100644 index da7a6d8..0000000 --- a/docs/en/classes/Clonal Selection Algorithms/AIRS.md +++ /dev/null @@ -1,266 +0,0 @@ -# AIRS (Artificial Immune Recognition System) - -This class extends the [**Base**](../../advanced-guides/base/classifier.md) class. - -## AIRS Constructor - -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](#ref1). - -Related and noteworthy works: access here [2](#ref2). - -### 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_mc_init** (``float``): Percentage of samples used to initialize memory cells. Defaults to 0.2. -* **rate_hypermutation** (``float``): 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 3. -* **max_iters** (``int``): Maximum number of iterations 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: - √( (x₁ - x₂)² + (y₁ - y₂)² + ... + (yn - yn)²). - * ``'minkowski'`` ➜ The calculation of the distance is given by the expression: - ( |X₁ - Y₁|p + |X₂ - Y₂|p + ... + |Xn - Yn|p) ¹/ₚ. - * ``'manhattan'`` ➜ The calculation of the distance is given by the expression: - ( |x₁ - x₂| + |y₁ - y₂| + ... + |yn - yn|). - Defaults to "Euclidean". - -* **seed** (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** (``Optional[Dict[str, list[BCell]]]``): This variable stores a list of memory cells by class. -* **affinity_threshold** (``float``): Defines the affinity threshold between antigens. -* **classes** (``Optional[npt.NDArray]``): List of output classes. - ---- - -## Public Methods - -### Method `fit(...)` - -The ``fit(...)`` function generates detectors for the non-owners relative to the samples: - -```python -def fit( - self, - X: Union[npt.NDArray, list], - y: Union[npt.NDArray, list], - verbose: bool = True, -) -> AIRS: -``` - -It performs the training according to ``X`` and ``y``, using the method Artificial Immune Recognition System (``AIRS``). - -****Parameters:**** - -* **X** (``Union[npt.NDArray, list]``): Array with sample features, with **N** samples (rows) and **N** features (columns), normalized to values between [0, 1]. -* **y** (``Union[npt.NDArray, list]``): Array with output classes corresponding to **N** samples related to ``X``. -* **verbose** (``bool``): Boolean, default ``True``, determines if the feedback from the detector generation will be printed. - -*Returns the class instance.* - ---- - -### Method `predict(...)` - -The ``predict(...)`` function performs class prediction using the generated detectors: - -```python -def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: -``` - -**Parameters:** - -* **X** (``Union[npt.NDArray, list]``): Array with the features for prediction, with **N** samples (rows) and **N** columns. - -**Raises** - -* `TypeError` - If X is not a ndarray or list. -* `FeatureDimensionMismatch` - If the number of features in X does not match the expected number. -* `ModelNotFittedError` - If the mode has not yet been adjusted and does not have defined memory cells, it is - not able to predictions - -**Returns:** - -* **C**: An array of predictions with the output classes for the given features. - ---- - -### Method `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 - -### Method `_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_stimulation: float, - arb_list: List[_ARB] -) -> _ARB: -``` - -**Parameters:** - -* **ai** (`npt.NDArray`): The current antigen. -* **c_match_stimulation** (``float``): The highest stimulation relative to aᵢ -* **arb_list** (``List[_ARB]``): ARB set. - -Returns the cell (_ARB) with the highest ARB stimulation. - ---- - -### Method `_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). - -```python -def _cells_affinity_threshold(self, antigens_list: npt.NDArray): -``` - -**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** (``npt.NDArray``): List of training antigens. - ---- - -### Method `_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. - ---- - -### Method `_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** (``npt.NDArray``): List of training antigens. - ---- - -### Method `_slice_index_list_by_class(...)` - -The function ``_slice_index_list_by_class(...)`` separates the indices of the rows according to the output class, to iterate over the sample array, only at the positions where the output corresponds to the class being trained: - -```python -def _slice_index_list_by_class(self, y: npt.NDArray) -> dict: -``` - -Returns a dictionary with classes as keys and indices in ``X`` of the samples. - ---- - -### Method `__prepare_features(...)` - -The function ``__prepare_features(...)`` check the samples, specifying the type, quantity of characteristics, and other parameters. - -```python -def _prepare_features(self, X: Union[npt.NDArray, list]) -> npt.NDArray: -``` - -* This method updates the following attributes: - * ``self._feature_type`` - * ``self.metric`` (only for binary features) - * ``self._bounds`` (only for ranged features) - * ``self._n_features`` - - -**Parameters:** - -* **X** (``Union[npt.NDArray, list]``): Array with the features for prediction, with **N** samples (rows) and **N** columns. - -Returns the processed input data. - ---- - -# Auxiliary Classes - ---- - -## _ARB Class (Inherits from [BCell](../../advanced-guides/base/immune/cell.md#bcell)) - -### Constructor - -**Parameters:** - -* vector (``npt.NDArray``): A feature vector of the cell. Defaults to None. - ---- - -### Method `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. - ---- - -# 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: . - -
- -> 2. AZZOUG, Aghiles. Artificial Immune Recognition System V2. - Available at: diff --git a/docs/en/classes/Clonal Selection Algorithms/Clonalg.md b/docs/en/classes/Clonal Selection Algorithms/Clonalg.md deleted file mode 100644 index 2d9a063..0000000 --- a/docs/en/classes/Clonal Selection Algorithms/Clonalg.md +++ /dev/null @@ -1,183 +0,0 @@ -# Clonal Selection Algorithm (CLONALG) - -## Clonalg - -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. - -The CLONALG implementation was inspired by the description presented in [1](#ref1). - -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. - ---- - -### 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=1.0): 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 - -#### Method `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. - -**Parameters:** - -* **max_iters** (`int`, default=50): The maximum number of iterations. -* **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:** - -* `List[Antibody]`: The best antibody population after clonal expansion. - ---- - -#### Method `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. - -**Parameters:** - -* **solution** (`npt.NDArray`): The candidate solution to be evaluated. - -**Returns:** - -* `np.float64`: The affinity value associated with the solution. - ---- - -### Private Methods - -#### Method `_select_top_antibodies(...)` - -```python -def _select_top_antibodies(self, n: int, antibodies: list[Antibody]) -> list[Antibody]: -``` - -This method selects the top `n` antibodies based on their affinity scores, according to the `mode` (`'min'` or `'max'`). - -**Parameters:** - -* **n** (`int`): The number of antibodies to select. -* **antibodies** (`list[Antibody]`): A list of tuples, where each tuple represents an antibody and its associated score. - -**Returns:** - -* `list[Antibody]`: A list containing the `n` selected antibodies. - ---- - -#### Method `_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. - ---- - -#### Method `_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. - ---- - -#### Method `_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'`). - -**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. - ---- - -#### Method `_clone_and_hypermutation(...)` - -```python -def _clone_and_hypermutation( - self, - population: list[Antibody] -) -> list[Antibody]: -``` - -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. - -**Parameters:** - -* **population** (`list[Antibody]`): The list of antibodies to be evaluated and cloned. - -**Returns:** - -* `list[Antibody]`: 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 \ No newline at end of file diff --git a/docs/en/classes/Clonal Selection Algorithms/README.md b/docs/en/classes/Clonal Selection Algorithms/README.md deleted file mode 100644 index b68e78e..0000000 --- a/docs/en/classes/Clonal Selection Algorithms/README.md +++ /dev/null @@ -1,24 +0,0 @@ -# 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 - -1. **[Artificial Immune Recognition System (AIRS)](AIRS.md)** - -> 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. - -2. **[Clonal Selection Algorithm (CLONALG)](Clonalg.md)** - -> Implementation of the clonal selection algorithm for optimization, adapted -> for both minimization and maximization of cost functions in binary, -> continuous, and permutation problems. - ---- - -### 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: . diff --git a/docs/en/classes/Negative Selection/BNSA.md b/docs/en/classes/Negative Selection/BNSA.md deleted file mode 100644 index 7212f38..0000000 --- a/docs/en/classes/Negative Selection/BNSA.md +++ /dev/null @@ -1,118 +0,0 @@ -# BNSA (Binary Negative Selection Algorithm) - -This class extends the [**Base**](../../advanced-guides/base/classifier.md) class. - -## Constructor BNSA - -The ``BNSA`` (Binary Negative Selection Algorithm) class has the purpose of classifying and identifying anomalies through the self and not self methods. - -**Attributes:** - -* *N* (``int``): Number of detectors. Defaults to ``100``. -* *aff_thresh* (``float``): The variable represents the percentage of similarity between the T cell and the own samples. The default value is 10% (0.1), while a value of 1.0 represents 100% dissimilarity. -* *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. - -### Method fit(...) - -The ``fit(...)`` function generates the detectors for non-fits with respect to the samples: - -```python -def fit( - self, - X: Union[npt.NDArray, list], - y: Union[npt.NDArray, list], - verbose: bool = True, -) -> BNSA: -``` - -In it, training is performed according to ``X`` and ``y``, using the negative selection method(``NegativeSelect``). - -**Parameters** - -* **X** (`Union[npt.NDArray, list]`): array with the characteristics of the samples with **N** samples (rows) and **N** characteristics (columns). - -* **y** (`Union[npt.NDArray, list]`): array with the output classes arranged in **N** samples that are related to ``X``. - -* **verbose** (`bool`): boolean with default value ``True``, determines if the feedback from the detector generation will be printed. - -**Raises** - -* ``TypeError``: If X or y are not ndarrays or have incompatible shapes. -* ``ValueError``: If the array contains values other than 0 and 1. -* ``MaxDiscardsReachedError``: The maximum number of detector discards was reached during - maturation. Check the defined radius value and consider reducing it. - -*Returns the instance of the class.* - ---- - -### Method predict(...) - -The ``predict(...)`` function performs class prediction using the generated detectors: - -```python -def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: -``` - -**Parameters** - -* **X** (`Union[npt.NDArray, list]`): array with the characteristics for the prediction, with **N** samples (Rows) and **N** columns. - -**Raises:** - -* ``TypeError``: If X is not an ndarray or list. -* ``ValueError``: X contains values that are not composed only of 0 and 1. -* ``FeatureDimensionMismatch``: If the number of features in X does not match the expected number. -* ``ModelNotFittedError``: If the mode has not yet been adjusted and does not have defined detectors or classes, it is not able to predictions - -**Returns:** - -* **C** (`npt.NDArray`): A ndarray of the form ``C`` (``n_samples``), containing the predicted classes for ``X``. - ---- - -### Method 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 - ---- - -### Method _assign_class_to_non_self_sample(...) - -This function 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): -``` - -**Parameters** - -* **line** (``npt.NDArray``): Sample to be classified. -* **c** (``list``): List of predictions to be updated with the new classification. - -**Raises** -* `ValueError`: If detectors is not initialized. - -**Returns:** - -``npt.NDArray``: The list of predictions `c` updated with the class assigned to the sample. diff --git a/docs/en/classes/Negative Selection/README.md b/docs/en/classes/Negative Selection/README.md deleted file mode 100644 index 0e8720b..0000000 --- a/docs/en/classes/Negative Selection/README.md +++ /dev/null @@ -1,31 +0,0 @@ -# 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. - -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. - -## 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: . - -### 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: . - -### 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: . - ---- diff --git a/docs/en/classes/Negative Selection/RNSA.md b/docs/en/classes/Negative Selection/RNSA.md deleted file mode 100644 index 2606294..0000000 --- a/docs/en/classes/Negative Selection/RNSA.md +++ /dev/null @@ -1,215 +0,0 @@ - -# RNSA (Real-Valued Negative Selection Algorithm) - -This class extends the [**Base**](../../advanced-guides/base/classifier.md) class. - -## Constructor RNSA - -The ``RNSA`` class has the purpose of classifying and identifying anomalies through the self and not self methods. - -**Attributes:** - -* **N** (``int``): Number of detectors. Defaults to ``100``. -* **r** (``float``): Radius of the detector. Defaults to ``0.05``. -* **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: √( (X₁ - X₂)² + (Y₁ - Y₂)² + ... + (Yn - Yn)²). - * ``'minkowski'`` ➜ The calculation of the distance is given by the expression: ( |X₁ - Y₁|p + |X₂ - Y₂|p + ... |Xn - Yn|p) ¹/ₚ , In this project ``p == 2``. - * ``'manhattan'`` ➜ The calculation of the distance is given by the expression: ( |X₁ - X₂| + |Y₁ - Y₂| + ...+ |Yn - Yn₂|) . - - 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. -* **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. Defaults to ``False``. - -**Other variables initiated:** - -* **detectors** (``dict``): This variable stores a list of detectors by class. -* **classes** (``npt.NDArray``): list of output classes. - ---- - -### Method fit(...) - -The ``fit(...)`` function generates the detectors for non-fits with respect to the samples: - -```python -def fit( - self, - X: Union[npt.NDArray, list], - y: Union[npt.NDArray, list], - verbose: bool = True, -) -> RNSA: -``` - -In it, training is performed according to ``X`` and ``y``, using the negative selection method(``NegativeSelect``). - -The input parameters are: - -* **X** (`Union[npt.NDArray, list]`): array with the characteristics of the samples with **N** samples (rows) and **N** characteristics (columns). -* **y** (`Union[npt.NDArray, list]`): array with the output classes arranged in **N** samples that are related to ``X``. -* **verbose** (`bool`): boolean with default value ``True``, determines if the feedback from the detector generation will be printed. - -**Raises** - -* ``TypeError``: If X or y are not ndarrays or have incompatible shapes. -* ``MaxDiscardsReachedError``: The maximum number of detector discards was reached during - maturation. Check the defined radius value and consider reducing it. - -**Returns** - - the instance of the class. - ---- - -### Method predict(...) - -The ``predict(...)`` function performs class prediction using the generated detectors: - -```python -def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: -``` - -**The input parameter is:** - -* **X** (`Union[npt.NDArray, list]`): array with the characteristics for the prediction, with **N** samples (Rows) and **N** columns. - -**Raises:** - -* ``TypeError``: If X is not an ndarray or list. -* ``FeatureDimensionMismatch``: If the number of features in X does not match the expected number. -* ``ModelNotFittedError``: If the mode has not yet been adjusted and does not have defined detectors or classes, it is not able to predictions - -**Returns:** - -* C (``npt.NDArray``): A ndarray of the form ``C`` (n_samples), containing the predicted classes for ``X``. - ---- - -### Method 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 - ---- - -### Method _checks_valid_detector(...) - -The ``def _checks_valid_detector(...)`` function check if the detector has a valid non-proper r radius for the class. - -```python -def _checks_valid_detector( - self, - x_class: npt.NDArray, - vector_x: npt.NDArray -) -> Union[bool, tuple[bool, float]]: -``` - -**Parameters** - -* **x_class** (`npt.NDArray`): Array ``x_class`` with the samples per class. -* **vector_x** (`npt.NDArray`): Randomly generated vector x candidate detector with values between[0, 1]. - -**Returns** -* **Validity** (``bool``): Returns whether the detector is valid or not. - ---- - -### Method _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_knearest_neighbors_list(self, knn: list, distance: float) -> None: -``` - -**Parameters** -* **knn** (`list`): List of k-nearest neighbor distances. -* **distance** (`float`): Distance to check. - -Returns a list of k-nearest neighbor distances. - ---- - -### Method _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: npt.NDArray) -> Optional[str]: -``` - -**Parameters** - -* line (`npt.NDArray`): vector with N-features - -**Returns** - -The predicted class with the detectors or None if the sample does not qualify for any class. - ---- - -### Method _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: float, - vector_x: npt.NDArray -) -> Union[bool, tuple[bool, float]]: -``` - -**Parameters** - -* distance (``float``): minimum distance calculated between all samples. -* vector_x (``npt.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.` - ---- - -### Method _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): -``` - -**Parameters** -* **u** (`npt.NDArray`): Coordinates of the first point. -* **v** (`npt.NDArray`): Coordinates of the second point. - -**Returns:** -* distance (`float`): the distance between the two points. diff --git a/docs/en/classes/Network Theory Algorithms/AiNet.md b/docs/en/classes/Network Theory Algorithms/AiNet.md deleted file mode 100644 index 5973618..0000000 --- a/docs/en/classes/Network Theory Algorithms/AiNet.md +++ /dev/null @@ -1,271 +0,0 @@ -# AiNet (Artificial Immune Network) - -This class extends the [**Base**](../../advanced-guides/base/clusterer.md) class. - -## AiNet Constructor - -The ``AiNet`` class implements the Artificial Immune Network algorithm for **compression** and **clustering**. -It uses principles from immune network theory, clonal selection, and affinity maturation to compress datasets and find clusters. - -For clustering, it optionally uses a **Minimum Spanning Tree (MST)** to separate distant nodes into groups. - -**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: - √( (x₁ - x₂)² + (y₁ - y₂)² + ... + (yn - yn)²). - * ``'minkowski'`` ➜ The calculation of the distance is given by the expression: - ( |X₁ - Y₁|p + |X₂ - Y₂|p + ... + |Xn - Yn|p) ¹/ₚ. - * ``'manhattan'`` ➜ The calculation of the distance is given by the expression: - ( |x₁ - x₂| + |y₁ - y₂| + ... + |yn - yn|). - 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** (``Optional[npt.NDArray]``): Stores the current set of antibodies. -* **_memory_network** (``Dict[int, List[Cell]]``): Dictionary mapping clusters to antibodies. -* **_mst_structure** (``Optional[npt.NDArray]``): MST adjacency structure. -* **_mst_mean_distance** (``Optional[float]``): Mean of MST edge distances. -* **_mst_std_distance** (``Optional[float]``): Standard deviation of MST edge distances. -* **labels** (``Optional[npt.NDArray]``): List of cluster labels. - ---- - -## Public Methods - -### Method `fit(...)` - -Trains the AiNet model on input data: - -```python -def fit(self, X: Union[npt.NDArray, list], verbose: bool = True) -> AiNet: -``` - -**Parameters:** - -* **X** (`Union[npt.NDArray, list]`): Array with input samples (rows) and features (columns). -* **verbose** (`bool`): Boolean, default True, enables progress feedback. - -**Raises** - -* `TypeError`: If X is not a ndarray or list. -* `UnsupportedTypeError`: If the data type of the vector is not supported. - -*Returns the class instance.* - ---- - -### Method `predict(...)` - -Predicts cluster labels for new samples: - -```python -def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: -``` - -**Parameters:** - -* **X** (`Union[npt.NDArray, list]`): Array of input features. - -**Raises** - -* `TypeError`: If X is not a ndarray or list. -* `ValueError`: If the array contains values other than 0 and 1. -* `FeatureDimensionMismatch`: If the number of features in X does not match the expected number. -* `ModelNotFittedError`: If the mode has not yet been adjusted and does not have defined memory cells, it is not able to predictions - -**Returns:** - -* **Predictions**: Array of cluster labels, or None if clustering is disabled. - ---- - -### Method `update_clusters(...)` - -Partitions clusters using the MST: - -```python -def update_clusters(self, mst_inconsistency_factor: Optional[float] = None): -``` - -**Parameters:** - -* **mst_inconsistency_factor** (`Optional[float]`): Optional float to override the MST inconsistency factor. - -**Updates:** - -* **_memory_network**: Dictionary of cluster labels to antibody arrays. -* **labels**: List of cluster labels. - ---- - -## Private Methods - -### Method `_init_population_antibodies(...)` - -Initializes antibody population randomly. - -```python -def _init_population_antibodies(self) -> npt.NDArray: -``` - -**Returns:** Initialized antibodies (`npt.NDArray`). - ---- - -### Method `_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: -``` - -**Parameters:** - -* **antigen** (`npt.NDArray`): Array representing the antigen to which affinities will be computed. -* **population** (`npt.NDArray`): Array of antibodies to be evaluated and cloned. - -**Returns:** List of mutated clones. - ---- - -### Method `_clonal_suppression(...)` - -Suppresses redundant clones based on thresholds: - -```python -def _clonal_suppression(self, antigen: npt.NDArray, clones: list): -``` - -**Parameters:** - -* **antigen** (`npt.NDArray`): Array representing the antigen. -* **clones** (`list`): List of candidate clones to be suppressed. - -**Returns:** List of non-redundant, high-affinity clones. - ---- - -### Method `_memory_suppression(...)` - -Removes redundant antibodies from memory pool: - -```python -def _memory_suppression(self, pool_memory: list) -> list: -``` - -**Parameters:** - -* **pool_memory** (`list`): List of antibodies currently in memory. - -**Returns:** Cleaned memory pool (`list`). - ---- - -### Method `_diversity_introduction(...)` - -Introduces new random antibodies: - -```python -def _diversity_introduction(self) -> npt.NDArray: -``` - -**Parameters:** None - -**Returns:** Array of new antibodies (`npt.NDArray`). - ---- - -### Method `_affinity(...)` - -Calculates stimulus between two vectors: - -```python -def _affinity(self, u: npt.NDArray, v: npt.NDArray) -> float: -``` - -**Parameters:** - -* **u** (`npt.NDArray`): Array representing the first point. -* **v** (`npt.NDArray`): Array representing the second point. - -**Returns:** Affinity score (`float`) in [0,1]. - ---- - -### Method `_calculate_affinities(...)` - -Calculates affinity matrix between reference and target vectors: - -```python -def _calculate_affinities(self, u: npt.NDArray, v: npt.NDArray) -> npt.NDArray: -``` - -**Parameters:** - -* **u** (`npt.NDArray`): Reference vector (`npt.NDArray`) of shape `(n_features,)`. -* **v** (`npt.NDArray`): Target vectors (`npt.NDArray`) of shape `(n_samples, n_features)`. - -**Returns:** Array of affinities (`npt.NDArray`) with shape `(n_samples,)`. - ---- - -### Method `_clone_and_mutate(...)` - -Generates mutated clones: - -```python -def _clone_and_mutate(self, antibody: npt.NDArray, n_clone: int) -> npt.NDArray: -``` - -**Parameters:** - -* **antibody** (`npt.NDArray`): Original antibody vector to clone and mutate. -* **n_clone** (`int`): Number of clones to generate. - -**Returns:** Array of mutated clones (`npt.NDArray`) of shape `(n_clone, len(antibody))`. - ---- - -### Method `_build_mst(...)` - -Constructs the MST and stores statistics. - -```python -def _build_mst(self): -``` - -**Parameters:** None - -**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/docs/en/classes/Network Theory Algorithms/README.md b/docs/en/classes/Network Theory Algorithms/README.md deleted file mode 100644 index 8171d83..0000000 --- a/docs/en/classes/Network Theory Algorithms/README.md +++ /dev/null @@ -1,15 +0,0 @@ -# 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. - -## Classes - -1. **[AiNet](AiNet.md)** - -> Artificial Immune Network for unsupervised clustering and compression tasks. ---- - -## References - -> BRABAZON, Anthony; O'NEILL, Michael; MCGARRAGHY, Seán. *Natural Computing Algorithms*. Springer Berlin Heidelberg, 2015. DOI: 10.1007/978-3-662-43631-8. Disponível em: [http://dx.doi.org/10.1007/978-3-662-43631-8](http://dx.doi.org/10.1007/978-3-662-43631-8). diff --git a/docs/en/index.md b/docs/en/index.md deleted file mode 100644 index bceec53..0000000 --- a/docs/en/index.md +++ /dev/null @@ -1,10 +0,0 @@ -##

**INDEX**

- ---- - -### Class module: - -> 1. [**Negative selection**](classes/Negative%20Selection/README.md) -> 2. **Danger Theory** -> 3. [**Clonal Selection Algorithms.**](classes/Clonal%20Selection%20Algorithms/README.md) -> 4. [**Immune Network Theory**](classes/Network%20Theory%20Algorithms/README.md) \ No newline at end of file diff --git a/docs/pt-br/README.md b/docs/pt-br/README.md index cef61ec..19dfaa5 100644 --- a/docs/pt-br/README.md +++ b/docs/pt-br/README.md @@ -1,22 +1,41 @@ +

+ +![Artificial Immune Systems Package](../assets/logos/logo.svg) + +# Artificial Immune Systems Package. + +
+ +--- + ## Sumário ->1. [Introdução.](#introdução) ->2. [Instalação.](#instalação) -> 1. [Dependências](#dependências) -> 2. [Instalação do usuário](#instalação-do-usuário) ->3. [Exemplos.](#exemplos) +1. [Introdução.](#introdução) +2. [Instalação.](#instalação) + 1. [Dependências](#dependências) + 2. [Instalação do usuário](#instalação-do-usuário) +3. [Exemplos.](#exemplos) --- +## Introdução + +**AISP (Artificial Immune Systems Package)** é um pacote pacote python com algoritmos imunoinspirados, os quaios aplicam +metáforas + +
## Introdução -O **AISP** é um pacote python que implementa as técnicas dos sistemas imunológicos artificiais, distribuído sob a licença GNU Lesser General Public License v3.0 (LGPLv3). +O **AISP** é um pacote python que implementa as técnicas dos sistemas imunológicos artificiais, distribuído sob a +licença GNU Lesser General Public License v3.0 (LGPLv3). -O pacote foi iniciado no ano de 2022, como parte de um projeto de pesquisa desenvolvido no Instituto Federal do Norte de Minas Gerais - Campus Salinas (IFNMG - Salinas). +O pacote foi iniciado no ano de 2022, como parte de um projeto de pesquisa desenvolvido no Instituto Federal do Norte de +Minas Gerais - Campus Salinas (IFNMG - Salinas). -Os sistemas imunológicos artificiais (SIA) inspiram-se no sistema imunológico dos vertebrados, criando metáforas que aplicam a capacidade de reconhecer e catalogar os patógenos, entre outras características desse sistema. +Os sistemas imunológicos artificiais (SIA) inspiram-se no sistema imunológico dos vertebrados, criando metáforas que +aplicam a capacidade de reconhecer e catalogar os patógenos, entre outras características desse sistema. ### Algoritmos implementados @@ -42,12 +61,12 @@ O módulo requer a instalação do [python 3.10](https://www.python.org/download
-| Pacotes | Versão | -|:-------------:|:-------------:| -| numpy | ≥ 1.22.4 | -| scipy | ≥ 1.8.1 | -| tqdm | ≥ 4.64.1 | -| numba | ≥ 0.59.0 | +| Pacotes | Versão | +|:-------:|:--------:| +| numpy | ≥ 1.22.4 | +| scipy | ≥ 1.8.1 | +| tqdm | ≥ 4.64.1 | +| numba | ≥ 0.59.0 |
diff --git a/docs/pt-br/advanced-guides/base/base.md b/docs/pt-br/advanced-guides/base/base.md deleted file mode 100644 index 97fc376..0000000 --- a/docs/pt-br/advanced-guides/base/base.md +++ /dev/null @@ -1,44 +0,0 @@ -# Classe Base - -Classe base para introspecção de parâmetros compatível com a API do scikit-learn. - -## Base - -Classe genérica para modelos com uma interface comum. -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) -> Base: -``` - -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. - -**Retorna:** - -* **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. - -**Retorna:** - -* **dict:** Dicionário contendo os atributos do objeto que não começam com "_". - ---- diff --git a/docs/pt-br/advanced-guides/base/classifier.md b/docs/pt-br/advanced-guides/base/classifier.md deleted file mode 100644 index a833c32..0000000 --- a/docs/pt-br/advanced-guides/base/classifier.md +++ /dev/null @@ -1,88 +0,0 @@ -Classe base para algoritmo de classificação. - -# BaseClassifier - -Classe base para algoritmos de classificação, definindo os métodos abstratos ``fit`` e ``predict``. - -## Métodos - -### Método `score(...)` - -```python -def score( - self, - X: Union[npt.NDArray, list], - y: Union[npt.NDArray, 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** (`Union[npt.NDArray, list]`): Conjunto de características com formato (n_amostras, n_características). -* **y** (`Union[npt.NDArray, list]`): 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: -``` - -**Parâmetros**: - -* **y** (`npt.NDArray`): Recebe um array ``n_samples`` com as classes de saída do array de amostras ``X``. - -**Retorna:** - -Retorna um dicionário com as classes como chave e os índices em ``X`` das amostras. - ---- - -## Métodos abstratos - -### Método `fit(...)` - -```python -@abstractmethod -def fit( - self, - X: Union[npt.NDArray, list], - y: Union[npt.NDArray, list], - verbose: bool = True -) -> BaseClassifier: -``` - -Ajusta o modelo aos dados de treinamento. - -Implementação: - -* [RNSA](../../classes/Negative%20Selection/RNSA.md#método-fit) -* [BNSA](../../classes/Negative%20Selection/BNSA.md#método-fit) -* [AIRS](../../classes/Clonal%20Selection%20Algorithms/AIRS.md#método-fit) - -### Método `predict(...)` - -```python -@abstractmethod -def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: -``` - -Realiza a previsão dos rótulos para os dados fornecidos. - -Implementação: - -* [RNSA](../../classes/Negative%20Selection/RNSA.md#método-predict) -* [BNSA](../../classes/Negative%20Selection/BNSA.md#método-predict) -* [AIRS](../../classes/Clonal%20Selection%20Algorithms/AIRS.md#método-predict) diff --git a/docs/pt-br/advanced-guides/base/clusterer.md b/docs/pt-br/advanced-guides/base/clusterer.md deleted file mode 100644 index c1ff15d..0000000 --- a/docs/pt-br/advanced-guides/base/clusterer.md +++ /dev/null @@ -1,79 +0,0 @@ -# BaseClusterer - -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`**. - ---- - -## Métodos abstratos - -### Método `fit(...)` - -```python -@abstractmethod -def fit(self, X: Union[npt.NDArray, list], verbose: bool = True) -> BaseClusterer: -``` - -Ajusta o modelo aos dados de treinamento. -Este método abstrato deve ser implementado pelas subclasses. - -**Parâmetros:** - -* **X** (`Union[npt.NDArray, list]`): 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ções:** - -* [AiNet](../../../classes/Immune%20Network%20Theory/AiNet.md#método-fit) - ---- - -### Método `predict(...)` - -```python -@abstractmethod -def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: -``` - -Gera previsões com base nos dados de entrada. -Este método abstrato deve ser implementado pelas subclasses. - -**Parâmetros:** - -* **X** (`Union[npt.NDArray, list]`): Dados de entrada para os quais as previsões serão geradas. - -**Retorna:** - -* **predictions** (`npt.NDArray`): Rótulos previstos dos clusters para cada amostra de entrada. - -**Implementações:** - -* [AiNet](../../../classes/Immune%20Network%20Theory/AiNet.md#método-predict) - ---- - -## Métodos - -### Método `fit_predict(...)` - -```python -def fit_predict(self, X: Union[npt.NDArray, list], verbose: bool = True) -> npt.NDArray: -``` - -Método de conveniência que combina `fit` e `predict` em uma única chamada. - -**Parâmetros:** - -* **X** (`Union[npt.NDArray, list]`): 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** (`npt.NDArray`): Rótulos previstos dos clusters para cada amostra de entrada. \ No newline at end of file diff --git a/docs/pt-br/advanced-guides/base/immune/cell.md b/docs/pt-br/advanced-guides/base/immune/cell.md deleted file mode 100644 index 90b9024..0000000 --- a/docs/pt-br/advanced-guides/base/immune/cell.md +++ /dev/null @@ -1,96 +0,0 @@ -# Cell Classes - -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 -) -> npt.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** (`FeatureType`, padrão="continuous-features"): Especifica o tipo de características com base na natureza das características de entrada. -* **bounds** (`Optional[npt.NDArray[np.float64]]`, padrão=None): 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. - ---- \ No newline at end of file diff --git a/docs/pt-br/advanced-guides/base/immune/mutation.md b/docs/pt-br/advanced-guides/base/immune/mutation.md deleted file mode 100644 index e5504d8..0000000 --- a/docs/pt-br/advanced-guides/base/immune/mutation.md +++ /dev/null @@ -1,115 +0,0 @@ -# Mutation - -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, types.float64)], cache=True) -def clone_and_mutate_continuous( - vector: npt.NDArray[np.float64], - n: int, - mutation_rate: float -) -> 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. -* **mutation_rate** : (`float`) Se 0 <= mutation_rate < 1: probabilidade de mutação de cada componente. - Se mutation_rate >= 1 ou mutation_rate <= 0: a mutação aleatoriza a quantidade de componentes entre 1 e len(vector). - - -### 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, types.float64)], cache=True) -def clone_and_mutate_binary( - vector: npt.NDArray[np.bool_], - n: int, - mutation_rate: float -) -> 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. -* **mutation_rate** (`float`): Se 0 <= mutation_rate < 1: probabilidade de mutação de cada componente. - Se mutation_rate >= 1 ou mutation_rate <= 0: a mutação aleatoriza a quantidade de componentes entre 1 e len(vector). - -### 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[:, :], types.float64)], cache=True) -def clone_and_mutate_ranged( - vector: npt.NDArray[np.float64], - n: int, - bounds: npt.NDArray[np.float64], - mutation_rate: float, -) -> 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 formato `(2, len(vector))` contendo os valores mínimo e máximo para cada dimensão. -* **mutation_rate** : (`float`) Se 0 <= mutation_rate < 1: probabilidade de mutação de cada componente. - Se mutation_rate >= 1 ou mutation_rate <= 0: a mutação aleatoriza a quantidade de componentes entre 1 e len(vector). - -### Retorna - -* `clone_set` (`npt.NDArray[np.float64]`): Array com forma `(n, len(vector))` contendo os `n` clones mutados do vetor original. - ---- - -## 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]: -``` - -Gera um conjunto de clones mutados a partir de um vetor de permutação. - -Esta função cria `n` clones do vetor de permutação de entrada e aplica mutações aleatórias em cada um, simulando a expansão clonal em sistemas imunes artificiais com permutações discretas. Cada clone recebe um número aleatório de trocas de elementos de acordo com a taxa de mutação. - -### Parâmetros - -* **vector** (`npt.NDArray[np.int64]`): A célula imune original com valores de permutação a serem clonados e mutados. -* **n** (`int`): Número de clones mutados a serem gerados. -* **mutation_rate** (`float`): Probabilidade de mutação de cada componente (0 <= mutation_rate < 1). - -### Retorna - -* `clone_set` (`npt.NDArray[np.int64]`): Array com dimensão `(n, len(vector))` contendo os `n` clones mutados do vetor original. diff --git a/docs/pt-br/advanced-guides/base/immune/populations.md b/docs/pt-br/advanced-guides/base/immune/populations.md deleted file mode 100644 index efefca1..0000000 --- a/docs/pt-br/advanced-guides/base/immune/populations.md +++ /dev/null @@ -1,28 +0,0 @@ -# Populations Module - -Fornece funções utilitárias para gerar populações de anticorpos em algoritmos imunológicos. - -# 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: -``` - -Gera uma população aleatória de anticorpos - -**Parâmetros**: -* **n_samples** (`int`): Número de anticorpos (amostras) a serem gerados. -* **n_features** (`int`): Número de características (dimensões) de cada anticorpo. -* **feature_type** (`FeatureTypeAll`, default="continuous-features"): Especifica o tipo de características:: "continuous-features", "binary-features", "ranged-features", or "permutation-features". -* **bounds** (`Optional[npt.NDArray[np.float64]]`, default=None): Array (2, n_features) com valores mínimo e máximo por dimensão. - -**Returns**: -* **npt.NDArray**: Array com forma (n_samples, n_features) contendo os anticorpos gerados. - -**Raises**: -* **ValueError**: Se o número de características for menor que 0. \ No newline at end of file diff --git a/docs/pt-br/advanced-guides/base/optimizer.md b/docs/pt-br/advanced-guides/base/optimizer.md deleted file mode 100644 index 066b153..0000000 --- a/docs/pt-br/advanced-guides/base/optimizer.md +++ /dev/null @@ -1,160 +0,0 @@ -# BaseOptimizer - -Classe base para algoritmos de otimização - -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 `affinity_function`. - ---- - -## Propriedades - -### Propriedade `cost_history` - -```python -@property -def cost_history(self) -> List[float] -``` - -Retorna o histórico de custos durante a otimização. - ---- - -### Propriedade `solution_history` - -```python -@property -def solution_history(self) -> List -``` - -Retorna o histórico de soluções avaliadas. - ---- - -### Propriedade `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. - ---- - -### Propriedade `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. - ---- - -## Métodos - -### Método `_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. - ---- - -### Método `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. - ---- - -### Método `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 Callable. -* **AttributeError**: Se `alias` for protegido e não puder ser modificado, ou se `alias` não existir na classe do otimizador. - ---- - -### Método `reset()` - -```python -def reset(self) -``` - -Reinicia o estado interno do objeto, limpando o histórico e resetando os valores. - ---- - -## Métodos abstratos - -### Método `optimize(...)` - -```python -@abstractmethod -def optimize( - self, - max_iters: int = 50, - n_iter_no_change: int = 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`, padrão=50): 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. - ---- - -### Método `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/docs/pt-br/advanced-guides/core/Negative Selection.md b/docs/pt-br/advanced-guides/core/Negative Selection.md deleted file mode 100644 index d274938..0000000 --- a/docs/pt-br/advanced-guides/core/Negative Selection.md +++ /dev/null @@ -1,93 +0,0 @@ -# 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 -@njit([(types.boolean[:, :], types.boolean[:], types.float64)], cache=True) -def check_detector_bnsa_validity( - x_class: npt.NDArray[np.bool_], - vector_x: npt.NDArray[np.bool_], - 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[np.bool_]``): Array contendo as amostras da classe. Formato esperado: (n_amostras, n_características). -* **vector_x** (``npt.NDArray[np.bool_]``): 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 -@njit([(types.boolean[:], types.boolean[:, :, :], types.float64)], cache=True) -def bnsa_class_prediction( - features: npt.NDArray[np.bool_], - class_detectors: npt.NDArray[np.bool_], - 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[np.bool_]``): amostra binária a ser classificada (shape: n_features). -* **class_detectors** (``npt.NDArray[np.bool_]``): 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 -@njit( - [ - ( - types.float64[:, :], - types.float64[:], - types.float64, - types.int32, - types.float64, - ) - ], - cache=True, -) -def check_detector_rnsa_validity( - x_class: npt.NDArray[np.float64], - vector_x: npt.NDArray[np.float64], - 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[np.float64]``): Array contendo as amostras da classe. Formato esperado: (n_amostras, n_características). -* **vector_x** (``npt.NDArray[np.float64]``): 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/docs/pt-br/advanced-guides/utils.md b/docs/pt-br/advanced-guides/utils.md deleted file mode 100644 index b69a951..0000000 --- a/docs/pt-br/advanced-guides/utils.md +++ /dev/null @@ -1,609 +0,0 @@ -# Utils - -Funções de utilidade para o desenvolvimento. - -## Métricas (Metrics) - -### Função `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. - -**Retorna:** - -* **Precisão** (``float``): A proporção de previsões corretas em relação - ao número total de previsões. - -**Exceções:** - -* `ValueError`: Se `y_true` ou `y_pred` estiverem vazios ou se não - tiverem o mesmo tamanho. - ---- - -## Multiclass - -### Função `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 -``` - -Função para prever classes usando k-vizinhos mais próximos e células treinadas. - -**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. - ---- - -### Função `slice_index_list_by_class(...)` - -```python -def slice_index_list_by_class(classes: Optional[Union[npt.NDArray, list]], y: npt.NDArray) -> dict -``` - -A função ``slice_index_list_by_class(...)``, separa os índices das amostras -conforme a classe de saída, para percorrer o array de amostra apenas nas posições -onde a saída corresponde à classe sendo treinada. - -**Parâmetros:** - -* **classes** (`Optional[Union[npt.NDArray, list]]`): Lista com classes únicas. Se None, retorna um dicionário vazio. -* **y** (`npt.NDArray`): Array com as classes de saída do array de amostra ``X``. - -**Retorna:** - -* `dict`: Um dicionário com a lista de posições do array, com as classes como chave. - -**Exemplos:** - -```python ->>> import numpy as np ->>> labels = ['a', 'b', 'c'] ->>> y = np.array(['a', 'c', 'b', 'a', 'c', 'b']) ->>> slice_index_list_by_class(labels, y) -{'a': [0, 3], 'b': [2, 5], 'c': [1, 4]} -``` - -## Sanitizers - -### Função `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. - -**Parâmetros:** - -* **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. - ---- - -### Função `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. - -**Parâmetros:** - -* **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. - ---- - -### Função `sanitize_seed(...)` - -```python -def sanitize_seed(seed: Any) -> Optional[int]: -``` - -A função ``sanitize_seed(...)``, retorna a semente se for um inteiro não negativo; caso contrário, retorna Nenhum. - -**Parâmetros:** - -* **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. - ---- - -### Função `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]}`. - -## Distance - -Funções utilitárias para distância normalizada entre matrizes com decoradores numba. - -### Função `hamming(...)` - -```python -@njit([(types.boolean[:], types.boolean[:])], cache=True) -def hamming(u: npt.NDArray[np.bool_], v: npt.NDArray[np.bool_]) -> float64: -``` - -Função para calcular a distância de Hamming normalizada entre dois pontos. - -$((x₁ ≠ x₂) + (y₁ ≠ y₂) + ... + (yn ≠ yn)) / n$ - -**Parâmetros:** - -* **u** (``npt.NDArray[np.bool_]``): Coordenadas do primeiro ponto -* **v** (``npt.NDArray[np.bool_]``): Coordenadas do segundo ponto. - -**Returns:** - -* Distância (``float64``) entre os dois pontos. - ---- - -### Função `euclidean(...)` - -```python -@njit() -def euclidean(u: npt.NDArray[np.float64], v: npt.NDArray[np.float64]) -> float64: -``` - -Função para calcular a distância euclidiana normalizada entre dois pontos. - -$√( (x₁ - x₂)² + (y₁ - y₂)² + ... + (yn - yn)²)$ - -**Parâmetros:** - -* **u** (``npt.NDArray[np.float64]``): Coordenadas do primeiro ponto -* **v** (``npt.NDArray[np.float64]``): Coordenadas do segundo ponto. - -**Returns:** - -* Distância (``float64``) entre os dois pontos. - ---- - -### Função `cityblock(...)` - -```python -@njit() -def cityblock(u: npt.NDArray[float64], v: npt.NDArray[float64]) -> float64: -``` - -Função para calcular a distância Manhattan normalizada entre dois pontos. - -$(|x₁ - x₂| + |y₁ - y₂| + ... + |yn - yn|) / n$ - -**Parâmetros:** - -* **u** (``npt.NDArray[float64]``): Coordenadas do primeiro ponto -* **v** (``npt.NDArray[float64]``): Coordenadas do segundo ponto. - -**Returns:** - -* Distância (``float64``) entre os dois pontos. - ---- - -### Função `minkowski(...)` - -```python -@njit() -def minkowski( - u: npt.NDArray[float64], - v: npt.NDArray[float64], - p: float = 2.0 -) -> float64: -``` - -Função para calcular a distância de Minkowski normalizada entre dois pontos. - -$(( |X₁ - Y₁|p + |X₂ - Y₂|p + ... + |Xn - Yn|p) ¹/ₚ) / n$ - -**Parâmetros:** - -* **u** (``npt.NDArray[float64]``): Coordenadas do primeiro ponto. -* **v** (``npt.NDArray[float64]``): Coordenadas do segundo ponto. -* **p** (``float``, padrão=2.0): 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. - ---- - -### Função `compute_metric_distance(...)` - -```python -@njit([(types.float64[:], types.float64[:], types.int32, types.float64)], cache=True) -def compute_metric_distance( - u: npt.NDArray[float64], - v: npt.NDArray[float64], - metric: int, - p: float = 2.0 -) -> float64: -``` - -Função para calcular a distância entre dois pontos pela ``métrica`` escolhida. - -**Parâmetros:** - -* **u** (``npt.NDArray[float64]``): Coordenadas do primeiro ponto. -* **v** (``npt.NDArray[float64]``): 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``, padrão=2.0): 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. - ---- - -### Função `min_distance_to_class_vectors(...)` - -```python -@njit([(types.float64[:, :], types.float64[:], types.int32, types.float64)], cache=True) -def min_distance_to_class_vectors( - x_class: npt.NDArray[float64], - vector_x: npt.NDArray[float64], - metric: int, - p: float = 2.0, -) -> float: -``` - -Calcula a menor distância entre um vetor de entrada e os vetores de uma classe. - -**Parâmetros:** - -* **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), 3 (Hamming). -* **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. - ---- - -### Função `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. - -**Parâmetros:** - -* **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. - ---- - -## Validation - -### Função `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:** - -* **vector** (`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. - ---- - -### Função `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. - -**Exceções:** - -* `TypeError`: Se não for possível converter para ndarray. - ---- - -### Função `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. - -**Exceções:** - -* `TypeError`: Se as dimensões não forem compatíveis. - ---- - -### Função `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. - -**Exceções:** - -* `FeatureDimensionMismatch`: Se o número de características não corresponder ao esperado. - ---- - -### Função `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. - -**Exceções:** - -* `ValueError`: Se o array contiver valores diferentes de 0 e 1. - ---- - -## Display - -Funções utilitárias para exibir informações de algoritmos - -### Função `_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. - ---- - -#### Função `_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. - ---- - -#### Função `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. - ---- - -#### Função `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. - ---- - -#### Função `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. - ---- - -#### Função `_print_header()` - -```python -def _print_header(self) -> None -``` - -Imprime o cabeçalho da tabela. - ---- - -#### Função `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`. - ---- - -#### Função `finish()` - -```python -def finish(self) -> None -``` - -Encerra a exibição da tabela, imprimindo a borda inferior e o tempo total. - ---- diff --git a/docs/pt-br/api/base/README.md b/docs/pt-br/api/base/README.md new file mode 100644 index 0000000..99b354e --- /dev/null +++ b/docs/pt-br/api/base/README.md @@ -0,0 +1,33 @@ +--- +id: base +sidebar_label: aisp.base +keywords: + - base + - imune + - abstrato +--- + +# aisp.base + +Classe base e utilitários centrais + +> **Módulos:** `aisp.base` + +## Visão geral + +Este modulo fornece as classes e utilidades fundamentais para todos os algoritmos de sistemas imunológicos artificiais +implementados no AISP. + +## Classes + +| Class | Descrição | +|------------------------------------------|--------------------------------------------------------| +| [`BaseClassifier`](./base-classifier.md) | Classe base abstrata para algoritmos de classificação. | +| [`BaseClusterer`](./base-clusterer.md) | Classe base abstrata para algoritmos de clustering. | +| [`BaseOptimizer`](./base-optimizer.md) | Classe base abstrata para algoritmos de otimização. | + +## Submódulos + +| Módulo | Descrição | +|--------------------------------|----------------------------------------------------------| +| [`immune`](./immune/README.md) | Módulo de suporte para sistemas imunológicos artificias. | \ No newline at end of file diff --git a/docs/pt-br/api/base/base-classifier.md b/docs/pt-br/api/base/base-classifier.md new file mode 100644 index 0000000..2f529aa --- /dev/null +++ b/docs/pt-br/api/base/base-classifier.md @@ -0,0 +1,128 @@ +--- +id: base-classifier +sidebar_label: BaseClassifier +keywords: + - base + - classificação + - classificação interface + - pontuação de acurácia + - fit + - predict +tags: + - classificador + - classificação +--- + +# BaseClassifier + +Classe base abstrata para algoritmos de classificação. + +> **Módulo:** `aisp.base` +> **Importação:** `from aisp.base import BaseClassifier` + +--- + +## Visão geral + +Esta classe define a interface principal para algoritmos de classificação. +Ela define a implementação dos metodos `fit` e `predict` em todas as classes derivadas, e fornece uma implementação +do método `score`. + +Caso de uso: + +- Classe base abstrata para estender classes de algoritmos de classificação. + +--- + +## Atributos + +| Nome | Tipo | Padrão | Descrição | +|-----------|-------------------------|:------:|----------------------------------------------------------------| +| `classes` | `Optional[npt.NDArray]` | `None` | Rótulos das classes identificado de `y` durante o treinamento. | + +--- + +## Métodos abstratos + +### fit + +```python +@abstractmethod +def fit( + self, + X: Union[npt.NDArray, list], + y: Union[npt.NDArray, list], + verbose: bool = True +) -> BaseClassifier: + ... +``` + +Treine o modelo usando os dados de entrada X e seus rótulos correspondentes y. +Este método abstrato é implementado é responsabilidade das classes filhas. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|-----------|----------------------------|:------:|----------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Dados de entrada utilizados para o treinamento. | +| `y` | `Union[npt.NDArray, list]` | - | Rótulos correspondentes as características dos dados de entrada. | +| `verbose` | `bool` | `True` | Indica se as mensagens de progresso do treinamento deve ser exibido. | + +**Returns** + +``BaseClassifier`` - Retorna a instancia da classe. + +--- + +### predict + +```python +@abstractmethod +def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: + ... +``` + +Gera previsões com base nos dados de entrada X. +Este método abstrato é implementado é responsabilidade das classes filhas. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|------|----------------------------|:------:|---------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Dados de entrada que serão previstos pelo modelo. | + +**Returns** + +`npt.NDArray` - Array com as previsões para cada amostra de `X`. + +--- + +## Métodos públicos + +### score + +```python +def score( + self, + X: Union[npt.NDArray, list], + y: Union[npt.NDArray, list] +) -> float: + ... +``` + +A função calcula o desempenho do modelo nas previsões utilizando a métrica de acurácia. + +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** + +| Nome | Tipo | Padrão | Descrição | +|------|----------------------------|:------:|--------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Conjunto de características com dimensões (n_samples, n_features). | +| `y` | `Union[npt.NDArray, list]` | - | Rótulos verdadeiros com dimensão (n_amostras,). | + +**Returns** + +`float` - A precisão do modelo. + diff --git a/docs/pt-br/api/base/base-clusterer.md b/docs/pt-br/api/base/base-clusterer.md new file mode 100644 index 0000000..ce84a13 --- /dev/null +++ b/docs/pt-br/api/base/base-clusterer.md @@ -0,0 +1,116 @@ +--- +id: base-clusterer +sidebar_label: BaseClusterer +keywords: + - base + - clusterer + - clusterer interface + - cluster labels + - fit + - predict + - fit_predict +tags: + - clusterer + - clustering +--- + +# BaseClusterer + +Classe base abstrata para algoritmos de clustering. + +> **Módulos:** `aisp.base` +> **Importação:** `from aisp.base import BaseClusterer` + +--- + +## Visão geral + +Esta classe define a interface principal para algoritmos de clusterização. +Ela define a implementação dos metodos fit e predict em todas as classes filhas, e fornece a implementação do +método `fit_predict`. + +Casos de uso: + +- Classe base abstrata para estender classes de algoritmos de clusterização. + +--- + +## Atributos + +| Nome | Tipo | Padrão | Descrição | +|----------|-------------------------|:------:|---------------------------------------------------------| +| `labels` | `Optional[npt.NDArray]` | `None` | Rótulos dos clusters encontrados durante o treinamento. | + +--- + +## Métodos abstratos + +### fit + +```python +@abstractmethod +def fit(self, X: Union[npt.NDArray, list], verbose: bool = True) -> BaseClusterer: + ... +``` + +Treinamento do modelo utilizando os dados de entrada `X`. +Este método abstrato é implementado é responsabilidade das classes filhas. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|-----------|----------------------------|:------:|----------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Dados de entrada utilizados para o treinamento. | +| `verbose` | `bool` | `True` | Indica se as mensagens de progresso do treinamento deve ser exibido. | + +**Returns** + +``BaseClassifier`` - Retorna a instancia da classe. + +--- + +### predict + +```python +@abstractmethod +def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: + ... +``` + +Gera previsões com base nos dados de entrada `X`. +Este método abstrato é implementado é responsabilidade das classes filhas. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|------|----------------------------|:------:|------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Dados de entrada para os quais as previsões serão geradas. | + +**Returns** + +`npt.NDArray` - Os labels do cluster previsto para cada amostra de entrada. + +--- + +## Métodos públicos + +### fit_predict + +```python +def fit_predict(self, X: Union[npt.NDArray, list], verbose: bool = True) -> npt.NDArray: + ... +``` + +Ajusta o modelo e com os dados de X e retorna os labels para cada amostra de X. +Este é um método que combina `fit` e `predict` em uma única chamada. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|-----------|----------------------------|:------:|----------------------------------------------------------------------| +| `X` | `Union[npt.NDArray, list]` | - | Conjunto de características com dimensões (n_samples, n_features). | +| `verbose` | `bool` | `True` | Indica se as mensagens de progresso do treinamento deve ser exibido. | + +**Returns** + +`npt.NDArray` - Os labels do cluster previsto para cada amostra de entrada. diff --git a/docs/pt-br/api/base/base-optimizer.md b/docs/pt-br/api/base/base-optimizer.md new file mode 100644 index 0000000..ac1ebc5 --- /dev/null +++ b/docs/pt-br/api/base/base-optimizer.md @@ -0,0 +1,157 @@ +--- +id: base-optimizer +sidebar_label: BaseOptimizer +keywords: + - base + - otimizar + - otimização + - otimizar interface + - objective function + - minimization + - maximization +tags: + - otimizar + - otimização +--- + +# BaseOptimizer + +Classe base abstrata para algoritmos de otimização. + +> **Módulos:** `aisp.base` +> **Importação:** `from aisp.base import BaseOptimizer` + +--- + +## Visão geral + +Esta classe define a interface principal para algoritmos de otimização. +Ela mantém o histórico de custos, soluções avaliadas, e a melhor solução encontrada durante a otimização. As classes +derivadas devem implementar os métodos ``optimize`` e ``affinity_function``. + +Casos de uso: + +- Classe base abstrata para estender classes de algoritmos de otimização. + +--- + +## Atributos + +| Nome | Tipo | Padrão | Descrição | +|--------------------|-------------------|:-------:|---------------------------------------------------------------| +| `cost_history` | `List[float]` | `[]` | Histórico dos melhores custos encontrados em cada iteração. | +| `solution_history` | `List` | `[]` | Histórico da melhor solução encontrada em cada iteração. | +| `best_solution` | `Any` | `None` | A melhor solução global encontrada. | +| `best_cost` | `Optional[float]` | `None` | Custo da melhor solução global encontrada. | +| `mode` | `{"min", "max"}` | `'min'` | Define se o algoritmo minimiza ou maximiza a função de custo. | + +--- + +## Métodos abstratos + +### optimize + +```python +@abstractmethod +def optimize( + self, + max_iters: int = 50, + n_iter_no_change: int = 10, + verbose: bool = True +) -> Any: + ... +``` + +Executa o processo de otimização. +Este método abstrato é implementado é responsabilidade das classes filhas, definindo a estratégia de otimização. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|--------------------|--------|:------:|----------------------------------------------------------------------| +| `max_iters` | `int` | `50` | Número máximo de iterações | +| `n_iter_no_change` | `int` | `10` | Número máximo de interações sem atualização da melhor solução. | +| `verbose` | `bool` | `True` | Indica se as mensagens de progresso do treinamento deve ser exibido. | + +**Returns** + +``BaseClassifier`` - Retorna a instância da classe. + + +--- + +### affinity_function + +```python +@abstractmethod +def affinity_function(self, solution: Any) -> float: + ... +``` + +Avalia a afinidade (qualidade) de uma solução candidata. + +Este método deve ser implementado conforme o problema de otimização específico, definindo como a solução sera medida. +O valor retornado deve representar a qualidade da solução avaliada. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|------------|-------|:------:|--------------------------------------| +| `solution` | `Any` | - | Solução candidata que será avaliada. | + +**Returns** + +`float` - Valor de custo associada a solução encontrada. + +--- + +## Métodos públicos + +### get_report + +```python +def get_report(self) -> str: + ... +``` + +Gera um relatorio resumindo e formatado do processo de otimização. +O relatorio incluir a melhor solução, seu custo, e a evolução dos valores a cada iteração. + +**Returns** + +`str` - Uma string formatada contendo o resumo da otimização. + +--- + +### register + +```python +def register(self, alias: str, function: Callable[..., Any]) -> None: + ... +``` + +Registra dinamicamente uma função na instância do otimizador. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|------------|----------------------|:------:|----------------------------------------------------| +| `alias` | `str` | - | Nome usado para acessar a função como um atributo. | +| `function` | `Callable[..., Any]` | - | Função que será registrada. | + +**Exceções** + +`TypeError` - Lançado quando não é uma função valida. + +`AttributeError` - Lançado quando o `alias` esta protegido e não pode ser modificado, ou se não existir na classe. + +--- + +### reset + +```python +def reset(self): + ... +``` + +Reseta o estado interno do objeto, limpando histórico e restaurando valores iniciais. diff --git a/docs/pt-br/api/base/immune/README.md b/docs/pt-br/api/base/immune/README.md new file mode 100644 index 0000000..82f0110 --- /dev/null +++ b/docs/pt-br/api/base/immune/README.md @@ -0,0 +1,22 @@ +--- +id: immune +sidebar_label: immune +keywords: + - célula + - mutações + - populações +--- + +# aisp.base.immune + +Módulo de suporte para sistemas imunológicos artificias. + +> **Módulo:** `aisp.base.immune` + +## Submódulos + +| Módulos | Descrição | +|-----------------------------------|------------------------------------------------------------------------------------------------------------| +| [`cell`](./cell/README.md) | Representação de células do sistema imunológico. | +| [`mutation`](./mutation.md) | Funções para gerar clones hipermutados similar a expansão clonal. | +| [`populations`](./populations.md) | Fornece funções utilitárias para gerar populações de anticorpos utilizadas em algoritmos imuno-inspirados. | \ No newline at end of file diff --git a/docs/pt-br/api/base/immune/cell/README.md b/docs/pt-br/api/base/immune/cell/README.md new file mode 100644 index 0000000..548c41c --- /dev/null +++ b/docs/pt-br/api/base/immune/cell/README.md @@ -0,0 +1,32 @@ +--- +id: immune-cell +sidebar_label: cell +keywords: + - vector representation + - cell + - immune + - immune cell + - base class + - bcell + - antibody + - dataclass +--- + +# aisp.base.immune.cell + +Representação de células do sistema imunológico. + +> **Módulos:** `aisp.base.immune.cell` + +## Visão geral + +Este módulo define as representações de células dos sistemas imunológicos artificiais e as implementa como dataclass. + +## Classes + +| Class | Descrição | +|-----------------------------|----------------------------------------------------| +| [`Cell`](./cell.md) | Representa uma célula imune básica. | +| [`BCell`](./b-cell.md) | Representa uma célula-B de memória. | +| [`Antibody`](./antibody.md) | Representa um anticorpo. | +| [`Detector`](./detector.md) | Representa um detector não-próprio da classe rnsa. | \ No newline at end of file diff --git a/docs/pt-br/api/base/immune/cell/antibody.md b/docs/pt-br/api/base/immune/cell/antibody.md new file mode 100644 index 0000000..5587a53 --- /dev/null +++ b/docs/pt-br/api/base/immune/cell/antibody.md @@ -0,0 +1,39 @@ +--- +id: antibody +sidebar_label: Antibody +keywords: + - anticorpo + - afinidade + - célula + - imune + - dataclass +--- + +# Antibody + +Representa um anticorpo. + +:::tip[Herança] + +Esta classe herda de [Cell](./cell.md) + +::: + +> **Módulo:** `aisp.base.immune.cell` +> **Importação:** `from aisp.base.immune.cell import Antibody` + +--- + +## Atributos + +| Nome | Tipo | Padrão | Descrição | +|------------|---------------|:------:|----------------------------------------| +| `vector` | `npt.NDArray` | - | Vetor com as características anticorpo | +| `affinity` | `float` | - | Valor da afinidade do anticorpo | + +--- + +## Métodos + +* `__lt__(other)`: Compara a célula atual com outra célula `Antibody` com base na afinidade. +* `__eq__(other)`: Verifica se o anticorpo possui a mesma afinidade do outro. diff --git a/docs/pt-br/api/base/immune/cell/b-cell.md b/docs/pt-br/api/base/immune/cell/b-cell.md new file mode 100644 index 0000000..1f8a027 --- /dev/null +++ b/docs/pt-br/api/base/immune/cell/b-cell.md @@ -0,0 +1,61 @@ +--- +id: b-cell +sidebar_label: BCell +keywords: + - célula-b + - memória imune + - dataclass + - mutação clonal + - expansão clonal +--- + +# BCell + +Representa uma célula-B de memória. + +:::tip[Herança] + +Esta classe herda de [Cell](./cell.md) + +::: + +> **Módulo:** `aisp.base.immune.cell` +> **Importação:** `from aisp.base.immune.cell import BCell` + +--- + +## Atributos + +| Nome | Tipo | Padrão | Descrição | +|----------|--------------|:------:|-----------------------------------------| +| `vector` | `np.ndarray` | - | Vetor com as características da célula. | + +--- + +## Métodos Públicos + +### hyper_clonal_mutate + +```python +def hyper_clonal_mutate( + self, + n: int, + feature_type: FeatureType = "continuous-features", + bounds: Optional[npt.NDArray[np.float64]] = None +) -> npt.NDArray: + ... +``` + +Gera **N** clones da célula atual e aplica hipermutação aos clones. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|----------------|------------------------------------------------------|:-----------------------:|-----------------------------------------------------------------| +| `n` | `int` | - | Numero de clones que serão gerados a partir da célula original. | +| `feature_type` | [`FeatureType`](../../../utils/types.md#featuretype) | `"continuous-features"` | Especifica o tipo de características da célula. | +| `bounds` | `Optional[npt.NDArray[np.float64]]` | `None` | Matriz (n_features, 2) com o min e o max de cada dimensão. | + +**Returns** + +`npt.NDArray` - Uma matriz contendo N clones mutados da célula original. diff --git a/docs/pt-br/api/base/immune/cell/cell.md b/docs/pt-br/api/base/immune/cell/cell.md new file mode 100644 index 0000000..0d7955c --- /dev/null +++ b/docs/pt-br/api/base/immune/cell/cell.md @@ -0,0 +1,35 @@ +--- +id: cell +sidebar_label: Cell +keywords: + - vector representation + - cell + - immune + - immune cell + - base class + - dataclass +--- + +# Cell + +Representa uma célula imune básica. + +> **Módulo:** `aisp.base.immune.cell` +> **Importação:** `from aisp.base.immune.cell import Cell` + +--- + +## Atributos + +| Nome | Tipo | Padrão | Descrição | +|----------|--------------|:------:|-----------------------------------------| +| `vector` | `np.ndarray` | - | Vetor com as características da célula. | + +--- + +## Métodos + +* `__eq__(other)`: Verifica se duas células são iguais com base nos seus vetores. +* `__array__()`: Interface de array Numpy, permite que a instância seja tratada como um `np.ndarray` +* `__getitem__(item)`: Obtém um elemento do vetor com base no index. + diff --git a/docs/pt-br/api/base/immune/cell/detector.md b/docs/pt-br/api/base/immune/cell/detector.md new file mode 100644 index 0000000..71fcfdc --- /dev/null +++ b/docs/pt-br/api/base/immune/cell/detector.md @@ -0,0 +1,28 @@ +--- +id: detector +sidebar_label: Detector +keywords: + - detector + - célula + - imune + - raio + - não-próprio + - nsa + - dataclass +--- + +# Detector + +Representa um detector não-próprio da classe rnsa. + +> **Módulo:** `aisp.base.immune.cell` +> **Importação:** `from aisp.base.immune.cell import Detector` + +--- + +## Atributos + +| Nome | Tipo | Padrão | Descrição | +|------------|---------------------------|:------:|--------------------------------------------------| +| `position` | `npt.NDArray[np.float64]` | - | Vetor com as características do detector. | +| `radius` | `float, optional` | - | Raio do detector, usado no algoritmo V-detector. | diff --git a/docs/pt-br/api/base/immune/mutation.md b/docs/pt-br/api/base/immune/mutation.md new file mode 100644 index 0000000..9665313 --- /dev/null +++ b/docs/pt-br/api/base/immune/mutation.md @@ -0,0 +1,138 @@ +--- +id: mutation +sidebar_label: mutation +keywords: + - mutações + - expansão clonal + - sistema imune + - funções python com numba + - vetor de mutações +--- + +# mutation + +As funções utilizam decoradores do Numba para compilação Just-In-Time(JIT). + +Contém funções que geram conjuntos de clones hipermutados a partir de vetores contínuos ou binários, simulando o +processo +de expansão clonal dos sistemas imunológicos artificiais. + +> **Módulo:** `aisp.base.immune` +> **Importação:** `from aisp.base.immune import mutation` + +## Funções + +### clone_and_mutate_continuous + +```python +@njit([(types.float64[:], types.int64, types.float64)], cache=True) +def clone_and_mutate_continuous( + vector: npt.NDArray[np.float64], + n: int, + mutation_rate: float +) -> 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 em cada um, simulando o processo +de expansão clonal em sistemas imunes artificiais. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|-----------------|---------------------------|:------:|----------------------------------------------------------------------------------------------------------------------------------------------| +| `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 que serão gerados. | +| `mutation_rate` | `float` | - | Se 0 ≤ mutation_rate < 1, usa probabilidade de mutação por características. Caso contrario, um número aleatorio de características é mutado. | + +**Returns** + +`npt.NDArray[np.float64]` - Array com dimensões (n, len(vector)) contendo os `n` clones mutados do vetor original. + +### clone_and_mutate_binary + +```python +@njit([(types.boolean[:], types.int64, types.float64)], cache=True) +def clone_and_mutate_binary( + vector: npt.NDArray[np.bool_], + n: int, + mutation_rate: float +) -> 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 aos bits, simulando a expansão +clonal em sistemas imunes artificiais com representações discretas. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|-----------------|---------------------------|:------:|----------------------------------------------------------------------------------------------------------------------------------------------| +| `vector` | `npt.NDArray[np.float64]` | - | Vetor binário original que representa a célula imune a ser clonada e mutada. | +| `n` | `int` | - | Quantidade de clones mutados a serão gerados. | +| `mutation_rate` | `float` | - | Se 0 ≤ mutation_rate < 1, usa probabilidade de mutação por características. Caso contrario, um número aleatorio de características é mutado. | + +**Returns** + +`npt.NDArray[np.bool_]` - Array com dimensões (n, len(vector)) contendo os `n` clones mutados do vetor original. + +### clone_and_mutate_ranged + +```python +@njit([(types.float64[:], types.int64, types.float64[:, :], types.float64)], cache=True) +def clone_and_mutate_ranged( + vector: npt.NDArray[np.float64], + n: int, + bounds: npt.NDArray[np.float64], + mutation_rate: float, +) -> npt.NDArray[np.float64]: + ... +``` + +Gera um conjunto de clones mutados a partir de uma célula representada pelo intervalo personalizados por dimensão.. + +Esta função cria `n` clones do vetor de entrada e aplica mutações em cada um, simulando o processo +de expansão clonal em sistemas imunes artificiais. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|-----------------|---------------------------|:------:|----------------------------------------------------------------------------------------------------------------------------------------------| +| `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 serão gerados. | +| `bounds` | `np.ndarray` | - | Array (n_features, 2) com valor mínimo e máximo por dimensão. | +| `mutation_rate` | `float` | - | Se 0 ≤ mutation_rate < 1, usa probabilidade de mutação por características. Caso contrario, um número aleatorio de características é mutado. | + +**Returns** + +`npt.NDArray[np.float64]` - Array com dimensões (n, len(vector)) contendo os `n` clones mutados do vetor original. + +### clone_and_mutate_continuous + +```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]: + ... +``` + +Gera um conjunto de clones com mutações por permutação. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|-----------------|-------------------------|:------:|------------------------------------------------------------------------------------| +| `vector` | `npt.NDArray[np.int64]` | - | Vetor de permutação original que representa a célula imune a ser clonada e mutada. | +| `n` | `int` | - | Quantidade de clones mutados a serão gerados. | +| `mutation_rate` | `float` | - | Probabilidade de mutação de uma característica. | + +**Returns** + +`npt.NDArray[np.float64]` - Array com dimensões (n, len(vector)) contendo os `n` clones mutados do vetor original. diff --git a/docs/pt-br/api/base/immune/populations.md b/docs/pt-br/api/base/immune/populations.md new file mode 100644 index 0000000..9e7c140 --- /dev/null +++ b/docs/pt-br/api/base/immune/populations.md @@ -0,0 +1,52 @@ +--- +id: populations +sidebar_label: populations +keywords: + - binário + - classificação + - limiar de afinidade + - real-valor + - célula-b de memória + - expansão clonal + - população +--- + +# populations + +Fornece funções utilitárias para **gerar populações** de anticorpos utilizadas em algoritmos imuno-inspirados. + +> **Módulo:** `aisp.base.immune` +> **Importação:** `from aisp.base.immune import populations` + +## Funções + +### 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: + ... +``` + +Gera uma população aleatória de anticorpos. + +**Parâmetros** + +| Nome | Tipo | Padrão | Descrição | +|----------------|---------------------------------------------------------|:-----------------------:|--------------------------------------------------------------------------------------------------------------------------------| +| `n_samples` | `int` | - | Número de anticorpos (amostras) que serão gerados. | +| `n_features` | `int` | - | Número de características (dimensões) para cada anticorpo. | +| `feature_type` | [`FeatureTypeAll`](../../utils/types.md#featuretypeall) | `"continuous-features"` | Especifica o tipo das características: "continuous-features", "binary-features", "ranged-features", or "permutation-features". | +| `bounds` | `npt.NDArray[np.float64]` | `None` | Array (n_features, 2) contendo os valores mínimo e máximo por dimensão. | + +**Exceções** + +`ValueError` - Lançado caso o número de características seja menor ou igual a zero. + +**Returns** + +`npt.NDArray` - Array de dimensão (n_samples, n_features) contendo os anticorpos gerados. diff --git a/docs/pt-br/classes/Clonal Selection Algorithms/AIRS.md b/docs/pt-br/classes/Clonal Selection Algorithms/AIRS.md deleted file mode 100644 index 02cac0e..0000000 --- a/docs/pt-br/classes/Clonal Selection Algorithms/AIRS.md +++ /dev/null @@ -1,280 +0,0 @@ -# AIRS (Sistema de Reconhecimento Imune Artificial) - -Esta classe estende a classe [**Base**](../../advanced-guides/base/classifier.md). - -## Construtor AIRS - -A classe `AIRS` realiza classificação utilizando metáforas de seleção e expansão clonal. - -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. - -Baseado no Algoritmo 16.5 de Brabazon et al. [1](#ref1). - -Estudos relacionados de destaque: [2](#ref2). - -**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_mc_init** (`float`): Percentual de amostras usadas para inicializar as células de memórias. O padrão é 0,75. -* **rate_hypermutation** (`float`): Taxa de clones mutados derivada de rate_clonal como um fator escalar. O padrão é 0,2. -* **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 é 3. -* **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: - * `'euclidean'` ➜ O cálculo da distância é dado pela expressão: - √( (x₁ - x₂)² + (y₁ - y₂)² + ... + (nₙ - nₙ)² ). - * `'minkowski'` ➜ O cálculo da distância é dado pela expressão: - ( |X₁ - Y₁|ᵖ + |X₂ - Y₂|ᵖ + ... + |Xₙ - Yₙ|ᵖ )¹/ᵖ. - * `'manhattan'` ➜ O cálculo da distância é dado pela expressão: - ( |x₁ - x₂| + |y₁ - y₂| + ... + |nₙ - nₙ| ). - O padrão é "euclidean". - -* **seed** (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: Union[npt.NDArray, list], - y: Union[npt.NDArray, list], - verbose: bool = True, -) -> AIRS: -``` - -Realiza o treinamento conforme `X` e `y`, utilizando o método Sistema de Reconhecimento Imune Artificial (`AIRS`). - -**Parâmetros:** - -* **X** (``Union[npt.NDArray, list]``): Array com as características das amostras, com **N** amostras (linhas) e **N** características (colunas), normalizado para valores entre [0, 1]. -* **y** (``Union[npt.NDArray, list]``): Array com as classes de saída correspondentes às **N** amostras relacionadas a `X`. -* **verbose**: (``bool``, padrão=True), determina se o feedback da geração dos detectores será impresso. - -**Retorna:** - -* `AIRS`: 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: Union[npt.NDArray, list]) -> npt.NDArray: -``` - -**Parâmetros:** - -* **X** (`Union[npt.NDArray, list]`): Array com as características para predição, com **N** amostras (linhas) e **N** colunas. - -**Raises** - -* `TypeError`: Se X não for um ndarray ou uma lista. -* `FeatureDimensionMismatch`: Se o número de características em X não corresponder ao número esperado. -* `ModelNotFittedError`: Se o modelo ainda não tiver sido ajustado e não possuir células de memória definidas, não conseguirá realizar predições. - - -**Retorna:** - -* **C**: Um array de predições com as classes de saída para as características fornecidas. - ---- - -### 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:** - -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`). - -```python -def _refinement_arb( - self, - ai: npt.NDArray, - c_match_stimulation: float, - arb_list: List[_ARB] -) -> _ARB: -``` - -**Parâmetros:** -* **ai** (`npt.NDArray`): Antígeno atual -* **c_match_stimulation** (``float``): Célula com o maior estímulo em relação a aᵢ. -* **arb_list** (`List[_ARB]`): Conjunto ARB. - -**Retorna:** - -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). - -```python -def _cells_affinity_threshold(self, antigens_list: npt.NDArray): -``` - -**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** (`npt.NDArray`): Lista de antígenos de treinamento. - ---- - -### Método `_affinity(...)` - -A função "_affinity(...)" calcula o estímulo entre dois vetores usando métricas. - - -```python -def _affinity(self, u: npt.NDArray, v: npt.NDArray) -> float: -``` - -**Parâmetros:** - -* **u** (`npt.NDArray`): Coordenadas do primeiro ponto. -* **v** (`npt.NDArray`): Coordenadas do segundo ponto. - -**Retorna:** - -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. - -```python -def _init_memory_c(self, antigens_list: npt.NDArray) -> List[Cell]: -``` - -**Parâmetros:** - -* **antigens_list** (`npt.NDArray`): Lista de antígenos de treinamento. - ---- - - -### Method `_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: -``` - -**Parâmetros**: - -* **y** (`npt.NDArray`): Recebe um array ``n_samples`` com as classes de saída do array de amostras ``X``. - -**Retorna:** - -Retorna um dicionário com as classes como chave e os índices em ``X`` das amostras. - ---- - -### Method `__prepare_features(...)` - -A função ``__prepare_features(...)`` verifica as amostras, especificando o tipo, a quantidade de características e outros parâmetros. - -```python -def _prepare_features(self, X: Union[npt.NDArray, list]) -> npt.NDArray: -``` - -* Este método atualiza os seguintes atributos: - * ``self._feature_type`` - * ``self.metric`` (apenas para características binárias) - * ``self._bounds`` (apenas para características com intervalo definido) - * ``self._n_features`` - - -**Parameters:** - -* **X** (``Union[npt.NDArray, list]``): Array com as características para predição, contendo N amostras (linhas) e N colunas. - -Retorna os dados de entrada processados. - ---- - -# Classes Auxiliares - ---- - -## Classe _ARB (Herdada de [BCell](../../advanced-guides/base/immune/cell.md#bcell)) - -### Construtor - -**Parâmetros:** - -* vector (`npt.NDArray`): Vetor de características da célula. Padrão é None. - ---- - -### Método `consume_resource(...)` - -```python -def consume_resource(self, n_resource: float, amplified: float = 1) -> float: -``` - -**Parâmetros:** - -* **n_resource** (`float`) : A quantidade inicial de recursos. -* **amplified** (`float`): Amplificador para o consumo de recursos pela célula. É multiplicado pelo estímulo da célula. O padrão é 1. - -**Retorna:** - -Retorna a quantidade restante de recursos após o consumo. - ---- - -# 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: [http://dx.doi.org/10.1007/978-3-662-43631-8](http://dx.doi.org/10.1007/978-3-662-43631-8). - -
- -> 2. AZZOUG, Aghiles. Artificial Immune Recognition System V2. -> Disponível em: [https://github.com/AghilesAzzoug/Artificial-Immune-System](https://github.com/AghilesAzzoug/Artificial-Immune-System) diff --git a/docs/pt-br/classes/Clonal Selection Algorithms/Clonalg.md b/docs/pt-br/classes/Clonal Selection Algorithms/Clonalg.md deleted file mode 100644 index 931dbe2..0000000 --- a/docs/pt-br/classes/Clonal Selection Algorithms/Clonalg.md +++ /dev/null @@ -1,183 +0,0 @@ -# Algoritmo de Seleção Clonal (CLONALG) - -## Clonalg - -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. - -A implementação do CLONALG foi inspirada na descrição apresentada em [1](#ref1). - -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. - ---- - -### Construtor - -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=1.0): 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:** - -* **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:** - -* `List[Antibody]`: A população de anticorpos 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:** - -* **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:** - -* **n** (`int`): Número de anticorpos a serem selecionados. -* **antibodies** (`list[Antibody]`): Lista de tuplas, onde cada tupla representa um anticorpo e sua pontuação associada. - -**Retorna:** - -* `list[Antibody]`: 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:** - -* **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[Antibody] -) -> list[Antibody]: -``` - -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:** - -* **population** (`list[Antibody]`): Lista de anticorpos a serem avaliados e clonados. - -**Retorna:** - -* `list[Antibody]`: Lista contendo os clones mutados. - ---- - -## Referências - -
- -> 1. BROWNLEE, Jason. Clonal Selection Algorithm. Clever Algorithms: Nature-inspired Programming Recipes., 2011. -> Available at: diff --git a/docs/pt-br/classes/Clonal Selection Algorithms/README.md b/docs/pt-br/classes/Clonal Selection Algorithms/README.md deleted file mode 100644 index 7ffd57e..0000000 --- a/docs/pt-br/classes/Clonal Selection Algorithms/README.md +++ /dev/null @@ -1,24 +0,0 @@ -# Clonal Selection Algorithm - -Clonal Selection Algorithms são inspirados no processo biológico de proliferação de anticorpos após a detecção de um -antígeno. Durante esse processo, os anticorpos gerados passam por mutações, com o objetivo de melhorar sua capacidade -de reconhecimento do patógeno. - -## classes - -1. **[Artificial Immune Recognition System (AIRS)](AIRS.md)** - -> O objetivo da classe AIRS é realizar classificação utilizando metáforas de seleção e expansão clonal. -> Esta implementação é inspirada no AIRS2, uma versão simplificada do algoritmo original, com adaptações que permitem -> lidar tanto com conjuntos de dados contínuos quanto binários. - -2. **[Clonal Selection Algorithm (CLONALG)](Clonalg.md)** - -> Implementação do algoritmo de seleção clonal para otimização, adaptado -> para minimização e maximização das funções de custo em binário, -> Problemas contínuos e de permutação. ---- - -### Referência - -> BRABAZON, Anthony; O'NEILL, Michael; MCGARRAGHY, Seán. *Natural Computing Algorithms*. Springer Berlin Heidelberg, 2015. DOI: 10.1007/978-3-662-43631-8. Disponível em: [http://dx.doi.org/10.1007/978-3-662-43631-8](http://dx.doi.org/10.1007/978-3-662-43631-8). diff --git a/docs/pt-br/classes/Negative Selection/BNSA.md b/docs/pt-br/classes/Negative Selection/BNSA.md deleted file mode 100644 index ccbdd2e..0000000 --- a/docs/pt-br/classes/Negative Selection/BNSA.md +++ /dev/null @@ -1,111 +0,0 @@ - -# BNSA (Algoritmo de Seleção Negativa Binária) - -Esta classe estende a classe [**Base**](../../advanced-guides/base/classifier.md). - -## Construtor BNSA - -A classe ``BNSA`` tem a finalidade de classificação e identificação de anomalias através do método self e not self. - -**Attributes:** - -* **N** (``int``): Quantidade de detectores. Defaults to ``100``. -* **aff_thresh** (``float``): A variável 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. -* **max_discards** (``int``): Este parâmetro indica o número máximo de descartes de detectores em sequência, cujo 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 ``100``. -* **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. - -### Método `fit(...)` - -A função ``fit(...)`` gera os detectores para os não próprios com relação às amostras: - -```python -def fit( - self, - X: Union[npt.NDArray, list], - y: Union[npt.NDArray, list], - verbose: bool = True, -) -> BNSA: -``` - -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** (`Union[npt.NDArray, list]`): array com as características das amostras com **N** amostras (linhas) e **N** características (colunas), normalizados para valores entre [0, 1]. -* **y** (`Union[npt.NDArray, list]`): array com as classes de saídas disposto em **N** amostras que são relacionadas ao ``X``. -* **verbose** (`bool`): boolean com valor default ``True``, determina se o feedback da geração dos detectores será imprimido. - -**Exceções:** - -* ``TypeError``: Se X ou y não forem ndarrays, ou tiverem formas incompatíveis. -* ``ValueError``: X contém valores que não são compostos apenas por 0 e 1. -* ``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. - -*Retorna a instância da classe.* - ---- - -### Método `predict(...)` - -A função ``predict(...)`` realiza a previsão das classes utilizando os detectores gerados: - -```python -def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: -``` - -**Parâmetros:** - -* **X** (`Union[npt.NDArray, list]`): array com as características para a previsão, com **N** amostras (Linhas) e **N** colunas. - -**Exceções:** - -* `TypeError`: Se X não for um ndarray ou uma lista. -* `FeatureDimensionMismatch`: Se o número de características em X não corresponder ao número esperado. -* `ValueError`: X contém valores que não são compostos apenas por 0 e 1. -* `ModelNotFittedError`: Se o modelo ainda não tiver sido ajustado e não possuir células de memória definidas, não conseguirá realizar predições. - -**Retorna:** - -* ``C``: Um array de previsão com as classes de saída para as características informadas. - ---- - -### Método `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 - -### Método `_assign_class_to_non_self_sample(...)` - -Essa função determina a classe de uma amostra quando todos os detectores a classificam como não-própria. A classificação é realizada utilizando os métodos ``max_average_difference`` ou ``max_nearest_difference``. - -```python -def _assign_class_to_non_self_sample(self, line: npt.NDArray, c: list): -``` - -**Parâmetros:** - -* **line** (``npt.NDArray``): Amostra a ser classificada. -* **c** (``list``): Lista de previsões para atualizar com a nova classificação. - -**Retorna:** - -``npt.NDArray``: A lista de previsões `c` atualizada com a classe atribuída à amostra. diff --git a/docs/pt-br/classes/Negative Selection/README.md b/docs/pt-br/classes/Negative Selection/README.md deleted file mode 100644 index 0efc743..0000000 --- a/docs/pt-br/classes/Negative Selection/README.md +++ /dev/null @@ -1,29 +0,0 @@ -# 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. - -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. - -## 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: . - -##### 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: . - -##### 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: . diff --git a/docs/pt-br/classes/Negative Selection/RNSA.md b/docs/pt-br/classes/Negative Selection/RNSA.md deleted file mode 100644 index 769e325..0000000 --- a/docs/pt-br/classes/Negative Selection/RNSA.md +++ /dev/null @@ -1,217 +0,0 @@ -# RNSA (Algoritmo de Seleção Negativa de Valor Real) - -Esta classe estende a classe [**Base**](../../advanced-guides/base/classifier.md). - -## 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 . - -**Attributes:** - -* **N** (``int``): Quantidade de detectores. Defaults to ``100``. -* **r** (``float``): Raio do detector. Defaults to ``0.05``. -* **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: √((X₁ - X₂)² + (Y₁ - Y₂)² + ... + (Yn - Yn)²). - * ``'minkowski'`` ➜ O cálculo da distância dá-se pela expressão: (|X₁ - Y₁|p + |X₂ - Y₂|p + ... + |Xn - Yn|p) ¹/ₚ, Neste projeto ``p == 2``. - * ``'manhattan'`` ➜ O cálculo da distância dá-se pela expressão: ( |X₁ - X₂| + |Y₁ - Y₂| + ... + |Yn - Yn₂|). - - 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. - -* **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``. - -**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. - ---- - -## Método `fit(...)` - -A função ``fit(...)`` gera os detectores para os não próprios com relação às amostras: - -```python -def fit( - self, - X: Union[npt.NDArray, list], - y: Union[npt.NDArray, list], - verbose: bool = True, -) -> RNSA: -``` - -Nela é realizado o treinamento de acordo com ``X`` e ``y``, usando o método de seleção negativa(``NegativeSelect``). - -**Parâmetros:** - -* **X** (`Union[npt.NDArray, list]`): array com as características das amostras com **N** amostras (linhas) e **N** características (colunas), normalizados para valores entre [0, 1]. -* **y** (`Union[npt.NDArray, list]`): array com as classes de saídas disposto em **N** amostras que são relacionadas ao ``X``. -* **verbose** (`bool`): boolean com valor default ``True``, determina se o feedback da geração dos detectores será impresso. - -**Exceções:** - -* ``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. - -*Retorna a instância da classe.* - ---- - -### Método `predict(...)` - -A função ``predict(...)`` realiza a previsão das classes utilizando os detectores gerados: - -```python -def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: -``` - -**Parâmetros:** - -* **X** (`Union[npt.NDArray, list]`): array com as características para a previsão, com **N** amostras (Linhas) e **N** colunas. - -**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. -* ``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. - - -**Retorna:** - -* C (``npt.NDArray``): Um array de previsão com as classes de saída para as características informadas. - ---- - -### Método `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 - ---- - -### Método `_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_class: npt.NDArray, - vector_x: npt.NDArray -) -> Union[bool, tuple[bool, float]]: -``` - -**Parâmetros:** - -* **X**(`npt.NDArray`): array com as características das amostras com **N** amostras (linhas) e **N** características (colunas), normalizados para valores entre [0, 1]. -* **vector_x**(`npt.NDArray`): Detector candidato gerado aleatoriamente. - -**Retorna:** - -* **Validity** (``bool``): Retorna se o detector é válido ou não. - ---- - -### Método `_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_knearest_neighbors_list(self, knn: list, distance: float) -> None: -``` - -**Parâmetros** -* **knn** (`list`): Lista das distâncias dos k vizinhos mais próximos. -* **distance** (`float`): Distância a ser verificada. - -**Retorna:** uma lista com as distâncias dos k-vizinhos mais próximo. - ---- - -### Método `_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. - -```python -def _compare_sample_to_detectors(self, line: npt.NDArray) -> Optional[str]: -``` - -**Parâmetros:** - -* **line** (`npt.NDArray`): vetor com N-características - -**Retorna:** - -A classe prevista com os detectores ou None se a amostra não se qualificar a nenhuma classe. - ---- - -### Método `_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: float, - vector_x: npt.NDArray -) -> Union[bool, tuple[bool, float]]: -``` - -**Parâmetros:** - -* **distance** (``float``): distância mínima calculada entre todas as amostras. -* **vector_x** (``npt.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. - ---- - -### Método `_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): -``` -**Parameters** -* **u** (`npt.NDArray`): Coordenadas do primeiro ponto. -* **v** (`npt.NDArray`): Coordenadas do segundo ponto. - -**Retorna:** - -Retorna a distância (``float``) entre os dois pontos. diff --git a/docs/pt-br/classes/Network Theory Algorithms/AiNet.md b/docs/pt-br/classes/Network Theory Algorithms/AiNet.md deleted file mode 100644 index cc51379..0000000 --- a/docs/pt-br/classes/Network Theory Algorithms/AiNet.md +++ /dev/null @@ -1,271 +0,0 @@ -# AiNet (Artificial Immune Network) - -Esta classe estende a classe [**Base**](../../advanced-guides/base/clusterer.md). - -## Construtor AiNet - -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. - -Para clustering, pode opcionalmente utilizar uma **Árvore Geradora Mínima (MST)** para separar nós distantes em grupos. - -**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: - - * `'euclidean'` ➜ Distância dada pela expressão: - √( (x₁ - x₂)² + (y₁ - y₂)² + ... + (yn - yn)²). - * `'minkowski'` ➜ Distância dada pela expressão: - ( |X₁ - Y₁|ᵖ + |X₂ - Y₂|ᵖ + ... + |Xn - Yn|ᵖ )^(¹/ₚ). - * `'manhattan'` ➜ Distância dada pela expressão: - ( |x₁ - x₂| + |y₁ - y₂| + ... + |yn - yn|). - 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** (``Optional[npt.NDArray]``): Conjunto atual de anticorpos. -* **_memory_network** (``Dict[int, List[Cell]]``): Dicionário que mapeia clusters para anticorpos. -* **_mst_structure** (``Optional[npt.NDArray]``): Estrutura de adjacência da MST. -* **_mst_mean_distance** (``Optional[float]``): Média das distâncias das arestas da MST. -* **_mst_std_distance** (``Optional[float]``): Desvio padrão das distâncias das arestas da MST. -* **labels** (``Optional[npt.NDArray]``): Lista de rótulos dos clusters. - ---- - -## Métodos Públicos - -### Método `fit(...)` - -Treina o modelo AiNet com os dados de entrada: - -```python -def fit(self, X: Union[npt.NDArray, list], verbose: bool = True) -> AiNet: -``` - -**Parâmetros:** - -* **X** (`Union[npt.NDArray, list]`): Matriz com amostras (linhas) e atributos (colunas). -* **verbose** (`bool`): Booleano, padrão True, habilita feedback de progresso. - -**Exceções** - -* `TypeError`: Se X não for um ndarray ou uma lista. -* `UnsupportedTypeError`: Se o tipo de dados do vetor não for suportado. - -*Retorna a instância da classe.* - ---- - -### Método `predict(...)` - -Prediz os rótulos dos clusters para novas amostras: - -```python -def predict(self, X: Union[npt.NDArray, list]) -> npt.NDArray: -``` - -**Parâmetros:** - -* **X** (`Union[npt.NDArray, list]`): Matriz de atributos de entrada. - -**Exceções** - -* `TypeError`: Se X não for um ndarray ou uma lista. -* `ValueError`: X contém valores que não são compostos apenas por 0 e 1. -* `FeatureDimensionMismatch`: Se o número de características em X não corresponder ao número esperado. -* `ModelNotFittedError`: Se o modelo ainda não tiver sido ajustado e não possuir células de memória definidas, não conseguirá realizar predições. - -**Retorna:** - -* **Predictions**: Matriz de rótulos de clusters, ou None caso o clustering esteja desabilitado. - ---- - -### Método `update_clusters(...)` - -Particiona os clusters utilizando a MST: - -```python -def update_clusters(self, mst_inconsistency_factor: Optional[float] = None): -``` - -**Parâmetros:** - -* **mst_inconsistency_factor** (`Optional[float]`): 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. -* **labels**: Lista de rótulos de clusters. - ---- - -## Métodos Privados - -### Método `_init_population_antibodies(...)` - -Inicializa a população de anticorpos aleatoriamente. - -```python -def _init_population_antibodies(self) -> npt.NDArray: -``` - -**Retorna:** Anticorpos inicializados (`npt.NDArray`). - ---- - -### Método` _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:** - -* **antigen** (`npt.NDArray`): Vetor representando o antígeno para o qual as afinidades serão calculadas. -* **population** (`npt.NDArray`): Matriz de anticorpos a serem avaliados e clonados. - -**Retorna:** Lista de clones mutados. - ---- - -### Método `_clonal_suppression(...)` - -Suprime clones redundantes com base em limiares: - -```python -def _clonal_suppression(self, antigen: npt.NDArray, clones: list): -``` - -**Parâmetros:** - -* **antigen** (`npt.NDArray`): Vetor representando o antígeno. -* **clones** (`list`): Lista de clones candidatos a serem suprimidos. - -**Retorna:** Lista de clones não redundantes e de alta afinidade. - ---- - -### Método `_memory_suppression(...)` - -Remove anticorpos redundantes da memória: - -```python -def _memory_suppression(self, pool_memory: list) -> list: -``` - -**Parâmetros:** - -* **pool_memory** (`list`): Lista de anticorpos atualmente na memória. - -**Retorna:** - -Memória filtrada (`list`). - ---- - -### Método `_diversity_introduction(...)` - -Introduz novos anticorpos para manter a diversidade. - -```python -def _diversity_introduction(self) -> npt.NDArray: -``` - -**Retorna:** Conjunto de novos anticorpos (`npt.NDArray`). - ---- - -### Método `_affinity(...)` - -Calcula o estímulo entre dois vetores: - -```python -def _affinity(self, u: npt.NDArray, v: npt.NDArray) -> float: -``` - -**Parâmetros:** - -* **u** (`npt.NDArray`): Vetor representando o primeiro ponto. -* **v** (`npt.NDArray`): Vetor representando o segundo ponto. - -**Retorna:** Valor de afinidade (`float`) no intervalo [0,1]. - ---- - -### Método `_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:** - -* **u** (`npt.NDArray`): Vetor de referência (`npt.NDArray`) de formato `(n_features,)`. -* **v** (`npt.NDArray`): Vetores-alvo (`npt.NDArray`) de formato `(n_samples, n_features)`. - -**Retorna:** Vetor de afinidades (`npt.NDArray`) com formato `(n_samples,)`. - ---- - -### Método `_clone_and_mutate(...)` - -Gera clones mutados: - -```python -def _clone_and_mutate(self, antibody: npt.NDArray, n_clone: int) -> npt.NDArray: -``` - -**Parâmetros:** - -* **antibody** (`npt.NDArray`): Vetor de anticorpo original a ser clonado e mutado. -* **n_clone** (`int`): Número de clones a serem gerados. - -**Retorna:** Matriz de clones mutados (`npt.NDArray`) de formato `(n_clone, len(antibody))`. - ---- - -### Método `_build_mst(...)` - -Constrói a MST e armazena estatísticas: - -```python -def _build_mst(self): -``` - -**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. De Castro, Leandro & José, Fernando & von Zuben, Antonio Augusto. (2001). aiNet: An Artificial Immune Network for Data Analysis. -> 2. 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. 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/docs/pt-br/classes/Network Theory Algorithms/README.md b/docs/pt-br/classes/Network Theory Algorithms/README.md deleted file mode 100644 index 4faa031..0000000 --- a/docs/pt-br/classes/Network Theory Algorithms/README.md +++ /dev/null @@ -1,16 +0,0 @@ -# Immune Network Theory - -Esta técnica foi introduzida por **Niels Jerne (1974)** e modela o sistema imunológico como uma rede dinâmica, -na qual as células e moléculas, capazes de reconhecer umas às outras. - -## Classes - -1. **[AiNet](AiNet.md)** - -> Rede Imune Artificial para tarefas de clustering e compressão não-supervisionada. - ---- - -## Referências - -> BRABAZON, Anthony; O'NEILL, Michael; MCGARRAGHY, Seán. *Natural Computing Algorithms*. Springer Berlin Heidelberg, 2015. DOI: 10.1007/978-3-662-43631-8. Disponível em: [http://dx.doi.org/10.1007/978-3-662-43631-8](http://dx.doi.org/10.1007/978-3-662-43631-8). diff --git a/docs/pt-br/index.md b/docs/pt-br/index.md deleted file mode 100644 index a8cddb4..0000000 --- a/docs/pt-br/index.md +++ /dev/null @@ -1,10 +0,0 @@ -##

**ÍNDICE**

- ---- - -### Classe do módulo: - -> 1. [**Seleção negativa**](classes/Negative%20Selection/README.md) -> 2. **Teoria do Perigo** -> 3. [**Algoritmo de Seleção Clonal.**](classes/Clonal%20Selection%20Algorithms/README.md) -> 4. [**Teoria da Rede Imune**](classes/Network%20Theory%20Algorithms/README.md) \ No newline at end of file diff --git a/pyproject.toml b/pyproject.toml index a46c054..81fb952 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -5,7 +5,7 @@ build-backend = "setuptools.build_meta" [project] name = "aisp" -version = "0.5.3" +version = "0.5.4" authors = [ { name="João Paulo da Silva Barros", email="jpsilvabarr@gmail.com" }, ]