Skip to content
2 changes: 1 addition & 1 deletion distclassipy/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
)
from .distances import _ALL_METRICS, _UNIQUE_METRICS

__version__ = "0.3.1"
__version__ = "0.4.0"

__all__ = [
"DistanceMetricClassifier",
Expand Down
146 changes: 95 additions & 51 deletions distclassipy/anomaly.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,21 @@
import numpy as np

from sklearn.base import BaseEstimator, OutlierMixin
from sklearn.preprocessing import minmax_scale
from sklearn.preprocessing import MinMaxScaler
from sklearn.utils.validation import check_array, check_is_fitted

from ._dispatch import pairwise_distance
from .classifier import DistanceMetricClassifier, initialize_metric_function
from .distances import _UNIQUE_METRICS


def _replace_inf(scores: np.ndarray) -> np.ndarray:
"""Copy of ``scores`` with +/-inf replaced by +/-1e9 (large finite values)."""
scores = scores.copy(order="K") # keep layout: same summation order as before
scores[scores == np.inf] = 1e9
scores[scores == -np.inf] = -1e9
return scores


class DistanceAnomaly(OutlierMixin, BaseEstimator):
"""
An anomaly detection system based on a multi-metric distance ensemble.
Expand Down Expand Up @@ -60,12 +67,29 @@ class DistanceAnomaly(OutlierMixin, BaseEstimator):
central_stat : {"mean", "median"}, default="median"
The statistic for calculating the class centroids.

dispersion_stat : {"std", "iqr"}, default="std"
The statistic for calculating class dispersion for scaling.
dispersion_stat : {"std", "iqr", "aiqr", "astd", "cdf"}, default="std"
The statistic for calculating class dispersion for scaling. See
DistanceMetricClassifier for details.

contamination : float, default=0.1
The proportion of outliers expected in the data set. Used for the `predict`
method to determine the threshold for marking outliers.

reference : {"centroid", "knn"}, default="centroid"
Whether an object's distance to a class is measured to the class
centroid, or as the mean distance to its ``n_neighbors`` nearest training
objects (a local density estimate). See DistanceMetricClassifier. With
"knn", the training scores used to set the ``predict`` threshold are
computed leave-one-out, so training objects do not count themselves as
neighbours.

.. versionadded:: 0.4.0

n_neighbors : int, default=5
Number of nearest training objects averaged per class when
``reference="knn"``. Ignored otherwise.

.. versionadded:: 0.4.0
"""

def __init__(
Expand All @@ -78,7 +102,8 @@ def __init__(
central_stat: str = "median",
dispersion_stat: str = "std",
contamination: float = 0.1,
**kwargs,
reference: str = "centroid",
n_neighbors: int = 5,
):
self.metrics = metrics
self.cluster_agg = cluster_agg
Expand All @@ -88,7 +113,8 @@ def __init__(
self.central_stat = central_stat
self.dispersion_stat = dispersion_stat
self.contamination = contamination
self.kwargs = kwargs
self.reference = reference
self.n_neighbors = n_neighbors

def fit(self, X: np.ndarray, y: np.ndarray) -> "DistanceAnomaly":
"""
Expand All @@ -113,6 +139,8 @@ def fit(self, X: np.ndarray, y: np.ndarray) -> "DistanceAnomaly":
scale=self.scale,
central_stat=self.central_stat,
dispersion_stat=self.dispersion_stat,
reference=self.reference,
n_neighbors=self.n_neighbors,
)
self.clf_.fit(X, y)

Expand All @@ -121,9 +149,29 @@ def fit(self, X: np.ndarray, y: np.ndarray) -> "DistanceAnomaly":
else:
self.metrics_ = self.metrics

# Calculate anomaly threshold based on train scores
train_scores = self.decision_function(X)
# Per-metric training scores. Leave-one-out for reference="knn":
# otherwise every training object is its own nearest neighbour, its
# score is biased low, and so is the threshold.
train_raw = self._metric_scores(X, exclude_self=True)

# Everything that turns per-metric scores into the final score is
# learned here, once, from the training scores. Recomputing it on each
# scored batch made a sample's score depend on the rest of the batch
# (a lone sample always scored 0 under min-max scaling).
#
# Drop metrics that are undefined for every training object. This
# happens for correlation-type metrics under dispersion_stat="cdf",
# where the transformed centroid is a constant vector and the
# correlation is therefore undefined; such a column carries no
# information and would otherwise propagate NaNs through aggregation.
self.usable_metrics_ = np.isfinite(train_raw).any(axis=0)
train_raw = _replace_inf(train_raw[:, self.usable_metrics_])
if self.normalize_scores:
# NaN fill value and min-max scaling per metric, from training data
self.score_fill_ = np.nanmean(train_raw, axis=0)
self.score_scaler_ = MinMaxScaler().fit(self._fill_nan(train_raw))

train_scores = self._combine(train_raw)
self.offset_ = np.quantile(train_scores, 1.0 - self.contamination)

return self
Expand All @@ -143,29 +191,50 @@ def decision_function(self, X: np.ndarray) -> np.ndarray:
Returns
-------
scores : ndarray of shape (n_samples,)
The anomaly score for each sample. Higher is more anomalous.
The anomaly score for each sample. Higher is more anomalous. Each
sample is scored independently of the others in X. With
``normalize_scores=True`` every metric's score is min-max scaled
using the *training* scores, so training objects score within
[0, 1] and objects beyond the training range can score above 1.
"""
check_is_fitted(self)
raw = self._metric_scores(X)[:, self.usable_metrics_]
return self._combine(_replace_inf(raw))

def _fill_nan(self, scores: np.ndarray) -> np.ndarray:
"""Replace NaN per-metric scores by that metric's mean training score."""
rows, cols = np.nonzero(np.isnan(scores))
scores = scores.copy(order="K") # keep layout: same summation order as before
scores[rows, cols] = self.score_fill_[cols]
return scores

def _combine(self, metric_scores: np.ndarray) -> np.ndarray:
"""Normalise per-metric scores (if enabled) and aggregate over metrics."""
if self.normalize_scores:
metric_scores = self.score_scaler_.transform(self._fill_nan(metric_scores))
if self.metric_agg == "median":
return np.nanmedian(metric_scores, axis=1)
if self.metric_agg == "mean":
return np.nanmean(metric_scores, axis=1)
if self.metric_agg == "min":
return np.nanmin(metric_scores, axis=1)
if self.metric_agg == "percentile_25":
return np.nanquantile(metric_scores, 0.25, axis=1)
raise ValueError(f"Unknown metric_agg method: {self.metric_agg}")

def _metric_scores(self, X: np.ndarray, exclude_self: bool = False) -> np.ndarray:
"""Per-metric scores (n_samples, n_metrics), aggregated over classes.

``exclude_self`` marks X as the fit data (see fit).
"""
X = check_array(X)

clf = self.clf_
metric_args = [initialize_metric_function(m)[1] for m in self.metrics_]

# Compute the distance matrix (n_samples, n_classes) for every metric.
# The per-class scaling of X is metric-independent, so loop classes
# on the outside and reuse each scaled copy across all metrics.
if clf.scale:
per_metric_cols = [[] for _ in metric_args]
for cl in clf.classes_:
XA, XB = clf._class_transform(X, cl)
for cols, metric_arg in zip(per_metric_cols, metric_args):
cols.append(pairwise_distance(XA, XB, metric_arg))
dist_arrs = [np.column_stack(cols) for cols in per_metric_cols]
else:
XB = clf.df_centroid_.to_numpy()
dist_arrs = [
pairwise_distance(X, XB, metric_arg) for metric_arg in metric_args
]
# Distance matrix (n_samples, n_classes) for every metric
dist_arrs = self.clf_._distance_matrices(
X, metric_args, exclude_self=exclude_self
)

metric_scores = []

Expand All @@ -183,32 +252,7 @@ def decision_function(self, X: np.ndarray) -> np.ndarray:

metric_scores.append(score_for_metric)

metric_scores_arr = np.array(metric_scores).T # shape (n_samples, n_metrics)
# remove infinities
metric_scores_arr[metric_scores_arr == np.inf] = 1e9 # A large number
metric_scores_arr[metric_scores_arr == -np.inf] = (
-1e9
) # A large negative number

if self.normalize_scores:
col_means = np.nanmean(metric_scores_arr, axis=0)
inds = np.where(np.isnan(metric_scores_arr))
metric_scores_arr[inds] = np.take(col_means, inds[1])
metric_scores_arr = minmax_scale(metric_scores_arr, axis=0)

# Aggregate scores across all metrics for final anomaly score
if self.metric_agg == "median":
scores = np.nanmedian(metric_scores_arr, axis=1)
elif self.metric_agg == "mean":
scores = np.nanmean(metric_scores_arr, axis=1)
elif self.metric_agg == "min":
scores = np.nanmin(metric_scores_arr, axis=1)
elif self.metric_agg == "percentile_25":
scores = np.nanquantile(metric_scores_arr, 0.25, axis=1)
else:
raise ValueError(f"Unknown metric_agg method: {self.metric_agg}")

return scores
return np.array(metric_scores).T # shape (n_samples, n_metrics)

def score_samples(self, X: np.ndarray) -> np.ndarray:
"""
Expand Down
Loading
Loading