Build a DBSCAN-Based Outlier Detection System for Sensor Data


classical-ml anomaly-detection feature-engineering model-evaluation
View full code for this problem

ML Problem & Solution

Sensor Outlier Detection with DBSCAN

One global radius, two population densities, and a model with no predict method.

⏱ 25 min read 📐 Intermediate 🧩 Classical ML

A facilities contractor maintains 4,100 rooftop HVAC units across 380 commercial buildings. Each unit streams nine channels at 1 Hz: discharge and suction pressure, discharge and return air temperature, ambient temperature, compressor current, three-axis vibration. A compressor that fails without warning costs $9,400 in emergency replacement, overtime and a tenant credit. The same compressor caught a week early costs $2,100 in a scheduled swap. There are 214 confirmed compressor failures in the 18 months of history, and the dispatch team can send 50 technicians a day.

So the target is not “find the anomalies”. It is: fill 50 daily dispatch slots with the units most likely to be failing, and do it early enough that a scheduled swap is still possible.

The obvious approach is static thresholds, and it is what the contractor already runs: alert if discharge temperature exceeds 115 C or vibration RMS exceeds 7.1 mm/s. It fires 340 times a day, catches 34% of the failures, and the median warning is 1.2 days, which is not enough time to order a compressor. The reason it fails is the same reason every fixed threshold on sensor data fails: a rooftop unit running at 38 C ambient under full load is legitimately hot, and the identical reading at 12 C ambient is a fault. A threshold has to be set loose enough for the hottest legitimate operating point, which makes it blind everywhere else.

The second thing that fails is more interesting, because it looks like it should work. A standard density-based outlier detector on the raw feature stream produced 3,100 alerts a day, 61% of which came from 164 units out of 4,100. Those units were not broken. They were in Minneapolis and Duluth, where the operating envelope is genuinely different and there are far fewer units, so they occupy a sparse, legitimate region of feature space. A method that defines an outlier as “a point in a low-density region” cannot distinguish a rare-but-normal operating regime from a fault, and with a single global density threshold it will always choose to condemn the minority.

The third failure is structural and it stops most projects at the deployment step rather than the modelling step. DBSCAN has no predict method, and that is not an oversight in scikit-learn. The algorithm is transductive: it labels the points it was fitted on and defines no function from feature space to a label. A new 10-minute window arriving from a rooftop in Phoenix has nothing to be scored against until someone decides what scoring a new point even means.

The analogy: a fixed threshold asks whether a city is hot. Density-based detection asks whether anyone lives at that temperature. The second question is much better, and asked globally it concludes that nobody should live in Duluth.

Formally: given 10-minute windows of nine-channel 1 Hz telemetry per rooftop unit, flag windows that are not drawn from the unit’s legitimate operating population, optimising precision at 50 dispatches per day and median lead time before a confirmed failure, subject to scoring 590,000 new windows a day and a weekly refit.

Framing the Problem

This is unsupervised outlier detection with a small labelled evaluation set, and keeping those two halves separate is most of the discipline. The 214 confirmed failures are never used to fit anything. They exist to answer three questions the unsupervised objective cannot: did we catch it, how early, and how many dispatches did we waste doing it. Treating them as training labels would be a reasonable alternative project, and a worse one, because 214 positives against 320 million windows is not enough to learn a decision boundary and the failure modes in the next 18 months will not be the ones in the last 18.

The target is a per-window binary flag, aggregated to a per-unit-day dispatch decision. A window is 10 minutes of 1 Hz data per unit, which is 600 samples per channel, chosen because it is long enough to estimate a vibration spectrum and short enough that the unit’s operating state is roughly constant within it. At 144 windows per unit per day and 4,100 units, that is 590,400 windows a day.

Constraints, in the order they bind:

  • Rare-but-normal operating regimes must not be condemned. This is the constraint that shaped the most code, and it is the one a single global eps cannot satisfy.
  • New windows must be scorable without a refit. 590,000 arrivals a day against a weekly refit means the model has to define an out-of-sample rule, which DBSCAN does not ship.
  • Each alert needs a channel attribution. A technician driving to a roof needs “suction superheat and axial vibration, both outside this unit’s envelope for this regime”, not an anomaly score.
  • Lead time of at least 5 days, because that is the compressor procurement lead time. An alert 18 hours before failure is a correct prediction and a useless one.

The success metric is precision at 50 dispatches per day, averaged across days. The guardrail metrics are recall of confirmed failures within a 21-day window before the failure, median lead time, and noise fraction per unit, which must stay within a band: a unit whose windows are 40% flagged is not 40% broken, it is a unit whose regime the model has not learned.

Metric That Matters

There is no ROC curve here, and reaching for one is the first mistake. With 214 positives and 320 million windows, the negative class is so overwhelming that ROC-AUC is determined entirely by how the model ranks normal windows against each other, which nobody cares about, and a detector can score 0.97 ROC-AUC while filling every one of the 50 daily slots with false alarms. The metric that tracks the actual system is **precision at 50 dispatches per day paired with median lead time**, and the pairing is not optional: precision alone is maximised by alerting 12 hours before failure, when the signal is unmistakable and the compressor is already unsaveable. We report the pair and treat any configuration with median lead time under 5 days as a failed configuration regardless of its precision, because 5 days is the procurement lead time and an alert that arrives later has no action attached to it.

Out of scope: remaining-useful-life regression, root-cause classification across the eleven known failure modes, and control actions. Each needs labels this project does not have.

Data and Features

Nine raw channels at 1 Hz become 34 window features, in four families. Eleven statistical summaries per channel group (mean, standard deviation, 5th and 95th percentile of the pressures, temperatures and current). Six spectral features from the FFT of each vibration axis: band energy in 0 to 20 Hz, 20 to 120 Hz, and 120 to 400 Hz, which is where bearing and valve signatures live. Nine thermodynamic derivations, the important ones being suction superheat and discharge subcooling, computed from the pressure and temperature pairs through a refrigerant property table, because those two numbers are what a service technician actually reads and they are not linear functions of the raw channels. And eight dynamics features: compressor cycling rate, current crest factor, the slope of discharge temperature within the window, and short-lag autocorrelations.

# Window featurisation. The spectral bands and the thermodynamic derivations
# carry most of the early-failure signal; the raw means carry almost none,
# because a failing compressor looks normal on average long before it looks
# normal in its spectrum.
import numpy as np
from scipy import signal

VIB_BANDS = [(0.0, 20.0), (20.0, 120.0), (120.0, 400.0)]

def spectral_band_energy(axis: np.ndarray, fs: float = 1.0,
                         bands=VIB_BANDS) -> dict:
    """Welch PSD integrated over fixed bands.

    At fs = 1 Hz the usable band is 0 to 0.5 Hz, so in production these come
    from the 400 Hz burst channel rather than the 1 Hz trend channel. The
    function is the same; only fs changes.
    """
    freqs, psd = signal.welch(axis, fs=fs, nperseg=min(256, len(axis)))
    out = {}
    for low, high in bands:
        mask = (freqs >= low) & (freqs < high)
        out[f"band_{int(low)}_{int(high)}"] = float(psd[mask].sum())
    total = float(psd.sum()) + 1e-12
    for key in list(out):
        out[f"{key}_frac"] = out[key] / total
    return out

def superheat_subcooling(suction_pressure_kpa: np.ndarray,
                         suction_temp_c: np.ndarray,
                         discharge_pressure_kpa: np.ndarray,
                         liquid_line_temp_c: np.ndarray,
                         sat_temp_fn) -> dict:
    """The two numbers a service technician reads first.

    Superheat is suction temperature minus the saturation temperature at
    suction pressure. It is not a linear function of either input, so a model
    given only the raw channels has to discover a refrigerant property table
    from data, which it will not do from 214 positives.

    Note the fourth argument. Subcooling is read at the LIQUID LINE, not at
    the compressor discharge: discharge gas sits well above saturation, so
    passing it here returns a large negative number that looks like a
    catastrophic charge fault on every healthy unit in the fleet. We shipped
    that substitution for two days.
    """
    superheat = suction_temp_c - sat_temp_fn(suction_pressure_kpa)
    subcooling = sat_temp_fn(discharge_pressure_kpa) - liquid_line_temp_c
    return {"superheat_mean": float(np.mean(superheat)),
            "superheat_std": float(np.std(superheat)),
            "subcooling_mean": float(np.mean(subcooling)),
            "pressure_ratio": float(np.mean(discharge_pressure_kpa
                                            / np.maximum(suction_pressure_kpa,
                                                         1.0)))}

Regime conditioning, which is the real feature engineering

A fixed threshold fails because the legitimate operating envelope moves with ambient temperature and load. The fix is not a cleverer detector, it is to subtract the envelope before detecting. Every feature is standardised within its operating regime and within its own unit, where a regime is a cell of the ambient temperature by load grid.

# Regime-conditioned standardisation. This is the step that turns "this unit
# is hot" into "this unit is hot for a 34 C afternoon at 80% load", and it is
# worth more than the choice of detector.
import numpy as np
import pandas as pd

AMBIENT_BINS = [-40, 0, 10, 18, 24, 30, 36, 60]
LOAD_BINS = [0.0, 0.25, 0.5, 0.75, 0.9, 1.01]

def assign_regime(frame: pd.DataFrame) -> pd.Series:
    """Ambient by load cell. 7 x 5 = 35 cells, of which 22 are populated."""
    ambient = pd.cut(frame["ambient_c"], AMBIENT_BINS, labels=False)
    load = pd.cut(frame["load_fraction"], LOAD_BINS, labels=False)
    return (ambient.astype("Int64") * 10 + load.astype("Int64")).astype("Int64")

def regime_conditioned_z(frame: pd.DataFrame, feature_cols: list[str],
                         scale_prior: float = 400.0,
                         mean_prior: float = 5.0) -> pd.DataFrame:
    """Standardise each feature against the unit's own history in that regime.

    Shrinkage toward the building then the fleet, rather than a hard
    threshold, and with very different prior weights for the mean and the
    scale. The two weights encode the thing that makes a hard threshold
    wrong: a unit's mean in a regime is usable from a handful of windows and
    its standard deviation is not usable until hundreds.

    Both ends of the threshold version fail. Below it, the unit's own mean is
    discarded, so the z score carries the unit's offset from its neighbours
    as signal, and with per-unit offsets of half a standard deviation the
    healthy population grows a tail that swallows the faults. Above it, a
    unit that happened to sit still in one regime gets a standard deviation
    near zero and every later window there becomes a z score in the hundreds:
    that is how 38 of 50 dispatches on the pilot's first day went to one
    building retrofitted the previous Friday.
    """
    out = frame.copy()
    keys = ["unit_id", "regime"]
    n = out.groupby(keys)[feature_cols[0]].transform("size").to_numpy()
    for col in feature_cols:
        unit_mu = out.groupby(keys)[col].transform("mean").to_numpy()
        unit_sd = out.groupby(keys)[col].transform("std").to_numpy()
        bldg_mu = out.groupby(["building_id", "regime"])[col].transform("mean")
        bldg_sd = out.groupby(["building_id", "regime"])[col].transform("std")
        fleet_mu = out.groupby("regime")[col].transform("mean").to_numpy()
        fleet_sd = out.groupby("regime")[col].transform("std").to_numpy()
        ref_mu = np.where(bldg_sd.notna(), bldg_mu, fleet_mu)
        ref_sd = np.where(bldg_sd.notna(), bldg_sd, fleet_sd)
        # Floor the borrowed scale. A building with two windows in some
        # regime reports a standard deviation three orders of magnitude
        # below the fleet's, and that single cell produces the entire tail.
        ref_sd = np.maximum(np.nan_to_num(ref_sd, nan=1.0),
                            0.2 * out[col].std())
        w_mu = n / (n + mean_prior)
        w_sd = n / (n + scale_prior)
        mu = w_mu * np.nan_to_num(unit_mu) + (1 - w_mu) * ref_mu
        var = (w_sd * np.nan_to_num(unit_sd, nan=ref_sd) ** 2
               + (1 - w_sd) * ref_sd ** 2)
        out[f"z_{col}"] = (out[col].to_numpy() - mu) / np.sqrt(var)
    return out

The reference statistics themselves need a period known to be healthy, and getting that wrong is more expensive than any parameter in this post. Computed over the whole archive, a failing unit’s own degradation inflates its own reference standard deviation, so the fault is partly normalised away by the statistics it produced. We compute them on a trailing 90-day window and exclude any unit with an open work order, which cost 2.8 days of median lead time to discover was necessary.

Regime conditioning was worth more than every subsequent modelling decision combined: precision at 50 went from 0.29 to 0.54 with the detector unchanged. It also fixes the scale problem for free. eps in DBSCAN is a single radius in the feature space, so a feature measured in kPa and a feature measured in mm/s cannot coexist unstandardised, and the conditioning leaves everything in units of within-regime standard deviations.

The leakage specific to this problem

Sensor data has one leak so characteristic of DBSCAN that it deserves the whole section.

Temporal autocorrelation turns a fault into a cluster. Consecutive 10-minute windows from one unit are near-duplicates: the lag-1 correlation of the regime-conditioned feature vector is 0.94. Now consider a fault that develops over four hours, producing 24 anomalous windows that are all similar to each other. DBSCAN’s definition of a core point is a point with at least min_samples neighbours within eps. Those 24 windows are each other’s neighbours. With min_samples = 10 they satisfy the core-point condition and DBSCAN labels them a cluster, which is to say normal. The fault becomes a cluster precisely because it lasted long enough to matter.

We measured this directly: without temporal handling, 71 of the 214 confirmed failures had their pre-failure windows assigned to a cluster rather than to noise, and the ones that escaped detection were disproportionately the slow-developing bearing failures, which are exactly the ones worth catching early.

The fix has two parts. Thin the fit set so that no two windows from the same unit are within 6 hours of each other, which removes the near-duplicate structure from the density estimate. And count neighbours for the core-point test at the level of distinct unit-days rather than windows, so a cluster has to be supported by many units rather than by one unit for a long time.

There is a second route to the same outcome that thinning does not touch, and it is worth separating because the fixes differ. DBSCAN clusters by transitive connectivity: if A is within eps of B and B of C, all three are one cluster, however far A is from C. A fault that drifts outward gradually leaves a continuum of intermediate windows behind it, so the endpoint stays chained to the normal cluster no matter how far out it ends up. Thinning does not help, because the chain is made of genuinely distinct windows, and neither does lowering eps, because the chain simply breaks at a different point. What helps is not relying on the label at all: the margin defined below keeps the distance the label discarded, and a chained window with a margin of 4.1 is still ranked above a healthy one at 0.3.

# Temporal handling. Without this, a four-hour fault is a cluster and DBSCAN
# reports it as normal, which is the single most common way this method
# silently fails on sensor data.
import numpy as np
import pandas as pd

def thin_for_fit(frame: pd.DataFrame, min_gap_hours: float = 6.0,
                 seed: int = 17) -> np.ndarray:
    """Row indices for the fit set, with near-duplicate windows removed.

    Lag-1 correlation of the conditioned feature vector is 0.94, so adjacent
    windows inflate every local density estimate and a long fault episode
    reaches the core-point threshold on its own.
    """
    rng = np.random.default_rng(seed)
    keep = []
    for _, block in frame.groupby("unit_id", sort=False):
        times = block["window_start"].to_numpy()
        order = np.argsort(times)
        last = None
        for pos in order:
            ts = times[pos]
            if last is None or (ts - last) / np.timedelta64(1, "h") >= min_gap_hours:
                keep.append(block.index[pos])
                last = ts
    return np.asarray(keep)

def unit_day_support(labels: np.ndarray, unit_day: np.ndarray) -> pd.Series:
    """How many distinct unit-days support each cluster.

    A cluster supported by 3 unit-days is one unit having a bad week, not a
    legitimate operating mode, and it should be reclassified as anomalous.
    This is the check that catches the residual cases thinning misses.
    """
    frame = pd.DataFrame({"label": labels, "unit_day": unit_day})
    return (frame[frame["label"] >= 0]
            .groupby("label")["unit_day"].nunique())

The second leak is ordinary and still worth naming: windows after a failure must be excluded from the fit set. A failed compressor produces spectacular telemetry, and leaving 40 hours of post-failure windows in the training data gives the model a dense cluster of catastrophic readings, which it then treats as a legitimate operating regime. Cut the fit set at the failure timestamp, not at the repair timestamp.

Key Insight

Everything in this section is an attempt to make one sentence true: the feature vector of a healthy unit should look the same whatever the weather. That reframing is what turns an anomaly detector into a tractable problem, and it is why the fallback rules in `regime_conditioned_z` get more lines than the detector does. It also sets the unit of `eps`, which is the quietly important consequence: after conditioning, every axis is measured in within-regime standard deviations, so `eps = 2.4` means "further from the normal operating envelope than 2.4 standard deviations of ordinary variation". That is a sentence a controls engineer can dispute, and a controls engineer disputing your parameter is the best thing that can happen to a monitoring system.

The Naive Baseline

Three baselines, because the interesting question is not whether DBSCAN beats a threshold. It is whether DBSCAN beats the detector you would reach for instead.

# The three baselines. The isolation forest is the important one: it is the
# default choice for this problem and it does not need eps, min_samples, or
# a solution to the no-predict problem.
import numpy as np
from sklearn.ensemble import IsolationForest
from sklearn.neighbors import LocalOutlierFactor

def static_threshold_scores(frame) -> np.ndarray:
    """What the contractor runs today: two fixed limits, ambient-blind."""
    temp_excess = (frame["discharge_temp_c"] - 115.0) / 10.0
    vib_excess = (frame["vib_rms_mms"] - 7.1) / 2.0
    return np.maximum(temp_excess, vib_excess)

def isolation_forest_baseline(Z_fit: np.ndarray, Z_score: np.ndarray,
                              contamination: float = 0.01,
                              seed: int = 17) -> np.ndarray:
    """Axis-aligned random splits. Has a decision_function, so no transduction
    problem, and no eps to choose."""
    model = IsolationForest(n_estimators=300, max_samples=8192,
                            contamination=contamination, random_state=seed,
                            n_jobs=-1).fit(Z_fit)
    return -model.score_samples(Z_score)  # higher is more anomalous

def lof_baseline(Z_fit: np.ndarray, Z_score: np.ndarray,
                 n_neighbors: int = 40) -> np.ndarray:
    """Local density relative to each point's own neighbourhood, which is the
    property DBSCAN's single global eps lacks. novelty=True gives it a
    score_samples, unlike DBSCAN."""
    model = LocalOutlierFactor(n_neighbors=n_neighbors, novelty=True,
                               n_jobs=-1).fit(Z_fit)
    return -model.score_samples(Z_score)

Numbers on the held-out final 5 months, 62 confirmed failures, 50 dispatches a day:

  • Static thresholds: precision at 50 0.21, recall 0.34, median lead time 1.2 days.
  • Isolation forest on the 34 raw features: precision 0.44, recall 0.56, median lead time 3.8 days.
  • Isolation forest on regime-conditioned features: precision 0.58, recall 0.69, median lead time 6.1 days.
  • Local outlier factor, regime-conditioned, n_neighbors=40: precision 0.61, recall 0.72, median lead time 7.0 days.

The third line is the one that matters for the rest of this post. Swapping the feature representation was worth 0.14 precision and 2.3 days of lead time with the detector untouched, which is more than any detector change that follows.

Key Insight

Two of those four baselines already have what DBSCAN lacks. `IsolationForest` and `LocalOutlierFactor` with `novelty=True` both expose a `score_samples`, so a new window is scored by a function call, and neither has an `eps` to calibrate. If you are choosing a detector on capability alone, DBSCAN loses to both. The reasons to use it anyway are specific and they are the reasons this post exists: it produces an explicit set of core points that define the normal operating population, which is an auditable artifact a technician can be shown; it has a notion of a border point, which distinguishes "unusual" from "unprecedented"; and its parameters are physically interpretable, so `eps = 2.4` in units of within-regime standard deviations is a sentence a controls engineer can argue with, where a 300-tree isolation forest's contamination parameter is not. If none of those three matter to you, use the isolation forest.

The Solution

Pipeline from nine-channel 1 Hz rooftop telemetry through 10-minute windowing and 34 features, regime-conditioned standardisation against the unit's own history, temporal thinning to a 6 hour minimum gap, dimension reduction from 34 to 8 by relative contrast, per-regime DBSCAN with eps calibrated to a target noise fraction, a nearest-core-point rule for scoring new windows, and triage into 50 daily dispatches at 0.71 precision

DBSCAN has exactly two parameters and one missing method, and all three of the sections below are about those.

The mechanism, stated so the parameters make sense: a point is a core point if at least min_samples other points lie within distance eps. Core points that are within eps of each other join the same cluster. A non-core point within eps of a core point is a border point and joins that cluster. Everything else is noise, and noise is the output we want. The analogy: eps is how far you are willing to walk to find a neighbour, min_samples is how many neighbours make a neighbourhood, and noise is everyone who lives too far from everyone else.

Dimensionality, because 34 features is too many

Density-based methods degrade in high dimensions for a reason that is easy to state and easy to forget: as dimension grows, the distance from a point to its nearest neighbour and to its farthest neighbour converge. If every point is roughly equidistant from every other point, there is no such thing as a dense region and eps has no useful value. The measurable version is relative contrast, the ratio of the mean pairwise distance to the mean nearest-neighbour distance.

# Relative contrast. If this is near 1, no eps exists that separates dense
# from sparse and DBSCAN cannot work at that dimension, whatever you tune.
import numpy as np
from sklearn.neighbors import NearestNeighbors

def relative_contrast(Z: np.ndarray, sample: int = 4000,
                      seed: int = 17) -> float:
    """(mean pairwise distance) / (mean 1-NN distance) on a random subsample."""
    rng = np.random.default_rng(seed)
    idx = rng.choice(len(Z), size=min(sample, len(Z)), replace=False)
    S = Z[idx]
    nn = NearestNeighbors(n_neighbors=2).fit(S)
    d_nn = nn.kneighbors(S)[0][:, 1].mean()
    pairs = rng.choice(len(S), size=(20000, 2))
    d_all = np.linalg.norm(S[pairs[:, 0]] - S[pairs[:, 1]], axis=1).mean()
    return float(d_all / max(d_nn, 1e-12))

On this data the contrast was 2.9 at 34 dimensions, 5.8 at 12, and 8.4 at 8. Below about 4 the parameter becomes impossible to set; above about 8 the gain flattens. We reduced to 8 dimensions, and the choice of how mattered: PCA to 8 components scored precision 0.66, and selecting 8 features by domain knowledge, keeping superheat, subcooling, pressure ratio, the three vibration band fractions, current crest factor and cycling rate, scored 0.71. PCA won on contrast and lost on the thing the project is for, because a component is a linear combination of 34 sensor features and a technician cannot be dispatched against it.

Common Pitfall

The `min_samples = 2 * D` rule of thumb, applied to `D = 34`. It gives `min_samples = 68`, and combined with a single `eps` on 34-dimensional data it produced exactly one cluster containing 99.2% of points and a noise set that was 91% cold-climate units. The rule is not wrong, it is a rule about the dimension you should be working in, and the fix is to reduce the dimension rather than to set the parameter. At `D = 8` the rule gives `min_samples = 16`, which was within a factor of two of the value we ended up with. There is a second, subtler version of the same mistake: reaching for `min_samples` to control the alert volume. It does not control volume, it controls what counts as a legitimate population, and turning it up to reduce alerts works by promoting small genuine anomaly groups into clusters. `eps` and the per-regime calibration are the volume controls.

Choosing eps, and why the k-distance knee is ambiguous here

The standard method is the k-distance graph: for k = min_samples, compute every point’s distance to its kth nearest neighbour, sort descending, and look for the knee. Points to the left of the knee are in sparse regions.

# The k-distance curve and its knee. Print the curve rather than trusting a
# knee finder: on multi-density data it has more than one knee and the
# automatic answer picks whichever is sharper, not whichever is right.
import numpy as np
from sklearn.neighbors import NearestNeighbors

def k_distance_curve(Z: np.ndarray, min_samples: int = 16) -> np.ndarray:
    """Sorted distance to the min_samples-th nearest neighbour, descending."""
    nn = NearestNeighbors(n_neighbors=min_samples).fit(Z)
    distances, _ = nn.kneighbors(Z)
    return np.sort(distances[:, -1])[::-1]

def knee_by_max_curvature(curve: np.ndarray) -> tuple[int, float]:
    """Kneedle-style: the point of maximum distance from the chord joining
    the curve's endpoints. Returns (index, eps)."""
    n = len(curve)
    x = np.arange(n, dtype=float)
    x0, y0, x1, y1 = 0.0, curve[0], float(n - 1), curve[-1]
    num = np.abs((y1 - y0) * x - (x1 - x0) * curve + x1 * y0 - y1 * x0)
    den = np.hypot(y1 - y0, x1 - x0)
    idx = int(np.argmax(num / den))
    return idx, float(curve[idx])

def eps_by_target_noise(Z: np.ndarray, min_samples: int = 16,
                        target_noise: float = 0.01) -> float:
    """The operational alternative: pick eps so a stated fraction of points
    fall below the k-distance threshold.

    This is a policy, not an estimate, and saying so out loud is the point.
    The knee is where the data's density changes; the target noise fraction
    is where the dispatch budget is. On multi-density data the second is
    defensible and the first is a coin flip between two knees.
    """
    curve = k_distance_curve(Z, min_samples)
    return float(np.quantile(curve, 1.0 - target_noise))

The curve on this data has two knees, at eps = 1.9 and eps = 3.4, and they correspond to the two populations: the 3,936 units in temperate and hot climates, and the 164 in cold climates. knee_by_max_curvature returns 1.9, the sharper one, which condemns the cold-climate units wholesale. Choosing 3.4 instead keeps them but raises the density threshold so high that early-stage faults in the dense population fall inside clusters, and recall drops from 0.78 to 0.51.

Neither knee is right, because the premise of a single eps is what is wrong.

The varying-density problem, and the fix we shipped

DBSCAN’s single global eps assumes one density scale for the whole dataset. This is its defining limitation and it is not tunable away. The three real options:

Fit DBSCAN per regime, with eps calibrated separately inside each. Fit HDBSCAN, which builds a hierarchy over all density scales and extracts clusters at whichever scale is locally stable. Or fit OPTICS, which computes a reachability ordering once and lets you extract DBSCAN-equivalent clusterings at any eps, or use its xi method for variable density.

# Per-regime DBSCAN. eps is calibrated inside each regime to a target noise
# fraction, which is what makes a sparse legitimate regime survive: it gets
# its own density scale rather than being measured against Phoenix.
import numpy as np
from sklearn.cluster import DBSCAN

def fit_per_regime(Z: np.ndarray, regimes: np.ndarray,
                   min_samples: int = 16, target_noise: float = 0.01,
                   min_regime_size: int = 2000) -> dict:
    """One DBSCAN per regime, keyed by regime id.

    Regimes below min_regime_size are pooled into a fallback model rather
    than given their own, because a regime with 400 points cannot support a
    density estimate and giving it one produces a model that calls everything
    noise. Pooling is the honest answer; the alternative is a per-regime
    model whose noise fraction is meaningless.
    """
    models = {}
    sizes = {r: int((regimes == r).sum()) for r in np.unique(regimes)}
    small = [r for r, n in sizes.items() if n < min_regime_size]
    for regime in np.unique(regimes):
        mask = ((regimes == regime) if regime not in small
                else np.isin(regimes, small))
        key = regime if regime not in small else "pooled"
        if key in models:
            continue
        Zr = Z[mask]
        eps = eps_by_target_noise(Zr, min_samples, target_noise)
        model = DBSCAN(eps=eps, min_samples=min_samples, n_jobs=-1).fit(Zr)
        models[key] = {
            "eps": eps,
            "min_samples": min_samples,
            "core_points": Zr[model.core_sample_indices_],
            "core_labels": model.labels_[model.core_sample_indices_],
            "noise_fraction": float((model.labels_ == -1).mean()),
            "n_clusters": int(model.labels_.max() + 1),
            "n_fit": len(Zr),
        }
    return models

The per-regime noise fractions are the diagnostic that makes this worth the complexity. With a single global eps = 1.9, the noise fraction was 0.4% in the hot-and-loaded regimes and 34% in the cold-and-light regimes. With per-regime calibration at a 1% target, every regime lands between 0.8% and 1.3% by construction, and the 61% of false alarms that came from 164 units dropped to 7%.

The no-predict problem

DBSCAN labels its fit set and defines no function from feature space to a label, so scoring a new window requires deciding what the label of a new point means. The standard construction, and the one consistent with the algorithm’s own definitions, is: a new point is a border point of cluster c if it lies within eps of any core point of c, and noise otherwise.

# Scoring new windows. This is the method sklearn does not give you, and it
# is 20 lines because the algorithm's own border-point definition already
# says what the answer should be.
import numpy as np
from sklearn.neighbors import NearestNeighbors

def build_core_index(model: dict) -> NearestNeighbors:
    """One index per regime model over its core points."""
    return NearestNeighbors(n_neighbors=1, algorithm="auto").fit(
        model["core_points"])

def assign_new_windows(model: dict, index: NearestNeighbors,
                       Z_new: np.ndarray) -> tuple:
    """Return (labels, margin).

    A new point within eps of a core point is a border point of that core
    point's cluster. Everything else is noise, which is the alert.

    The margin, distance to nearest core point divided by eps, is what makes
    this usable operationally: it is continuous, so the 50 daily dispatch
    slots can be filled by ranking on it rather than by taking an arbitrary
    50 of however many binary flags fired that day. DBSCAN gives a label;
    the margin is the score the label was hiding.
    """
    distances, neighbours = index.kneighbors(Z_new, n_neighbors=1)
    distances = distances.ravel()
    labels = np.where(distances <= model["eps"],
                      model["core_labels"][neighbours.ravel()], -1)
    return labels, distances / model["eps"]

Per-regime calibration creates one more problem here that is easy to miss. eps ranges from 1.7 to 3.6 across the 22 regimes, so distance / eps is not comparable between them, and a single dispatch queue ranked on the raw margin fills up from whichever regimes happened to get a small radius. The fix is to score each window against its own regime’s k-distance distribution, which is a percentile and therefore comparable by construction, and to use the margin only to break ties inside the top bucket. Anyone who calibrates per group and then pools the results into one queue needs this step, and it is not specific to DBSCAN.

The margin is the part worth stealing even if you never use DBSCAN. A density-based detector appears to return a binary label, and the distance that produced the label is a perfectly good continuous anomaly score that most implementations throw away. Ranking the day’s flagged windows by margin instead of taking them in arrival order was worth 0.09 precision at 50 dispatches, which is a larger gain than the entire move from a global eps to per-regime.

Hyperparameters that mattered, with the values we shipped: min_samples = 18 at D = 8, target_noise = 0.01 per regime giving eps between 1.7 and 3.6 across the 22 populated regimes, min_gap_hours = 6 for fit-set thinning, and a min_unit_day_support = 25 floor below which a cluster is demoted to anomalous.

Key Insight

The design decision that mattered most was treating `eps` as a policy rather than an estimate. The k-distance knee is presented everywhere as the way to choose it, and it answers a question about the data: where does the density scale change. What the project needs answered is a question about the operation: how many alerts can 50 technicians absorb. Calibrating `eps` per regime to a 1% target noise fraction makes the second question the one being answered, makes the parameter comparable across regimes with genuinely different densities, and makes a refit's alert volume predictable, which is what let the dispatch team trust the system enough to keep using it. The knee, by contrast, moved between 1.9 and 2.6 across four weekly refits on the same population, which is a 40% swing in alert volume driven entirely by whichever of the two knees happened to be sharper that week.

Evaluation and Metrics

Four measurements, and they are unusual because there is no ground-truth label on the object being scored. Windows are not labelled. Failures are.

Precision at 50 dispatches per day is computed by ranking each day’s units by their worst window margin, taking the top 50, and asking what fraction had a confirmed compressor failure within the following 21 days. That definition contains two choices worth defending: the aggregation to unit-day by worst margin rather than mean, because a unit with one severe window and 143 normal ones is exactly the case worth dispatching, and the 21-day attribution window, which is generous but bounded by the procurement lead time plus the maintenance cycle.

Median lead time is the median across caught failures of the time between the first alert and the failure timestamp. Reporting the mean here is a mistake: the distribution has a long right tail from units that were flagged for months before failing for unrelated reasons, and the mean was 19.1 days against a median of 9.4.

Stability is the Jaccard similarity of the noise set across bootstrap refits. DBSCAN has no likelihood and no held-out score, so stability is the closest thing available to a model-quality metric that does not consult the incident labels.

# The four evaluation layers. Nothing here is a standard sklearn metric,
# because the thing being scored (a window) has no label and the thing with
# a label (a failure) is not what the model outputs.
import numpy as np
import pandas as pd

def precision_at_daily_dispatch(scored: pd.DataFrame, failures: pd.DataFrame,
                                k: int = 50,
                                attribution_days: int = 21) -> dict:
    """scored: [unit_id, day, margin]. failures: [unit_id, failure_ts].

    Aggregates to unit-day by WORST margin, ranks, takes k, and asks whether
    a confirmed failure followed within attribution_days.
    """
    per_unit_day = (scored.groupby(["unit_id", "day"])["margin"]
                    .max().reset_index())
    fail_by_unit = failures.groupby("unit_id")["failure_ts"].apply(list)
    hits, total, leads = 0, 0, []
    for day, block in per_unit_day.groupby("day"):
        take = block.nlargest(min(k, len(block)), "margin")
        for _, row in take.iterrows():
            total += 1
            for ts in fail_by_unit.get(row["unit_id"], []):
                delta = (pd.Timestamp(ts) - pd.Timestamp(day)).days
                if 0 <= delta <= attribution_days:
                    hits += 1
                    leads.append(delta)
                    break
    return {"precision_at_k": hits / total if total else float("nan"),
            "median_lead_days": float(np.median(leads)) if leads else float("nan"),
            "mean_lead_days": float(np.mean(leads)) if leads else float("nan"),
            "dispatches": total}

def noise_set_stability(fit_fn, Z: np.ndarray, n_boot: int = 8,
                        frac: float = 0.8, seed: int = 17) -> float:
    """Mean pairwise Jaccard of the noise sets across bootstrap refits.

    The only model-quality number available that does not consult the
    incident labels. Below about 0.6 the parameters are being fitted to
    sampling noise and a refit will change the alert list for no reason the
    dispatch team can be told.
    """
    rng = np.random.default_rng(seed)
    sets = []
    for _ in range(n_boot):
        idx = rng.choice(len(Z), size=int(frac * len(Z)), replace=False)
        labels = fit_fn(Z[idx])
        sets.append(set(idx[labels == -1].tolist()))
    scores = []
    for i in range(len(sets)):
        for j in range(i + 1, len(sets)):
            union = len(sets[i] | sets[j])
            scores.append(len(sets[i] & sets[j]) / union if union else 1.0)
    return float(np.mean(scores)) if scores else float("nan")

Baseline against solution, held-out final 5 months, 62 confirmed failures, 50 dispatches a day:

Configuration Precision at 50 Recall of failures Median lead (days) Noise Jaccard Alerts from cold-climate units
Static thresholds 0.21 0.34 1.2 n/a 4%
Isolation forest, raw features 0.44 0.56 3.8 n/a 22%
Isolation forest, regime-conditioned 0.58 0.69 6.1 n/a 9%
DBSCAN, global eps, D=34 0.31 0.41 2.9 0.38 61%
DBSCAN, global eps, D=8 0.52 0.63 5.4 0.61 44%
DBSCAN, per-regime eps, D=8 0.62 0.74 8.1 0.79 7%
Plus temporal thinning 0.66 0.78 9.1 0.84 7%
Plus margin ranking 0.71 0.78 9.4 0.84 6%
HDBSCAN, D=8, min_cluster_size=40 0.69 0.77 9.0 0.88 5%

Three readings matter more than the headline. DBSCAN at D=34 with a global eps scores 0.31, well below the isolation forest baseline it was supposed to improve on, and a team that measured only that would correctly conclude the method does not work. The dimension reduction and the per-regime calibration are not refinements, they are the difference between a working detector and a broken one. Recall does not move between the last two rows, because margin ranking reorders the alert list without changing which windows are flagged, and yet precision rises 0.05: the same catches, fewer wasted dispatches. And HDBSCAN, which needs no eps at all, lands within 0.02 of a carefully calibrated per-regime DBSCAN, which is the honest summary of what all that calibration bought.

Metric That Matters

The number that catches a silent regression is **per-regime noise fraction**, tracked as a vector. The aggregate noise fraction is stable by construction because `eps` is calibrated to hit a target, so it will sit at 1% while the model quietly stops working. What moves is the distribution across regimes, and it moves for two distinguishable reasons. A regime whose noise fraction climbs toward 5% has usually lost its reference statistics, because a sensor recalibration or a firmware change shifted the raw channel and the regime-conditioned z scores are now measured against a stale mean. A regime whose noise fraction falls toward zero has usually acquired a genuine fault population large enough to form its own cluster, which is the temporal-autocorrelation failure reappearing at the regime level. We alert when any populated regime leaves the 0.5% to 2.5% band, and that has fired five times: three sensor recalibrations, one firmware rollout that changed the vibration channel's units, and once when a building's 34 units were all genuinely failing after a refrigerant contamination event.

Common Pitfalls and Failure Modes

Pitfall Why It Happens How to Detect How to Fix
A long fault episode is labelled a cluster Consecutive windows correlate at 0.94, so a four-hour fault is its own dense neighbourhood and meets the core-point condition A cluster supported by very few distinct unit-days; known failures whose pre-failure windows are not noise Thin the fit set to a minimum time gap per unit, and demote clusters with fewer than a floor of distinct unit-days
One global eps condemns a rare-but-normal regime Density-based detection cannot distinguish “unusual” from “wrong” and a single radius always favours the majority Noise fraction varying by an order of magnitude across regimes; alerts concentrated in a small set of units Calibrate eps per regime to a target noise fraction, or use HDBSCAN or OPTICS
DBSCAN run on unstandardised features eps is one radius in the joint space, so kPa and mm/s cannot coexist Distances dominated by whichever channel has the largest numeric range Regime-conditioned z scoring, which handles the scale problem and the envelope problem in one step
min_samples set by 2 times the dimension at high D The rule is right and the dimension is wrong; relative contrast near 1 means no eps separates anything Relative contrast under about 4; one cluster holding over 99% of points Reduce dimension first, to where contrast is above about 6, then apply the rule
The k-distance knee used as the answer It is the textbook method and it presumes a single density scale Two or more knees in the curve; the chosen eps moving by tens of percent between refits on the same population Treat eps as a policy calibrated to the alert budget, per regime, and print the curve rather than trusting a knee finder
No rule for scoring new points DBSCAN is transductive and has no predict, so the gap is only discovered at deployment The pipeline works in the notebook and has no serving path Nearest-core-point rule: within eps of a core point makes it a border point of that cluster, otherwise noise
The binary label shipped without the margin The API returns labels, so the distance that produced them looks like an implementation detail An alert queue that cannot be ranked, filled in arrival order when more windows fire than there is capacity Return distance to nearest core point over eps as a continuous score. Worth 0.09 precision here
A newly commissioned unit floods the alert queue Near-zero variance in every regime makes every z score enormous Alerts concentrated on units with a short history Shrink the unit’s scale toward the building then the fleet, with a floor at a fraction of the fleet scale
A drifting fault stays linked to the normal cluster by chaining DBSCAN clusters by transitive connectivity, so a chain of intermediate windows joins a distant point to the main cluster A known incident whose windows are far from every cluster centre and still labelled a cluster Serve the margin rather than the label, and use HDBSCAN if the chaining is structural rather than incidental
Common Pitfall

The most common beginner mistake on this exact problem is calling `DBSCAN(eps=0.5).fit(X)` on raw sensor features and reading the noise labels as anomalies. Every one of the four things that had to be fixed is invisible in that call. The features are on incomparable scales, so the distance is effectively one channel. The dimension is high enough that relative contrast is 2.9 and no `eps` separates dense from sparse. Consecutive windows are near-duplicates, so the faults that lasted longest are labelled clusters and the compressors worth catching are the ones missed. And a single `eps` condemns the cold-climate minority, which is where 61% of the false alarms came from. The configuration scores 0.31 precision against an isolation forest's 0.58 on the same features, and the honest conclusion from that single experiment would be that DBSCAN does not work on sensor data. It is a fair conclusion from the evidence and it is wrong: the same algorithm with the representation fixed reaches 0.71.

Three panels showing the varying-density failure where a single eps labels a sparse legitimate cold-climate regime entirely as noise, the k-distance curve with two knees at eps 1.9 and 3.4 corresponding to the two population densities, and the transductive problem where a new window has no predict method and is resolved by the nearest-core-point rule with the distance over eps margin as the anomaly score

Scaling and Productionizing

The asymmetry here is the opposite of most models: fitting is cheap and scoring is where the engineering goes, because there are 590,000 arrivals a day and no native scoring path.

Fitting is bounded by the thinned set, not the raw stream. Thinning to a 6-hour minimum gap per unit takes 320 million windows down to 4,100 units times 4 windows a day times 540 days, which is 8.9 million, and a further stratified sample of 1.2 million is enough to estimate 22 regime models.

Raw telemetry, 9 channels at 1 Hz     4,100 units x 540 days           = 1.7 TB
Windowed features, 34 columns         320M windows x 34 float32        = 43.5 GB
After 6 h thinning                    8.9M windows                     = 1.2 GB
Stratified fit sample                 1.2M windows x 8 dims            = 38 MB
Per-regime DBSCAN, 22 models          ball-tree, min_samples=18        = 6 min 20 s
eps calibration, 22 k-distance curves 55k points each                  = 1 min 40 s
Core point set, all regimes           1.04M core points x 8 dims       = 33 MB
Core indices, 22 ball-trees           built once per refit             = 14 s
Nightly scoring                       590k windows, 1-NN against cores = 48 s
Per-window inference                  one 1-NN query in 8 dimensions   = 0.08 ms
Bootstrap stability, 8 refits         on the fit sample                = 51 min

Scoring is a nearest-neighbour query and it stays cheap because the dimension is 8. A ball tree over a million core points in 8 dimensions answers a 1-NN query in about 80 microseconds. The same query at D=34 takes 2.1 ms, a factor of 26, because tree pruning degrades with dimension. Reducing the dimension was chosen for statistical reasons and paid for itself again in serving cost.

The core point set is the artifact to version. It is 33 MB and it is the entire model: the definition of the normal operating population, auditable by a controls engineer, and diffable between refits. When a refit changes behaviour, the question “which core points appeared and disappeared” has a literal answer, which is not true of a retrained isolation forest.

Refit cadence is set by the drift of the regime statistics, not the clustering. Frozen for four weeks, precision decayed 0.71, 0.70, 0.66, 0.59. Decomposing it, almost none of the decay came from the cluster structure and almost all from the regime-conditioning means and standard deviations going stale as the season moved. We now refresh the regime statistics weekly, which is a cheap groupby, and refit the DBSCAN models monthly, which is the expensive step, and that split holds precision within 0.02 of a full weekly refit.

Key Insight

The core point set is the model, and that is an operational property rather than a conceptual one. It is 33 MB of coordinates, it is the literal definition of the normal operating population, and it diffs. When a refit changes the alert list, "which core points appeared and disappeared, and in which regimes" has a concrete answer, and an engineer can pull the ten that vanished and look at what those units were doing. A retrained gradient-boosted forest offers nothing comparable: two forests with near-identical accuracy have no meaningful diff, so a behaviour change between refits is investigated by re-running metrics rather than by reading the model. On a system whose output sends a human to a roof, and whose false alarms are argued about in a weekly meeting, being able to answer "why did this change" from the artifact is worth more than the 0.03 precision the residual approach would have bought.

The monitoring signal for silent degradation is the triple of per-regime noise fraction, core point count per regime, and the margin distribution of the top 50 daily dispatches. Noise fraction catches stale reference statistics. Core point count catches a regime losing its population, which happens when a building is decommissioned and the regime’s density collapses. The margin distribution is the fastest of the three: a day where the 50th-ranked dispatch has a margin of 1.02 rather than the usual 1.4 means the queue is being filled with borderline windows, and that shows up before either of the other two moves.

Real World

DBSCAN's origin is Ester, Kriegel, Sander and Xu's 1996 KDD paper, and the two limitations this post spent most of its length on are both named in the original: the parameters are global, so varying density is a known failure, and the method is defined over a fixed database rather than as a classifier. HDBSCAN, from Campello, Moulavi and Sander's 2013 work and McInnes and Healy's 2017 implementation paper, exists specifically to remove the global-`eps` assumption by extracting clusters from a hierarchy at whichever density scale is locally stable, which is why it lands within 0.02 of a hand-calibrated per-regime DBSCAN here with none of the calibration. On the industrial side, the honest note is that large-fleet condition monitoring has largely moved past clustering: NASA's C-MAPSS turbofan benchmark and the bearing datasets out of NSF IMS and FEMTO-ST are dominated by supervised and deep sequence models, and the vendors who monitor wind turbine and chiller fleets at scale mostly run per-asset regression residual models, predicting each sensor from the others and flagging when the residual leaves its envelope. Density-based detection survives where the normal population has to be an inspectable artifact rather than a set of weights, which is exactly the constraint a technician union and an insurance auditor impose.

Alternative Approaches

Approach Precision at 50 Fit and serve cost Interpretability Best fit
DBSCAN, per-regime eps, D=8 0.71 8 min refit, 0.08 ms per window Good: core points are an inspectable normal population, margin is a score Normal behaviour must be auditable, and regimes are known and enumerable
HDBSCAN, D=8 0.69 24 min refit, 0.11 ms per window Moderate: cluster hierarchy plus an outlier score, no single radius to explain Varying density with no natural regime variable to condition on
OPTICS, xi extraction 0.67 41 min refit, no incremental scoring Moderate: reachability plot is informative and hard to show a technician Exploration, and re-extracting many eps values from one expensive ordering
Local outlier factor, novelty mode 0.61 11 min refit, 0.09 ms per window Poor: a ratio of local densities with no population artifact Local density contrast matters and no regime variable exists
Isolation forest, regime-conditioned 0.58 4 min refit, 0.02 ms per window Moderate: path-length attribution per feature Speed matters, dimension is high, and no auditable normal set is required
One-class SVM, RBF 0.54 2 h 10 min refit, 0.4 ms per window Poor: support vectors in kernel space Small fit sets where a tight boundary matters more than cost
Per-sensor regression residual envelope 0.74 3 h 40 min refit, 0.3 ms per window Good: per-channel residual is directly actionable Channels are physically coupled and enough history exists per asset

What we shipped is the top row, and it is not the most accurate row in the table. The per-sensor residual approach beats it by 0.03 and we did not ship it, for two reasons that are both about the shape of the project rather than the shape of the data: it needs one model per sensor per asset, which is 36,900 models to monitor instead of 22, and its output is a residual envelope rather than a population of normal operating points, which does not satisfy the audit requirement that drove the method choice. HDBSCAN in the second row is the better default for anyone without an enumerable regime variable, and if this project restarted today with no existing regime definition in the controls system, it is what we would use.

We would switch to the isolation forest immediately if the dimension had to stay above about 20, because density-based methods stop working there and no amount of calibration recovers it. We would move to the residual approach if the audit constraint were dropped and the fleet were homogeneous enough that per-asset models were maintainable.

Key Takeaways

  • Regime conditioning is worth more than the detector. Standardising each feature against the unit’s own history in its own ambient-by-load cell moved precision at 50 from 0.29 to 0.54 with the detector untouched, which is larger than every subsequent modelling decision combined. It also solves the scale problem eps creates, since everything ends up in within-regime standard deviations.
  • A long fault becomes a cluster, and the ones you most want to catch are the worst affected. Consecutive windows correlate at 0.94, so a four-hour episode is its own dense neighbourhood and satisfies the core-point condition. Untreated, 71 of 214 confirmed failures had their pre-failure windows labelled as clusters, concentrated in the slow bearing failures.
  • One global eps always condemns the minority regime. 61% of false alarms came from 164 of 4,100 units, which were in cold climates and not broken. Per-regime calibration took that to 7% and precision from 0.52 to 0.62.
  • Reduce dimension before tuning parameters. Relative contrast was 2.9 at D=34 and 8.4 at D=8, and at 34 dimensions no eps separates dense from sparse, so DBSCAN scored 0.31 against an isolation forest’s 0.58 on identical features. Domain-selected features beat PCA by 0.05 despite worse contrast, because a principal component cannot be handed to a technician.
  • Treat eps as a policy, not an estimate. The k-distance curve had two knees, and the automatic knee finder picked the sharper one, which condemned the cold-climate units. Calibrating to a 1% target noise fraction per regime answers the question the operation is actually asking and made alert volume predictable across refits.
  • The margin is the score the label was hiding. Distance to nearest core point divided by eps is a continuous anomaly score that DBSCAN computes and discards. Ranking the daily queue by it was worth 0.09 precision with no change to which windows were flagged.
  • DBSCAN has no predict, and the fix is the algorithm’s own border-point definition. Within eps of a core point makes a new window a border point of that cluster; otherwise it is noise. That is 20 lines and it is the entire serving path.
  • Stability is the only model-quality metric available. With no likelihood and no window labels, bootstrap Jaccard of the noise set is the closest substitute, and it tracked precision well: 0.38 for the broken configuration, 0.84 for the shipped one.

The counter-intuitive lesson is that the algorithm was never the problem and the algorithm was never the solution. DBSCAN at D=34 with a global eps scored 0.31, comfortably worse than a four-line isolation forest, and the same algorithm after the representation was fixed scored 0.71. Everything that moved the number was upstream of the clustering: what a feature means relative to its operating regime, which windows are allowed to vote on each other’s density, and how many dimensions the distance is computed in. A team that benchmarks detectors against each other on the raw feature matrix will pick the one most robust to a bad representation, which is a real property worth having and a poor reason to stop looking. The representation is where the 0.40 was.

Frequently Asked Questions

Q: Why not just use an isolation forest, which has no eps and does have a predict method? A: That is the right default and we shipped it as the baseline at 0.58. The three reasons to go further here were specific. DBSCAN produces an explicit set of core points that constitutes an auditable definition of normal operation, which the maintenance contract required and a 300-tree forest cannot provide. Its parameters are physically interpretable, so eps = 2.4 in within-regime standard deviations is a number a controls engineer can dispute. And the margin gives a continuous score whose units are meaningful, where score_samples from a forest is a path length with no physical reading. If none of those constraints exist, the forest is 4 minutes to fit against 8 and 0.02 ms to score against 0.08.

Q: Why not HDBSCAN, since it removes the global eps problem you spent the whole post on? A: It is a legitimate choice and it scored 0.69 against our 0.71, so the accuracy argument is nearly a wash and it needed none of the per-regime calibration. Two reasons we stayed with DBSCAN. The controls system already had an enumerable regime definition, ambient by load, which meant per-regime calibration was a groupby rather than a modelling problem, and conditioning on a variable you know beats inferring the density scale when you do have the variable. And the explanation cost differs: “each regime gets its own radius, calibrated so one window in a hundred is flagged” is a sentence the dispatch team accepted, where the excess-of-mass cluster extraction over a mutual-reachability hierarchy is not. If we were starting without the regime variable, we would use HDBSCAN.

Q: How do I choose min_samples without guessing? A: Reduce the dimension first, then the heuristic works. The 2 * D rule is not wrong, it is a rule about the dimension you should be working in, and at D=34 it gives 68, which combined with a global eps produced one cluster holding 99.2% of points. At D=8 it gives 16, within a factor of two of the 18 we shipped. Then check the two symptoms: a cluster count of one means min_samples is too high or eps too large, and a noise fraction far above your target at the calibrated eps means it is too low. What min_samples must not be used for is alert volume control, because turning it up reduces alerts by promoting small genuine anomaly groups into legitimate clusters, which is the opposite of what you wanted.

Q: Why is the metric precision at 50 rather than an AUC of some kind? A: Because 50 is the number of technicians and every threshold-free metric ignores it. With 214 positives against 320 million windows, ROC-AUC is determined by how normal windows rank against each other, and a detector can reach 0.97 while filling all 50 slots with false alarms. PR-AUC is better and still measures a curve nobody operates on, since the queue is exactly 50 deep every day regardless of how many windows fired. The one insistence worth adding is that precision at 50 must be reported paired with median lead time, because precision alone is maximised by alerting 12 hours before failure, when the signal is unmistakable and the compressor is already unsaveable.

Q: What do I do about a brand new unit with no history to condition against? A: Fall back, in two steps, and treat the fallback as a first-class part of the pipeline rather than an edge case. A unit with fewer than 400 windows in a regime borrows that regime’s mean and standard deviation from its building; a building short of data borrows from the fleet. Without this, a newly commissioned unit has near-zero variance in every regime, so every z score is enormous and the whole alert budget goes to last week’s retrofit. That is not hypothetical, it happened in week two of our pilot: 38 of the first day’s 50 dispatches went to one building that had been retrofitted the previous Friday.

Q: What breaks first in production? A: The regime-conditioning statistics, and they break quietly. A sensor recalibration or a firmware update shifts a raw channel by a constant, the regime means are now stale, and that regime’s z scores drift until its noise fraction climbs. The cluster structure is fine, eps is fine, the aggregate noise fraction is pinned at 1% because it was calibrated to be, and the alert queue fills with one regime. Monitor the per-regime noise fraction as a vector and alert when any populated regime leaves a 0.5% to 2.5% band. Of the five times that fired for us, three were sensor recalibrations, one was a firmware rollout that changed the vibration channel’s units, and one was a genuine refrigerant contamination event that took out 34 units in a building.

Interview Questions

Q: Explain how DBSCAN decides a point is an outlier, and what its two parameters control. Expected depth: Give the three point types and the definitions that generate them. A core point has at least min_samples points within eps. Core points within eps of each other are transitively connected into one cluster, which is why DBSCAN finds arbitrarily shaped clusters where k-means cannot. A non-core point within eps of a core point is a border point and joins that cluster; everything else is noise, and noise is the outlier set. Then be precise about what each parameter means: eps sets the length scale of the density estimate and min_samples sets the count threshold, and together they define one density, min_samples points per eps-ball. Strong answers note the consequences that follow from the definitions rather than from the implementation: cluster assignment for border points depends on processing order and is therefore not deterministic, the method has no objective function being minimised, and because the definitions are stated over a fixed database there is no function from feature space to a label, which is why there is no predict.

Q: Your DBSCAN run puts 99% of points in one cluster and calls the rest noise, and the noise is all from one subpopulation. Diagnose it. Expected depth: Two causes and they compound. First, dimension: compute relative contrast, the ratio of mean pairwise distance to mean nearest-neighbour distance, and if it is near 1 then no eps distinguishes dense from sparse because distances have concentrated, and the fix is dimension reduction rather than parameter tuning. Second, varying density: a single global eps encodes one density scale, so a subpopulation that is legitimately sparse is condemned wholesale, and the diagnostic is the noise fraction computed per subgroup rather than overall. Name the fixes with their tradeoffs: per-group eps calibration when a grouping variable exists, HDBSCAN when it does not, OPTICS when you want to re-extract many eps values from one ordering. Add the scaling check, since eps is one radius in the joint feature space and an unstandardised feature with a large numeric range makes the distance effectively univariate. A strong answer also asks whether the sparse subpopulation is actually anomalous, because “rare” and “wrong” are different claims and density-based methods cannot tell them apart without help.

Q: You have a fitted DBSCAN model and a new data point. How do you score it, and what are you assuming? Expected depth: Derive the rule from the algorithm’s own definitions rather than inventing one: a new point within eps of an existing core point satisfies the border-point condition, so assign it that core point’s cluster, and otherwise call it noise. Then name what that construction assumes and what it costs. It freezes the cluster structure, so a genuinely new normal mode appearing after the fit is scored as anomalous until the next refit, which is correct behaviour for a monitoring system and wrong for a discovery one. It cannot create new clusters or promote the new point to core status. And it is asymmetric with the fit, since a point that would have been core had it been present is merely border now. Mention the operational upgrade: keep the distance to the nearest core point divided by eps as a continuous score rather than thresholding it, which turns a binary label into a rankable margin, and note the serving cost is a nearest-neighbour query over the core set, which is cheap in low dimensions and degrades with dimension as tree pruning fails.

Q: How would you evaluate an unsupervised anomaly detector before shipping it, when you have almost no labels? Expected depth: Separate the three kinds of evidence available and be explicit that no single one is sufficient. First, a small labelled incident set used only for evaluation, never for fitting, scored at the operating point the system will actually run at, which for a capacity-constrained alert queue means precision at k computed within each decision period and a lead-time distribution reported as a median rather than a mean. Insist on the pairing, because precision alone is maximised by alerting so late that the prediction is useless. Second, stability: refit on bootstrap resamples and measure the Jaccard similarity of the flagged set, since a detector whose alert list changes substantially under resampling is fitting sampling noise and no explanation given to an operator will survive the next refit. Third, structural checks that need no labels at all, such as the flagged fraction per subgroup, which catches a detector that has learned to condemn a minority regime, and the feature attribution of the flags, which catches one channel dominating through a scaling error. Close on what is not available and why: there is no likelihood, no held-out score, and internal cluster-validity indices such as silhouette measure compactness under a distance metric rather than anomalousness, so a well-behaved detector on overlapping real-world data will score badly by construction.

Q: Your sensor anomaly detector misses exactly the slow-developing faults and catches the abrupt ones. What is happening? Expected depth: Reach for temporal autocorrelation first and explain the mechanism in terms of the core-point condition. Consecutive windows from one asset are near-duplicates, so a fault that develops over hours produces many mutually similar points, and once that group exceeds min_samples within eps it satisfies the core-point definition and is labelled a legitimate cluster. The longer and more gradual the fault, the more likely it forms its own cluster, which produces exactly the observed selectivity: abrupt faults are isolated points and get caught, slow faults become clusters and are reported as normal. Give the diagnostic, which is to check known incidents and count how many have pre-failure windows assigned to clusters rather than to noise, and to compute each cluster’s support in distinct assets and asset-days. Then the fixes: thin the fit set so no two windows from one asset are within some minimum gap, count neighbours for the core-point test at the asset level rather than the window level, and demote clusters whose support comes from too few distinct assets. Add the related trap if there is room, which is that post-failure windows left in the fit set form a dense cluster of catastrophic readings that the model then treats as a legitimate operating regime.

View full code for this problem