aisp 0.1.41__tar.gz → 0.1.42__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: aisp
3
- Version: 0.1.41
3
+ Version: 0.1.42
4
4
  Summary: Package with techniques of artificial immune systems.
5
5
  Author-email: João Paulo da Silva Barros <jpsilvabarr@gmail.com>
6
6
  Maintainer-email: Alison Zille Lopes <alisonzille@gmail.com>
@@ -0,0 +1,4 @@
1
+ """Artificial Immune Systems Package."""
2
+
3
+ __author__ = "João Paulo da Silva Barros"
4
+ __version__ = "0.1.42"
@@ -1,4 +1,5 @@
1
1
  """Base class modules."""
2
+
2
3
  from ._classifier import BaseClassifier
3
4
 
4
5
  __all__ = ['BaseClassifier']
@@ -0,0 +1,116 @@
1
+ """Base class for classification algorithm."""
2
+
3
+ from abc import ABC, abstractmethod
4
+ from typing import Optional, Union
5
+
6
+ import numpy.typing as npt
7
+
8
+ from ..utils import slice_index_list_by_class
9
+ from ..utils.metrics import accuracy_score
10
+
11
+
12
+ class BaseClassifier(ABC):
13
+ """Base class for classification algorithms.
14
+
15
+ Defines the abstract methods ``fit`` and ``predict``, and implements the ``score``,
16
+ ``get_params`` method.
17
+ """
18
+
19
+ classes: Optional[Union[npt.NDArray, list]] = None
20
+
21
+ @abstractmethod
22
+ def fit(self, X: npt.NDArray, y: npt.NDArray, verbose: bool = True):
23
+ """
24
+ Train the model using the input data X and corresponding labels y.
25
+
26
+ This abstract method is implemented by the class that inherits it.
27
+
28
+ Parameters
29
+ ----------
30
+ X : npt.NDArray
31
+ Input data used for training the model.
32
+ y : npt.NDArray
33
+ Corresponding labels or target values for the input data.
34
+ verbose : bool, default=True
35
+ Flag to enable or disable detailed output during training.
36
+
37
+ Returns
38
+ -------
39
+ self : BaseClassifier
40
+ Returns the instance of the class that implements this method.
41
+ """
42
+
43
+ @abstractmethod
44
+ def predict(self, X) -> Optional[npt.NDArray]:
45
+ """
46
+ Generate predictions based on the input data X.
47
+
48
+ This abstract method is implemented by the class that inherits it.
49
+
50
+ Parameters
51
+ ----------
52
+ X : npt.NDArray
53
+ Input data for which predictions will be generated.
54
+
55
+ Returns
56
+ -------
57
+ Predictions : Optional[npt.NDArray]
58
+ Predicted values for each input sample, or ``None`` if the prediction fails.
59
+ """
60
+
61
+ def score(self, X: npt.NDArray, y: list) -> float:
62
+ """
63
+ Score function calculates forecast accuracy.
64
+
65
+ Details
66
+ -------
67
+ This function performs the prediction of X and checks how many elements are equal
68
+ between vector y and y_predicted. This function was added for compatibility with some
69
+ scikit-learn functions.
70
+
71
+ Parameters
72
+ ----------
73
+ X : np.ndarray
74
+ Feature set with shape (n_samples, n_features).
75
+ y : np.ndarray
76
+ True values with shape (n_samples,).
77
+
78
+ Returns
79
+ -------
80
+ accuracy : float
81
+ The accuracy of the model.
82
+ """
83
+ if len(y) == 0:
84
+ return 0
85
+ y_pred = self.predict(X)
86
+ return accuracy_score(y, y_pred)
87
+
88
+ def _slice_index_list_by_class(self, y: npt.NDArray) -> dict:
89
+ """Separate the indices of the lines according to the output class.
90
+
91
+ Loop through the sample array only in positions where the output matches the class
92
+ being trained.
93
+
94
+ Parameters
95
+ ----------
96
+ y : npt.NDArray
97
+ Receives a y [``N sample``] array with the output classes of the ``X`` sample array.
98
+
99
+ Returns
100
+ -------
101
+ dict: dict
102
+ A dictionary with the list of array positions(``y``), with the classes as key.
103
+ """
104
+ return slice_index_list_by_class(self.classes, y)
105
+
106
+ def get_params(self, deep: bool = True) -> dict: # pylint: disable=W0613
107
+ """
108
+ Return a dictionary with the object's main parameters.
109
+
110
+ This method is required to ensure compatibility with scikit-learn functions.
111
+ """
112
+ return {
113
+ key: value
114
+ for key, value in self.__dict__.items()
115
+ if not key.startswith("_")
116
+ }
@@ -1,4 +1,4 @@
1
- """Custom warnings and errors"""
1
+ """Custom warnings and errors."""
2
2
 
3
3
 
4
4
  class MaxDiscardsReachedError(Exception):
@@ -17,16 +17,17 @@ class MaxDiscardsReachedError(Exception):
17
17
 
18
18
 
19
19
  class FeatureDimensionMismatch(Exception):
20
- """
21
- Exception raised when the number of input features does not match the expected number
22
- required by the model for prediction
20
+ """
21
+ Exception raised when the number of input features does not match the expected number.
22
+
23
+ This exception is triggered during prediction if the input features' dimension is incorrect.
23
24
  """
24
25
 
25
26
  def __init__(
26
- self,
27
- expected: int,
28
- received: int,
29
- variable_name: str = None
27
+ self,
28
+ expected: int,
29
+ received: int,
30
+ variable_name: str = None
30
31
  ):
31
32
  parts = []
32
33
  if variable_name:
@@ -1,11 +1,11 @@
1
- """nsa: Module (NSA) Negative Selection Algorithm
1
+ """Module (NSA) Negative Selection Algorithm.
2
2
 
3
3
  NSAs simulate the maturation process of T-cells in the immune system, where these cells learn to
4
4
  distinguish between self and non-self. Only T-cells capable of recognizing non-self elements are
5
5
  preserved.
6
6
  """
7
+
7
8
  from ._negative_selection import BNSA, RNSA
8
9
 
9
10
  __author__ = "João Paulo da Silva Barros"
10
11
  __all__ = ["RNSA", "BNSA"]
11
- __version__ = "0.1.40"
@@ -13,8 +13,9 @@ from ..exceptions import FeatureDimensionMismatch
13
13
 
14
14
  class BaseNSA(BaseClassifier, ABC):
15
15
  """
16
- The base class contains functions that are used by more than one class in the package, and
17
- therefore are considered essential for the overall functioning of the system.
16
+ Base class containing functions used by multiple classes in the package.
17
+
18
+ These functions are essential for the overall functioning of the system.
18
19
  """
19
20
 
20
21
  @staticmethod
@@ -23,22 +24,26 @@ class BaseNSA(BaseClassifier, ABC):
23
24
  y: npt.NDArray = None,
24
25
  _class_: Literal["RNSA", "BNSA"] = "RNSA",
25
26
  ) -> None:
26
- """
27
- Function responsible for verifying fit function parameters and throwing exceptions if the
28
- verification is not successful.
27
+ """Verify fit function parameters.
28
+
29
+ Throw exceptions if the verification fails.
29
30
 
30
31
  Parameters
31
32
  ----------
32
- * X (``npt.NDArray``) Training array, containing the samples and their
33
- characteristics, [``N samples`` (rows)][``N features`` (columns)].
34
- * y (``npt.NDArray``) Array of target classes of ``X`` with [``N samples`` (lines)].
35
- * _class_ (``Literal[RNSA, BNSA], optional``) Current class. Defaults to 'RNSA'.
33
+ * X : npt.NDArray
34
+ Training array, containing the samples and their characteristics, [``N samples`` (
35
+ rows)][``N features`` (columns)].
36
+ * y : npt.NDArray
37
+ Array of target classes of ``X`` with [``N samples`` (lines)].
38
+ * _class_ : Literal[RNSA, BNSA], default="RNSA"
39
+ Current class.
36
40
 
37
41
  Raises
38
- ----------
39
- * TypeError: If X or y are not ndarrays or have incompatible shapes.
40
- * ValueError: If _class_ is BNSA and X contains values that are not composed only of
41
- 0 and 1.
42
+ ------
43
+ TypeError
44
+ If X or y are not ndarrays or have incompatible shapes.
45
+ ValueError
46
+ If _class_ is BNSA and X contains values that are not composed only of 0 and 1.
42
47
  """
43
48
  if isinstance(X, list):
44
49
  X = np.array(X)
@@ -66,27 +71,28 @@ class BaseNSA(BaseClassifier, ABC):
66
71
  expected: int = 0,
67
72
  _class_: Literal["RNSA", "BNSA"] = "RNSA",
68
73
  ) -> None:
69
- """
70
- Function responsible for verifying predict function parameters and throwing exceptions if
71
- the verification is not successful.
74
+ """Verify predict function parameters.
75
+
76
+ Throw exceptions if the verification fails.
72
77
 
73
78
  Parameters
74
79
  ----------
75
- * X (``npt.NDArray``)
80
+ X : npt.NDArray
76
81
  Input array for prediction, containing the samples and their characteristics,
77
82
  [``N samples`` (rows)][``N features`` (columns)].
78
- * expected (``int``)
83
+ expected : int
79
84
  Expected number of features per sample (columns in X).
80
- * _class_ (``Literal[RNSA, BNSA], optional``)
85
+ _class_ : Literal[RNSA, BNSA], default="RNSA"
81
86
  Current class. Defaults to 'RNSA'.
82
87
 
83
88
  Raises
84
- ----------
85
- * TypeError: If X is not an ndarray or list.
86
- * FeatureDimensionMismatch: If the number of features in X does not match the expected
87
- number.
88
- * ValueError: If _class_ is BNSA and X contains values that are not composed only of 0
89
- and 1.
89
+ ------
90
+ TypeError
91
+ If X is not an numpy.ndarray or list.
92
+ FeatureDimensionMismatch
93
+ If the number of features in X does not match the expected number.
94
+ ValueError
95
+ If _class_ is BNSA and X contains values that are not composed only of 0 and 1.
90
96
  """
91
97
  if not isinstance(X, (np.ndarray, list)):
92
98
  raise TypeError("X is not an ndarray or list")
@@ -110,8 +116,10 @@ class Detector:
110
116
 
111
117
  Attributes
112
118
  ----------
113
- * position (``npt.NDArray[np.float64]``): Detector feature vector.
114
- * radius (``float, optional``): Detector radius, used in the V-detector algorithm.
119
+ position : npt.NDArray[np.float64]
120
+ Detector feature vector.
121
+ radius : float, optional
122
+ Detector radius, used in the V-detector algorithm.
115
123
  """
116
124
 
117
125
  position: npt.NDArray[np.float64]