aisp 0.1.0__py3-none-any.whl → 0.1.2__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.
@@ -1,8 +1,11 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: aisp
3
- Version: 0.1.0
3
+ Version: 0.1.2
4
4
  Summary: Package with techniques of artificial immune systems.
5
+ Home-page: https://github.com/AIS-Package/aisp
6
+ Author: João Paulo da Silva Barros
5
7
  Author-email: João Paulo da Silva Barros <jpsilvabarr@gmail.com>
8
+ Maintainer: Alison Zille Lopes
6
9
  Maintainer-email: Alison Zille Lopes <alisonzille@gmail.com>
7
10
  License: LGPL-3.0 license
8
11
  Project-URL: Homepage, https://ais-package.github.io/
@@ -21,9 +24,9 @@ Classifier: Programming Language :: Python :: 3.11
21
24
  Requires-Python: >=3.8.10
22
25
  Description-Content-Type: text/markdown
23
26
  License-File: LICENSE
24
- Requires-Dist: numpy (>=1.23.0)
27
+ Requires-Dist: numpy (>=1.22.4)
25
28
  Requires-Dist: scipy (>=1.8.1)
26
- Requires-Dist: tqdm (==4.64.1)
29
+ Requires-Dist: tqdm (>=4.64.1)
27
30
 
28
31
  <div align = center>
29
32
 
@@ -72,7 +75,7 @@ Requires-Dist: tqdm (==4.64.1)
72
75
 
73
76
  #### Introduction
74
77
 
75
- The **AISP** is a python package that implements artificial immune systems techniques, distributed under the GNU Lesser General Public License v3.0 (GPLv3).
78
+ The **AISP** is a python package that implements artificial immune systems techniques, distributed under the GNU Lesser General Public License v3.0 (LGPLv3).
76
79
 
77
80
  The package started in **2022** as a research package at the Federal Institute of Northern Minas Gerais - Salinas campus (**IFNMG - Salinas**).
78
81
 
@@ -102,7 +105,7 @@ The module requires installation of [python 3.8.10](https://www.python.org/downl
102
105
 
103
106
  | Packages | Version |
104
107
  |:-------------:|:-------------:|
105
- | numpy | ≥ 1.23.0 |
108
+ | numpy | ≥ 1.22.4 |
106
109
  | scipy | ≥ 1.8.1 |
107
110
  | tqdm | ≥ 4.64.1 |
108
111
 
@@ -182,7 +185,7 @@ Below are some examples that use a database for classification with the [Jupyter
182
185
 
183
186
  #### Introdução
184
187
 
185
- 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 (GPLv3).
188
+ 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).
186
189
 
187
190
  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**).
188
191
 
@@ -211,7 +214,7 @@ O módulo requer a instalação do [python 3.8.10](https://www.python.org/downlo
211
214
 
212
215
  | Pacotes | Versão |
213
216
  |:-------------:|:-------------:|
214
- | numpy | ≥ 1.23.0 |
217
+ | numpy | ≥ 1.22.4 |
215
218
  | scipy | ≥ 1.8.1 |
216
219
  | tqdm | ≥ 4.64.1 |
217
220
 
@@ -0,0 +1,5 @@
1
+ aisp-0.1.2.dist-info/LICENSE,sha256=fTqV5eBpeAZO0_jit8j4Ref9ikBSlHJ8xwj5TLg7gFk,7817
2
+ aisp-0.1.2.dist-info/METADATA,sha256=xFBao7vEWR_R05xAj8nfa0f3QiuYkzPRRaY5ngIjFW8,8232
3
+ aisp-0.1.2.dist-info/WHEEL,sha256=pkctZYzUS4AYVn6dJ-7367OJZivF2e8RA9b_ZBjif18,92
4
+ aisp-0.1.2.dist-info/top_level.txt,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
5
+ aisp-0.1.2.dist-info/RECORD,,
@@ -0,0 +1 @@
1
+
aisp/NSA/__init__.py DELETED
@@ -1,4 +0,0 @@
1
- from ._negativeSelection import RNSA, BNSA
2
-
3
- __author__ = 'João Paulo da Silva Barros'
4
- __all__ = ['RNSA', 'BNSA']
@@ -1,1068 +0,0 @@
1
- import numpy as np
2
- import numpy.typing as npt
3
- from tqdm import tqdm
4
- from typing import Literal
5
- from collections import namedtuple
6
- from scipy.spatial.distance import hamming
7
-
8
- from aisp._base import Base
9
-
10
-
11
- class RNSA(Base):
12
- """
13
- The ``RNSA`` (Real-Valued Negative Selection Algorithm) class is for classification and identification purposes.
14
- of anomalies through the self and not self method.
15
-
16
- Attributes:
17
- ---
18
- * N (``int``): Number of detectors.
19
- * r (``float``): Radius of the detector.
20
- * r_s (``float``): rₛ Radius of the ``X`` own samples.
21
- * k (``int``): K number of near neighbors to calculate the average distance of the detectors.
22
- * metric (``str``): Way to calculate the distance: ``'euclidean', 'minkowski', or 'manhattan'``.
23
- * max_discards (``int``): This parameter indicates the maximum number of consecutive detector discards,
24
- aimed at preventing a possible infinite loop in case a radius is defined that cannot generate non-self
25
- detectors.
26
- * seed (``int``): Seed for the random generation of detector values.
27
- * algorithm(``str``), Set the algorithm version:
28
-
29
- * ``'default-NSA'``: Default algorithm with fixed radius.
30
- * ``'V-detector'``: This algorithm uses a variable radius for anomaly detection in feature spaces.
31
-
32
- Defaults to ``'default-NSA'``.
33
-
34
- * cell_bounds (``bool``): If set to ``True``, this option limits the generation of detectors to
35
- the space within the plane between 0 and 1.
36
- * detectors (``dict``): This variable stores a list of detectors by class.
37
- * classes (``npt.NDArray``): list of output classes.
38
-
39
- ---
40
-
41
- A classe ``RNSA`` (Algoritmo de Seleção Negativa de Valor Real) tem a finalidade de classificação e identificação
42
- de anomalias através do método self e not self .
43
-
44
- Attributes:
45
- ---
46
- * N (``int``): Quantidade de detectores.
47
- * r (``float``): Raio do detector.
48
- * r_s (``float``): O valor de ``rₛ`` é o raio das amostras próprias da matriz ``X``.
49
- * k (``int``): K quantidade de vizinhos próximos para calcular a média da distância dos detectores.
50
- * metric (``str``): Forma de calcular a distância: ``'euclidiana', 'minkowski', or 'manhattan'``.
51
- * max_discards (``int``): Este parâmetro indica o número máximo de descartes de detectores em sequência,
52
- que tem como objetivo evitar um possível loop infinito caso seja definido um raio que não seja possível
53
- gerar detectores do não-próprio.
54
- * seed (``int``): Semente para a geração randômica dos valores dos detectores.
55
- * algorithm (``str``), Definir a versão do algoritmo:
56
-
57
- * ``'default-NSA'``: Algoritmo padrão com raio fixo.
58
- * ``'V-detector'``: Este algoritmo utiliza um raio variável para a detecção de anomalias em espaços
59
- de características.
60
-
61
- Defaults to ``'default-NSA'``.
62
-
63
- * cell_bounds (``bool``): Se definido como ``True``, esta opção limita a geração dos detectores ao espaço
64
- do plano compreendido entre 0 e 1.
65
-
66
-
67
- * detectors (``dict``): Essa variável armazena uma lista com detectores por classes.
68
- * classes (``npt.NDArray``): lista com as classes de saída.
69
- """
70
- def __init__(
71
- self,
72
- N: int = 100,
73
- r: float = 0.05,
74
- r_s: float = 0.0001,
75
- k: int = 1,
76
- metric: Literal['manhattan', 'minkowski', 'euclidean'] = 'euclidean',
77
- max_discards: int = 100,
78
- seed: int = None,
79
- algorithm: Literal['default-NSA', 'V-detector'] ='default-NSA',
80
- cell_bounds: bool = False
81
- ):
82
- """
83
- Negative Selection class constructor (``RNSA``).
84
-
85
- Details:
86
- ---
87
- This method initializes the ``detectors``, ``classes``, ``k``, ``metric``, ``N``, ``r``, ``r_S``,
88
- ``max_discards``, ``seed`` and ``algorithm`` attributes.
89
-
90
- Parameters:
91
- ---
92
- * N (``int``): Number of detectors. Defaults to ``100``.
93
- * r (``float``): Radius of the detector. Defaults to ``0.05``.
94
- * r_s (``float``): rₛ Radius of the ``X`` own samples. Defaults to ``0.0001``.
95
- * k (``int``): Number of neighbors near the randomly generated detectors to perform the
96
- distance average calculation. Defaults to ``1``.
97
- * metric (``str``): Way to calculate the distance between the detector and the sample:
98
-
99
- * ``'Euclidean'`` ➜ The calculation of the distance is given by the expression: √( (x₁ – x₂)² + (y₁ – y₂)² + ... + (yn – yn)²).
100
- * ``'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``.
101
- * ``'manhattan'`` ➜ The calculation of the distance is given by the expression: ( |x₁ – x₂| + |y₁ – y₂| + ... + |yn – yn|) .
102
-
103
- Defaults to ``'euclidean'``.
104
-
105
- * max_discards (``int``): This parameter indicates the maximum number of consecutive detector discards, aimed at preventing a
106
- possible infinite loop in case a radius is defined that cannot generate non-self detectors. Defaults to ``100``.
107
- * seed (``int``): Seed for the random generation of values in the detectors. Defaults to ``None``.
108
-
109
- * algorithm(``str``), Set the algorithm version:
110
-
111
- * ``'default-NSA'``: Default algorithm with fixed radius.
112
- * ``'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.
113
-
114
- Defaults to ``'default-NSA'``.
115
-
116
-
117
- * cell_bounds (``bool``): If set to ``True``, this option limits the generation of detectors to the space within
118
- the plane between 0 and 1. This means that any detector whose radius exceeds this limit is discarded,
119
- this variable is only used in the ``V-detector`` algorithm. Defaults to ``False``.
120
-
121
- ---
122
-
123
- Construtor da classe de Seleção negativa (``RNSA``).
124
-
125
- Details:
126
- ---
127
- Este método inicializa os atributos ``detectors``, ``classes``, ``k``, ``metric``, ``N``, ``r`` e ``seed``.
128
-
129
- Parameters:
130
- ---
131
- * N (``int``): Quantidade de detectores. Defaults to ``100``.
132
- * r (``float``): Raio do detector. Defaults to ``0.05``.
133
- * r_s (``float``): O valor de ``rₛ`` é o raio das amostras próprias da matriz ``X``. Defaults to ``0.0001``.
134
- * k (``int``): Quantidade de vizinhos próximos dos detectores gerados aleatoriamente para efetuar o
135
- cálculo da média da distância. Defaults to ``1``.
136
- * metric (``str``): Forma para se calcular a distância entre o detector e a amostra:
137
-
138
- * ``'euclidiana'`` ➜ O cálculo da distância dá-se pela expressão: √( (x₁ – x₂)² + (y₁ – y₂)² + ... + (yn – yn)²).
139
- * ``'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``.
140
- * ``'manhattan'`` ➜ O cálculo da distância dá-se pela expressão: ( |x₁ – x₂| + |y₁ – y₂| + ... + |yn – yn|).
141
-
142
- Defaults to ``'euclidean'``.
143
-
144
- * 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
145
- 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``.
146
- * seed (``int``): Semente para a geração randômica dos valores nos detectores. Defaults to ``None``.
147
- * algorithm (``str``), Definir a versão do algoritmo:
148
-
149
- * ``'default-NSA'``: Algoritmo padrão com raio fixo.
150
- * ``'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.
151
-
152
- Defaults to ``'default-NSA'``.
153
-
154
- * cell_bounds (``bool``): Se definido como ``True``, esta opção limita a geração dos detectores ao espaço do plano
155
- compreendido entre 0 e 1. Isso significa que qualquer detector cujo raio ultrapasse esse limite é descartado,
156
- e esta variável é usada exclusivamente no algoritmo ``V-detector``.
157
- """
158
-
159
- if metric == 'manhattan' or metric == 'minkowski' or metric == 'euclidean':
160
- self.metric = metric
161
- else:
162
- self.metric = 'euclidean'
163
-
164
- if seed is not None and isinstance(seed, int):
165
- np.random.seed(seed)
166
- self.seed: int = seed
167
- else:
168
- self.seed = None
169
-
170
- if k < 1:
171
- self.k: int = 1
172
- else:
173
- self.k: int = k
174
-
175
- if N < 1:
176
- self.N: int = 100
177
- else:
178
- self.N: int = N
179
-
180
- if r < 0:
181
- self.r: float = 0.05
182
- else:
183
- self.r: float = r
184
-
185
- if r_s > 0:
186
- self.r_s: float = r_s
187
- else:
188
- self.r_s: float = 0
189
-
190
- if algorithm == 'V-detector':
191
- self._Detector = namedtuple("Detector", "position radius")
192
- self._algorithm: str = algorithm
193
- else:
194
- self._Detector = namedtuple("Detector", "position")
195
- self._algorithm: str = 'default-NSA'
196
-
197
- self._cell_bounds: bool = cell_bounds
198
- self.max_discards: int = max_discards
199
- self.detectors: dict = None
200
- self.classes: npt.NDArray = None
201
-
202
- def fit(self, X: npt.NDArray, y: npt.NDArray, verbose: bool = True):
203
- """
204
- The function ``fit(...)``, performs the training according to ``X`` and ``y``, using the method
205
- negative selection method(``NegativeSelect``).
206
-
207
- Parameters:
208
- ---
209
- * X (``npt.NDArray``): Training array, containing the samples and their characteristics,
210
- [``N samples`` (rows)][``N features`` (columns)].
211
- * y (``npt.NDArray``): Array of target classes of ``X`` with [``N samples`` (lines)].
212
- * verbose (``bool``): Feedback from detector generation to the user.
213
- returns:
214
- ---
215
- (``self``): Returns the instance itself.
216
-
217
- ----
218
-
219
- A função ``fit(...)``, realiza o treinamento de acordo com ``X`` e ``y``, usando o método
220
- de seleção negativa(``NegativeSelect``).
221
-
222
- Parameters:
223
- ---
224
- * X (``npt.NDArray``): Array de treinamento, contendo as amostras é suas características,
225
- [``N amostras`` (linhas)][``N características`` (colunas)].
226
- * y (``npt.NDArray``): Array com as classes alvos de ``X`` com [``N amostras`` (linhas)].
227
- * verbose (``bool``): Feedback da geração de detectores para o usuário.
228
- Returns:
229
- ---
230
- (``self``): Retorna a própria instância.
231
- """
232
- if not isinstance(X, (np.ndarray)):
233
- if isinstance(X, (list)):
234
- X = np.array(X)
235
- else:
236
- raise TypeError("X is not an ndarray.")
237
- elif not isinstance(y, (np.ndarray)):
238
- if isinstance(y, (list)):
239
- y = np.array(y)
240
- else:
241
- raise TypeError("y is not an ndarray.")
242
- if X.shape[0] != y.shape[0]:
243
- raise TypeError(
244
- "X does not have the same amount of sample for the output classes in y.")
245
-
246
- # Identificando as classes possíveis, dentro do array de saídas ``y``.
247
- self.classes = np.unique(y)
248
- # Dict que armazenará os detectores com as classes como key.
249
- list_detectors_by_class = dict()
250
- # Separa as classes para o treinamento.
251
- sample_index = self.__slice_index_list_by_class(y)
252
- # Barra de progresso para a geração de todos os detectores.
253
- if verbose:
254
- progress = tqdm(total=int(self.N * (len(self.classes))),
255
- bar_format='{desc} ┇{bar}┇ {n}/{total} detectors', postfix='\n')
256
- for _class_ in self.classes:
257
- # Inicia o conjunto vazio que conterá os detectores válidos.
258
- valid_detectors_set = []
259
- discard_count = 0
260
- # Informando em qual classe o algoritmo está para a barra de progresso.
261
- if verbose:
262
- progress.set_description_str(
263
- f'Generating the detectors for the {_class_} class:')
264
- while len(valid_detectors_set) < self.N:
265
- # Gera um vetor candidato a detector aleatoriamente com valores entre 0 e 1.
266
- vector_x = np.random.random_sample(size=X.shape[1])
267
- # Verifica a validade do detector para o não-próprio com relação às amostras da classe.
268
- valid_detector = self.__checks_valid_detector(
269
- X=X, vector_x=vector_x, samples_index_class=sample_index[_class_])
270
-
271
- # Se o detector for válido, adicione a lista dos válidos.
272
- if self._algorithm == 'V-detector' and valid_detector != False:
273
- discard_count = 0
274
- valid_detectors_set.append(
275
- self._Detector(vector_x, valid_detector[1]))
276
- if verbose:
277
- progress.update(1)
278
- elif valid_detector:
279
- discard_count = 0
280
- valid_detectors_set.append(self._Detector(vector_x))
281
- if verbose:
282
- progress.update(1)
283
- else:
284
- discard_count += 1
285
- if discard_count == self.max_discards:
286
- raise Exception('An error has been identified:\n'+
287
- f'the maximum number of discards of detectors for the {_class_} class has been reached.\n'+
288
- 'It is recommended to check the defined radius and consider reducing its value.')
289
-
290
- # Adicionar detectores, com as classes como chave na dict.
291
- list_detectors_by_class[_class_] = valid_detectors_set
292
- # Informar a finalização da geração dos detectores para as classes.
293
- if verbose:
294
- progress.set_description(
295
- f'\033[92m✔ Non-self detectors for classes ({", ".join(map(str, self.classes))}) successfully generated\033[0m')
296
- # Armazena os detectores encontrados no atributo, para os detectores da classe.
297
- self.detectors = list_detectors_by_class
298
- return self
299
-
300
- def predict(self, X: npt.NDArray) -> npt.NDArray:
301
- """
302
- Function to perform the prediction of classes based on detectors
303
- created after training.
304
-
305
- Parameters:
306
- ---
307
- * X (``npt.NDArray``): Array with input samples with [``N samples`` (Lines)] and
308
- [``N characteristics``(Columns)]
309
-
310
- returns:
311
- ---
312
- * C – (``npt.NDArray``): an ndarray of the form ``C`` [``N samples``],
313
- containing the predicted classes for ``X``.
314
- * ``None``: If there are no detectors for the prediction.
315
-
316
- ---
317
-
318
- Função para efetuar a previsão das classes com base nos detectores
319
- criados após o treinamento.
320
-
321
- Parameters:
322
- ---
323
- * X (``npt.NDArray``): Array com as amostras de entradas com [``N amostras`` (Linhas)] e
324
- [``N características``(Colunas)]
325
-
326
- Returns:
327
- ---
328
- * C – (``npt.NDArray``): um ndarray de forma ``C`` [``N amostras``],
329
- contendo as classes previstas para ``X``.
330
- * ``None``: Se não existir detectores para a previsão.
331
- """
332
- # se não houver detectores retorna None.
333
- if self.detectors is None:
334
- return None
335
- elif not isinstance(X, (np.ndarray, list)):
336
- raise TypeError("X is not an ndarray or list")
337
- elif len(self.detectors[self.classes[0]][0].position) != len(X[0]):
338
- raise Exception('X does not have {} features to make the prediction'.format(
339
- len(self.detectors[self.classes[0]][0])))
340
-
341
- # Inicia um array vazio.
342
- C = np.empty(shape=(0))
343
- # Para cada linha de amostra em X.
344
- for line in X:
345
- class_found: bool
346
- _class_ = self.__compare_sample_to_detectors(line)
347
- if _class_ is None:
348
- class_found = False
349
- else:
350
- C = np.append(C, [_class_])
351
- class_found = True
352
-
353
- # Se possuir apenas uma classe e não classificar a amostra define a saída como não-própria.
354
- if not class_found and len(self.classes) == 1:
355
- C = np.append(C, ['non-self'])
356
- # Se não identificar a classe com os detectores, coloca a classe com a maior distância da média dos seus detectores.
357
- elif not class_found:
358
- average_distance = dict()
359
- for _class_ in self.classes:
360
- detectores = list(
361
- map(lambda x: x.position, self.detectors[_class_]))
362
- average_distance[_class_] = self.__distance(
363
- np.average(detectores, axis=0), line)
364
- C = np.append(
365
- C, [max(average_distance, key=average_distance.get)])
366
- return C
367
-
368
- def __checks_valid_detector(self, X: npt.NDArray = None, vector_x: npt.NDArray = None, samples_index_class: npt.NDArray = None):
369
- """
370
- Function to check if the detector has a valid non-proper ``r`` radius for the class.
371
-
372
- Parameters:
373
- ---
374
- * X (``npt.NDArray``): Array ``X`` with the samples.
375
- * vector_x (``npt.NDArray``): Randomly generated vector x candidate detector with values ​​between [0, 1].
376
- * samples_index_class (``npt.NDArray``): Sample positions of a class in ``X``.
377
-
378
- returns:
379
- ---
380
- * Validity (``bool``): Returns whether the detector is valid or not.
381
-
382
- ---
383
-
384
- Função para verificar se o detector possui raio ``r`` válido do não-próprio para a classe.
385
-
386
- Parameters:
387
- ---
388
- * X (``npt.NDArray``): Array ``X`` com as amostras.
389
- * vector_x (``npt.NDArray``): Vetor x candidato a detector gerado aleatoriamente com valores entre [0, 1].
390
- * samples_index_class (``npt.NDArray``): Posições das amostras de uma classe em ``X``.
391
-
392
- Returns:
393
- ---
394
- * Validade (``bool``): Retorna se o detector é válido ou não.
395
-
396
- """
397
- # Se um ou mais array de entrada possuir zero dados, retorna falso.
398
- if np.size(samples_index_class) == 0 or np.size(X) == 0 or np.size(vector_x) == 0:
399
- return False
400
- # se self.k > 1 utiliza os k vizinhos mais próximos (knn), se não verifica o detector sem considerar os knn,.
401
- if self.k > 1:
402
- # Iniciar a lista dos knn vazia.
403
- knn_list = np.empty(shape=(0))
404
- for i in samples_index_class:
405
- # Calcula a distância entre os dois vetores e adiciona a lista dos knn, se a distância for menor que a maior da lista.
406
- knn_list = self.__compare_KnearestNeighbors_List(
407
- knn_list, self.__distance(X[i], vector_x))
408
- # Se a média das distâncias na lista dos knn, for menor que o raio, retorna verdadeiro.
409
- distance_mean = np.mean(knn_list)
410
- if self._algorithm == 'V-detector':
411
- return self.__detector_is_valid_to_Vdetector(distance_mean, vector_x)
412
- elif distance_mean > (self.r + self.r_s):
413
- return True # Detector é valido!
414
- else:
415
- distance = None
416
- for i in samples_index_class:
417
- if self._algorithm == 'V-detector':
418
- if distance == None:
419
- distance = self.__distance(X[i], vector_x)
420
- elif distance > self.__distance(X[i], vector_x):
421
- distance = self.__distance(X[i], vector_x)
422
- else:
423
- # Calcula a distância entre os vetores, se menor ou igual ao raio + raio da amostra define a validade do detector como falso.
424
- if (self.r + self.r_s) >= self.__distance(X[i], vector_x):
425
- return False # Detector não é valido!
426
- if self._algorithm == 'V-detector':
427
- return self.__detector_is_valid_to_Vdetector(distance, vector_x)
428
- return True # Detector é valido!
429
-
430
- return False # Detector não é valido!
431
-
432
- def __compare_KnearestNeighbors_List(self, knn: npt.NDArray, distance: float) -> npt.NDArray:
433
- """
434
- Compares the k-nearest neighbor distance at position ``k-1`` in the list ``knn``,
435
- if the distance of the new sample is less, replace it and sort in ascending order.
436
-
437
-
438
- Parameters:
439
- ---
440
- knn (npt.NDArray): List of k-nearest neighbor distances.
441
- distance (float): Distance to check.
442
-
443
- returns:
444
- ---
445
- npt.NDArray: Updated and sorted nearest neighbor list.
446
-
447
- ---
448
-
449
- Compara a distância do k-vizinho mais próximo na posição ``k-1``da lista ``knn``,
450
- se a distância da nova amostra for menor, substitui ela e ordena em ordem crescente.
451
-
452
-
453
- Parameters:
454
- ---
455
- knn (npt.NDArray): Lista de distâncias dos k-vizinhos mais próximos.
456
- distance (float): Distância a ser verificada.
457
-
458
- Returns:
459
- ---
460
- npt.NDArray: Lista de vizinhos mais próximos atualizada e ordenada.
461
- """
462
- # Se a quantidade de distâncias em knn, for menor que k, adiciona a distância.
463
- if (len(knn) < self.k):
464
- knn = np.append(knn, distance)
465
- knn.sort()
466
- else:
467
- # Se não, adicione a distância, se a nova distancia for menor que a maior distância da lista.
468
- if (knn[self.k - 1] > distance):
469
- knn[self.k - 1] = distance
470
- knn.sort()
471
-
472
- return knn
473
-
474
- def __compare_sample_to_detectors(self, line: npt.NDArray):
475
- """
476
- Function to compare a sample with the detectors, verifying if the sample is proper.
477
-
478
- Details:
479
- ---
480
- In this function, when there is class ambiguity, it returns the class that has the greatest
481
- average distance between the detectors.
482
-
483
- Parameters:
484
- ---
485
- * line: vector with N-features
486
-
487
- returns:
488
- ---
489
- * Returns the predicted class with the detectors or None if the sample does not qualify for any class.
490
-
491
- ---
492
-
493
- Função para comparar uma amostra com os detectores, verificando se a amostra é própria.
494
-
495
- Details:
496
- ---
497
- Nesta função, quando possui ambiguidade de classes, retorna a classe que possuir a média de distância
498
- maior entre os detectores.
499
-
500
- Parameters:
501
- ---
502
- * line: vetor com N-características
503
-
504
- Returns:
505
- ---
506
- * Retorna a classe prevista com os detectores ou None se a amostra não se qualificar a nenhuma classe.
507
- """
508
-
509
- # Lista para armazenar as classes e a distância média entre os detectores e a amostra.
510
- possible_classes = []
511
- for _class_ in self.classes:
512
- # Variável para identificar, se a classe foi encontrada com os detectores.
513
- class_found: bool = True
514
- sum_distance = 0 # Variável para fazer o somatório das distâncias.
515
- for detector in self.detectors[_class_]:
516
- # Calcula a distância entre a amostra e os detectores.
517
- distance = self.__distance(detector.position, line)
518
- # Soma as distâncias para calcular a média.
519
- sum_distance += distance
520
- if self._algorithm == 'V-detector':
521
- if distance <= detector.radius:
522
- class_found = False
523
- break
524
- elif distance <= self.r:
525
- class_found = False
526
- break
527
-
528
- # Se a amostra passar por todos os detectores de uma classe, adiciona a classe como possivel previsão.
529
- if class_found:
530
- possible_classes.append([_class_, sum_distance/self.N])
531
- # Se classificar como pertencentes a apenas uma classe, retorna a classe.
532
- if len(possible_classes) == 1:
533
- return possible_classes[0][0]
534
- # Se, pertencer a mais de uma classe, retorna a classe com a distância média mais distante.
535
- elif len(possible_classes) > 1:
536
- return max(possible_classes, key=lambda x: x[1])[0]
537
- else: # Se não, retorna None
538
- return None
539
-
540
- def __distance(self, u: npt.NDArray, v: npt.NDArray):
541
- """
542
- Function to calculate the distance between two points by the chosen ``metric``.
543
-
544
- Parameters:
545
- ---
546
- * u (``npt.NDArray``): Coordinates of the first point.
547
- * v (``npt.NDArray``): Coordinates of the second point.
548
-
549
- returns:
550
- ---
551
- * Distance (``double``) between the two points.
552
-
553
- ---
554
-
555
- Função para calcular a distância entre dois pontos pela ``metric`` escolhida.
556
-
557
- Parameters:
558
- ---
559
- * u (``npt.NDArray``): Coordenadas do primeiro ponto.
560
- * v (``npt.NDArray``): Coordenadas do segundo ponto.
561
-
562
- Returns:
563
- ---
564
- * Distância (``double``) entre os dois pontos.
565
- """
566
- return super().distance(u, v)
567
-
568
- def __detector_is_valid_to_Vdetector(self, distance: float, vector_x: npt.NDArray):
569
- """
570
- Check if the distance between the detector and the samples, minus the radius of the samples,
571
- is greater than the minimum radius.
572
-
573
- Parameters:
574
- ---
575
- distance (``float``): minimum distance calculated between all samples.
576
- vector_x (``numpy.ndarray``): randomly generated candidate detector vector x with values between 0 and 1.
577
- Returns:
578
- ---
579
- * ``False``: if the calculated radius is smaller than the minimum distance or exceeds the edge of the space,
580
- if this option is enabled.
581
- * ``True`` and the distance minus the radius of the samples, if the radius is valid.`
582
-
583
- ----
584
-
585
- Verifique se a distância entre o detector e as amostras, descontando o raio das amostras, é maior do que o raio mínimo.
586
-
587
- Parameters:
588
- ---
589
- distance (``float``): distância mínima calculada entre todas as amostras.
590
- vector_x (``numpy.ndarray``): vetor x candidato do detector gerado aleatoriamente, com valores entre 0 e 1.
591
-
592
- Returns:
593
- ---
594
-
595
- * ``False``: caso o raio calculado seja menor do que a distância mínima ou ultrapasse a borda do espaço,
596
- caso essa opção esteja habilitada.
597
- * ``True`` e a distância menos o raio das amostras, caso o raio seja válido.
598
- """
599
- new_detector_r = float(distance - self.r_s)
600
- if self.r >= new_detector_r:
601
- return False # Detector não é valido!
602
- else:
603
- # se _cell_bounds igual a True, considera o detector esta dentro do limite do plano.
604
- if self._cell_bounds:
605
- for p in vector_x:
606
- if (p - new_detector_r) < 0 or (p + new_detector_r) > 1:
607
- return False
608
- return True, new_detector_r
609
-
610
- def __slice_index_list_by_class(self, y: npt.NDArray) -> dict:
611
- """
612
- The function ``__slice_index_list_by_class(...)``, separates the indices of the lines according to the output class,
613
- to loop through the sample array, only in positions where the output is the class being trained.
614
-
615
- Parameters:
616
- ---
617
- * y (npt.NDArray): Receives a ``y``[``N sample``] array with the output classes of the ``X`` sample array.
618
-
619
- returns:
620
- ---
621
- * dict: A dictionary with the list of array positions(``y``), with the classes as key.
622
-
623
- ---
624
-
625
- A função ``__slice_index_list_by_class(...)``, separa os índices das linhas conforme a classe de saída,
626
- para percorrer o array de amostra, apenas nas posições que a saída for a classe que está sendo treinada.
627
-
628
- Parameters:
629
- ---
630
- * y (npt.NDArray): Recebe um array ``y``[``N amostra``] com as classes de saida do array de amostra ``X``.
631
-
632
- Returns:
633
- ---
634
- * dict: Um dicionário com a lista de posições do array(``y``), com as classes como chave.
635
- """
636
- return super().slice_index_list_by_class(y)
637
-
638
- def score(self, X: npt.NDArray, y: list) -> float:
639
- """
640
- Score function calculates forecast accuracy.
641
-
642
- Details:
643
- ---
644
- This function performs the prediction of X and checks how many elements are equal between vector y and y_predicted.
645
- This function was added for compatibility with some scikit-learn functions.
646
-
647
- Parameters:
648
- -----------
649
-
650
- X: np.ndarray
651
- Feature set with shape (n_samples, n_features).
652
- y: np.ndarray
653
- True values with shape (n_samples,).
654
-
655
- Returns:
656
- -------
657
-
658
- accuracy: float
659
- The accuracy of the model.
660
-
661
- ---
662
-
663
- Função score calcular a acurácia da previsão.
664
-
665
- Details:
666
- ---
667
- Esta função realiza a previsão de X e verifica quantos elementos são iguais entre o vetor y e y_previsto.
668
- Essa função foi adicionada para oferecer compatibilidade com algumas funções do scikit-learn.
669
-
670
- Parameters:
671
- ---
672
-
673
- * X : np.ndarray
674
- Conjunto de características com shape (n_samples, n_features).
675
- * y : np.ndarray
676
- Valores verdadeiros com shape (n_samples,).
677
-
678
- returns:
679
- ---
680
-
681
- accuracy : float
682
- A acurácia do modelo.
683
- """
684
- return super().score(X, y)
685
-
686
- def get_params(self, deep: bool = True) -> dict:
687
- return {
688
- 'N': self.N,
689
- 'r': self.r,
690
- 'k': self.k,
691
- 'metric': self.metric,
692
- 'seed': self.seed,
693
- 'algorithm': self._algorithm,
694
- 'r_s': self.r_s,
695
- 'cell_bounds': self._cell_bounds
696
- }
697
-
698
- class BNSA(Base):
699
- """
700
- The ``BNSA`` (Binary Negative Selection Algorithm) class is for classification and identification purposes.
701
- of anomalies through the self and not self method.
702
-
703
- Attributes:
704
- ---
705
-
706
- * N (``int``): Number of detectors.
707
- * aff_thresh (``float``): The variable represents the percentage of similarity between the T cell and the own samples.
708
- * max_discards (``int``): This parameter indicates the maximum number of detector discards in sequence, which aims to avoid a
709
- possible infinite loop if a radius is defined that it is not possible to generate non-self detectors.
710
- * seed (``int``): Seed for the random generation of values in the detectors.
711
-
712
- * detectors (``dict``): This variable stores a list of detectors by class.
713
- * classes (``npt.NDArray``): list of output classes.
714
-
715
-
716
- ---
717
-
718
- A classe ``BNSA`` (Algoritmo de Seleção Negativa Binária) tem a finalidade de classificação e identificação
719
- de anomalias através do método self e not self .
720
-
721
- Attributes:
722
- ---
723
- * N (``int``): Quantidade de detectores. Defaults to ``100``.
724
- * aff_thresh (``float``): A variável representa a porcentagem de similaridade entre a célula T e as amostras próprias.
725
- O valor padrão é de 10% (0,1), enquanto que o valor de 1,0 representa 100% de similaridade.
726
- * 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
727
- 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``.
728
- * seed (``int``): Semente para a geração randômica dos valores nos detectores. Defaults to ``None``.
729
-
730
- * detectors (``dict``): Essa variável armazena uma lista com detectores por classes.
731
- * classes (``npt.NDArray``): lista com as classes de saída.
732
-
733
- """
734
- def __init__(
735
- self,
736
- N: int = 100,
737
- aff_thresh: float = 0.1,
738
- max_discards: int = 100,
739
- seed: int = None
740
- ):
741
- """
742
- Constructor of the Negative Selection class (``BNSA``).
743
-
744
- Details:
745
- ---
746
- This method initializes the ``detectors``, ``classes``, ``N``, ``t`` and ``seed`` attributes.
747
-
748
- Parameters:
749
- ---
750
- * N (``int``): Number of detectors. Defaults to ``100``.
751
- * aff_thresh (``float``): The variable represents the percentage of similarity between the T cell and the own samples.
752
- The default value is 10% (0.1), while a value of 1.0 represents 100% similarity.
753
- * max_discards (``int``): This parameter indicates the maximum number of detector discards in sequence, which aims to avoid a
754
- possible infinite loop if a radius is defined that it is not possible to generate non-self detectors. Defaults to ``100``.
755
- * seed (``int``): Seed for the random generation of values in the detectors. Defaults to ``None``.
756
-
757
- ---
758
-
759
- Construtor da classe de Seleção negativa (``BNSA``).
760
-
761
- Details:
762
- ---
763
- Este método inicializa os atributos ``detectors``, ``classes``, ``N``, ``t`` e ``seed``.
764
-
765
- Parameters:
766
- ---
767
- * N (``int``): Quantidade de detectores. Defaults to ``100``.
768
- * aff_thresh (``float``): A variável representa a porcentagem de similaridade entre a célula T e as amostras próprias.
769
- O valor padrão é de 10% (0,1), enquanto que o valor de 1,0 representa 100% de similaridade.
770
- * 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
771
- 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``.
772
- * seed (``int``): Semente para a geração randômica dos valores nos detectores. Defaults to ``None``.
773
- """
774
- if N > 0:
775
- self.N: int = N
776
- else:
777
- self.N: int = 100
778
-
779
- if aff_thresh > 0 and aff_thresh < 1:
780
- self.aff_thresh: float = aff_thresh
781
- else:
782
- self.aff_thresh: float = 0.1
783
- if max_discards > 0:
784
- self.max_discards: int = max_discards
785
- else:
786
- self.max_discards: int = 0
787
-
788
- if seed is not None and isinstance(seed, int):
789
- np.random.seed(seed)
790
- self.seed: int = seed
791
- else:
792
- self.seed = None
793
- self.classes: npt.NDArray = None
794
- self.detectors: npt.NDArray = None
795
-
796
- def fit(self, X: npt.NDArray, y: npt.NDArray, verbose: bool = True):
797
- """
798
- The function ``fit(...)``, performs the training according to ``X`` and ``y``, using the method
799
- negative selection method(``NegativeSelect``).
800
-
801
- Parameters:
802
- ---
803
- * X (``npt.NDArray``): Training array, containing the samples and their characteristics,
804
- [``N samples`` (rows)][``N features`` (columns)].
805
- * y (``npt.NDArray``): Array of target classes of ``X`` with [``N samples`` (lines)].
806
- * verbose (``bool``): Feedback from detector generation to the user.
807
- returns:
808
- ---
809
- (``self``): Returns the instance itself.
810
-
811
- ----
812
-
813
- A função ``fit(...)``, realiza o treinamento de acordo com ``X`` e ``y``, usando o método
814
- de seleção negativa(``NegativeSelect``).
815
-
816
- Parameters:
817
- ---
818
- * X (``npt.NDArray``): Array de treinamento, contendo as amostras é suas características,
819
- [``N amostras`` (linhas)][``N características`` (colunas)].
820
- * y (``npt.NDArray``): Array com as classes alvos de ``X`` com [``N amostras`` (linhas)].
821
- * verbose (``bool``): Feedback da geração de detectores para o usuário.
822
- Returns:
823
- ---
824
- (``self``): Retorna a própria instância.
825
- """
826
- if not isinstance(X, (np.ndarray)):
827
- if isinstance(X, (list)):
828
- X = np.array(X)
829
- else:
830
- raise TypeError("X is not an ndarray.")
831
- elif not isinstance(y, (np.ndarray)):
832
- if isinstance(y, (list)):
833
- y = np.array(y)
834
- else:
835
- raise TypeError("y is not an ndarray.")
836
- if X.shape[0] != y.shape[0]:
837
- raise TypeError(
838
- "X does not have the same amount of sample for the output classes in y.")
839
- elif not np.isin(X, [0, 1]).all():
840
- raise Exception(
841
- "The array X contains values that are not composed only of 0 and 1.")
842
-
843
- if X.dtype != bool:
844
- X = X.astype(bool)
845
-
846
- self.classes = np.unique(y)
847
- # Dict que armazenará os detectores com as classes como key.
848
- list_detectors_by_class = dict()
849
- # Separa as classes para o treinamento.
850
- sample_index: dict = self.__slice_index_list_by_class(y)
851
- # Barra de progresso para a geração de todos os detectores.
852
- if verbose:
853
- progress = tqdm(total=int(self.N * (len(self.classes))),
854
- bar_format='{desc} ┇{bar}┇ {n}/{total} detectors', postfix='\n')
855
-
856
- for _class_ in self.classes:
857
- # Inicia o conjunto vazio que conterá os detectores válidos.
858
- valid_detectors_set: list = []
859
- discard_count: int = 0
860
- # Informando em qual classe o algoritmo está para a barra de progresso.
861
- if verbose:
862
- progress.set_description_str(
863
- f'Generating the detectors for the {_class_} class:')
864
- while len(valid_detectors_set) < self.N:
865
-
866
- is_valid_detector: bool = True
867
- # Gera um vetor candidato a detector aleatoriamente com valores 0 e 1.
868
- vector_x = np.random.randint(0, 2, X.shape[1], dtype=bool)
869
- for i in sample_index[_class_]:
870
- # Verifica a validade do detector para o não-próprio com relação às amostras da classe.
871
- if hamming(X[i], vector_x) <= self.aff_thresh:
872
- is_valid_detector = False
873
- break
874
- # Se o detector for válido, adicione a lista dos válidos.
875
- if is_valid_detector:
876
- discard_count = 0
877
- valid_detectors_set.append(vector_x)
878
- if verbose:
879
- progress.update(1)
880
- else:
881
- discard_count += 1
882
- if discard_count == self.max_discards:
883
- raise Exception('An error has been identified:\n'+
884
- f'the maximum number of discards of detectors for the {_class_} class has been reached.\n'+
885
- 'It is recommended to check the defined radius and consider reducing its value.')
886
-
887
- # Adicionar detectores, com as classes como chave na dict.
888
- list_detectors_by_class[_class_] = valid_detectors_set
889
-
890
- # Informar a finalização da geração dos detectores para as classes.
891
- if verbose:
892
- progress.set_description(
893
- f'\033[92m✔ Non-self detectors for classes ({", ".join(map(str, self.classes))}) successfully generated\033[0m')
894
- # Armazena os detectores encontrados no atributo, para os detectores da classe.
895
- self.detectors = list_detectors_by_class
896
- return self
897
-
898
- def predict(self, X: npt.NDArray) -> npt.NDArray:
899
- """
900
- Function to perform the prediction of classes based on detectors
901
- created after training.
902
-
903
- Parameters:
904
- ---
905
- * X (``npt.NDArray``): Array with input samples with [``N samples`` (Lines)] and
906
- [``N characteristics``(Columns)]
907
-
908
- returns:
909
- ---
910
- * C – (``npt.NDArray``): an ndarray of the form ``C`` [``N samples``],
911
- containing the predicted classes for ``X``.
912
- * ``None``: If there are no detectors for the prediction.
913
-
914
- ---
915
-
916
- Função para efetuar a previsão das classes com base nos detectores
917
- criados após o treinamento.
918
-
919
- Parameters:
920
- ---
921
- * X (``npt.NDArray``): Array com as amostras de entradas com [``N amostras`` (Linhas)] e
922
- [``N características``(Colunas)]
923
-
924
- Returns:
925
- ---
926
- * C – (``npt.NDArray``): um ndarray de forma ``C`` [``N amostras``],
927
- contendo as classes previstas para ``X``.
928
- * ``None``: Se não existir detectores para a previsão.
929
- """
930
- if not isinstance(X, (np.ndarray)):
931
- if isinstance(X, (list)):
932
- X = np.array(X)
933
- else:
934
- raise TypeError("X is not an ndarray.")
935
-
936
- if not np.isin(X, [0, 1]).all():
937
- raise Exception(
938
- "The array X contains values that are not composed only of 0 and 1.")
939
-
940
- if X.dtype != bool:
941
- X = X.astype(bool)
942
-
943
- # Inicia um array vazio.
944
- C = np.empty(shape=(0))
945
- # Para cada linha de amostra em X.
946
- for line in X:
947
- class_found: bool = True
948
- # Lista para armazenar as possíveis classes às quais a amostra se adequou ao self na comparação com os detectores non-self.
949
- possible_classes: list = []
950
- for _class_ in self.classes:
951
- # Lista para armzenar as taxas de similaridade entre a amostra e os detectores.
952
- similarity_list: list = []
953
- for detector in self.detectors[_class_]:
954
- similarity = hamming(line, detector)
955
- if similarity <= self.aff_thresh:
956
- class_found = False
957
- break
958
- else:
959
- similarity_list.append(similarity)
960
- # Se a amostra passar por todos os detectores de uma classe, adiciona a classe como possivel previsão e sua media de similaridade.
961
- if class_found:
962
- possible_classes.append([_class_, min(similarity_list)])
963
-
964
- # Se, pertencer a uma ou mais classes, adiciona a classe com a distância média mais distante.
965
- if len(possible_classes) > 0 :
966
- C = np.append(C, [max(possible_classes, key=lambda x: x[1])[0]])
967
- class_found = True
968
- else:
969
- class_found = False
970
-
971
- # Se possuir apenas uma classe e não classificar a amostra define a saída como não-própria.
972
- if not class_found and len(self.classes) == 1:
973
- C = np.append(C, ['non-self'])
974
- # Se não identificar a classe com os detectores, coloca a classe com a maior distância da média dos seus detectores.
975
- elif not class_found:
976
- class_differences = []
977
- for _class_ in self.classes:
978
- differences = []
979
- for detector in self.detectors[_class_]:
980
- differences.append(hamming(line, detector))
981
- class_differences.append(min(differences))
982
- C = np.append(C, [self.classes[class_differences.index(max(class_differences))]])
983
-
984
- return C
985
-
986
- def __slice_index_list_by_class(self, y: npt.NDArray) -> dict:
987
- """
988
- The function ``__slice_index_list_by_class(...)``, separates the indices of the lines according to the output class,
989
- to loop through the sample array, only in positions where the output is the class being trained.
990
-
991
- Parameters:
992
- ---
993
- * y (npt.NDArray): Receives a ``y``[``N sample``] array with the output classes of the ``X`` sample array.
994
-
995
- returns:
996
- ---
997
- * dict: A dictionary with the list of array positions(``y``), with the classes as key.
998
-
999
- ---
1000
-
1001
- A função ``__slice_index_list_by_class(...)``, separa os índices das linhas conforme a classe de saída,
1002
- para percorrer o array de amostra, apenas nas posições que a saída for a classe que está sendo treinada.
1003
-
1004
- Parameters:
1005
- ---
1006
- * y (npt.NDArray): Recebe um array ``y``[``N amostra``] com as classes de saida do array de amostra ``X``.
1007
-
1008
- Returns:
1009
- ---
1010
- * dict: Um dicionário com a lista de posições do array(``y``), com as classes como chave.
1011
- """
1012
- return super().slice_index_list_by_class(y)
1013
-
1014
- def score(self, X: npt.NDArray, y: list) -> float:
1015
- """
1016
- Score function calculates forecast accuracy.
1017
-
1018
- Details:
1019
- ---
1020
- This function performs the prediction of X and checks how many elements are equal between vector y and y_predicted.
1021
- This function was added for compatibility with some scikit-learn functions.
1022
-
1023
- Parameters:
1024
- -----------
1025
-
1026
- X: np.ndarray
1027
- Feature set with shape (n_samples, n_features).
1028
- y: np.ndarray
1029
- True values with shape (n_samples,).
1030
-
1031
- Returns:
1032
- -------
1033
-
1034
- accuracy: float
1035
- The accuracy of the model.
1036
-
1037
- ---
1038
-
1039
- Função score calcular a acurácia da previsão.
1040
-
1041
- Details:
1042
- ---
1043
- Esta função realiza a previsão de X e verifica quantos elementos são iguais entre o vetor y e y_previsto.
1044
- Essa função foi adicionada para oferecer compatibilidade com algumas funções do scikit-learn.
1045
-
1046
- Parameters:
1047
- ---
1048
-
1049
- * X : np.ndarray
1050
- Conjunto de características com shape (n_samples, n_features).
1051
- * y : np.ndarray
1052
- Valores verdadeiros com shape (n_samples,).
1053
-
1054
- returns:
1055
- ---
1056
-
1057
- accuracy : float
1058
- A acurácia do modelo.
1059
- """
1060
- return super().score(X, y)
1061
-
1062
- def get_params(self, deep: bool = True) -> dict:
1063
- return {
1064
- 'N': self.N,
1065
- 'aff_thresh': self.aff_thresh,
1066
- 'max_discards': self.max_discards,
1067
- 'seed': self.seed,
1068
- }
aisp/_base.py DELETED
@@ -1,157 +0,0 @@
1
- import numpy as np
2
- import numpy.typing as npt
3
- from scipy.spatial.distance import euclidean, cityblock, minkowski
4
-
5
- class Base:
6
- """
7
- The base class contains functions that are used by more than one class in the package,
8
- and therefore are considered essential for the overall functioning of the system.
9
-
10
- ---
11
-
12
- A classe base contém funções que são utilizadas por mais de uma classe do pacote,
13
- e por isso são consideradas essenciais para o funcionamento geral do sistema.
14
- """
15
- def __init__(self, metric: str = 'euclidean'):
16
- """
17
- Parameters:
18
- ---
19
- * metric (``str``): Way to calculate the distance between the detector and the sample:
20
-
21
- * ``'Euclidean'`` ➜ The calculation of the distance is given by the expression: √( (x₁ – x₂)² + (y₁ – y₂)² + ... + (yn – yn)²).
22
- * ``'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``.
23
- * ``'manhattan'`` ➜ The calculation of the distance is given by the expression: ( |x₁ – x₂| + |y₁ – y₂| + ... + |yn – yn|) .
24
-
25
- ---
26
-
27
- Parameters:
28
- ---
29
- * metric (``str``): Forma para se calcular a distância entre o detector e a amostra:
30
-
31
- * ``'euclidiana'`` ➜ O cálculo da distância dá-se pela expressão: √( (x₁ – x₂)² + (y₁ – y₂)² + ... + (yn – yn)²).
32
- * ``'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``.
33
- * ``'manhattan'`` ➜ O cálculo da distância dá-se pela expressão: ( |x₁ – x₂| + |y₁ – y₂| + ... + |yn – yn|).
34
-
35
- Defaults to ``'euclidean'``.
36
- """
37
- if metric == 'manhattan' or metric == 'minkowski' or metric == 'euclidean':
38
- self.metric = metric
39
- else:
40
- self.metric = 'euclidean'
41
-
42
- def distance(self, u: npt.NDArray, v: npt.NDArray):
43
- """
44
- Function to calculate the distance between two points by the chosen ``metric``.
45
-
46
- Parameters:
47
- ---
48
- * u (``npt.NDArray``): Coordinates of the first point.
49
- * v (``npt.NDArray``): Coordinates of the second point.
50
-
51
- returns:
52
- ---
53
- * Distance (``double``) between the two points.
54
-
55
- ---
56
-
57
- Função para calcular a distância entre dois pontos pela ``metric`` escolhida.
58
-
59
- Parameters:
60
- ---
61
- * u (``npt.NDArray``): Coordenadas do primeiro ponto.
62
- * v (``npt.NDArray``): Coordenadas do segundo ponto.
63
-
64
- Returns:
65
- ---
66
- * Distância (``double``) entre os dois pontos.
67
- """
68
- if self.metric == 'manhattan':
69
- return cityblock(u, v)
70
- elif self.metric == 'minkowski':
71
- return minkowski(u, v, 2)
72
- else:
73
- return euclidean(u, v)
74
-
75
- def slice_index_list_by_class(self, y: npt.NDArray) -> dict:
76
- """
77
- The function ``__slice_index_list_by_class(...)``, separates the indices of the lines according to the output class,
78
- to loop through the sample array, only in positions where the output is the class being trained.
79
-
80
- Parameters:
81
- ---
82
- * y (npt.NDArray): Receives a ``y``[``N sample``] array with the output classes of the ``X`` sample array.
83
-
84
- returns:
85
- ---
86
- * dict: A dictionary with the list of array positions(``y``), with the classes as key.
87
-
88
- ---
89
-
90
- A função ``__slice_index_list_by_class(...)``, separa os índices das linhas conforme a classe de saída,
91
- para percorrer o array de amostra, apenas nas posições que a saída for a classe que está sendo treinada.
92
-
93
- Parameters:
94
- ---
95
- * y (npt.NDArray): Recebe um array ``y``[``N amostra``] com as classes de saida do array de amostra ``X``.
96
-
97
- Returns:
98
- ---
99
- * dict: Um dicionário com a lista de posições do array(``y``), com as classes como chave.
100
- """
101
- positionSamples = dict()
102
- for _class_ in self.classes:
103
- # Pega as posições das amostras por classes a partir do y.
104
- positionSamples[_class_] = list(np.where(y == _class_)[0])
105
-
106
- return positionSamples
107
-
108
- def score(self, X: npt.NDArray, y: list) -> float:
109
- """
110
- Score function calculates forecast accuracy.
111
-
112
- Details:
113
- ---
114
- This function performs the prediction of X and checks how many elements are equal between vector y and y_predicted.
115
- This function was added for compatibility with some scikit-learn functions.
116
-
117
- Parameters:
118
- -----------
119
-
120
- X: np.ndarray
121
- Feature set with shape (n_samples, n_features).
122
- y: np.ndarray
123
- True values with shape (n_samples,).
124
-
125
- Returns:
126
- -------
127
-
128
- accuracy: float
129
- The accuracy of the model.
130
-
131
- ---
132
-
133
- Função score calcular a acurácia da previsão.
134
-
135
- Details:
136
- ---
137
- Esta função realiza a previsão de X e verifica quantos elementos são iguais entre o vetor y e y_previsto.
138
- Essa função foi adicionada para oferecer compatibilidade com algumas funções do scikit-learn.
139
-
140
- Parameters:
141
- ---
142
-
143
- * X : np.ndarray
144
- Conjunto de características com shape (n_samples, n_features).
145
- * y : np.ndarray
146
- Valores verdadeiros com shape (n_samples,).
147
-
148
- returns:
149
- ---
150
-
151
- accuracy : float
152
- A acurácia do modelo.
153
- """
154
- if len(y) == 0:
155
- return 0
156
- y_pred = self.predict(X)
157
- return np.sum(y == y_pred)/len(y)
@@ -1,8 +0,0 @@
1
- aisp/_base.py,sha256=79DN0Jlt6sy5UbeJxCQ5BJVlgyNY1nbqNfDD5aYMIsk,6023
2
- aisp/NSA/__init__.py,sha256=difX4pOYWybVO9K-Nwrfn122cJYBlftKWad2w0WK2BE,116
3
- aisp/NSA/_negativeSelection.py,sha256=BOhx-eq_MtsK5tCZS6j1jW5O601IWC0KzvQlDBJjENU,48311
4
- aisp-0.1.0.dist-info/LICENSE,sha256=fTqV5eBpeAZO0_jit8j4Ref9ikBSlHJ8xwj5TLg7gFk,7817
5
- aisp-0.1.0.dist-info/METADATA,sha256=UgjpJmJyn0O_PoBmHbjDjCQvZiBvm3Etz2CWJbp7N8E,8113
6
- aisp-0.1.0.dist-info/WHEEL,sha256=pkctZYzUS4AYVn6dJ-7367OJZivF2e8RA9b_ZBjif18,92
7
- aisp-0.1.0.dist-info/top_level.txt,sha256=Q5aJi_rAVT5UNS1As0ZafoyS5dwNibnoyOYV7RWUB9s,5
8
- aisp-0.1.0.dist-info/RECORD,,
@@ -1 +0,0 @@
1
- aisp
File without changes
File without changes