aisp 0.1.34__py3-none-any.whl → 0.1.35__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/__init__.py +4 -0
- aisp/exceptions.py +42 -0
- aisp/nsa/__init__.py +11 -0
- aisp/nsa/_base.py +212 -0
- aisp/nsa/_negative_selection.py +752 -0
- aisp/utils/__init__.py +2 -1
- aisp/utils/_multiclass.py +15 -30
- aisp/utils/metrics.py +20 -41
- aisp/utils/sanitizers.py +54 -0
- {aisp-0.1.34.dist-info → aisp-0.1.35.dist-info}/METADATA +2 -106
- aisp-0.1.35.dist-info/RECORD +14 -0
- aisp/NSA/__init__.py +0 -18
- aisp/NSA/_base.py +0 -281
- aisp/NSA/_negative_selection.py +0 -1115
- aisp-0.1.34.dist-info/RECORD +0 -11
- {aisp-0.1.34.dist-info → aisp-0.1.35.dist-info}/WHEEL +0 -0
- {aisp-0.1.34.dist-info → aisp-0.1.35.dist-info}/licenses/LICENSE +0 -0
- {aisp-0.1.34.dist-info → aisp-0.1.35.dist-info}/top_level.txt +0 -0
aisp/utils/__init__.py
CHANGED
aisp/utils/_multiclass.py
CHANGED
@@ -1,3 +1,4 @@
|
|
1
|
+
"""Utility functions for handling classes with multiple categories."""
|
1
2
|
from typing import Union
|
2
3
|
import numpy as np
|
3
4
|
import numpy.typing as npt
|
@@ -5,37 +6,21 @@ import numpy.typing as npt
|
|
5
6
|
|
6
7
|
def slice_index_list_by_class(classes: Union[npt.NDArray, list], y: npt.NDArray) -> dict:
|
7
8
|
"""
|
8
|
-
The function ``
|
9
|
-
|
10
|
-
|
11
|
-
|
12
|
-
Parameters
|
13
|
-
|
14
|
-
|
15
|
-
|
16
|
-
|
17
|
-
|
18
|
-
returns
|
19
|
-
|
20
|
-
|
21
|
-
|
22
|
-
---
|
23
|
-
|
24
|
-
A função ``__slice_index_list_by_class(...)``, separa os índices das linhas conforme a \
|
25
|
-
classe de saída, para percorrer o array de amostra, apenas nas posições que a saída for \
|
26
|
-
a classe que está sendo treinada.
|
27
|
-
|
28
|
-
Parameters:
|
29
|
-
---
|
30
|
-
* classes (``list or npt.NDArray``): lista com classes únicas.
|
31
|
-
* y (npt.NDArray): Recebe um array ``y``[``N amostra``] com as classes de saída do \
|
32
|
-
array de amostra ``X``.
|
33
|
-
|
34
|
-
Returns:
|
35
|
-
---
|
36
|
-
* dict: Um dicionário com a lista de posições do array(``y``), com as classes como chave.
|
9
|
+
The function ``slice_index_list_by_class(...)``, separates the indices of the lines according
|
10
|
+
to the output class, to loop through the sample array, only in positions where the output is the
|
11
|
+
class being trained.
|
12
|
+
|
13
|
+
Parameters
|
14
|
+
----------
|
15
|
+
* classes (``list or npt.NDArray``): list with unique classes.
|
16
|
+
* y (``npt.NDArray``): Receives a ``y``[``N sample``] array with the output classes of the
|
17
|
+
``X`` sample array.
|
18
|
+
|
19
|
+
returns
|
20
|
+
----------
|
21
|
+
* dict: A dictionary with the list of array positions(``y``), with the classes as key.
|
37
22
|
"""
|
38
|
-
position_samples =
|
23
|
+
position_samples = {}
|
39
24
|
for _class_ in classes:
|
40
25
|
# Gets the sample positions by class from y.
|
41
26
|
position_samples[_class_] = list(np.nonzero(y == _class_)[0])
|
aisp/utils/metrics.py
CHANGED
@@ -1,4 +1,6 @@
|
|
1
|
+
"""Utility functions for measuring accuracy and performance."""
|
1
2
|
from typing import Union
|
3
|
+
|
2
4
|
import numpy as np
|
3
5
|
import numpy.typing as npt
|
4
6
|
|
@@ -8,54 +10,31 @@ def accuracy_score(
|
|
8
10
|
y_pred: Union[npt.NDArray, list]
|
9
11
|
) -> float:
|
10
12
|
"""
|
11
|
-
Function to calculate
|
12
|
-
|
13
|
-
|
14
|
-
|
15
|
-
|
16
|
-
|
17
|
-
|
18
|
-
|
19
|
-
|
20
|
-
|
21
|
-
|
22
|
-
|
23
|
-
|
24
|
-
|
25
|
-
|
26
|
-
|
27
|
-
Raises:
|
28
|
-
---
|
29
|
-
* ValueError: If `y_true` or `y_pred` are empty or if they do not have the same length.
|
30
|
-
|
31
|
-
---
|
32
|
-
|
33
|
-
Função para calcular a acurácia de precisão com base em listas de rótulos
|
34
|
-
verdadeiros e nos rótulos previstos.
|
35
|
-
|
36
|
-
Parâmetros:
|
37
|
-
---
|
38
|
-
* y_true (``Union[npt.NDArray, list]``): Rótulos verdadeiros (corretos)..
|
39
|
-
* y_pred (``Union[npt.NDArray, list]``): Rótulos previstos.
|
40
|
-
|
41
|
-
Retornos:
|
42
|
-
---
|
43
|
-
* Precisão (``float``): A proporção de previsões corretas em relação
|
44
|
-
ao número total de previsões.
|
45
|
-
|
46
|
-
Lança:
|
47
|
-
---
|
48
|
-
* ValueError: Se `y_true` ou `y_pred` estiverem vazios ou se não
|
49
|
-
tiverem o mesmo tamanho.
|
13
|
+
Function to calculate the accuracy score based on true and predicted labels.
|
14
|
+
|
15
|
+
Parameters
|
16
|
+
----------
|
17
|
+
* y_true ()``Union[npt.NDArray, list]``):
|
18
|
+
Ground truth (correct) labels. Expected to be of the same length as `y_pred`.
|
19
|
+
* y_pred (``Union[npt.NDArray, list]``):
|
20
|
+
Predicted labels. Expected to be of the same length as `y_true`.
|
21
|
+
|
22
|
+
Returns
|
23
|
+
----------
|
24
|
+
* float: The ratio of correct predictions to the total number of predictions.
|
25
|
+
|
26
|
+
Raises
|
27
|
+
----------
|
28
|
+
* ValueError: If `y_true` or `y_pred` are empty or if they do not have the same length.
|
50
29
|
"""
|
51
30
|
n = len(y_true)
|
52
31
|
if n == 0:
|
53
32
|
raise ValueError(
|
54
33
|
"Division by zero: y_true cannot be an empty list or array."
|
55
34
|
)
|
56
|
-
|
35
|
+
if n != len(y_pred):
|
57
36
|
raise ValueError(
|
58
37
|
f"Error: The arrays must have the same size. Size of y_true: "
|
59
38
|
f"{len(y_true)}, Size of y_pred: {len(y_pred)}"
|
60
39
|
)
|
61
|
-
return np.sum(np.
|
40
|
+
return np.sum(np.array(y_true) == np.array(y_pred)) / n
|
aisp/utils/sanitizers.py
ADDED
@@ -0,0 +1,54 @@
|
|
1
|
+
"""Utility functions for validation and treatment of parameters."""
|
2
|
+
from typing import TypeVar, Iterable, Callable, Any, Optional
|
3
|
+
|
4
|
+
T = TypeVar('T')
|
5
|
+
|
6
|
+
def sanitize_choice(value: T, valid_choices: Iterable[T], default: T) -> T:
|
7
|
+
"""
|
8
|
+
Returns the value if it is present in the set of valid choices; otherwise,
|
9
|
+
returns the default value.
|
10
|
+
|
11
|
+
Parameters
|
12
|
+
----------
|
13
|
+
* value: The value to be checked.
|
14
|
+
* valid_choices (iterable): A collection of valid choices.
|
15
|
+
* default: The default value to be returned if 'value' is not in 'valid_choices'.
|
16
|
+
|
17
|
+
Returns
|
18
|
+
----------
|
19
|
+
* The original value if valid, or the default value if not.
|
20
|
+
"""
|
21
|
+
return value if value in valid_choices else default
|
22
|
+
|
23
|
+
|
24
|
+
def sanitize_param(value: T, default: T, condition: Callable[[T], bool]) -> T:
|
25
|
+
"""
|
26
|
+
Returns the value if it satisfies the specified condition; otherwise, returns the default value.
|
27
|
+
|
28
|
+
Parameters
|
29
|
+
----------
|
30
|
+
* value: The value to be checked.
|
31
|
+
* default (``T``): The default value to be returned if the condition is not satisfied.
|
32
|
+
* condition (``Callable[[T], bool]``): A function that takes a value and returns a boolean,
|
33
|
+
determining if the value is valid.
|
34
|
+
|
35
|
+
Returns
|
36
|
+
----------
|
37
|
+
* T: The original value if the condition is satisfied, or the default value if not.
|
38
|
+
"""
|
39
|
+
return value if condition(value) else default
|
40
|
+
|
41
|
+
|
42
|
+
def sanitize_seed(seed: Any) -> Optional[int]:
|
43
|
+
"""
|
44
|
+
Returns the seed if it is a non-negative integer; otherwise, returns None.
|
45
|
+
|
46
|
+
Parameters
|
47
|
+
----------
|
48
|
+
* seed (``Any``): The seed value to be validated.
|
49
|
+
|
50
|
+
Returns
|
51
|
+
----------
|
52
|
+
* Optional[int]: The original seed if it is a non-negative integer, or None if it is invalid.
|
53
|
+
"""
|
54
|
+
return seed if isinstance(seed, int) and seed >= 0 else None
|
@@ -1,6 +1,6 @@
|
|
1
1
|
Metadata-Version: 2.4
|
2
2
|
Name: aisp
|
3
|
-
Version: 0.1.
|
3
|
+
Version: 0.1.35
|
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>
|
@@ -39,7 +39,7 @@ Dynamic: license-file
|
|
39
39
|
<div class='language-options'>
|
40
40
|
|
41
41
|
* [English.](#english)
|
42
|
-
* [Português.](
|
42
|
+
* [Português.](https://ais-package.github.io/pt-br/docs/intro)
|
43
43
|
|
44
44
|
</div>
|
45
45
|
|
@@ -52,11 +52,6 @@ Dynamic: license-file
|
|
52
52
|
---
|
53
53
|
|
54
54
|
<section id='english'>
|
55
|
-
<div align = center>
|
56
|
-
|
57
|
-
## English
|
58
|
-
|
59
|
-
</div>
|
60
55
|
|
61
56
|
#### Summary:
|
62
57
|
|
@@ -144,104 +139,5 @@ Below are some examples that use a database for classification with the [Jupyter
|
|
144
139
|
|
145
140
|
---
|
146
141
|
|
147
|
-
|
148
|
-
</section>
|
149
|
-
</section>
|
150
|
-
|
151
|
-
---
|
152
|
-
|
153
|
-
<section id='português'>
|
154
|
-
<div align = center>
|
155
|
-
|
156
|
-
## Português
|
157
|
-
|
158
|
-
</div>
|
159
|
-
|
160
|
-
#### Sumário:
|
161
|
-
|
162
|
-
> 1. [Introdução.](#introdução)
|
163
|
-
> 2. [Instalação.](#instalação)
|
164
|
-
> 1. [Dependências](#dependências)
|
165
|
-
> 2. [Instalação do usuário](#instalação-do-usuário)
|
166
|
-
> 3. [Exemplos.](#exemplos)
|
167
|
-
|
168
|
-
---
|
169
|
-
<section id='introdução'>
|
170
|
-
|
171
|
-
#### Introdução
|
172
|
-
|
173
|
-
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).
|
174
|
-
|
175
|
-
O pacote teve início no ano de **2022** como um pacote de pesquisa no instituto federal do norte de minas gerais - campus salinas (**IFNMG - Salinas**).
|
176
|
-
|
177
|
-
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.
|
178
|
-
|
179
|
-
##### Algoritmos implementados:
|
180
|
-
|
181
|
-
> - [x] [**Seleção Negativa.**](https://ais-package.github.io/docs/aisp-techniques/Negative%20Selection/)
|
182
|
-
> - [ ] *Algoritmos de Seleção Clonal.*
|
183
|
-
> - [ ] *Células Dendríticas.*
|
184
|
-
> - [ ] *Teoria da Rede Imune.*
|
185
|
-
|
186
|
-
</section>
|
187
|
-
|
188
|
-
<section id='introdução'>
|
189
|
-
|
190
|
-
#### **Instalação**
|
191
|
-
|
192
|
-
|
193
|
-
O módulo requer a instalação do [python 3.8.10](https://www.python.org/downloads/) ou superior.
|
194
|
-
|
195
|
-
<section id='dependências'>
|
196
|
-
|
197
|
-
##### **Dependências:**
|
198
|
-
<div align = center>
|
199
|
-
|
200
|
-
| Pacotes | Versão |
|
201
|
-
|:-------------:|:-------------:|
|
202
|
-
| numpy | ≥ 1.22.4 |
|
203
|
-
| scipy | ≥ 1.8.1 |
|
204
|
-
| tqdm | ≥ 4.64.1 |
|
205
|
-
|
206
|
-
</div>
|
207
|
-
</section>
|
208
|
-
|
209
|
-
<section id='instalação-do-usuário'>
|
210
|
-
|
211
|
-
##### **Instalação do usuário**
|
212
|
-
|
213
|
-
A maneira mais simples de instalação do AISP é utilizando o ``pip``:
|
214
|
-
|
215
|
-
```Bash
|
216
|
-
pip install aisp
|
217
|
-
```
|
218
|
-
|
219
|
-
</section>
|
220
|
-
|
221
|
-
</section>
|
222
|
-
<section id='exemplos'>
|
223
|
-
|
224
|
-
#### Exemplos:
|
225
|
-
|
226
|
-
---
|
227
|
-
|
228
|
-
##### Exemplo utilizando a técnica de seleção negativa (**nsa**):
|
229
|
-
|
230
|
-
No exemplo presente nesse [notebook](https://github.com/AIS-Package/aisp/blob/main/examples/RNSA/example_with_randomly_generated_dataset-pt.ipynb), gerando **500** amostras aleatórias dispostas em dois grupos um para cada classe.
|
231
|
-
|
232
|
-
A seguir alguns exemplos que utiliza-se de base de dados para classificação com a ferramenta [Jupyter notebook](https://jupyter.org/).
|
233
|
-
|
234
|
-
#### **Seleção Negativa:**
|
235
|
-
|
236
|
-
+ **RNSA** Aplicação das tecnica de seleção negativa para classificação utilizando a base de dados de flores da família Iris e Old Faithful Geyser:
|
237
|
-
+ [iris_dataBase_example](https://github.com/AIS-Package/aisp/blob/main/examples/RNSA/iris_dataBase_example_pt-br.ipynb)
|
238
|
-
+ [geyser_dataBase_example](https://github.com/AIS-Package/aisp/blob/main/examples/RNSA/geyser_dataBase_example_pt-br.ipynb)
|
239
|
-
|
240
|
-
+ **BNSA**
|
241
|
-
+ [mushrooms_dataBase_example](https://github.com/AIS-Package/aisp/blob/main/examples/BNSA/mushrooms_dataBase_example_en.ipynb)
|
242
|
-
|
243
|
-
|
244
|
-
---
|
245
|
-
|
246
142
|
</section>
|
247
143
|
</section>
|
@@ -0,0 +1,14 @@
|
|
1
|
+
aisp/__init__.py,sha256=6is9Nwltdm6JZAsdLPXY56WXC7qnd0kNUEJoizOxWHg,111
|
2
|
+
aisp/exceptions.py,sha256=ONiKCZrBhfUaMO1vYHnOr1_eL9PtVJ7b_HRroMbORpc,1405
|
3
|
+
aisp/nsa/__init__.py,sha256=wgoFb-0WovzFovQG6UFkAb-IbZWK2wlytuJ03wmV4Q0,411
|
4
|
+
aisp/nsa/_base.py,sha256=OpBC3loiWk8NEb4ulogulIOKeh6hTnxcpImF6BNy8iI,8086
|
5
|
+
aisp/nsa/_negative_selection.py,sha256=iYtd39eR4O2y1bOVAAEqfMmgzIzQ_oexLCN3sRO8Mxg,32089
|
6
|
+
aisp/utils/__init__.py,sha256=-r--qdfTq4dVJU-VoJ7dvXTNS5_I1q1aGAQ02zNBOGw,217
|
7
|
+
aisp/utils/_multiclass.py,sha256=KJ2Le62KsSPRQB3UDMv7HT13xQLvwwZQM3QekTATDiY,1049
|
8
|
+
aisp/utils/metrics.py,sha256=RmqR5FRxQUZkF9GZhAUXNplaeRldhXv592DeeYPdyV8,1300
|
9
|
+
aisp/utils/sanitizers.py,sha256=QKpIu8YyNLIZT472O49QybLZB5P-NQqGaNI5xylyJ8k,1856
|
10
|
+
aisp-0.1.35.dist-info/licenses/LICENSE,sha256=fTqV5eBpeAZO0_jit8j4Ref9ikBSlHJ8xwj5TLg7gFk,7817
|
11
|
+
aisp-0.1.35.dist-info/METADATA,sha256=aHoORgNbmyDlN7Pd2MXCaNgGD7T30g_jtM_XIH20pZs,4603
|
12
|
+
aisp-0.1.35.dist-info/WHEEL,sha256=CmyFI0kx5cdEMTLiONQRbGQwjIoR1aIYB7eCAQ4KPJ0,91
|
13
|
+
aisp-0.1.35.dist-info/top_level.txt,sha256=Q5aJi_rAVT5UNS1As0ZafoyS5dwNibnoyOYV7RWUB9s,5
|
14
|
+
aisp-0.1.35.dist-info/RECORD,,
|
aisp/NSA/__init__.py
DELETED
@@ -1,18 +0,0 @@
|
|
1
|
-
"""Module (NSA) Negative Selection Algorithm
|
2
|
-
|
3
|
-
NSAs simulate the maturation process of T-cells in the immune system, where these \
|
4
|
-
cells learn to distinguish between self and non-self. Only T-cells capable \
|
5
|
-
of recognizing non-self elements are preserved.
|
6
|
-
|
7
|
-
----
|
8
|
-
|
9
|
-
Os NSAs simulam o processo de maturação das células-T no sistema imunológico, onde \
|
10
|
-
essas células aprendem a distinguir entre o próprio e não-próprio.
|
11
|
-
Apenas as células-T capazes de reconhecer elementos não-próprios são preservadas.
|
12
|
-
|
13
|
-
"""
|
14
|
-
from ._negative_selection import BNSA, RNSA
|
15
|
-
|
16
|
-
__author__ = "João Paulo da Silva Barros"
|
17
|
-
__all__ = ["RNSA", "BNSA"]
|
18
|
-
__version__ = "0.1.34"
|
aisp/NSA/_base.py
DELETED
@@ -1,281 +0,0 @@
|
|
1
|
-
from abc import abstractmethod
|
2
|
-
|
3
|
-
import numpy as np
|
4
|
-
import numpy.typing as npt
|
5
|
-
from typing import Literal, Optional
|
6
|
-
from scipy.spatial.distance import euclidean, cityblock, minkowski
|
7
|
-
|
8
|
-
from ..utils.metrics import accuracy_score
|
9
|
-
|
10
|
-
|
11
|
-
class Base:
|
12
|
-
"""
|
13
|
-
The base class contains functions that are used by more than one class in the package, and \
|
14
|
-
therefore are considered essential for the overall functioning of the system.
|
15
|
-
|
16
|
-
---
|
17
|
-
|
18
|
-
A classe base contém funções que são utilizadas por mais de uma classe do pacote, e por isso \
|
19
|
-
são consideradas essenciais para o funcionamento geral do sistema.
|
20
|
-
"""
|
21
|
-
|
22
|
-
def __init__(self, metric: str = "euclidean", p: float = 2):
|
23
|
-
"""
|
24
|
-
Parameters:
|
25
|
-
---
|
26
|
-
* metric (``str``): Way to calculate the distance between the detector and the sample:
|
27
|
-
|
28
|
-
* ``'Euclidean'`` ➜ The calculation of the distance is given by the expression: \
|
29
|
-
√( (x₁ – x₂)² + (y₁ – y₂)² + ... + (yn – yn)²).
|
30
|
-
* ``'minkowski'`` ➜ The calculation of the distance is given by the expression: \
|
31
|
-
( |X₁ – Y₁|p + |X₂ – Y₂|p + ... + |Xn – Yn|p) ¹/ₚ.
|
32
|
-
* ``'manhattan'`` ➜ The calculation of the distance is given by the expression: \
|
33
|
-
( |x₁ – x₂| + |y₁ – y₂| + ... + |yn – yn|) .
|
34
|
-
|
35
|
-
|
36
|
-
* p (``float``): This parameter stores the value of ``p`` used in the Minkowski distance.\
|
37
|
-
The default is ``2``, which represents normalized Euclidean distance. Different \
|
38
|
-
values of p lead to different variants of the Minkowski distance \
|
39
|
-
[learn more](https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.minkowski.html).
|
40
|
-
|
41
|
-
---
|
42
|
-
|
43
|
-
Parameters:
|
44
|
-
---
|
45
|
-
* metric (``str``): Forma para se calcular a distância entre o detector e a amostra:
|
46
|
-
|
47
|
-
* ``'euclidiana'`` ➜ O cálculo da distância dá-se pela expressão: \
|
48
|
-
√( (x₁ – x₂)² + (y₁ – y₂)² + ... + (yn – yn)²).
|
49
|
-
* ``'minkowski'`` ➜ O cálculo da distância dá-se pela expressão: \
|
50
|
-
( |X₁ – Y₁|p + |X₂ – Y₂|p + ... + |Xn – Yn|p).
|
51
|
-
* ``'manhattan'`` ➜ O cálculo da distância dá-se pela expressão: \
|
52
|
-
( |x₁ – x₂| + |y₁ – y₂| + ... + |yn – yn|).
|
53
|
-
|
54
|
-
Defaults to ``'euclidean'``.
|
55
|
-
|
56
|
-
* p (``float``): Este parâmetro armazena o valor de ``p`` utilizada na distância de Minkowski. \
|
57
|
-
O padrão é ``2``, o que significa distância euclidiana normalizada. Diferentes valores \
|
58
|
-
de p levam a diferentes variantes da distância de Minkowski \
|
59
|
-
[saiba mais](https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.minkowski.html).
|
60
|
-
"""
|
61
|
-
if metric == "manhattan" or metric == "minkowski":
|
62
|
-
self.metric: str = metric
|
63
|
-
else:
|
64
|
-
self.metric: str = "euclidean"
|
65
|
-
self.p: float = p
|
66
|
-
|
67
|
-
def _distance(self, u: npt.NDArray, v: npt.NDArray):
|
68
|
-
"""
|
69
|
-
Function to calculate the distance between two points by the chosen ``metric``.
|
70
|
-
|
71
|
-
Parameters:
|
72
|
-
---
|
73
|
-
* u (``npt.NDArray``): Coordinates of the first point.
|
74
|
-
* v (``npt.NDArray``): Coordinates of the second point.
|
75
|
-
|
76
|
-
returns:
|
77
|
-
---
|
78
|
-
* Distance (``double``) between the two points.
|
79
|
-
|
80
|
-
---
|
81
|
-
|
82
|
-
Função para calcular a distância entre dois pontos pela ``metric`` escolhida.
|
83
|
-
|
84
|
-
Parameters:
|
85
|
-
---
|
86
|
-
* u (``npt.NDArray``): Coordenadas do primeiro ponto.
|
87
|
-
* v (``npt.NDArray``): Coordenadas do segundo ponto.
|
88
|
-
|
89
|
-
Returns:
|
90
|
-
---
|
91
|
-
* Distância (``double``) entre os dois pontos.
|
92
|
-
"""
|
93
|
-
if self.metric == "manhattan":
|
94
|
-
return cityblock(u, v)
|
95
|
-
elif self.metric == "minkowski":
|
96
|
-
return minkowski(u, v, self.p)
|
97
|
-
else:
|
98
|
-
return euclidean(u, v)
|
99
|
-
|
100
|
-
@staticmethod
|
101
|
-
def _check_and_raise_exceptions_fit(
|
102
|
-
X: npt.NDArray = None,
|
103
|
-
y: npt.NDArray = None,
|
104
|
-
_class_: Literal["RNSA", "BNSA"] = "RNSA",
|
105
|
-
):
|
106
|
-
"""
|
107
|
-
Function responsible for verifying fit function parameters and throwing exceptions if the \
|
108
|
-
verification is not successful.
|
109
|
-
|
110
|
-
Parameters:
|
111
|
-
---
|
112
|
-
* X (``npt.NDArray``): Training array, containing the samples and their characteristics, \
|
113
|
-
[``N samples`` (rows)][``N features`` (columns)].
|
114
|
-
* y (``npt.NDArray``): Array of target classes of ``X`` with [``N samples`` (lines)].
|
115
|
-
* _class_ (Literal[RNSA, BNSA], optional): Current class. Defaults to 'RNSA'.
|
116
|
-
|
117
|
-
Raises:
|
118
|
-
---
|
119
|
-
* TypeError: If X or y are not ndarrays or have incompatible shapes.
|
120
|
-
* ValueError: If _class_ is BNSA and X contains values that are not composed only of 0 and 1.
|
121
|
-
|
122
|
-
---
|
123
|
-
|
124
|
-
Função responsável por verificar os parâmetros da função fit e lançar exceções se a \
|
125
|
-
verificação não for bem-sucedida.
|
126
|
-
|
127
|
-
Parâmetros:
|
128
|
-
---
|
129
|
-
* X (``npt.NDArray``): Array de treinamento, contendo as amostras e suas características, \
|
130
|
-
[``N samples`` (linhas)][``N features`` (colunas)].
|
131
|
-
* y (``npt.NDArray``): Array de classes alvo de ``X`` com [``N samples`` (linhas)].
|
132
|
-
* _class_ (Literal[RNSA, BNSA], opcional): Classe atual. O padrão é 'RNSA'.
|
133
|
-
|
134
|
-
Lança:
|
135
|
-
---
|
136
|
-
* TypeError: Se X ou y não forem ndarrays ou tiverem formas incompatíveis.
|
137
|
-
* ValueError: Se _class_ for BNSA e X contiver valores que não sejam compostos apenas por 0 e 1.
|
138
|
-
"""
|
139
|
-
if not isinstance(X, np.ndarray):
|
140
|
-
if isinstance(X, list):
|
141
|
-
X = np.array(X)
|
142
|
-
else:
|
143
|
-
raise TypeError("X is not an ndarray or list.")
|
144
|
-
elif not isinstance(y, np.ndarray):
|
145
|
-
if isinstance(y, list):
|
146
|
-
y = np.array(y)
|
147
|
-
else:
|
148
|
-
raise TypeError("y is not an ndarray or list.")
|
149
|
-
if X.shape[0] != y.shape[0]:
|
150
|
-
raise TypeError(
|
151
|
-
"X does not have the same amount of sample for the output classes in y."
|
152
|
-
)
|
153
|
-
|
154
|
-
if _class_ == "BNSA" and not np.isin(X, [0, 1]).all():
|
155
|
-
raise ValueError(
|
156
|
-
"The array X contains values that are not composed only of 0 and 1."
|
157
|
-
)
|
158
|
-
|
159
|
-
def score(self, X: npt.NDArray, y: list) -> float:
|
160
|
-
"""
|
161
|
-
Score function calculates forecast accuracy.
|
162
|
-
|
163
|
-
Details:
|
164
|
-
---
|
165
|
-
This function performs the prediction of X and checks how many elements are equal between \
|
166
|
-
vector y and y_predicted. This function was added for compatibility with some scikit-learn \
|
167
|
-
functions.
|
168
|
-
|
169
|
-
Parameters:
|
170
|
-
-----------
|
171
|
-
|
172
|
-
X: np.ndarray
|
173
|
-
Feature set with shape (n_samples, n_features).
|
174
|
-
y: np.ndarray
|
175
|
-
True values with shape (n_samples,).
|
176
|
-
|
177
|
-
Returns:
|
178
|
-
-------
|
179
|
-
|
180
|
-
accuracy: float
|
181
|
-
The accuracy of the model.
|
182
|
-
|
183
|
-
---
|
184
|
-
|
185
|
-
Função score calcular a acurácia da previsão.
|
186
|
-
|
187
|
-
Details:
|
188
|
-
---
|
189
|
-
Esta função realiza a previsão de X e verifica quantos elementos são iguais entre o vetor \
|
190
|
-
y e y_previsto. Essa função foi adicionada para oferecer compatibilidade com algumas funções \
|
191
|
-
do scikit-learn.
|
192
|
-
|
193
|
-
Parameters:
|
194
|
-
---
|
195
|
-
|
196
|
-
* X : np.ndarray
|
197
|
-
Conjunto de características com shape (n_samples, n_features).
|
198
|
-
* y : np.ndarray
|
199
|
-
Valores verdadeiros com shape (n_samples,).
|
200
|
-
|
201
|
-
returns:
|
202
|
-
---
|
203
|
-
|
204
|
-
accuracy : float
|
205
|
-
A acurácia do modelo.
|
206
|
-
"""
|
207
|
-
if len(y) == 0:
|
208
|
-
return 0
|
209
|
-
y_pred = self.predict(X)
|
210
|
-
return accuracy_score(y, y_pred)
|
211
|
-
|
212
|
-
@abstractmethod
|
213
|
-
def fit(self, X: npt.NDArray, y: npt.NDArray, verbose: bool = True):
|
214
|
-
"""
|
215
|
-
Function to train the model using the input data ``X`` and corresponding labels ``y``.
|
216
|
-
|
217
|
-
This abstract method is implemented by the class that inherits it.
|
218
|
-
|
219
|
-
Parameters:
|
220
|
-
---
|
221
|
-
* X (``npt.NDArray``): Input data used for training the model, previously normalized to the range [0, 1].
|
222
|
-
* y (``npt.NDArray``): Corresponding labels or target values for the input data.
|
223
|
-
* verbose (``bool``, optional): Flag to enable or disable detailed output during \
|
224
|
-
training. Default is ``True``.
|
225
|
-
|
226
|
-
Returns:
|
227
|
-
---
|
228
|
-
* self: Returns the instance of the class that implements this method.
|
229
|
-
|
230
|
-
---
|
231
|
-
|
232
|
-
Função para treinar o modelo usando os dados de entrada ``X`` e os classes correspondentes ``y``.
|
233
|
-
|
234
|
-
Este método abstrato é implementado pela classe que o herdar.
|
235
|
-
|
236
|
-
Parâmetros:
|
237
|
-
---
|
238
|
-
* X (``npt.NDArray``): Dados de entrada utilizados para o treinamento do modelo, previamente \
|
239
|
-
normalizados no intervalo [0, 1].
|
240
|
-
* y (``npt.NDArray``): Rótulos ou valores-alvo correspondentes aos dados de entrada.
|
241
|
-
* verbose (``bool``, opcional): Flag para ativar ou desativar a saída detalhada durante o \
|
242
|
-
treinamento. O padrão é ``True``.
|
243
|
-
|
244
|
-
Retornos:
|
245
|
-
---
|
246
|
-
* self: Retorna a instância da classe que implementa este método.
|
247
|
-
"""
|
248
|
-
pass
|
249
|
-
|
250
|
-
@abstractmethod
|
251
|
-
def predict(self, X) -> Optional[npt.NDArray]:
|
252
|
-
"""
|
253
|
-
Function to generate predictions based on the input data ``X``.
|
254
|
-
|
255
|
-
This abstract method is implemented by the class that inherits it.
|
256
|
-
|
257
|
-
Parameters:
|
258
|
-
---
|
259
|
-
* X (``npt.NDArray``): Input data for which predictions will be generated.
|
260
|
-
|
261
|
-
Returns:
|
262
|
-
---
|
263
|
-
* Predictions (``Optional[npt.NDArray]``): Predicted values for each input sample, or ``None``
|
264
|
-
if the prediction fails.
|
265
|
-
|
266
|
-
---
|
267
|
-
|
268
|
-
Função para gerar previsões com base nos dados de entrada ``X``.
|
269
|
-
|
270
|
-
Este método abstrato é implementado pela classe que o herdar.
|
271
|
-
|
272
|
-
Parâmetros:
|
273
|
-
---
|
274
|
-
* X (``npt.NDArray``): Dados de entrada para os quais as previsões serão geradas.
|
275
|
-
|
276
|
-
Retornos:
|
277
|
-
---
|
278
|
-
* Previsões (``Optional[npt.NDArray]``): Valores previstos para cada amostra de entrada,
|
279
|
-
ou ``None`` se a previsão falhar.
|
280
|
-
"""
|
281
|
-
pass
|