aisp 0.1.35__tar.gz → 0.1.41__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.35
3
+ Version: 0.1.41
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>
@@ -9,18 +9,21 @@ Project-URL: Homepage, https://ais-package.github.io/
9
9
  Project-URL: Documentation, https://ais-package.github.io/docs/intro
10
10
  Project-URL: Source Code, https://github.com/AIS-Package/aisp
11
11
  Project-URL: Tracker, https://github.com/AIS-Package/aisp/issues
12
- Keywords: Artificial Immune Systems,classification,Natural computing,machine learning,artificial intelligence
12
+ Keywords: Artificial Immune Systems,classification,Natural computing,machine learning,artificial intelligence,AIS
13
13
  Classifier: Operating System :: OS Independent
14
14
  Classifier: Programming Language :: Python
15
15
  Classifier: Programming Language :: Python :: 3
16
- Classifier: Programming Language :: Python :: 3.8
17
- Classifier: Programming Language :: Python :: 3.9
18
16
  Classifier: Programming Language :: Python :: 3.10
19
17
  Classifier: Programming Language :: Python :: 3.11
20
- Requires-Python: >=3.8.10
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
21
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
22
+ Requires-Python: >=3.10
21
23
  Description-Content-Type: text/markdown
22
24
  License-File: LICENSE
23
25
  Requires-Dist: numpy>=1.22.4
26
+ Requires-Dist: numba>=0.59.0
24
27
  Requires-Dist: scipy>=1.8.1
25
28
  Requires-Dist: tqdm>=4.64.1
26
29
  Dynamic: license-file
@@ -86,7 +89,7 @@ Artificial Immune Systems (AIS) are inspired by the vertebrate immune system, cr
86
89
 
87
90
  #### **Installation**
88
91
 
89
- The module requires installation of [python 3.8.10](https://www.python.org/downloads/) or higher.
92
+ The module requires installation of [python 3.10](https://www.python.org/downloads/) or higher.
90
93
 
91
94
  <section id='dependencies'>
92
95
 
@@ -99,6 +102,7 @@ The module requires installation of [python 3.8.10](https://www.python.org/downl
99
102
  | numpy | ≥ 1.22.4 |
100
103
  | scipy | ≥ 1.8.1 |
101
104
  | tqdm | ≥ 4.64.1 |
105
+ | numba | ≥ 0.59.0 |
102
106
 
103
107
  </div>
104
108
 
@@ -59,7 +59,7 @@ Artificial Immune Systems (AIS) are inspired by the vertebrate immune system, cr
59
59
 
60
60
  #### **Installation**
61
61
 
62
- The module requires installation of [python 3.8.10](https://www.python.org/downloads/) or higher.
62
+ The module requires installation of [python 3.10](https://www.python.org/downloads/) or higher.
63
63
 
64
64
  <section id='dependencies'>
65
65
 
@@ -72,6 +72,7 @@ The module requires installation of [python 3.8.10](https://www.python.org/downl
72
72
  | numpy | ≥ 1.22.4 |
73
73
  | scipy | ≥ 1.8.1 |
74
74
  | tqdm | ≥ 4.64.1 |
75
+ | numba | ≥ 0.59.0 |
75
76
 
76
77
  </div>
77
78
 
@@ -1,4 +1,4 @@
1
1
  """Artificial Immune Systems Package"""
2
2
 
3
3
  __author__ = "João Paulo da Silva Barros"
4
- __version__ = "0.1.35"
4
+ __version__ = "0.1.40"
@@ -0,0 +1,4 @@
1
+ """Base class modules."""
2
+ from ._classifier import BaseClassifier
3
+
4
+ __all__ = ['BaseClassifier']
@@ -0,0 +1,110 @@
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
+ """
14
+ Base class for classification algorithms, defining the abstract methods ``fit`` and ``predict``,
15
+ and implementing the ``get_params`` method.
16
+ """
17
+
18
+ classes: Optional[Union[npt.NDArray, list]] = None
19
+
20
+ @abstractmethod
21
+ def fit(self, X: npt.NDArray, y: npt.NDArray, verbose: bool = True):
22
+ """
23
+ Function to train the model using the input data ``X`` and corresponding labels ``y``.
24
+
25
+ This abstract method is implemented by the class that inherits it.
26
+
27
+ Parameters
28
+ ----------
29
+ * X (``npt.NDArray``): Input data used for training the model, previously normalized to the
30
+ range [0, 1].
31
+ * y (``npt.NDArray``): Corresponding labels or target values for the input data.
32
+ * verbose (``bool``, optional): Flag to enable or disable detailed output during training.
33
+ Default is ``True``.
34
+
35
+ Returns
36
+ ----------
37
+ * self: Returns the instance of the class that implements this method.
38
+ """
39
+
40
+ @abstractmethod
41
+ def predict(self, X) -> Optional[npt.NDArray]:
42
+ """
43
+ Function to generate predictions based on the input data ``X``.
44
+
45
+ This abstract method is implemented by the class that inherits it.
46
+
47
+ Parameters
48
+ ----------
49
+ * X (``npt.NDArray``): Input data for which predictions will be generated.
50
+
51
+ Returns
52
+ ----------
53
+ * Predictions (``Optional[npt.NDArray]``): Predicted values for each input sample, or
54
+ ``None`` if the prediction fails.
55
+ """
56
+
57
+ def score(self, X: npt.NDArray, y: list) -> float:
58
+ """
59
+ Score function calculates forecast accuracy.
60
+
61
+ Details
62
+ ----------
63
+ This function performs the prediction of X and checks how many elements are equal
64
+ between vector y and y_predicted. This function was added for compatibility with some
65
+ scikit-learn functions.
66
+
67
+ Parameters
68
+ ----------
69
+ * X (``np.ndarray``):
70
+ Feature set with shape (n_samples, n_features).
71
+ * y (``np.ndarray``):
72
+ True values with shape (n_samples,).
73
+
74
+ Returns
75
+ ----------
76
+ * accuracy (``float``): The accuracy of the model.
77
+ """
78
+ if len(y) == 0:
79
+ return 0
80
+ y_pred = self.predict(X)
81
+ return accuracy_score(y, y_pred)
82
+
83
+ def _slice_index_list_by_class(self, y: npt.NDArray) -> dict:
84
+ """
85
+ The function ``_slice_index_list_by_class(...)``, separates the indices of the lines \
86
+ according to the output class, to loop through the sample array, only in positions where \
87
+ the output is the class being trained.
88
+
89
+ Parameters
90
+ ----------
91
+ * y (npt.NDArray): Receives a ``y``[``N sample``] array with the output classes of the \
92
+ ``X`` sample array.
93
+
94
+ returns
95
+ ----------
96
+ * dict: A dictionary with the list of array positions(``y``), with the classes as key.
97
+ """
98
+ return slice_index_list_by_class(self.classes, y)
99
+
100
+ def get_params(self, deep: bool = True) -> dict: # pylint: disable=W0613
101
+ """
102
+ The get_params function Returns a dictionary with the object's main parameters.
103
+
104
+ This function is required to ensure compatibility with scikit-learn functions.
105
+ """
106
+ return {
107
+ key: value
108
+ for key, value in self.__dict__.items()
109
+ if not key.startswith("_")
110
+ }
@@ -8,4 +8,4 @@ from ._negative_selection import BNSA, RNSA
8
8
 
9
9
  __author__ = "João Paulo da Silva Barros"
10
10
  __all__ = ["RNSA", "BNSA"]
11
- __version__ = "0.1.35"
11
+ __version__ = "0.1.40"
@@ -0,0 +1,118 @@
1
+ """Base Class for Negative Selection Algorithm."""
2
+
3
+ from abc import ABC
4
+ from dataclasses import dataclass
5
+ from typing import Literal, Optional
6
+
7
+ import numpy as np
8
+ import numpy.typing as npt
9
+
10
+ from ..base import BaseClassifier
11
+ from ..exceptions import FeatureDimensionMismatch
12
+
13
+
14
+ class BaseNSA(BaseClassifier, ABC):
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.
18
+ """
19
+
20
+ @staticmethod
21
+ def _check_and_raise_exceptions_fit(
22
+ X: npt.NDArray = None,
23
+ y: npt.NDArray = None,
24
+ _class_: Literal["RNSA", "BNSA"] = "RNSA",
25
+ ) -> None:
26
+ """
27
+ Function responsible for verifying fit function parameters and throwing exceptions if the
28
+ verification is not successful.
29
+
30
+ Parameters
31
+ ----------
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'.
36
+
37
+ 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
+ if isinstance(X, list):
44
+ X = np.array(X)
45
+ if isinstance(y, list):
46
+ y = np.array(y)
47
+
48
+ if not isinstance(X, np.ndarray):
49
+ raise TypeError("X is not an ndarray or list.")
50
+ if not isinstance(y, np.ndarray):
51
+ raise TypeError("y is not an ndarray or list.")
52
+
53
+ if X.shape[0] != y.shape[0]:
54
+ raise TypeError(
55
+ "X does not have the same amount of sample for the output classes in y."
56
+ )
57
+
58
+ if _class_ == "BNSA" and not np.isin(X, [0, 1]).all():
59
+ raise ValueError(
60
+ "The array X contains values that are not composed only of 0 and 1."
61
+ )
62
+
63
+ @staticmethod
64
+ def _check_and_raise_exceptions_predict(
65
+ X: npt.NDArray = None,
66
+ expected: int = 0,
67
+ _class_: Literal["RNSA", "BNSA"] = "RNSA",
68
+ ) -> None:
69
+ """
70
+ Function responsible for verifying predict function parameters and throwing exceptions if
71
+ the verification is not successful.
72
+
73
+ Parameters
74
+ ----------
75
+ * X (``npt.NDArray``)
76
+ Input array for prediction, containing the samples and their characteristics,
77
+ [``N samples`` (rows)][``N features`` (columns)].
78
+ * expected (``int``)
79
+ Expected number of features per sample (columns in X).
80
+ * _class_ (``Literal[RNSA, BNSA], optional``)
81
+ Current class. Defaults to 'RNSA'.
82
+
83
+ 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.
90
+ """
91
+ if not isinstance(X, (np.ndarray, list)):
92
+ raise TypeError("X is not an ndarray or list")
93
+ if expected != len(X[0]):
94
+ raise FeatureDimensionMismatch(expected, len(X[0]), "X")
95
+
96
+ if _class_ != "BNSA":
97
+ return
98
+
99
+ # Checks if matrix X contains only binary samples. Otherwise, raises an exception.
100
+ if not np.isin(X, [0, 1]).all():
101
+ raise ValueError(
102
+ "The array X contains values that are not composed only of 0 and 1."
103
+ )
104
+
105
+
106
+ @dataclass(slots=True)
107
+ class Detector:
108
+ """
109
+ Represents a non-self detector of the RNSA class.
110
+
111
+ Attributes
112
+ ----------
113
+ * position (``npt.NDArray[np.float64]``): Detector feature vector.
114
+ * radius (``float, optional``): Detector radius, used in the V-detector algorithm.
115
+ """
116
+
117
+ position: npt.NDArray[np.float64]
118
+ radius: Optional[float] = None