milia.anomaly.models.knn#

k-nearest-neighbour distance to the training data.

Classes

KNN([n_neighbors, method, metric, contamination])

Distance detector (Ramaswamy et al., 2000): far from its neighbours means anomalous.

KNNConfig(*[, name, kind, space, ...])

Validated hyperparameters of the k-nearest-neighbour detector.

class milia.anomaly.models.knn.KNN(n_neighbors=5, method='largest', metric='minkowski', contamination=0.1)#

Bases: BaseDetector

Distance detector (Ramaswamy et al., 2000): far from its neighbours means anomalous.

Scoring a training row counts the row itself as its nearest neighbour, as any scorer applied to data it was fitted on does; calibrate on held-out normal data (calibrate()) for a threshold with a guarantee.

Parameters:
  • n_neighbors (int) – Number of neighbours.

  • method (Literal['largest', 'mean', 'median']) – "largest" (distance to the k-th neighbour), "mean" or "median".

  • metric (str) – Distance metric.

  • contamination (float) – Expected share of outliers, used for the default threshold.

Examples

>>> import numpy as np
>>> rng = np.random.default_rng(0)
>>> train, cal = rng.normal(size=(200, 2)), rng.normal(size=(100, 2))
>>> model = KNN().fit(train).calibrate(cal, alpha=0.1)
>>> model.flag(np.array([[0.0, 0.0], [8.0, 8.0]])).tolist()
[False, True]
reduce(distances)#

Collapse each row of neighbour distances to one anomaly score.

Parameters:

distances (ndarray) – Neighbour distances, shape (n, k), nearest first.

Return type:

ndarray

Returns:

The k-th distance ("largest"), or the mean or median of the k.

class milia.anomaly.models.knn.KNNConfig(*, name='knn', kind='detector', space=SearchSpace(n_neighbors=(2, 50), method=['largest', 'mean']), n_neighbors=5, method='largest', metric='minkowski', contamination=0.1)#

Bases: BaseModelConfig

Validated hyperparameters of the k-nearest-neighbour detector.

Fields mirror KNN’s constructor; space is the default Optuna search space. Build the detector with make("detector", "knn", ...) or KNN(**config.params()).

Examples

>>> KNNConfig().name
'knn'