alibi_detect.od.pytorch.knn module

class alibi_detect.od.pytorch.knn.KNNTorch(k, kernel=None, ensembler=None, device=None)[source]

Bases: TorchOutlierDetector

__init__(k, kernel=None, ensembler=None, device=None)[source]

PyTorch backend for KNN detector.

Parameters:
  • k (Union[ndarray, List, Tuple, int]) – Number of nearest neighbors to compute distance to. k can be a single value or an array of integers. If k is a single value the outlier score is the distance/kernel similarity to the k-th nearest neighbor. If k is a list then it returns the distance/kernel similarity to each of the specified k neighbors.

  • kernel (Optional[Module]) – If a kernel is specified then instead of using torch.cdist the kernel defines the k nearest neighbor distance.

  • ensembler (Optional[Ensembler]) – If k is an array of integers then the ensembler must not be None. Should be an instance of alibi_detect.od.pytorch.ensemble.ensembler. Responsible for combining multiple scores into a single score.

  • device (Union[Literal[‘cuda’, ‘gpu’, ‘cpu’], device, None]) – Device type used. The default tries to use the GPU and falls back on CPU if needed. Can be specified by passing either 'cuda', 'gpu', 'cpu' or an instance of torch.device.

fit(x_ref)[source]

Fits the detector

Parameters:

x_ref (Tensor) – The Dataset tensor.

forward(x)[source]

Detect if x is an outlier.

Parameters:

x (Tensor) – torch.Tensor with leading batch dimension.

Return type:

Tensor

Returns:

torch.Tensor of bool values with leading batch dimension.

Raises:

ThresholdNotInferredError – If called before detector has had infer_threshold method called.

score(x)[source]

Computes the score of x

Parameters:

x (Tensor) – The tensor of instances. First dimension corresponds to batch.

Return type:

Tensor

Returns:

Tensor of scores for each element in x.

Raises:

NotFittedError – If called before detector has been fit.