diff --git a/distclassipy/__init__.py b/distclassipy/__init__.py index 71c832e..0a37762 100755 --- a/distclassipy/__init__.py +++ b/distclassipy/__init__.py @@ -34,7 +34,7 @@ ) from .distances import _ALL_METRICS, _UNIQUE_METRICS -__version__ = "0.3.1" +__version__ = "0.4.0" __all__ = [ "DistanceMetricClassifier", diff --git a/distclassipy/anomaly.py b/distclassipy/anomaly.py index 937c824..ca2b855 100755 --- a/distclassipy/anomaly.py +++ b/distclassipy/anomaly.py @@ -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. @@ -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__( @@ -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 @@ -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": """ @@ -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) @@ -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 @@ -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 = [] @@ -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: """ diff --git a/distclassipy/classifier.py b/distclassipy/classifier.py index 462d263..6d26057 100755 --- a/distclassipy/classifier.py +++ b/distclassipy/classifier.py @@ -34,6 +34,8 @@ along with this program. If not, see . """ +import numbers +import warnings from typing import Callable, Tuple import numpy as np @@ -58,6 +60,47 @@ "distclassipy.distances": distances, } +# Accepted values for DistanceMetricClassifier parameters (checked in fit) +_CENTRAL_STATS = ("median", "mean") +_DISPERSION_STATS = ("std", "iqr", "aiqr", "astd", "cdf") +_REFERENCES = ("centroid", "knn") + +# reference="knn": at most this many query-to-training distances are held in +# memory at once (query rows are processed in blocks); 2**22 float64 = 32 MiB. +_KNN_BLOCK_ELEMS = 2**22 + + +def _mean_k_smallest(D: np.ndarray, k: int) -> np.ndarray: + """Row-wise mean of the ``k`` smallest entries of ``D``, ignoring NaN. + + NaN entries (undefined distances, or a training object's distance to + itself when excluded) sort last, so they are only averaged over when fewer + than ``k`` finite values exist, and then skipped by the nan-mean. + """ + smallest = np.partition(D, k - 1, axis=1)[:, :k] + with warnings.catch_warnings(): # all-NaN rows -> NaN, silently + warnings.simplefilter("ignore", RuntimeWarning) + return np.nanmean(smallest, axis=1) + + +def _side_rms(d: np.ndarray, mask: np.ndarray) -> np.ndarray: + """Per-column root-mean-square of ``d`` over ``mask`` entries (0 if none).""" + n = mask.sum(axis=0) + ss = np.where(mask, d**2, 0.0).sum(axis=0) + return np.sqrt(np.divide(ss, n, out=np.zeros_like(ss), where=n > 0)) + + +def _asymmetric_rescale(A, centre, lo, hi): + """Express ``A`` in side-specific spreads around a *unit* reference. + + Deviations above ``centre`` are measured in units of ``hi`` and those below + it in units of ``lo``. The result is offset to 1 rather than 0: keeping the + raw centre as an additive offset would make ratio-type metrics (Canberra, + Clark, ...) evaluate |d| / (2*centre + d), which saturates to zero + sensitivity whenever the centre is large. + """ + return 1.0 + (A - centre) / np.where(A > centre, hi, lo) + def initialize_metric_function(metric): """Set the metric function based on the provided metric. @@ -139,12 +182,68 @@ class in the feature space. If True, the data will be scaled based on the central_stat : {"mean", "median"}, default="median" The statistic used to calculate the central tendency of the data to construct the feature-space centroid. Supported statistics are "mean" and "median". - dispersion_stat : {"std", "iqr"}, default="std" - The statistic used to calculate the dispersion of the data for scaling the - distance. Supported statistics are "std" for standard deviation and "iqr" - for inter-quartile range. + dispersion_stat : {"std", "iqr", "aiqr", "astd", "cdf"}, default="std" + How each class's feature space is rescaled before the distance is taken. + + - "std" : divide by the per-feature standard deviation (the original + Mahalanobis-inspired scaling). + - "iqr" : divide by the inter-quartile range; more robust to outliers. + - "aiqr" : *asymmetric* quantile scaling. Deviations above the median + are measured in units of (q3 - q2) and deviations below it in units + of (q2 - q1), so a skewed feature is no longer forced to be + symmetric. The map is continuous and monotone (piecewise linear with + its kink at the median), i.e. a fixed reparametrisation of each + feature per class, so as with "cdf" the metric axioms hold in the + transformed space. + - "astd" : *asymmetric* standard deviation. Like "aiqr", but the two + sides are measured in units of the class's semi-deviations: the + root-mean-square deviation of its training objects above, and + below, the centroid. This keeps the second-moment sensitivity of + "std" while allowing skew; on symmetric data both sides equal the + standard deviation. + - "cdf" : map each feature through the class's empirical CDF, making + the class uniform on [0, 1]. This generalises the scaling from the + second moment to the whole marginal distribution, and so absorbs + skew, heavy tails and marginal multimodality at once. Because the + map is a fixed monotone reparametrisation per class, the metric + axioms still hold in the transformed space. Caveat: extreme values + saturate at 0 or 1, which is desirable for classification but + discards magnitude information for anomaly ranking. .. versionadded:: 0.1.0 + .. versionchanged:: 0.4.0 + Added "aiqr", "astd" and "cdf". + + cdf_grid_size : int, default=1001 + Number of quantile grid points stored per class and feature when + ``dispersion_stat="cdf"``. Keeps memory independent of training-set + size. + + .. versionadded:: 0.4.0 + + reference : {"centroid", "knn"}, default="centroid" + What a test object's distance to each class is measured against, in + that class's scaled feature space. + + - "centroid" : the class centroid (see ``central_stat``). The original + behaviour. + - "knn" : the class's own training objects. The distance to a class is + the mean distance to its ``n_neighbors`` nearest training objects, so + it follows the shape of the class's distribution (several modes, + curved or elongated classes) instead of a single prototype, and acts + as a local density estimate. ``n_neighbors=1`` is the distance to the + nearest training object; ``n_neighbors`` >= the class size gives the + mean distance to all of its objects. The training data is stored, and + prediction costs one distance per (test object, training object) + pair. + + .. versionadded:: 0.4.0 + + n_neighbors : int, default=5 + Number of nearest training objects averaged per class when + ``reference="knn"`` (capped at the class size). Ignored otherwise. + + .. versionadded:: 0.4.0 References ---------- @@ -171,12 +270,18 @@ def __init__( scale: bool = True, central_stat: str = "median", dispersion_stat: str = "std", + cdf_grid_size: int = 1001, + reference: str = "centroid", + n_neighbors: int = 5, ) -> None: """Initialize the classifier with specified parameters.""" self.metric = metric self.scale = scale self.central_stat = central_stat self.dispersion_stat = dispersion_stat + self.cdf_grid_size = cdf_grid_size + self.reference = reference + self.n_neighbors = n_neighbors def fit( self, X: np.array, y: np.array, feat_labels: list[str] = None @@ -204,6 +309,7 @@ def fit( self : object Fitted estimator. """ + self._validate_params() X, y = validate_data(self, X, y) self.classes_ = unique_labels(y) @@ -222,6 +328,12 @@ def fit( ) self.df_centroid_ = df_centroid + if self.reference == "knn": + # Each class's training objects, plus their row positions in X + # (lets DistanceAnomaly score the training set leave-one-out). + self.train_X_ = {c: X[y == c] for c in self.classes_} + self._train_rows = {c: np.flatnonzero(y == c) for c in self.classes_} + if self.scale and self.dispersion_stat == "std": std_list = [] for cur_class in self.classes_: @@ -249,16 +361,92 @@ def fit( data=np.array(iqr_list), index=self.classes_, columns=feat_labels ) self.df_iqr_ = df_iqr + elif self.scale and self.dispersion_stat == "aiqr": + # Asymmetric (two-sided) quantile scale: the half-width below the + # median and the half-width above it are stored separately, so a + # skewed feature is measured in the units of the side the test + # object actually falls on. + q1, q2, q3 = ( + np.array( + [np.quantile(X[y == c], q=q, axis=0).ravel() for c in self.classes_] + ) + for q in (0.25, 0.5, 0.75) + ) + self.df_q1_ = pd.DataFrame(q1, index=self.classes_, columns=feat_labels) + self.df_q2_ = pd.DataFrame(q2, index=self.classes_, columns=feat_labels) + self.df_q3_ = pd.DataFrame(q3, index=self.classes_, columns=feat_labels) + elif self.scale and self.dispersion_stat == "astd": + # Asymmetric standard deviation: RMS deviation of the class's + # training objects above / below the centroid, per feature. A side + # with no objects gets 0 here and is floored in _class_transform, + # against the full standard deviation (also stored for that). + lo_list, hi_list, std_list = [], [], [] + for cur_class, centre in zip(self.classes_, centroid_list): + cur_X = X[y == cur_class] + d = cur_X - centre + hi_list.append(_side_rms(d, d > 0)) + lo_list.append(_side_rms(d, d < 0)) + std_list.append(np.std(cur_X, axis=0, ddof=1).ravel()) + self.df_semistd_lo_, self.df_semistd_hi_, self.df_std_ = ( + pd.DataFrame(np.array(a), index=self.classes_, columns=feat_labels) + for a in (lo_list, hi_list, std_list) + ) + elif self.scale and self.dispersion_stat == "cdf": + # Full per-class marginal: each feature is mapped through that + # class's empirical CDF, so the class becomes uniform on [0, 1] + # regardless of skew, heavy tails or marginal multimodality. + # A fixed quantile grid keeps the memory cost independent of the + # training-set size. + self.cdf_q_ = np.linspace(0.0, 1.0, self.cdf_grid_size) + self.cdf_grid_ = { + c: np.maximum.accumulate( + np.quantile(X[y == c], q=self.cdf_q_, axis=0), axis=0 + ) + for c in self.classes_ + } self.is_fitted_ = True return self + def _validate_params(self) -> None: + """Raise ValueError for invalid constructor parameters.""" + if self.central_stat not in _CENTRAL_STATS: + raise ValueError( + f"Unknown central_stat: {self.central_stat!r}; " + f"expected one of {_CENTRAL_STATS}." + ) + if self.dispersion_stat not in _DISPERSION_STATS: + raise ValueError( + f"Unknown dispersion_stat: {self.dispersion_stat!r}; " + f"expected one of {_DISPERSION_STATS}." + ) + if not ( + isinstance(self.cdf_grid_size, numbers.Integral) and self.cdf_grid_size >= 2 + ): + raise ValueError( + f"cdf_grid_size must be an integer >= 2, got {self.cdf_grid_size!r}." + ) + if self.reference not in _REFERENCES: + raise ValueError( + f"Unknown reference: {self.reference!r}; expected one of {_REFERENCES}." + ) + if not ( + isinstance(self.n_neighbors, numbers.Integral) + and not isinstance(self.n_neighbors, bool) + and self.n_neighbors >= 1 + ): + raise ValueError( + f"n_neighbors must be an integer >= 1, got {self.n_neighbors!r}." + ) + def _class_transform(self, X: np.ndarray, cl) -> tuple: """Map X and class `cl`'s centroid into that class's scaled space. - Returns ``(XA, XB)`` ready for a pairwise distance call, reproducing - the original multiplicative ``std`` / ``iqr`` scaling exactly. + Returns ``(XA, XB)`` ready for a pairwise distance call. The ``std`` + and ``iqr`` options reproduce the original multiplicative scaling + exactly; ``aiqr`` and ``cdf`` apply a monotone per-feature transform + instead (see the class docstring). """ XB = self.df_centroid_.loc[cl].to_numpy().reshape(1, -1) if not self.scale: @@ -270,8 +458,104 @@ def _class_transform(self, X: np.ndarray, cl) -> tuple: w = (1 / np.clip(disp, a_min=eps, a_max=None)).loc[cl].to_numpy() return X * w, XB * w + if self.dispersion_stat == "aiqr": + q1 = self.df_q1_.loc[cl].to_numpy() + q2 = self.df_q2_.loc[cl].to_numpy() + q3 = self.df_q3_.loc[cl].to_numpy() + # Floor each half-width against the full IQR, not machine epsilon: + # spiky features routinely have one degenerate side (q2 == q1), + # and an epsilon floor would turn that into a ~1e16 scale factor + # that swamps every other feature. + iqr = np.clip(q3 - q1, a_min=eps, a_max=None) + floor = 0.05 * iqr + lo = np.maximum(q2 - q1, floor) + hi = np.maximum(q3 - q2, floor) + return ( + _asymmetric_rescale(X, q2, lo, hi), + _asymmetric_rescale(XB, q2, lo, hi), + ) + + if self.dispersion_stat == "astd": + centre = XB.ravel() + # Same flooring rationale as aiqr, against the full std + std = np.clip(self.df_std_.loc[cl].to_numpy(), a_min=eps, a_max=None) + floor = 0.05 * std + lo = np.maximum(self.df_semistd_lo_.loc[cl].to_numpy(), floor) + hi = np.maximum(self.df_semistd_hi_.loc[cl].to_numpy(), floor) + return ( + _asymmetric_rescale(X, centre, lo, hi), + _asymmetric_rescale(XB, centre, lo, hi), + ) + + if self.dispersion_stat == "cdf": + return self._cdf_transform(X, cl), self._cdf_transform(XB, cl) + raise ValueError(f"Unknown dispersion_stat: {self.dispersion_stat}") + def _distance_matrices( + self, X: np.ndarray, metric_args: list, exclude_self: bool = False + ) -> list: + """Distance from every row of X to every class, for each metric. + + Returns one ``(n_samples, n_classes)`` array per entry of + ``metric_args``: the distance to each class's centroid, or with + ``reference="knn"`` the mean distance to its ``n_neighbors`` nearest + training objects (both in the class's scaled space). Each class's + scaling of X is metric-independent, so classes are looped on the + outside and each scaled copy is reused across all metrics. + + ``exclude_self=True`` means X is the training data passed to ``fit``: + each training object's distance to itself is ignored (leave-one-out). + It only affects ``reference="knn"``. + """ + knn = self.reference == "knn" + if knn and exclude_self: + n_train = sum(len(rows) for rows in self._train_rows.values()) + if X.shape[0] != n_train: + raise ValueError("exclude_self=True requires X to be the fit data.") + cols = [[] for _ in metric_args] + for cl in self.classes_: + XA, XB = self._class_transform(X, cl) + if knn: + XB = self._class_transform(self.train_X_[cl], cl)[0] + self_rows = self._train_rows[cl] if exclude_self else None + for col, metric_arg in zip(cols, metric_args): + if knn: + d = self._knn_distance(XA, XB, metric_arg, self_rows) + col.append(d[:, None]) + else: + col.append(pairwise_distance(XA, XB, metric_arg)) + return [np.column_stack(col) for col in cols] + + def _knn_distance(self, XA, XT, metric_arg, self_rows=None) -> np.ndarray: + """Mean distance from each row of XA to its nearest rows of XT. + + ``self_rows[j]`` is the row of XA that *is* training object ``XT[j]``; + that pair is skipped. Query rows are processed in blocks so at most + ``_KNN_BLOCK_ELEMS`` distances are held in memory at once. + """ + n_train = XT.shape[0] + k = min(self.n_neighbors, n_train) + step = max(1, _KNN_BLOCK_ELEMS // n_train) + out = np.empty(XA.shape[0]) + for start in range(0, XA.shape[0], step): + stop = min(start + step, XA.shape[0]) + D = np.asarray(pairwise_distance(XA[start:stop], XT, metric_arg), float) + if self_rows is not None: + j = np.flatnonzero((self_rows >= start) & (self_rows < stop)) + D[self_rows[j] - start, j] = np.nan + out[start:stop] = _mean_k_smallest(D, k) + return out + + def _cdf_transform(self, X: np.ndarray, cl) -> np.ndarray: + """Empirical-CDF map for one class: feature values -> [0, 1] ranks.""" + grid = self.cdf_grid_[cl] + out = np.empty(X.shape, dtype=float) + for j in range(X.shape[1]): + out[:, j] = np.interp(X[:, j], grid[:, j], self.cdf_q_) + # keep strictly positive: several metrics divide by (u + v) + return np.clip(out, np.finfo(float).eps, 1.0) + def predict( self, X: np.array, @@ -280,8 +564,9 @@ def predict( """Predict the class labels for the provided X. The prediction is based on the distance of each data point in the input sample - to the centroid for each class in the feature space. The predicted class is the - one whose centroid is the closest to the input sample. + to the centroid for each class in the feature space (or, with + ``reference="knn"``, to the class's nearest training objects). The predicted + class is the closest one. Parameters ---------- @@ -322,16 +607,7 @@ def predict( metric_to_use = "euclidean" metric_fn_, metric_arg_ = initialize_metric_function(metric_to_use) - if not self.scale: - dist_arr = pairwise_distance(X, self.df_centroid_.to_numpy(), metric_arg_) - - else: - dist_arr_list = [] - for cl in self.classes_: - XA, XB = self._class_transform(X, cl) - cl_dist = pairwise_distance(XA, XB, metric_arg_) - dist_arr_list.append(cl_dist) - dist_arr = np.column_stack(dist_arr_list) + dist_arr = self._distance_matrices(X, [metric_arg_])[0] y_pred = self.classes_[dist_arr.argmin(axis=1)] return y_pred @@ -344,8 +620,9 @@ def predict_and_analyse( """Predict the class labels for the provided X and perform analysis. The prediction is based on the distance of each data point in the input sample - to the centroid for each class in the feature space. The predicted class is the - one whose centroid is the closest to the input sample. + to the centroid for each class in the feature space (or, with + ``reference="knn"``, to the class's nearest training objects). The predicted + class is the closest one. The analysis involves saving all calculated distances and confidences as an attribute for inspection and analysis later. @@ -387,16 +664,7 @@ def predict_and_analyse( metric_to_use = "euclidean" metric_fn_, metric_arg_ = initialize_metric_function(metric_to_use) - if not self.scale: - dist_arr = pairwise_distance(X, self.df_centroid_.to_numpy(), metric_arg_) - - else: - dist_arr_list = [] - for cl in self.classes_: - XA, XB = self._class_transform(X, cl) - cl_dist = pairwise_distance(XA, XB, metric_arg_) - dist_arr_list.append(cl_dist) - dist_arr = np.column_stack(dist_arr_list) + dist_arr = self._distance_matrices(X, [metric_arg_])[0] self.centroid_dist_df_ = pd.DataFrame( data=dist_arr, index=np.arange(X.shape[0]), columns=self.classes_ diff --git a/tests/test_anomaly.py b/tests/test_anomaly.py new file mode 100644 index 0000000..d7f9e1f --- /dev/null +++ b/tests/test_anomaly.py @@ -0,0 +1,56 @@ +"""Tests for DistanceAnomaly behaviour not tied to a specific scaling option.""" + +import numpy as np + +import pytest + +from distclassipy.anomaly import DistanceAnomaly + + +@pytest.fixture +def data(): + rng = np.random.default_rng(0) + X = np.vstack([rng.normal(0, 1, (150, 4)), rng.normal(5, 1, (150, 4))]) + 10 + y = np.repeat([0, 1], 150) + X_new = np.vstack([rng.normal(0, 1, (40, 4)) + 10, rng.normal(0, 4, (20, 4)) + 30]) + return X, y, X_new + + +@pytest.mark.parametrize("normalize_scores", [True, False]) +@pytest.mark.parametrize("reference", ["centroid", "knn"]) +def test_scores_do_not_depend_on_the_batch(data, normalize_scores, reference): + """A sample's score is the same however the input is split into batches.""" + X, y, X_new = data + det = DistanceAnomaly(normalize_scores=normalize_scores, reference=reference) + det.fit(X, y) + all_at_once = det.decision_function(X_new) + in_pieces = np.concatenate( + [det.decision_function(X_new[:1]), det.decision_function(X_new[1:25])] + + [det.decision_function(X_new[i : i + 1]) for i in range(25, len(X_new))] + ) + np.testing.assert_allclose(in_pieces, all_at_once) + + +def test_single_outlier_scored_alone_is_flagged(data): + """With per-batch min-max scaling, any lone sample used to score 0.""" + X, y, _ = data + det = DistanceAnomaly().fit(X, y) + inlier, outlier = X[:1], np.full((1, X.shape[1]), 60.0) + assert det.decision_function(outlier)[0] > det.decision_function(inlier)[0] + assert det.predict(outlier)[0] == -1 + + +def test_training_scores_are_scaled_to_unit_range(data): + """Normalisation is learned on the training scores (each metric in [0, 1]).""" + X, y, X_new = data + det = DistanceAnomaly(metric_agg="mean").fit(X, y) + train = det.decision_function(X) + assert train.min() >= 0.0 and train.max() <= 1.0 + # objects beyond the training range are not squashed back into [0, 1] + assert det.decision_function(X_new).max() > 1.0 + + +def test_unknown_constructor_argument_is_rejected(): + """A typo must fail loudly instead of being silently ignored.""" + with pytest.raises(TypeError): + DistanceAnomaly(n_neighbours=5) # sic: n_neighbors diff --git a/tests/test_dispersion_stats.py b/tests/test_dispersion_stats.py index f1c3dee..6dd01d3 100644 --- a/tests/test_dispersion_stats.py +++ b/tests/test_dispersion_stats.py @@ -1,4 +1,4 @@ -"""Tests for the dispersion_stat options.""" +"""Tests for the aiqr / cdf dispersion options (v0.4.0).""" import numpy as np @@ -9,7 +9,7 @@ import distclassipy as dcpy from distclassipy.anomaly import DistanceAnomaly -STATS = ["std", "iqr"] +STATS = ["std", "iqr", "aiqr", "astd", "cdf"] @pytest.fixture @@ -20,6 +20,18 @@ def data(): return X - X.min() + 0.1, y # shift positive: many metrics assume >= 0 +@pytest.fixture +def skewed_data(): + """Strongly right-skewed features - the case aiqr/cdf are built for.""" + rng = np.random.default_rng(0) + y = np.repeat([0, 1], 150) + X = np.column_stack( + [rng.lognormal(mean=(0.0 if c else 0.6), sigma=1.2, size=300) for c in range(4)] + ) + X[y == 1] *= 1.8 + return X, y + + @pytest.mark.parametrize("stat", STATS) def test_fit_predict_runs(data, stat): X, y = data @@ -44,6 +56,101 @@ def test_std_path_unchanged(data): ) +def test_cdf_maps_class_to_uniform(data): + """Training members of a class should be ~uniform in the transformed space.""" + X, y = data + clf = dcpy.DistanceMetricClassifier(dispersion_stat="cdf").fit(X, y) + cl = clf.classes_[0] + U = clf._cdf_transform(X[y == cl], cl) + assert U.min() >= 0.0 and U.max() <= 1.0 + # a uniform sample has mean ~0.5 per feature + np.testing.assert_allclose(U.mean(axis=0), 0.5, atol=0.06) + # the class centroid maps to the middle + cent = clf.df_centroid_.loc[cl].to_numpy().reshape(1, -1) + np.testing.assert_allclose(clf._cdf_transform(cent, cl), 0.5, atol=0.02) + + +def test_cdf_is_monotone_and_outlier_bounded(data): + X, y = data + clf = dcpy.DistanceMetricClassifier(dispersion_stat="cdf").fit(X, y) + cl = clf.classes_[0] + probe = np.sort(np.linspace(X.min(), X.max(), 50)) + U = clf._cdf_transform(np.tile(probe[:, None], (1, X.shape[1])), cl) + assert np.all(np.diff(U, axis=0) >= -1e-12) # monotone non-decreasing + wild = clf._cdf_transform(np.full((1, X.shape[1]), 1e9), cl) + assert np.all(wild <= 1.0) # extreme values saturate rather than explode + + +def test_aiqr_uses_side_specific_scale(skewed_data): + """A point above the median is scaled by (q3-q2), below by (q2-q1).""" + X, y = skewed_data + clf = dcpy.DistanceMetricClassifier(dispersion_stat="aiqr").fit(X, y) + cl = clf.classes_[0] + q1 = clf.df_q1_.loc[cl].to_numpy() + q2 = clf.df_q2_.loc[cl].to_numpy() + q3 = clf.df_q3_.loc[cl].to_numpy() + assert np.any((q3 - q2) / (q2 - q1) > 1.5) # genuinely skewed fixture + above, below = (q2 + (q3 - q2))[None, :], (q2 - (q2 - q1))[None, :] + XA, XB = clf._class_transform(np.vstack([above, below]), cl) + # results are expressed in half-widths around a unit reference, so a point + # one half-width above the median lands at 2 and one below at 0 -- the + # asymmetry of the raw feature is absorbed by the side-specific scale + np.testing.assert_allclose(XA[0], 2.0, atol=1e-6) + np.testing.assert_allclose(XA[1], 0.0, atol=1e-6) + np.testing.assert_allclose(XB, 1.0, atol=1e-6) # centroid -> reference + + +def test_astd_semideviations_match_definition(skewed_data): + """Upper/lower spreads are RMS deviations of the points on each side.""" + X, y = skewed_data + clf = dcpy.DistanceMetricClassifier(dispersion_stat="astd").fit(X, y) + for cl in clf.classes_: + Xc = X[y == cl] + c = clf.df_centroid_.loc[cl].to_numpy() + for j in range(X.shape[1]): + d = Xc[:, j] - c[j] + np.testing.assert_allclose( + clf.df_semistd_hi_.loc[cl].iloc[j], np.sqrt(np.mean(d[d > 0] ** 2)) + ) + np.testing.assert_allclose( + clf.df_semistd_lo_.loc[cl].iloc[j], np.sqrt(np.mean(d[d < 0] ** 2)) + ) + + +def test_astd_uses_side_specific_scale(skewed_data): + """A point above the centroid is scaled by the upper spread, below by the lower.""" + X, y = skewed_data + clf = dcpy.DistanceMetricClassifier(dispersion_stat="astd").fit(X, y) + cl = clf.classes_[0] + c = clf.df_centroid_.loc[cl].to_numpy() + lo = clf.df_semistd_lo_.loc[cl].to_numpy() + hi = clf.df_semistd_hi_.loc[cl].to_numpy() + assert np.any(hi / lo > 1.5) # genuinely skewed fixture + XA, XB = clf._class_transform(np.vstack([c + hi, c - lo]), cl) + # same unit-reference convention as aiqr: one spread above -> 2, below -> 0 + np.testing.assert_allclose(XA[0], 2.0, atol=1e-6) + np.testing.assert_allclose(XA[1], 0.0, atol=1e-6) + np.testing.assert_allclose(XB, 1.0, atol=1e-6) # centroid -> reference + + +def test_astd_symmetric_class_has_equal_sides(): + """On symmetric data both spreads coincide (astd reduces to a std scale).""" + z = np.random.default_rng(3).normal(size=(200, 3)) + X = np.vstack([z, -z]) + 5.0 # exactly symmetric about 5 in every feature + y = np.zeros(len(X), dtype=int) + clf = dcpy.DistanceMetricClassifier(dispersion_stat="astd").fit(X, y) + np.testing.assert_allclose(clf.df_semistd_lo_, clf.df_semistd_hi_) + + +def test_astd_one_sided_feature_is_floored(): + """A side with no training points gets a finite (floored) scale.""" + X = np.column_stack([np.r_[np.zeros(30), np.arange(1.0, 11.0)], np.arange(40.0)]) + y = np.zeros(len(X), dtype=int) # feature 0: median 0, nothing below it + clf = dcpy.DistanceMetricClassifier(dispersion_stat="astd").fit(X, y) + XA, _ = clf._class_transform(np.array([[-1.0, 20.0]]), 0) + assert np.all(np.isfinite(XA)) + + @pytest.mark.parametrize("stat", STATS) def test_anomaly_detector_accepts_stat(data, stat): X, y = data @@ -57,13 +164,28 @@ def test_anomaly_detector_accepts_stat(data, stat): def test_sklearn_clone_roundtrip(stat): from sklearn.base import clone - clf = dcpy.DistanceMetricClassifier(dispersion_stat=stat) + clf = dcpy.DistanceMetricClassifier(dispersion_stat=stat, cdf_grid_size=201) c2 = clone(clf) assert c2.get_params()["dispersion_stat"] == stat + assert c2.get_params()["cdf_grid_size"] == 201 + + +@pytest.mark.parametrize( + "params, match", + [ + (dict(dispersion_stat="nonsense"), "Unknown dispersion_stat"), + (dict(central_stat="mode"), "Unknown central_stat"), + (dict(dispersion_stat="cdf", cdf_grid_size=1), "cdf_grid_size"), + ], +) +def test_invalid_params_raise_in_fit(data, params, match): + """Bad parameters fail fast in fit(), not later in predict().""" + X, y = data + with pytest.raises(ValueError, match=match): + dcpy.DistanceMetricClassifier(**params).fit(X, y) -def test_unknown_stat_raises(data): +def test_anomaly_invalid_params_raise_in_fit(data): X, y = data - clf = dcpy.DistanceMetricClassifier(dispersion_stat="nonsense").fit(X, y) with pytest.raises(ValueError, match="Unknown dispersion_stat"): - clf.predict(X, metric="euclidean") + DistanceAnomaly(dispersion_stat="nonsense").fit(X, y) diff --git a/tests/test_knn_reference.py b/tests/test_knn_reference.py new file mode 100644 index 0000000..a97786b --- /dev/null +++ b/tests/test_knn_reference.py @@ -0,0 +1,170 @@ +"""Tests for the neighbour-based class reference (reference="knn", issue #25).""" + +import numpy as np + +import pytest + +from scipy.spatial.distance import cdist + +from sklearn.base import clone + +import distclassipy as dcpy +from distclassipy import classifier as classifier_module +from distclassipy.anomaly import DistanceAnomaly + + +@pytest.fixture +def two_class(): + rng = np.random.default_rng(0) + X = np.vstack([rng.normal(0, 1, (60, 3)), rng.normal(4, 1, (40, 3))]) + 10 + y = np.repeat([0, 1], [60, 40]) + return X, y + + +def brute_force_knn(Xq, Xc, k, metric="euclidean"): + """Mean of the k smallest distances from each query row to Xc.""" + return np.sort(cdist(Xq, Xc, metric=metric), axis=1)[:, :k].mean(axis=1) + + +@pytest.mark.parametrize("k", [1, 3, 1000]) +def test_knn_distance_matches_brute_force_unscaled(two_class, k): + """Mean distance to the k nearest training objects (k capped at class size).""" + X, y = two_class + Xq = X[::7] + 0.3 + clf = dcpy.DistanceMetricClassifier(scale=False, reference="knn", n_neighbors=k) + clf.fit(X, y).predict_and_analyse(Xq, metric="euclidean") + for j, cl in enumerate(clf.classes_): + expected = brute_force_knn(Xq, X[y == cl], min(k, (y == cl).sum())) + np.testing.assert_allclose(clf.centroid_dist_df_.iloc[:, j], expected) + + +def test_knn_distance_uses_class_scaling(two_class): + """With scale=True, query and training objects share the class's scaling.""" + X, y = two_class + Xq = X[::5] - 0.2 + clf = dcpy.DistanceMetricClassifier( + dispersion_stat="std", reference="knn", n_neighbors=4 + ) + clf.fit(X, y).predict_and_analyse(Xq, metric="canberra") + for j, cl in enumerate(clf.classes_): + w = 1 / X[y == cl].std(axis=0, ddof=1) + expected = brute_force_knn(Xq * w, X[y == cl] * w, 4, metric="canberra") + np.testing.assert_allclose(clf.centroid_dist_df_.iloc[:, j], expected) + + +def test_knn_follows_multimodal_class(): + """A two-mode class whose centroid sits on top of another class.""" + rng = np.random.default_rng(1) + + def sample(n): + return ( + np.vstack( + [ + rng.normal([-6, 0], 0.5, (n, 2)), # class 0, mode 1 + rng.normal([6, 0], 0.5, (n, 2)), # class 0, mode 2 + rng.normal([0, 0], 0.5, (n, 2)), # class 1, between them + ] + ), + np.repeat([0, 0, 1], n), + ) + + X, y = sample(100) + Xt, yt = sample(50) + + def accuracy(**params): + clf = dcpy.DistanceMetricClassifier(scale=False, **params).fit(X, y) + return np.mean(clf.predict(Xt) == yt) + + assert accuracy(reference="centroid") < 0.8 + assert accuracy(reference="knn", n_neighbors=5) > 0.98 + + +def test_knn_blocking_matches_single_block(two_class, monkeypatch): + X, y = two_class + clf = dcpy.DistanceMetricClassifier(reference="knn", n_neighbors=3).fit(X, y) + single = clf._distance_matrices(X, ["clark"])[0] + monkeypatch.setattr(classifier_module, "_KNN_BLOCK_ELEMS", 7) # many tiny blocks + np.testing.assert_array_equal(clf._distance_matrices(X, ["clark"])[0], single) + + +def test_knn_exclude_self_is_leave_one_out(two_class): + X, y = two_class + clf = dcpy.DistanceMetricClassifier(scale=False, reference="knn", n_neighbors=1) + clf.fit(X, y) + with_self = clf._distance_matrices(X, ["euclidean"])[0] + loo = clf._distance_matrices(X, ["euclidean"], exclude_self=True)[0] + rows, own = np.arange(len(y)), np.searchsorted(clf.classes_, y) + np.testing.assert_array_equal(with_self[rows, own], 0.0) # finds its own copy + for i in rows: # ... versus the nearest *other* member of its class + others = X[(y == y[i]) & (rows != i)] + np.testing.assert_allclose(loo[i, own[i]], cdist(X[i : i + 1], others).min()) + other = 1 - own # distances to the other class are unaffected + np.testing.assert_array_equal(loo[rows, other], with_self[rows, other]) + + +@pytest.mark.parametrize("k", [1, 5]) +def test_knn_anomaly_threshold_is_calibrated_for_new_data(k): + """Leave-one-out training scores: predict() flags ~contamination of new data. + + normalize_scores=False: per-batch min-max rescaling would mask the (roughly + multiplicative) self-match bias for k > 1; with a single metric it is moot. + """ + rng = np.random.default_rng(2) + + def sample(n): + X = np.vstack([rng.normal(0, 1, (n, 3)), rng.normal(6, 1, (n, 3))]) + 10 + return X, np.repeat([0, 1], n) + + X, y = sample(750) + Xnew, _ = sample(750) + det = DistanceAnomaly( + metrics=["euclidean"], + reference="knn", + n_neighbors=k, + contamination=0.1, + normalize_scores=False, + ).fit(X, y) + assert det.clf_.reference == "knn" # reaches the internal classifier + flagged = np.mean(det.predict(Xnew) == -1) + assert 0.05 < flagged < 0.16 # self-matches would give ~1.0 (k=1), ~0.23 (k=5) + + +def test_knn_anomaly_ranks_outlier_highest(two_class): + X, y = two_class + det = DistanceAnomaly(reference="knn", n_neighbors=5).fit(X, y) + assert det.clf_.reference == "knn" + Xq = np.vstack([X[:20], [[40.0, 40.0, 40.0]]]) + assert det.decision_function(Xq).argmax() == len(Xq) - 1 + + +@pytest.mark.parametrize("stat", ["std", "iqr", "aiqr", "astd", "cdf"]) +def test_knn_works_with_every_dispersion_stat(two_class, stat): + X, y = two_class + clf = dcpy.DistanceMetricClassifier(dispersion_stat=stat, reference="knn") + clf.fit(X, y) + assert np.isfinite(clf._distance_matrices(X, ["canberra"])[0]).all() + + +@pytest.mark.parametrize( + "params, match", + [ + (dict(reference="density"), "Unknown reference"), + (dict(reference="knn", n_neighbors=0), "n_neighbors"), + (dict(reference="knn", n_neighbors=2.5), "n_neighbors"), + ], +) +def test_knn_invalid_params_raise_in_fit(two_class, params, match): + X, y = two_class + with pytest.raises(ValueError, match=match): + dcpy.DistanceMetricClassifier(**params).fit(X, y) + with pytest.raises(ValueError, match=match): + DistanceAnomaly(**params).fit(X, y) + + +def test_knn_params_survive_clone(): + for est in ( + dcpy.DistanceMetricClassifier(reference="knn", n_neighbors=7), + DistanceAnomaly(reference="knn", n_neighbors=7), + ): + params = clone(est).get_params() + assert params["reference"] == "knn" and params["n_neighbors"] == 7