aisp 0.1.21__py3-none-any.whl → 0.1.31__py3-none-any.whl
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.
- aisp/NSA/__init__.py +4 -4
- aisp/{_base.py → NSA/_base.py} +93 -61
- aisp/NSA/{_negativeSelection.py → _negative_selection.py} +395 -280
- {aisp-0.1.21.dist-info → aisp-0.1.31.dist-info}/METADATA +4 -4
- aisp-0.1.31.dist-info/RECORD +8 -0
- {aisp-0.1.21.dist-info → aisp-0.1.31.dist-info}/WHEEL +1 -1
- aisp-0.1.21.dist-info/RECORD +0 -8
- {aisp-0.1.21.dist-info → aisp-0.1.31.dist-info}/LICENSE +0 -0
- {aisp-0.1.21.dist-info → aisp-0.1.31.dist-info}/top_level.txt +0 -0
aisp/NSA/__init__.py
CHANGED
@@ -1,5 +1,5 @@
|
|
1
|
-
from .
|
1
|
+
from ._negative_selection import BNSA, RNSA
|
2
2
|
|
3
|
-
__author__ =
|
4
|
-
__all__ = [
|
5
|
-
__version__ =
|
3
|
+
__author__ = "João Paulo da Silva Barros"
|
4
|
+
__all__ = ["RNSA", "BNSA"]
|
5
|
+
__version__ = "0.1.31"
|
aisp/{_base.py → NSA/_base.py}
RENAMED
@@ -3,30 +3,36 @@ import numpy.typing as npt
|
|
3
3
|
from typing import Literal
|
4
4
|
from scipy.spatial.distance import euclidean, cityblock, minkowski
|
5
5
|
|
6
|
+
|
6
7
|
class Base:
|
7
8
|
"""
|
8
|
-
The base class contains functions that are used by more than one class in the package,
|
9
|
-
|
9
|
+
The base class contains functions that are used by more than one class in the package, and \
|
10
|
+
therefore are considered essential for the overall functioning of the system.
|
10
11
|
|
11
12
|
---
|
12
13
|
|
13
|
-
A classe base contém funções que são utilizadas por mais de uma classe do pacote,
|
14
|
-
|
14
|
+
A classe base contém funções que são utilizadas por mais de uma classe do pacote, e por isso \
|
15
|
+
são consideradas essenciais para o funcionamento geral do sistema.
|
15
16
|
"""
|
16
|
-
|
17
|
+
|
18
|
+
def __init__(self, metric: str = "euclidean", p: float = 2):
|
17
19
|
"""
|
18
20
|
Parameters:
|
19
21
|
---
|
20
22
|
* metric (``str``): Way to calculate the distance between the detector and the sample:
|
21
23
|
|
22
|
-
* ``'Euclidean'`` ➜ The calculation of the distance is given by the expression:
|
23
|
-
|
24
|
-
* ``'
|
25
|
-
|
26
|
-
|
27
|
-
|
28
|
-
|
29
|
-
|
24
|
+
* ``'Euclidean'`` ➜ The calculation of the distance is given by the expression: \
|
25
|
+
√( (x₁ – x₂)² + (y₁ – y₂)² + ... + (yn – yn)²).
|
26
|
+
* ``'minkowski'`` ➜ The calculation of the distance is given by the expression: \
|
27
|
+
( |X₁ – Y₁|p + |X₂ – Y₂|p + ... + |Xn – Yn|p) ¹/ₚ.
|
28
|
+
* ``'manhattan'`` ➜ The calculation of the distance is given by the expression: \
|
29
|
+
( |x₁ – x₂| + |y₁ – y₂| + ... + |yn – yn|) .
|
30
|
+
|
31
|
+
|
32
|
+
* p (``float``): This parameter stores the value of ``p`` used in the Minkowski distance.\
|
33
|
+
The default is ``2``, which represents normalized Euclidean distance. Different \
|
34
|
+
values of p lead to different variants of the Minkowski distance \
|
35
|
+
[learn more](https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.minkowski.html).
|
30
36
|
|
31
37
|
---
|
32
38
|
|
@@ -34,20 +40,24 @@ class Base:
|
|
34
40
|
---
|
35
41
|
* metric (``str``): Forma para se calcular a distância entre o detector e a amostra:
|
36
42
|
|
37
|
-
* ``'euclidiana'`` ➜ O cálculo da distância dá-se pela expressão:
|
38
|
-
|
39
|
-
* ``'
|
43
|
+
* ``'euclidiana'`` ➜ O cálculo da distância dá-se pela expressão: \
|
44
|
+
√( (x₁ – x₂)² + (y₁ – y₂)² + ... + (yn – yn)²).
|
45
|
+
* ``'minkowski'`` ➜ O cálculo da distância dá-se pela expressão: \
|
46
|
+
( |X₁ – Y₁|p + |X₂ – Y₂|p + ... + |Xn – Yn|p).
|
47
|
+
* ``'manhattan'`` ➜ O cálculo da distância dá-se pela expressão: \
|
48
|
+
( |x₁ – x₂| + |y₁ – y₂| + ... + |yn – yn|).
|
40
49
|
|
41
50
|
Defaults to ``'euclidean'``.
|
42
|
-
|
43
|
-
* p (``float``): Este parâmetro armazena o valor de ``p`` utilizada na distância de Minkowski.
|
44
|
-
|
45
|
-
|
51
|
+
|
52
|
+
* p (``float``): Este parâmetro armazena o valor de ``p`` utilizada na distância de Minkowski. \
|
53
|
+
O padrão é ``2``, o que significa distância euclidiana normalizada. Diferentes valores \
|
54
|
+
de p levam a diferentes variantes da distância de Minkowski \
|
55
|
+
[saiba mais](https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.minkowski.html).
|
46
56
|
"""
|
47
|
-
if metric ==
|
57
|
+
if metric == "manhattan" or metric == "minkowski":
|
48
58
|
self.metric: str = metric
|
49
59
|
else:
|
50
|
-
self.metric: str =
|
60
|
+
self.metric: str = "euclidean"
|
51
61
|
self.p: float = p
|
52
62
|
|
53
63
|
def _distance(self, u: npt.NDArray, v: npt.NDArray):
|
@@ -76,61 +86,79 @@ class Base:
|
|
76
86
|
---
|
77
87
|
* Distância (``double``) entre os dois pontos.
|
78
88
|
"""
|
79
|
-
if self.metric ==
|
89
|
+
if self.metric == "manhattan":
|
80
90
|
return cityblock(u, v)
|
81
|
-
elif self.metric ==
|
91
|
+
elif self.metric == "minkowski":
|
82
92
|
return minkowski(u, v, self.p)
|
83
93
|
else:
|
84
94
|
return euclidean(u, v)
|
85
|
-
|
86
|
-
def _check_and_raise_exceptions_fit(self, X: npt.NDArray = None, y: npt.NDArray = None,
|
95
|
+
|
96
|
+
def _check_and_raise_exceptions_fit(self, X: npt.NDArray = None, y: npt.NDArray = None,
|
97
|
+
_class_: Literal["RNSA", "BNSA"] = "RNSA",
|
98
|
+
):
|
87
99
|
"""
|
88
|
-
Function responsible for verifying fit function parameters and throwing exceptions if the
|
100
|
+
Function responsible for verifying fit function parameters and throwing exceptions if the \
|
101
|
+
verification is not successful.
|
89
102
|
|
90
103
|
Parameters:
|
91
104
|
---
|
92
|
-
|
93
|
-
|
105
|
+
* X (``npt.NDArray``): Training array, containing the samples and their characteristics, \
|
106
|
+
[``N samples`` (rows)][``N features`` (columns)].
|
94
107
|
* y (``npt.NDArray``): Array of target classes of ``X`` with [``N samples`` (lines)].
|
95
108
|
* _class_ (Literal[RNSA, BNSA], optional): Current class. Defaults to 'RNSA'.
|
96
109
|
|
110
|
+
Raises:
|
97
111
|
---
|
112
|
+
* TypeError: If X or y are not ndarrays or have incompatible shapes.
|
113
|
+
* ValueError: If _class_ is BNSA and X contains values that are not composed only of 0 and 1.
|
98
114
|
|
99
|
-
|
115
|
+
---
|
100
116
|
|
101
|
-
|
102
|
-
|
103
|
-
|
104
|
-
|
105
|
-
|
106
|
-
|
117
|
+
Função responsável por verificar os parâmetros da função fit e lançar exceções se a \
|
118
|
+
verificação não for bem-sucedida.
|
119
|
+
|
120
|
+
Parâmetros:
|
121
|
+
---
|
122
|
+
* X (``npt.NDArray``): Array de treinamento, contendo as amostras e suas características, \
|
123
|
+
[``N samples`` (linhas)][``N features`` (colunas)].
|
124
|
+
* y (``npt.NDArray``): Array de classes alvo de ``X`` com [``N samples`` (linhas)].
|
125
|
+
* _class_ (Literal[RNSA, BNSA], opcional): Classe atual. O padrão é 'RNSA'.
|
126
|
+
|
127
|
+
Lança:
|
128
|
+
---
|
129
|
+
* TypeError: Se X ou y não forem ndarrays ou tiverem formas incompatíveis.
|
130
|
+
* ValueError: Se _class_ for BNSA e X contiver valores que não sejam compostos apenas por 0 e 1.
|
107
131
|
"""
|
108
|
-
if not isinstance(X,
|
109
|
-
if isinstance(X,
|
132
|
+
if not isinstance(X, np.ndarray):
|
133
|
+
if isinstance(X, list):
|
110
134
|
X = np.array(X)
|
111
135
|
else:
|
112
|
-
raise TypeError("X is not an ndarray.")
|
113
|
-
elif not isinstance(y,
|
114
|
-
if isinstance(y,
|
136
|
+
raise TypeError("X is not an ndarray or list.")
|
137
|
+
elif not isinstance(y, np.ndarray):
|
138
|
+
if isinstance(y, list):
|
115
139
|
y = np.array(y)
|
116
140
|
else:
|
117
|
-
raise TypeError("y is not an ndarray.")
|
141
|
+
raise TypeError("y is not an ndarray or list.")
|
118
142
|
if X.shape[0] != y.shape[0]:
|
119
143
|
raise TypeError(
|
120
|
-
"X does not have the same amount of sample for the output classes in y."
|
121
|
-
|
122
|
-
|
144
|
+
"X does not have the same amount of sample for the output classes in y."
|
145
|
+
)
|
146
|
+
|
147
|
+
if _class_ == "BNSA" and not np.isin(X, [0, 1]).all():
|
123
148
|
raise ValueError(
|
124
|
-
"The array X contains values that are not composed only of 0 and 1."
|
149
|
+
"The array X contains values that are not composed only of 0 and 1."
|
150
|
+
)
|
125
151
|
|
126
152
|
def _slice_index_list_by_class(self, y: npt.NDArray) -> dict:
|
127
153
|
"""
|
128
|
-
The function ``__slice_index_list_by_class(...)``, separates the indices of the lines
|
129
|
-
to loop through the sample array, only in positions where
|
154
|
+
The function ``__slice_index_list_by_class(...)``, separates the indices of the lines \
|
155
|
+
according to the output class, to loop through the sample array, only in positions where \
|
156
|
+
the output is the class being trained.
|
130
157
|
|
131
158
|
Parameters:
|
132
159
|
---
|
133
|
-
* y (npt.NDArray): Receives a ``y``[``N sample``] array with the output classes of the
|
160
|
+
* y (npt.NDArray): Receives a ``y``[``N sample``] array with the output classes of the \
|
161
|
+
``X`` sample array.
|
134
162
|
|
135
163
|
returns:
|
136
164
|
---
|
@@ -138,32 +166,35 @@ class Base:
|
|
138
166
|
|
139
167
|
---
|
140
168
|
|
141
|
-
A função ``__slice_index_list_by_class(...)``, separa os índices das linhas conforme a
|
142
|
-
para percorrer o array de amostra, apenas nas posições que a saída for
|
169
|
+
A função ``__slice_index_list_by_class(...)``, separa os índices das linhas conforme a \
|
170
|
+
classe de saída, para percorrer o array de amostra, apenas nas posições que a saída for \
|
171
|
+
a classe que está sendo treinada.
|
143
172
|
|
144
173
|
Parameters:
|
145
174
|
---
|
146
|
-
* y (npt.NDArray): Recebe um array ``y``[``N amostra``] com as classes de
|
175
|
+
* y (npt.NDArray): Recebe um array ``y``[``N amostra``] com as classes de saída do \
|
176
|
+
array de amostra ``X``.
|
147
177
|
|
148
178
|
Returns:
|
149
179
|
---
|
150
180
|
* dict: Um dicionário com a lista de posições do array(``y``), com as classes como chave.
|
151
181
|
"""
|
152
|
-
|
182
|
+
position_samples = dict()
|
153
183
|
for _class_ in self.classes:
|
154
184
|
# Pega as posições das amostras por classes a partir do y.
|
155
|
-
|
185
|
+
position_samples[_class_] = list(np.where(y == _class_)[0])
|
186
|
+
|
187
|
+
return position_samples
|
156
188
|
|
157
|
-
return positionSamples
|
158
|
-
|
159
189
|
def _score(self, X: npt.NDArray, y: list) -> float:
|
160
190
|
"""
|
161
191
|
Score function calculates forecast accuracy.
|
162
192
|
|
163
193
|
Details:
|
164
194
|
---
|
165
|
-
This function performs the prediction of X and checks how many elements are equal between
|
166
|
-
This function was added for compatibility with some scikit-learn
|
195
|
+
This function performs the prediction of X and checks how many elements are equal between \
|
196
|
+
vector y and y_predicted. This function was added for compatibility with some scikit-learn \
|
197
|
+
functions.
|
167
198
|
|
168
199
|
Parameters:
|
169
200
|
-----------
|
@@ -185,8 +216,9 @@ class Base:
|
|
185
216
|
|
186
217
|
Details:
|
187
218
|
---
|
188
|
-
Esta função realiza a previsão de X e verifica quantos elementos são iguais entre o vetor
|
189
|
-
Essa função foi adicionada para oferecer compatibilidade com algumas funções
|
219
|
+
Esta função realiza a previsão de X e verifica quantos elementos são iguais entre o vetor \
|
220
|
+
y e y_previsto. Essa função foi adicionada para oferecer compatibilidade com algumas funções \
|
221
|
+
do scikit-learn.
|
190
222
|
|
191
223
|
Parameters:
|
192
224
|
---
|
@@ -205,4 +237,4 @@ class Base:
|
|
205
237
|
if len(y) == 0:
|
206
238
|
return 0
|
207
239
|
y_pred = self.predict(X)
|
208
|
-
return np.sum(y == y_pred)/len(y)
|
240
|
+
return np.sum(y == y_pred) / len(y)
|