-
Notifications
You must be signed in to change notification settings - Fork 5
AiNet
The AiNet class implements the Artificial Immune Network algorithm for compression and clustering.
It uses principles from immune network theory, clonal selection, and affinity maturation to compress datasets and find clusters.
For clustering, it optionally uses a Minimum Spanning Tree (MST) to separate distant nodes into groups.
Attributes:
-
N (
int): Number of memory cells (antibodies) in the population. Defaults to 50. -
n_clone (
int): Number of clones generated per selected memory cell. Defaults to 10. -
top_clonal_memory_size (
Optional[int]): Number of highest-affinity antibodies selected for cloning. Defaults to 5. -
n_diversity_injection (
int): Number of new random antibodies injected to maintain diversity. Defaults to 5. -
affinity_threshold (
float): Threshold for cell selection/suppression. Defaults to 0.5. -
suppression_threshold (
float): Threshold for removing similar memory cells. Defaults to 0.5. -
mst_inconsistency_factor (
float): Factor to determine inconsistent MST edges. Defaults to 2.0. -
max_iterations (
int): Maximum number of training iterations. Defaults to 10. -
k (
int): Number of nearest neighbors used for label prediction. Defaults to 3. -
metric (Literal["manhattan", "minkowski", "euclidean"]): Way to calculate the distance between the detector and the sample:
-
'Euclidean'➜ The calculation of the distance is given by the expression: √( (x₁ - x₂)² + (y₁ - y₂)² + ... + (yn - yn)²). -
'minkowski'➜ The calculation of the distance is given by the expression: ( |X₁ - Y₁|p + |X₂ - Y₂|p + ... + |Xn - Yn|p) ¹/ₚ. -
'manhattan'➜ The calculation of the distance is given by the expression: ( |x₁ - x₂| + |y₁ - y₂| + ... + |yn - yn|). Defaults to "Euclidean".
-
-
seed (
Optional[int]): Seed for random number generation. Defaults to None. -
use_mst_clustering (
bool): Whether to perform MST-based clustering. Defaults to True. -
kwargs:
-
p (
float): Parameter for Minkowski distance. Defaults to 2.
-
p (
Other initialized variables:
-
_population_antibodies (
npt.NDArray): Stores the current set of antibodies. -
_memory_network (
dict): Dictionary mapping clusters to antibodies. -
_mst_structure (
scipy.sparse.csr_matrix): MST adjacency structure. -
_mst_mean_distance (
float): Mean of MST edge distances. -
_mst_std_distance (
float): Standard deviation of MST edge distances. -
classes (
list): List of cluster labels.
Trains the AiNet model on input data:
def fit(self, X: npt.NDArray, verbose: bool = True):Input parameters:
- X: Array with input samples (rows) and features (columns).
- verbose: Boolean, default True, enables progress feedback.
Returns the class instance.
Predicts cluster labels for new samples:
def predict(self, X) -> Optional[npt.NDArray]:Input parameters:
- X: Array of input features.
Returns:
- Predictions: Array of cluster labels, or None if clustering is disabled.
Partitions clusters using the MST:
def update_clusters(self, mst_inconsistency_factor: Optional[float] = None):Input parameters:
- mst_inconsistency_factor: Optional float to override the MST inconsistency factor.
Updates:
- _memory_network: Dictionary of cluster labels to antibody arrays.
- classes: List of cluster labels.
Initializes antibody population randomly.
def _init_population_antibodies(self) -> npt.NDArray:Input parameters: None
Returns: Initialized antibodies (npt.NDArray).
Selects top antibodies and generates mutated clones:
def _select_and_clone_population(self, antigen: npt.NDArray, population: npt.NDArray) -> list:Input parameters:
- antigen: Array representing the antigen to which affinities will be computed.
- population: Array of antibodies to be evaluated and cloned.
Returns: List of mutated clones.
Suppresses redundant clones based on thresholds:
def _clonal_suppression(self, antigen: npt.NDArray, clones: list):Input parameters:
- antigen: Array representing the antigen.
- clones: List of candidate clones to be suppressed.
Returns: List of non-redundant, high-affinity clones.
Removes redundant antibodies from memory pool:
def _memory_suppression(self, pool_memory: list) -> list:Input parameters:
- pool_memory: List of antibodies currently in memory.
Returns: Cleaned memory pool (list).
Introduces new random antibodies:
def _diversity_introduction(self) -> npt.NDArray:Input parameters: None
Returns: Array of new antibodies (npt.NDArray).
Calculates stimulus between two vectors:
def _affinity(self, u: npt.NDArray, v: npt.NDArray) -> float:Input parameters:
- u: Array representing the first point.
- v: Array representing the second point.
Returns: Affinity score (float) in [0,1].
Calculates affinity matrix between reference and target vectors:
def _calculate_affinities(self, u: npt.NDArray, v: npt.NDArray) -> npt.NDArray:Input parameters:
-
u: Reference vector (
npt.NDArray) of shape(n_features,). -
v: Target vectors (
npt.NDArray) of shape(n_samples, n_features).
Returns: Array of affinities (npt.NDArray) with shape (n_samples,).
Generates mutated clones:
def _clone_and_mutate(self, antibody: npt.NDArray, n_clone: int) -> npt.NDArray:Input parameters:
- antibody: Original antibody vector to clone and mutate.
- n_clone: Number of clones to generate.
Returns: Array of mutated clones (npt.NDArray) of shape (n_clone, len(antibody)).
Constructs the MST and stores statistics.
def _build_mst(self):Input parameters: None
Raises: ValueError if antibody population is empty.
Updates internal variables:
- _mst_structure: MST adjacency structure.
- _mst_mean_distance: Mean edge distance.
- _mst_std_distance: Standard deviation of MST edge distances.
- De Castro, Leandro & José, Fernando & von Zuben, Antonio Augusto. (2001). aiNet: An Artificial Immune Network for Data Analysis. Available at: https://www.researchgate.net/publication/228378350_aiNet_An_Artificial_Immune_Network_for_Data_Analysis
- SciPy Documentation. Minimum Spanning Tree. Available at: https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csgraph.minimum_spanning_tree
A classe AiNet implementa o algoritmo de Rede Imune Artificial para compressão e clustering.
Ela utiliza princípios da teoria de redes imunes, seleção clonal e maturação por afinidade para comprimir conjuntos de dados e encontrar clusters.
Para clustering, pode opcionalmente utilizar uma Árvore Geradora Mínima (MST) para separar nós distantes em grupos.
Atributos:
-
N (
int): Número de células de memória (anticorpos) na população. Padrão: 50. -
n_clone (
int): Número de clones gerados por célula de memória selecionada. Padrão: 10. -
top_clonal_memory_size (
Optional[int]): Número de anticorpos de maior afinidade selecionados para clonagem. Padrão: 5. -
n_diversity_injection (
int): Número de novos anticorpos aleatórios injetados para manter a diversidade. Padrão: 5. -
affinity_threshold (
float): Limite para seleção/supressão de células. Padrão: 0.5. -
suppression_threshold (
float): Limite para remoção de células de memória semelhantes. Padrão: 0.5. -
mst_inconsistency_factor (
float): Fator para determinar arestas inconsistentes na MST. Padrão: 2.0. -
max_iterations (
int): Número máximo de iterações de treinamento. Padrão: 10. -
k (
int): Número de vizinhos mais próximos usados para predição de rótulos. Padrão: 3. -
metric (Literal["manhattan", "minkowski", "euclidean"]): Forma de calcular a distância entre o detector e a amostra:
-
'euclidean'➜ Distância dada pela expressão: √( (x₁ - x₂)² + (y₁ - y₂)² + ... + (yn - yn)²). -
'minkowski'➜ Distância dada pela expressão: ( |X₁ - Y₁|ᵖ + |X₂ - Y₂|ᵖ + ... + |Xn - Yn|ᵖ )^(¹/ₚ). -
'manhattan'➜ Distância dada pela expressão: ( |x₁ - x₂| + |y₁ - y₂| + ... + |yn - yn|). Padrão: "euclidean".
-
-
seed (
Optional[int]): Semente para geração de números aleatórios. Padrão: None. -
use_mst_clustering (
bool): Define se o clustering baseado em MST deve ser utilizado. Padrão: True. -
kwargs:
-
p (
float): Parâmetro para distância de Minkowski. Padrão: 2.
-
p (
Outras variáveis inicializadas:
-
_population_antibodies (
npt.NDArray): Conjunto atual de anticorpos. -
_memory_network (
dict): Dicionário que mapeia clusters para anticorpos. -
_mst_structure (
scipy.sparse.csr_matrix): Estrutura de adjacência da MST. -
_mst_mean_distance (
float): Média das distâncias das arestas da MST. -
_mst_std_distance (
float): Desvio padrão das distâncias das arestas da MST. -
classes (
list): Lista de rótulos dos clusters.
Treina o modelo AiNet com os dados de entrada:
def fit(self, X: npt.NDArray, verbose: bool = True):Parâmetros de entrada:
- X: Matriz com amostras (linhas) e atributos (colunas).
- verbose: Booleano, padrão True, habilita feedback de progresso.
Retorna a instância da classe.
Prediz os rótulos dos clusters para novas amostras:
def predict(self, X) -> Optional[npt.NDArray]:Parâmetros de entrada:
- X: Matriz de atributos de entrada.
Retorna:
- Predictions: Matriz de rótulos de clusters, ou None caso o clustering esteja desabilitado.
Particiona os clusters utilizando a MST:
def update_clusters(self, mst_inconsistency_factor: Optional[float] = None):Parâmetros de entrada:
- mst_inconsistency_factor: Valor opcional (float) para sobrescrever o fator de inconsistência da MST.
Atualiza:
- _memory_network: Dicionário de rótulos de clusters para vetores de anticorpos.
- classes: Lista de rótulos de clusters.
Inicializa a população de anticorpos aleatoriamente.
def _init_population_antibodies(self) -> npt.NDArray:Parâmetros de entrada: Nenhum
Retorna: Anticorpos inicializados (npt.NDArray).
Seleciona os melhores anticorpos e gera clones mutados:
def _select_and_clone_population(self, antigen: npt.NDArray, population: npt.NDArray) -> list:Parâmetros de entrada:
- antigen: Vetor representando o antígeno para o qual as afinidades serão calculadas.
- population: Matriz de anticorpos a serem avaliados e clonados.
Retorna: Lista de clones mutados.
Suprime clones redundantes com base em limiares:
def _clonal_suppression(self, antigen: npt.NDArray, clones: list):Parâmetros de entrada:
- antigen: Vetor representando o antígeno.
- clones: Lista de clones candidatos a serem suprimidos.
Retorna: Lista de clones não redundantes e de alta afinidade.
Remove anticorpos redundantes da memória:
def _memory_suppression(self, pool_memory: list) -> list:Parâmetros de entrada:
- pool_memory: Lista de anticorpos atualmente na memória.
Retorna: Memória filtrada (list).
Introduce novos anticorpos aleatórios:
def _diversity_introduction(self) -> npt.NDArray:Parâmetros de entrada: Nenhum
Retorna: Conjunto de novos anticorpos (npt.NDArray).
Calcula o estímulo entre dois vetores:
def _affinity(self, u: npt.NDArray, v: npt.NDArray) -> float:Parâmetros de entrada:
- u: Vetor representando o primeiro ponto.
- v: Vetor representando o segundo ponto.
Retorna: Valor de afinidade (float) no intervalo [0,1].
Calcula a matriz de afinidades entre um vetor de referência e vetores-alvo:
def _calculate_affinities(self, u: npt.NDArray, v: npt.NDArray) -> npt.NDArray:Parâmetros de entrada:
-
u: Vetor de referência (
npt.NDArray) de formato(n_features,). -
v: Vetores-alvo (
npt.NDArray) de formato(n_samples, n_features).
Retorna: Vetor de afinidades (npt.NDArray) com formato (n_samples,).
Gera clones mutados:
def _clone_and_mutate(self, antibody: npt.NDArray, n_clone: int) -> npt.NDArray:Parâmetros de entrada:
- antibody: Vetor de anticorpo original a ser clonado e mutado.
- n_clone: Número de clones a serem gerados.
Retorna: Matriz de clones mutados (npt.NDArray) de formato (n_clone, len(antibody)).
Constrói a MST e armazena estatísticas:
def _build_mst(self):Parâmetros de entrada: Nenhum
Exceções: ValueError se a população de anticorpos estiver vazia.
Atualiza variáveis internas:
- _mst_structure: Estrutura de adjacência da MST.
- _mst_mean_distance: Distância média das arestas.
- _mst_std_distance: Desvio padrão das distâncias das arestas da MST.
- De Castro, Leandro & José, Fernando & von Zuben, Antonio Augusto. (2001). aiNet: An Artificial Immune Network for Data Analysis.
- Disponível em: https://www.researchgate.net/publication/228378350_aiNet_An_Artificial_Immune_Network_for_Data_Analysis
- SciPy Documentation. Minimum Spanning Tree. Disponível em: https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csgraph.minimum_spanning_tree