From c53d0da839688127bfc728e70ece228624c7b8e5 Mon Sep 17 00:00:00 2001 From: Siddharth Chaini <40721514+sidchaini@users.noreply.github.com> Date: Sun, 15 Nov 2026 16:01:37 -0500 Subject: [PATCH 1/8] Restore aiqr/cdf dispersion options (work in progress for 0.4.0) Reverts 0c327b0 ("Defer aiqr/cdf dispersion options to 0.4.0") on top of the 0.3.0 release work, bringing back dispersion_stat="aiqr"/"cdf", cdf_grid_size, their tests, and DistanceAnomaly's all-NaN metric-column drop. Before releasing as 0.4.0, consider: fit() should reject unknown dispersion_stat values (currently only predict() raises), and the aiqr docstring caveat ("a score rather than a metric distance in a fixed space") reads inconsistently with the cdf one - both are fixed monotone per-class maps. --- distclassipy/anomaly.py | 9 +++ distclassipy/classifier.py | 101 +++++++++++++++++++++++++++++++-- tests/test_dispersion_stats.py | 63 +++++++++++++++++++- 3 files changed, 164 insertions(+), 9 deletions(-) diff --git a/distclassipy/anomaly.py b/distclassipy/anomaly.py index 937c824..cdfb7d6 100755 --- a/distclassipy/anomaly.py +++ b/distclassipy/anomaly.py @@ -184,6 +184,15 @@ 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) + # Drop metrics that are undefined for every 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 the aggregation. + usable = np.isfinite(metric_scores_arr).any(axis=0) + if not usable.all(): + metric_scores_arr = metric_scores_arr[:, usable] + # remove infinities metric_scores_arr[metric_scores_arr == np.inf] = 1e9 # A large number metric_scores_arr[metric_scores_arr == -np.inf] = ( diff --git a/distclassipy/classifier.py b/distclassipy/classifier.py index 462d263..c8aae97 100755 --- a/distclassipy/classifier.py +++ b/distclassipy/classifier.py @@ -139,12 +139,37 @@ 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", "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. Note this makes the transform depend on which side of the + median the test object lies, so the resulting dissimilarity is a + score rather than a metric distance in a fixed space. + - "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" 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 References ---------- @@ -171,12 +196,14 @@ def __init__( scale: bool = True, central_stat: str = "median", dispersion_stat: str = "std", + cdf_grid_size: int = 1001, ) -> 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 def fit( self, X: np.array, y: np.array, feat_labels: list[str] = None @@ -249,6 +276,33 @@ 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 == "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 @@ -257,8 +311,10 @@ def fit( 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 +326,41 @@ 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) + # Express the result in half-widths around a *unit* reference + # rather than around the raw median. Keeping q2 as an additive + # offset would make ratio-type metrics (Canberra, Clark, ...) + # evaluate |d| / (2*q2 + d), which saturates to zero sensitivity + # whenever the median is large. + ref = 1.0 + rescale = lambda A: ref + (A - q2) / np.where(A > q2, hi, lo) # noqa: E731 + return rescale(X), rescale(XB) + + 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 _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, diff --git a/tests/test_dispersion_stats.py b/tests/test_dispersion_stats.py index f1c3dee..a1752e3 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", "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,50 @@ 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 + + @pytest.mark.parametrize("stat", STATS) def test_anomaly_detector_accepts_stat(data, stat): X, y = data @@ -57,9 +113,10 @@ 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 def test_unknown_stat_raises(data): From b2b99169bbff081bb8406c642e29b55663b8ff11 Mon Sep 17 00:00:00 2001 From: Siddharth Chaini <40721514+sidchaini@users.noreply.github.com> Date: Sun, 15 Nov 2026 17:00:18 -0500 Subject: [PATCH 2/8] Validate parameters in fit(); correct the aiqr docstring caveat DistanceMetricClassifier.fit() now rejects an unknown dispersion_stat or central_stat and a cdf_grid_size < 2 with a clear ValueError. Previously an unknown dispersion_stat was accepted and only failed at predict(), and an unknown central_stat crashed inside pandas ("Empty data passed with indices specified."). DistanceAnomaly and EnsembleDistanceClassifier inherit the check through the classifier they fit. The aiqr caveat called the result "a score rather than a metric distance in a fixed space"; like cdf, aiqr is a fixed continuous monotone per-class reparametrisation, so the metric axioms hold in the transformed space. --- distclassipy/classifier.py | 32 +++++++++++++++++++++++++++++--- tests/test_dispersion_stats.py | 20 +++++++++++++++++--- 2 files changed, 46 insertions(+), 6 deletions(-) diff --git a/distclassipy/classifier.py b/distclassipy/classifier.py index c8aae97..9cdb201 100755 --- a/distclassipy/classifier.py +++ b/distclassipy/classifier.py @@ -34,6 +34,7 @@ along with this program. If not, see . """ +import numbers from typing import Callable, Tuple import numpy as np @@ -58,6 +59,10 @@ "distclassipy.distances": distances, } +# Accepted values for DistanceMetricClassifier parameters (checked in fit) +_CENTRAL_STATS = ("median", "mean") +_DISPERSION_STATS = ("std", "iqr", "aiqr", "cdf") + def initialize_metric_function(metric): """Set the metric function based on the provided metric. @@ -148,9 +153,10 @@ class in the feature space. If True, the data will be scaled based on the - "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. Note this makes the transform depend on which side of the - median the test object lies, so the resulting dissimilarity is a - score rather than a metric distance in a fixed space. + 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. - "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 @@ -231,6 +237,7 @@ def fit( self : object Fitted estimator. """ + self._validate_params() X, y = validate_data(self, X, y) self.classes_ = unique_labels(y) @@ -308,6 +315,25 @@ def fit( 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}." + ) + def _class_transform(self, X: np.ndarray, cl) -> tuple: """Map X and class `cl`'s centroid into that class's scaled space. diff --git a/tests/test_dispersion_stats.py b/tests/test_dispersion_stats.py index a1752e3..273c5f4 100644 --- a/tests/test_dispersion_stats.py +++ b/tests/test_dispersion_stats.py @@ -119,8 +119,22 @@ def test_sklearn_clone_roundtrip(stat): assert c2.get_params()["cdf_grid_size"] == 201 -def test_unknown_stat_raises(data): +@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_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) From a15343ff51a04817a3f97fdb7debc9c6d03cb9d7 Mon Sep 17 00:00:00 2001 From: Siddharth Chaini <40721514+sidchaini@users.noreply.github.com> Date: Sun, 15 Nov 2026 17:02:19 -0500 Subject: [PATCH 3/8] Add asymmetric standard deviation scaling (dispersion_stat="astd") Closes #24 together with "aiqr". "astd" is the second-moment counterpart of "aiqr": per class and feature, deviations above the centroid are measured in units of the upper semi-deviation (RMS deviation of the class's training objects above the centroid) and deviations below it in units of the lower one. On symmetric data both sides equal the standard deviation. Each side is floored at 5% of the full std so a one-sided feature does not blow up the scale (same rationale as the aiqr floor against the IQR). aiqr and astd now share one _asymmetric_rescale helper (unit-reference convention unchanged). Also update DistanceAnomaly's dispersion_stat docstring, which still listed only std/iqr. --- distclassipy/anomaly.py | 5 ++- distclassipy/classifier.py | 71 ++++++++++++++++++++++++++++------ tests/test_dispersion_stats.py | 53 ++++++++++++++++++++++++- 3 files changed, 115 insertions(+), 14 deletions(-) diff --git a/distclassipy/anomaly.py b/distclassipy/anomaly.py index cdfb7d6..3a9d6a3 100755 --- a/distclassipy/anomaly.py +++ b/distclassipy/anomaly.py @@ -60,8 +60,9 @@ 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` diff --git a/distclassipy/classifier.py b/distclassipy/classifier.py index 9cdb201..cdf3803 100755 --- a/distclassipy/classifier.py +++ b/distclassipy/classifier.py @@ -61,7 +61,26 @@ # Accepted values for DistanceMetricClassifier parameters (checked in fit) _CENTRAL_STATS = ("median", "mean") -_DISPERSION_STATS = ("std", "iqr", "aiqr", "cdf") +_DISPERSION_STATS = ("std", "iqr", "aiqr", "astd", "cdf") + + +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): @@ -144,7 +163,7 @@ 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", "aiqr", "cdf"}, default="std" + 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 @@ -157,6 +176,12 @@ class in the feature space. If True, the data will be scaled based on the 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 @@ -168,7 +193,7 @@ class in the feature space. If True, the data will be scaled based on the .. versionadded:: 0.1.0 .. versionchanged:: 0.4.0 - Added "aiqr" and "cdf". + Added "aiqr", "astd" and "cdf". cdf_grid_size : int, default=1001 Number of quantile grid points stored per class and feature when @@ -297,6 +322,22 @@ def fit( 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] @@ -364,14 +405,22 @@ def _class_transform(self, X: np.ndarray, cl) -> tuple: floor = 0.05 * iqr lo = np.maximum(q2 - q1, floor) hi = np.maximum(q3 - q2, floor) - # Express the result in half-widths around a *unit* reference - # rather than around the raw median. Keeping q2 as an additive - # offset would make ratio-type metrics (Canberra, Clark, ...) - # evaluate |d| / (2*q2 + d), which saturates to zero sensitivity - # whenever the median is large. - ref = 1.0 - rescale = lambda A: ref + (A - q2) / np.where(A > q2, hi, lo) # noqa: E731 - return rescale(X), rescale(XB) + 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) diff --git a/tests/test_dispersion_stats.py b/tests/test_dispersion_stats.py index 273c5f4..6dd01d3 100644 --- a/tests/test_dispersion_stats.py +++ b/tests/test_dispersion_stats.py @@ -9,7 +9,7 @@ import distclassipy as dcpy from distclassipy.anomaly import DistanceAnomaly -STATS = ["std", "iqr", "aiqr", "cdf"] +STATS = ["std", "iqr", "aiqr", "astd", "cdf"] @pytest.fixture @@ -100,6 +100,57 @@ def test_aiqr_uses_side_specific_scale(skewed_data): 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 From 614eece4bce5ac7adef14865f82b35b56f98324c Mon Sep 17 00:00:00 2001 From: Siddharth Chaini <40721514+sidchaini@users.noreply.github.com> Date: Sun, 15 Nov 2026 17:03:25 -0500 Subject: [PATCH 4/8] Compute class distances in one helper predict(), predict_and_analyse() and DistanceAnomaly.decision_function() each had their own copy of the per-class scale-then-cdist loop (the classifier ones also special-cased scale=False). Route all three through DistanceMetricClassifier._distance_matrices(), which loops classes on the outside and reuses each scaled copy across metrics. No behaviour change: bit-identical predictions and distances to 0.3.0 across 43 metrics x 4 scaling configs x 4 datasets (688 cases), and identical DistanceAnomaly scores (32 cases). --- distclassipy/anomaly.py | 19 ++----------------- distclassipy/classifier.py | 37 +++++++++++++++++-------------------- 2 files changed, 19 insertions(+), 37 deletions(-) diff --git a/distclassipy/anomaly.py b/distclassipy/anomaly.py index 3a9d6a3..5aee205 100755 --- a/distclassipy/anomaly.py +++ b/distclassipy/anomaly.py @@ -10,7 +10,6 @@ from sklearn.preprocessing import minmax_scale 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 @@ -149,24 +148,10 @@ def decision_function(self, X: np.ndarray) -> np.ndarray: check_is_fitted(self) 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) metric_scores = [] diff --git a/distclassipy/classifier.py b/distclassipy/classifier.py index cdf3803..aae700a 100755 --- a/distclassipy/classifier.py +++ b/distclassipy/classifier.py @@ -427,6 +427,21 @@ def _class_transform(self, X: np.ndarray, cl) -> tuple: raise ValueError(f"Unknown dispersion_stat: {self.dispersion_stat}") + def _distance_matrices(self, X: np.ndarray, metric_args: list) -> 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``. 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. + """ + cols = [[] for _ in metric_args] + for cl in self.classes_: + XA, XB = self._class_transform(X, cl) + for col, metric_arg in zip(cols, metric_args): + col.append(pairwise_distance(XA, XB, metric_arg)) + return [np.column_stack(col) for col in cols] + 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] @@ -486,16 +501,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 @@ -551,16 +557,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_ From bbaaa67cd5ae759ee17b47ec51d0f481295c3ef7 Mon Sep 17 00:00:00 2001 From: Siddharth Chaini <40721514+sidchaini@users.noreply.github.com> Date: Sun, 15 Nov 2026 17:08:30 -0500 Subject: [PATCH 5/8] Add neighbour-based class distance (reference="knn") Closes #25. New `reference` parameter on DistanceMetricClassifier and DistanceAnomaly. "centroid" (default) is unchanged: bit-identical to 0.3.0 on 688 classifier and 32 anomaly cases. With "knn", the distance from a test object to a class is the mean distance to the class's `n_neighbors` (default 5) nearest training objects, in that class's scaled space and with any metric. It follows the shape of the class's distribution rather than a single prototype and acts as a local density estimate: on a toy class with two modes straddling another class, accuracy goes from 0.49 (centroid) to 1.00. n_neighbors=1 is the nearest-training-object distance; n_neighbors >= class size is the mean distance to the whole class. - Query rows are processed in blocks (at most 2**22 distances in memory). - DistanceAnomaly.fit computes its threshold scores leave-one-out: with the training objects counting themselves as neighbours the threshold is biased low (new inliers flagged: ~1.0 at k=1 and ~0.23 at k=5 for contamination=0.1, vs ~0.10 with the fix). - `reference` and `n_neighbors` are validated in fit(). Cost: O(n_test x n_train) distances, e.g. 5000 train x 2000 test x 20 features: classifier predict 2.5 ms -> 0.26 s; DistanceAnomaly with the 16 default metrics 0.02 s -> 17 s. --- distclassipy/anomaly.py | 36 +++++++- distclassipy/classifier.py | 125 ++++++++++++++++++++++++-- tests/test_knn_reference.py | 170 ++++++++++++++++++++++++++++++++++++ 3 files changed, 319 insertions(+), 12 deletions(-) create mode 100644 tests/test_knn_reference.py diff --git a/distclassipy/anomaly.py b/distclassipy/anomaly.py index 5aee205..3e155f2 100755 --- a/distclassipy/anomaly.py +++ b/distclassipy/anomaly.py @@ -66,6 +66,22 @@ class DistanceAnomaly(OutlierMixin, BaseEstimator): 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,6 +94,8 @@ def __init__( central_stat: str = "median", dispersion_stat: str = "std", contamination: float = 0.1, + reference: str = "centroid", + n_neighbors: int = 5, **kwargs, ): self.metrics = metrics @@ -88,6 +106,8 @@ def __init__( self.central_stat = central_stat self.dispersion_stat = dispersion_stat self.contamination = contamination + self.reference = reference + self.n_neighbors = n_neighbors self.kwargs = kwargs def fit(self, X: np.ndarray, y: np.ndarray) -> "DistanceAnomaly": @@ -113,6 +133,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,8 +143,10 @@ 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) + # Calculate anomaly threshold based on train 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_scores = self._scores(X, exclude_self=True) self.offset_ = np.quantile(train_scores, 1.0 - self.contamination) @@ -146,12 +170,18 @@ def decision_function(self, X: np.ndarray) -> np.ndarray: The anomaly score for each sample. Higher is more anomalous. """ check_is_fitted(self) + return self._scores(X) + + def _scores(self, X: np.ndarray, exclude_self: bool = False) -> np.ndarray: + """Anomaly scores; ``exclude_self`` marks X as the fit data (see fit).""" X = check_array(X) metric_args = [initialize_metric_function(m)[1] for m in self.metrics_] # Distance matrix (n_samples, n_classes) for every metric - dist_arrs = self.clf_._distance_matrices(X, metric_args) + dist_arrs = self.clf_._distance_matrices( + X, metric_args, exclude_self=exclude_self + ) metric_scores = [] diff --git a/distclassipy/classifier.py b/distclassipy/classifier.py index aae700a..6d26057 100755 --- a/distclassipy/classifier.py +++ b/distclassipy/classifier.py @@ -35,6 +35,7 @@ """ import numbers +import warnings from typing import Callable, Tuple import numpy as np @@ -62,6 +63,24 @@ # 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: @@ -202,6 +221,30 @@ class in the feature space. If True, the data will be scaled based on the .. 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 ---------- .. [1] "Light Curve Classification with DistClassiPy: a new distance-based @@ -228,6 +271,8 @@ def __init__( 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 @@ -235,6 +280,8 @@ def __init__( 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 @@ -281,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_: @@ -374,6 +427,18 @@ def _validate_params(self) -> None: 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. @@ -427,21 +492,61 @@ def _class_transform(self, X: np.ndarray, cl) -> tuple: raise ValueError(f"Unknown dispersion_stat: {self.dispersion_stat}") - def _distance_matrices(self, X: np.ndarray, metric_args: list) -> list: + 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``. 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. + ``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): - col.append(pairwise_distance(XA, XB, metric_arg)) + 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] @@ -459,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 ---------- @@ -514,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. diff --git a/tests/test_knn_reference.py b/tests/test_knn_reference.py new file mode 100644 index 0000000..b9083cf --- /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" # not silently swallowed by **kwargs + 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 From bf935db8d9044b470e6da5253f7163c8036b1b1d Mon Sep 17 00:00:00 2001 From: Siddharth Chaini <40721514+sidchaini@users.noreply.github.com> Date: Sun, 15 Nov 2026 18:16:04 -0500 Subject: [PATCH 6/8] DistanceAnomaly: reject unknown constructor arguments __init__ accepted **kwargs and stored them in self.kwargs, which nothing ever read, so a typo such as DistanceAnomaly(n_neighbours=5) was silently ignored (and dropped by sklearn's clone/get_params). Remove it; unknown arguments now raise TypeError like any other scikit-learn estimator. --- distclassipy/anomaly.py | 2 -- tests/test_anomaly.py | 11 +++++++++++ tests/test_knn_reference.py | 2 +- 3 files changed, 12 insertions(+), 3 deletions(-) create mode 100644 tests/test_anomaly.py diff --git a/distclassipy/anomaly.py b/distclassipy/anomaly.py index 3e155f2..2050809 100755 --- a/distclassipy/anomaly.py +++ b/distclassipy/anomaly.py @@ -96,7 +96,6 @@ def __init__( contamination: float = 0.1, reference: str = "centroid", n_neighbors: int = 5, - **kwargs, ): self.metrics = metrics self.cluster_agg = cluster_agg @@ -108,7 +107,6 @@ def __init__( self.contamination = contamination self.reference = reference self.n_neighbors = n_neighbors - self.kwargs = kwargs def fit(self, X: np.ndarray, y: np.ndarray) -> "DistanceAnomaly": """ diff --git a/tests/test_anomaly.py b/tests/test_anomaly.py new file mode 100644 index 0000000..8d59868 --- /dev/null +++ b/tests/test_anomaly.py @@ -0,0 +1,11 @@ +"""Tests for DistanceAnomaly behaviour not tied to a specific scaling option.""" + +import pytest + +from distclassipy.anomaly import DistanceAnomaly + + +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_knn_reference.py b/tests/test_knn_reference.py index b9083cf..a97786b 100644 --- a/tests/test_knn_reference.py +++ b/tests/test_knn_reference.py @@ -124,7 +124,7 @@ def sample(n): contamination=0.1, normalize_scores=False, ).fit(X, y) - assert det.clf_.reference == "knn" # not silently swallowed by **kwargs + 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) From f881e891e8c0c9b41dc9ea3ba5b57527456a6a4e Mon Sep 17 00:00:00 2001 From: Siddharth Chaini <40721514+sidchaini@users.noreply.github.com> Date: Sun, 15 Nov 2026 18:19:26 -0500 Subject: [PATCH 7/8] DistanceAnomaly: learn score normalisation at fit time decision_function() recomputed its per-metric normalisation (min-max scaling, NaN fill values, and which metrics are usable) from whatever batch it was given, so a sample's score depended on the other samples scored with it. With the default normalize_scores=True, any sample scored on its own always got 0: e.g. in 0.3.0 predict() on a single point far from all training data returned "inlier". It also made the predict() threshold (learned on training scores) inconsistent with scores of new batches. These are now learned once in fit() from the training scores (usable_metrics_, score_fill_, score_scaler_) and applied unchanged to every batch. Training-set scores, offset_ and predict() on the training data are bit-identical to 0.3.0 (72 configurations); new data can now score above 1 when it lies beyond the training range. Calibration of predict() on new inliers with normalize_scores=True and reference="knn", n_neighbors=1: 15.3% flagged at contamination=0.1 before, 11.0% now. --- distclassipy/anomaly.py | 109 ++++++++++++++++++++++++---------------- tests/test_anomaly.py | 45 +++++++++++++++++ 2 files changed, 110 insertions(+), 44 deletions(-) diff --git a/distclassipy/anomaly.py b/distclassipy/anomaly.py index 2050809..ca2b855 100755 --- a/distclassipy/anomaly.py +++ b/distclassipy/anomaly.py @@ -7,13 +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 .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. @@ -141,11 +149,29 @@ def fit(self, X: np.ndarray, y: np.ndarray) -> "DistanceAnomaly": else: self.metrics_ = self.metrics - # Calculate anomaly threshold based on train 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_scores = self._scores(X, exclude_self=True) + # 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 @@ -165,13 +191,42 @@ 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) - return self._scores(X) + 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 _scores(self, X: np.ndarray, exclude_self: bool = False) -> np.ndarray: - """Anomaly scores; ``exclude_self`` marks X as the fit data (see fit).""" + 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) metric_args = [initialize_metric_function(m)[1] for m in self.metrics_] @@ -197,41 +252,7 @@ def _scores(self, X: np.ndarray, exclude_self: bool = False) -> np.ndarray: metric_scores.append(score_for_metric) - metric_scores_arr = np.array(metric_scores).T # shape (n_samples, n_metrics) - # Drop metrics that are undefined for every 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 the aggregation. - usable = np.isfinite(metric_scores_arr).any(axis=0) - if not usable.all(): - metric_scores_arr = metric_scores_arr[:, usable] - - # 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/tests/test_anomaly.py b/tests/test_anomaly.py index 8d59868..d7f9e1f 100644 --- a/tests/test_anomaly.py +++ b/tests/test_anomaly.py @@ -1,10 +1,55 @@ """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): From 2fd1a72f61dabdf6dba306b240f5aa110ec8adc8 Mon Sep 17 00:00:00 2001 From: Siddharth Chaini <40721514+sidchaini@users.noreply.github.com> Date: Mon, 16 Nov 2026 01:16:45 -0500 Subject: [PATCH 8/8] Set version to 0.4.0 New dispersion options (aiqr, astd, cdf), the neighbour-based class distance (reference="knn"), parameter validation in fit(), and the DistanceAnomaly changes (unknown arguments rejected, score normalisation learned in fit). --- distclassipy/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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",