CDiscover · discover.robust_cov
Robust covariance (MCD) outliers
Which rows are multivariate outliers once a few extreme rows can no longer distort the mean and covariance?
Minimum covariance determinant (FastMCD): finds the half (or chosen share) of rows with the tightest covariance, rescales it to be consistent at the normal, reweights, and scores every row by its robust Mahalanobis distance. Rows beyond the 97.5% χ² cutoff are outliers — including rows that look ordinary one variable at a time. Random subsets come from the shared stream, so both engines reach the same estimate.
A real result
Example “Usarrests”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
15 of 50 rows (30.0%) are flagged as anomalies (Robust distance ≥ 3.34).
- Anomalies
- 15
- Threshold
- 3.338
Plots
View data
| Anomaly | Robust distance |
|---|---|
| false | 2.630 |
| true | 9.402 |
| true | 4.553 |
| false | 1.583 |
| true | 6.725 |
| true | 6.805 |
| false | 2.132 |
| false | 2.797 |
| false | 2.522 |
| true | 4.253 |
| false | 2.927 |
| false | 1.934 |
| false | 1.657 |
| false | 1.384 |
| false | 1.169 |
| false | 0.6352 |
| false | 2.588 |
| true | 3.615 |
| false | 1.732 |
| false | 2.708 |
| false | 2.015 |
| true | 3.742 |
| false | 1.450 |
| true | 5.347 |
| false | 2.663 |
| false | 0.8962 |
| false | 1.011 |
| true | 7.431 |
| false | 1.280 |
| false | 2.053 |
| true | 3.371 |
| false | 1.727 |
| true | 5.100 |
| false | 1.777 |
| false | 1.433 |
| false | 0.7964 |
| true | 5.193 |
| false | 1.558 |
| true | 4.130 |
| false | 3.290 |
| false | 1.396 |
| false | 2.400 |
| false | 2.070 |
| true | 3.494 |
| false | 2.489 |
| false | 0.6891 |
| true | 4.337 |
| false | 2.456 |
| false | 1.484 |
| false | 0.9951 |
Most anomalous rows
| Rank | Row | Robust distance | Most unusual | Biggest score drop | Murder | Assault | UrbanPop | Rape |
|---|---|---|---|---|---|---|---|---|
| 1 | 2 | 9.402 | Rape = 44.5 (robust z +2.8); 40% of its tail score | Rape: falls 6.62 at its median | 10 | 263 | 48 | 44.500 |
| 2 | 28 | 7.431 | Rape = 46 (robust z +3.0); 45% of its tail score | Rape: falls 4.39 at its median | 12.200 | 252 | 81 | 46 |
| 3 | 6 | 6.805 | Rape = 38.7 (robust z +2.2); 45% of its tail score | Rape: falls 5.51 at its median | 7.900 | 204 | 78 | 38.700 |
| 4 | 5 | 6.725 | Rape = 40.6 (robust z +2.4); 29% of its tail score | Rape: falls 3.65 at its median | 9 | 276 | 91 | 40.600 |
| 5 | 24 | 5.347 | Murder = 16.1 (robust z +1.6); 39% of its tail score | Murder: falls 1.83 at its median | 16.100 | 259 | 44 | 17.100 |
| 6 | 37 | 5.193 | Rape = 29.3 (robust z +1.1); 40% of its tail score | Rape: falls 3.22 at its median | 4.900 | 159 | 67 | 29.300 |
| 7 | 33 | 5.100 | Assault = 337 (robust z +1.6); 43% of its tail score | Assault: falls 0.96 at its median | 13 | 337 | 45 | 16.100 |
| 8 | 3 | 4.553 | Rape = 31 (robust z +1.3); 28% of its tail score | Rape: falls 1.35 at its median | 8.100 | 294 | 80 | 31 |
| 9 | 47 | 4.337 | Rape = 26.2 (robust z +0.7); 29% of its tail score | Rape: falls 2.04 at its median | 4 | 145 | 73 | 26.200 |
| 10 | 10 | 4.253 | Murder = 17.4 (robust z +1.9); 55% of its tail score | Murder: falls 1.01 at its median | 17.400 | 211 | 60 | 25.800 |
| 11 | 39 | 4.130 | Rape = 8.3 (robust z -1.4); 36% of its tail score | Rape: falls 1.09 at its median | 3.400 | 174 | 87 | 8.300 |
| 12 | 22 | 3.742 | Rape = 35.1 (robust z +1.7); 35% of its tail score | Rape: falls 1.02 at its median | 12.100 | 255 | 74 | 35.100 |
| 13 | 18 | 3.615 | Murder = 15.4 (robust z +1.5); 47% of its tail score | Murder: falls 0.966 at its median | 15.400 | 249 | 66 | 22.200 |
| 14 | 44 | 3.494 | UrbanPop = 80 (robust z +0.8); 28% of its tail score | Murder: falls 1.58 at its median | 3.200 | 120 | 80 | 22.900 |
| 15 | 31 | 3.371 | Rape = 32.1 (robust z +1.4); 32% of its tail score | Rape: falls 0.594 at its median | 11.400 | 285 | 70 | 32.100 |
| 16 | 40 | 3.290 | Murder = 14.4 (robust z +1.3); 32% of its tail score | UrbanPop: falls 0.251 at its median | 14.400 | 279 | 48 | 22.500 |
| 17 | 11 | 2.927 | Assault = 46 (robust z -1.0); 46% of its tail score | Assault: falls 1.08 at its median | 5.300 | 46 | 83 | 20.200 |
| 18 | 8 | 2.797 | Assault = 238 (robust z +0.7); 28% of its tail score | Assault: falls 1.62 at its median | 5.900 | 238 | 72 | 15.800 |
| 19 | 20 | 2.708 | Assault = 300 (robust z +1.3); 44% of its tail score | Assault: falls 0.303 at its median | 11.300 | 300 | 67 | 27.800 |
| 20 | 25 | 2.663 | Rape = 28.2 (robust z +0.9); 38% of its tail score | Rape: falls 1.87 at its median | 9 | 178 | 70 | 28.200 |
15 of 50 rows (30.0%) are flagged as anomalies (Robust distance ≥ 3.34).
- Anomalies
- 15
- Threshold
- 3.338
To keep this page light, the plots are shown once, under the R tab.
Most anomalous rows
| Rank | Row | Robust distance | Most unusual | Biggest score drop | Murder | Assault | UrbanPop | Rape |
|---|---|---|---|---|---|---|---|---|
| 1 | 2 | 9.402 | Rape = 44.5 (robust z +2.8); 40% of its tail score | Rape: falls 6.62 at its median | 10 | 263 | 48 | 44.500 |
| 2 | 28 | 7.431 | Rape = 46 (robust z +3.0); 45% of its tail score | Rape: falls 4.39 at its median | 12.200 | 252 | 81 | 46 |
| 3 | 6 | 6.805 | Rape = 38.7 (robust z +2.2); 45% of its tail score | Rape: falls 5.51 at its median | 7.900 | 204 | 78 | 38.700 |
| 4 | 5 | 6.725 | Rape = 40.6 (robust z +2.4); 29% of its tail score | Rape: falls 3.65 at its median | 9 | 276 | 91 | 40.600 |
| 5 | 24 | 5.347 | Murder = 16.1 (robust z +1.6); 39% of its tail score | Murder: falls 1.83 at its median | 16.100 | 259 | 44 | 17.100 |
| 6 | 37 | 5.193 | Rape = 29.3 (robust z +1.1); 40% of its tail score | Rape: falls 3.22 at its median | 4.900 | 159 | 67 | 29.300 |
| 7 | 33 | 5.100 | Assault = 337 (robust z +1.6); 43% of its tail score | Assault: falls 0.96 at its median | 13 | 337 | 45 | 16.100 |
| 8 | 3 | 4.553 | Rape = 31 (robust z +1.3); 28% of its tail score | Rape: falls 1.35 at its median | 8.100 | 294 | 80 | 31 |
| 9 | 47 | 4.337 | Rape = 26.2 (robust z +0.7); 29% of its tail score | Rape: falls 2.04 at its median | 4 | 145 | 73 | 26.200 |
| 10 | 10 | 4.253 | Murder = 17.4 (robust z +1.9); 55% of its tail score | Murder: falls 1.01 at its median | 17.400 | 211 | 60 | 25.800 |
| 11 | 39 | 4.130 | Rape = 8.3 (robust z -1.4); 36% of its tail score | Rape: falls 1.09 at its median | 3.400 | 174 | 87 | 8.300 |
| 12 | 22 | 3.742 | Rape = 35.1 (robust z +1.7); 35% of its tail score | Rape: falls 1.02 at its median | 12.100 | 255 | 74 | 35.100 |
| 13 | 18 | 3.615 | Murder = 15.4 (robust z +1.5); 47% of its tail score | Murder: falls 0.966 at its median | 15.400 | 249 | 66 | 22.200 |
| 14 | 44 | 3.494 | UrbanPop = 80 (robust z +0.8); 28% of its tail score | Murder: falls 1.58 at its median | 3.200 | 120 | 80 | 22.900 |
| 15 | 31 | 3.371 | Rape = 32.1 (robust z +1.4); 32% of its tail score | Rape: falls 0.594 at its median | 11.400 | 285 | 70 | 32.100 |
| 16 | 40 | 3.290 | Murder = 14.4 (robust z +1.3); 32% of its tail score | UrbanPop: falls 0.251 at its median | 14.400 | 279 | 48 | 22.500 |
| 17 | 11 | 2.927 | Assault = 46 (robust z -1.0); 46% of its tail score | Assault: falls 1.08 at its median | 5.300 | 46 | 83 | 20.200 |
| 18 | 8 | 2.797 | Assault = 238 (robust z +0.7); 28% of its tail score | Assault: falls 1.62 at its median | 5.900 | 238 | 72 | 15.800 |
| 19 | 20 | 2.708 | Assault = 300 (robust z +1.3); 44% of its tail score | Assault: falls 0.303 at its median | 11.300 | 300 | 67 | 27.800 |
| 20 | 25 | 2.663 | Rape = 28.2 (robust z +0.9); 38% of its tail score | Rape: falls 1.87 at its median | 9 | 178 | 70 | 28.200 |
Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.
Worked examples in the app
- Usarrestsml_usarrests · features: Murder, Assault, UrbanPop, Rape
- Pima shareml_pima · features: glu, bp, skin, bmi, age
In the guides
Where it sits in the decision guides
- Anomaly detection · DS & ML Decision Guide · Discover — find structure without labels
What you need
- Variablesnumeric · 2–50 columns
- Numbers whose joint shape is roughly elliptical (missing values → median).
Choices you make
model
- Share of rows in the coredefault 0.5
0.5 = most robust (up to half the rows may be outliers); 0.75 = more efficient when outliers are few.
options
- Flag anomalies bydefault cutoff
Flag a fixed share of the most unusual rows, or every row whose score passes a cutoff.
- χ² cutoff (robust distance)(default) — Flag rows beyond the cutoff; leave it empty for √χ²(0.975, p).
- Share of rows (the highest scores) — Flag a fixed share of rows.
- Share flaggeddefault 0.05
Share of rows to flag (the largest robust distances).
- Distance cutoffdefault —
Robust distances at or above this are outliers.
What it reports
- n
- How many independent units the analysis used; it sets precision and power.
- n_flagged
- How many independent units the analysis used; it sets precision and power.
- threshold
- The probability above which the model predicts the positive class; 0.5 is rarely the best choice.
- score_check
- A built-in check that CodeSplash's own recomputation from the engine's predictions matches the score the engine reported.
- score_max
- A built-in check that CodeSplash's own recomputation from the engine's predictions matches the score the engine reported.
- score_mean
- A built-in check that CodeSplash's own recomputation from the engine's predictions matches the score the engine reported.
- h
- Mean and covariance from the tightest half of the rows, so outliers cannot hide themselves by inflating the spread.
- logdet_raw
- Mean and covariance from the tightest half of the rows, so outliers cannot hide themselves by inflating the spread.
- n_reweighted
- How many independent units the analysis used; it sets precision and power.
- chi2_cutoff
- Mean and covariance from the tightest half of the rows, so outliers cannot hide themselves by inflating the spread.
- n_beyond_cutoff
- How many independent units the analysis used; it sets precision and power.
- classical_flagged
- Mean and covariance from the tightest half of the rows, so outliers cannot hide themselves by inflating the spread.
Per group, level or term: top_row[<rank>], top_score[<rank>], why_feature[<rank>], why_z[<rank>], why_share[<rank>], drop_feature[<rank>], drop_score[<rank>], center[<variable>]
Python and R
Python and R agree to 6 decimals (relative tolerance 1e-7). Python uses scipy; R uses codesplashr.
Default traps between the two languages
- Both engines run codesplash's FastMCD twin (500 random (p+1)-subsets from the shared stream, two C-steps each, the ten best iterated to convergence, consistency factor at the normal, one reweighting step at χ²(0.975)). scikit-learn's MinCovDet and robustbase::covMcd draw their own subsets and robustbase also applies small-sample correction factors, so their scatter matrices differ slightly; the robust distances rank rows the same way in practice.
The exact script CodeSplash ran for example “Usarrests” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Robust covariance (MCD) outliers
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.robust_cov 1.1.0 · spec 264b07cb26a3e2fe
# Dataset: ml_usarrests (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash import ml as csml
from codesplash.ml import anomaly as csanom
from codesplash.ml import discover_ext as dx
from codesplash.ml import embed as csembed
# %% Data
IMPUTE = "median"
SCALE = "none" # MCD is affine equivariant: scaling does not change the distances
FEATURES = ["Murder", "Assault", "UrbanPop", "Rape"]
df = pd.read_parquet("tests/parity/fixtures/ml_usarrests.parquet", columns=FEATURES)
warnings = []
design = csml.Design.for_frame(
df,
FEATURES,
kinds={
"Murder": "numeric",
"Assault": "numeric",
"UrbanPop": "numeric",
"Rape": "numeric",
},
levels={
},
impute=IMPUTE,
scale=SCALE,
)
fitted = design.fit(df)
X = fitted.transform(df) # numbers imputed / scaled; categories one-hot (missing → all zero)
rows = np.arange(len(df))
SEED = 42
# %% Minimum covariance determinant (FastMCD twin, subsets from the shared stream)
fit = dx.mcd(X, 0.5, SEED)
scores = fit["robust_distance"]
DEFAULT_CUTOFF = fit["cutoff"]
SCORE_LABEL = "Robust distance"
ENGINE_PACKAGES = ("numpy", "scipy", "pandas")
extra_values = {
"h": fit["h"],
"logdet_raw": fit["logdet_raw"],
"n_reweighted": fit["n_reweighted"],
"chi2_cutoff": fit["cutoff"],
"n_beyond_cutoff": int(np.sum(scores >= fit["cutoff"])),
"classical_flagged": int(np.sum(fit["classical_distance"] >= fit["cutoff"])),
}
for name, v in zip(FEATURES, fit["center"]):
extra_values[f"center[{name}]"] = float(v)
rescore = lambda Q, where, col: np.sqrt(dx.mahalanobis2(Q, fit["center"], fit["cov"])) # the fitted center and scatter
# %% Flag anomalies
RULE = "cutoff"
_cutoff = None
if _cutoff is None:
_cutoff = DEFAULT_CUTOFF # set by the including template (e.g. the χ² cutoff for MCD)
flags, threshold = csanom.flag(scores, RULE, 0.05, _cutoff)
order = np.lexsort((rows, -scores)) # highest score first, ties by row
out = csml.out_dir("target/academy-parity/run-8142/discover.robust_cov/usarrests/out-python")
labels = pd.DataFrame({"row": rows.astype(np.int64), "score": scores, "anomaly": flags})
labels.to_parquet(os.path.join(out, "labels.parquet"), index=False)
# %% Result
values = {
"n": len(rows),
"n_flagged": int(flags.sum()),
"threshold": float(threshold),
"score_check": csembed.checksum(scores, rows),
"score_max": float(scores.max()),
"score_mean": float(scores.mean()),
}
values.update(extra_values)
for rank, i in enumerate(order[:10], start=1):
values[f"top_row[{rank}]"] = int(rows[i])
values[f"top_score[{rank}]"] = float(scores[i])
top = order[:20]
# %% Why these rows (numeric features: robust z and the ECOD tail-score share; Phase 11 DS1)
from codesplash.ml import discover_ext as _dx
NUMERIC = ["Murder", "Assault", "UrbanPop", "Rape", ]
why = None
if NUMERIC:
_F = df.iloc[rows][NUMERIC].apply(pd.to_numeric, errors="coerce").to_numpy(dtype=np.float64)
_med = np.array([np.median(c[~np.isnan(c)]) if np.any(~np.isnan(c)) else 0.0 for c in _F.T])
_F = np.where(np.isnan(_F), _med[None, :], _F)
why = _dx.explain_rows(_F, top)
for rank in range(1, min(10, len(top)) + 1):
values[f"why_feature[{rank}]"] = int(why["feature"][rank - 1])
values[f"why_z[{rank}]"] = float(why["z"][rank - 1])
values[f"why_share[{rank}]"] = float(why["share"][rank - 1])
# Score drop: move one feature to its median, leave the rest of the row alone, and rescore.
_cols = [fitted.names.index(f) for f in NUMERIC]
drop = _dx.score_drops(X, top, _cols, scores, rescore)
for rank in range(1, min(10, len(top)) + 1):
values[f"drop_feature[{rank}]"] = int(drop["feature"][rank - 1])
values[f"drop_score[{rank}]"] = float(drop["drop"][rank - 1])
shown = df.iloc[rows[top]][FEATURES]
table_rows = []
for rank, (i, (_, rec)) in enumerate(zip(top, shown.iterrows()), start=1):
r = {"rank": rank, "row": int(rows[i]) + 1, "score": float(scores[i])}
if why is not None:
_j = int(why["feature"][rank - 1])
_share = why["share"][rank - 1]
r["why"] = f"{NUMERIC[_j]} = {_F[i, _j]:.4g} (robust z {why['z'][rank - 1]:+.1f})" + ("" if _share != _share else f"; {_share:.0%} of its tail score")
_d = float(drop["drop"][rank - 1])
r["drop"] = f"{NUMERIC[int(drop['feature'][rank - 1])]}: falls {_d:.3g} at its median" if _d > 0 else "no single feature lowers it"
for f in FEATURES:
v = rec[f]
r[f] = None if pd.isna(v) else (v if isinstance(v, (int, float)) else str(v)) # None, NaN, pd.NA, NaT
table_rows.append(r)
pct = flags.mean()
cs.publish({
"title": "Robust covariance (MCD) outliers",
"engine": cs.engine_info(*ENGINE_PACKAGES),
"n": len(rows),
"summary": f"{int(flags.sum())} of {len(rows)} rows ({pct:.1%}) are flagged as anomalies ({SCORE_LABEL} ≥ {threshold:.3g}).",
"statistics": [
{"key": "n_flagged", "label": "Anomalies", "value": int(flags.sum()), "format": "integer"},
{"key": "threshold", "label": "Threshold", "value": float(threshold)},
],
"tables": [{
"key": "top",
"title": "Most anomalous rows",
"columns": [{"key": "rank", "label": "Rank", "type": "integer"}, {"key": "row", "label": "Row", "type": "integer"},
{"key": "score", "label": SCORE_LABEL, "type": "number"}]
+ ([{"key": "why", "label": "Most unusual"}, {"key": "drop", "label": "Biggest score drop"}] if why is not None else [])
+ [{"key": f, "label": f} for f in FEATURES],
"rows": table_rows,
}],
"charts": [cs.chart("scores", "anomaly-scores", f"{SCORE_LABEL} distribution", {
"score": cs.col(SCORE_LABEL, scores, "numeric"),
"anomaly": cs.col("Anomaly", [bool(x) for x in flags], "boolean"),
}, controls={"threshold": float(threshold)})],
"values": values,
"warnings": warnings,
"artifacts": [{"key": "labels", "path": os.path.join(out, "labels.parquet"), "format": "parquet"}],
})
The exact script CodeSplash ran for example “Usarrests” · R version 4.5.1 (2025-06-13)
# Robust covariance (MCD) outliers
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.robust_cov 1.1.0 · spec 264b07cb26a3e2fe
# Dataset: ml_usarrests (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
IMPUTE <- "median"
SCALE <- "none" # MCD is affine equivariant: scaling does not change the distances
FEATURES <- c("Murder", "Assault", "UrbanPop", "Rape")
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_usarrests.parquet", col_select = FEATURES))
warnings <- list()
design <- cs_ml_design(
df, FEATURES,
kinds = list(
Murder = "numeric",
Assault = "numeric",
UrbanPop = "numeric",
Rape = "numeric"
),
levels = list(
),
impute = IMPUTE,
scale = SCALE
)
fitted <- cs_ml_design_fit(design, df)
X <- unname(cs_ml_design_apply(fitted, df)) # numbers imputed / scaled; categories one-hot (missing -> all zero)
rows <- seq_len(nrow(df)) - 1L
SEED <- 42
# %% Minimum covariance determinant (FastMCD twin, subsets from the shared stream)
fit <- cs_ml_mcd(X, 0.5, SEED)
scores <- fit$robust_distance
DEFAULT_CUTOFF <- fit$cutoff
SCORE_LABEL <- "Robust distance"
ENGINE_PACKAGES <- c("codesplashr", "nanoparquet")
extra_values <- list(h = fit$h, logdet_raw = fit$logdet_raw, n_reweighted = fit$n_reweighted, chi2_cutoff = fit$cutoff,
n_beyond_cutoff = sum(scores >= fit$cutoff), classical_flagged = sum(fit$classical_distance >= fit$cutoff))
for (i in seq_along(FEATURES)) extra_values[[sprintf("center[%s]", FEATURES[i])]] <- fit$center[i]
rescore <- function(Q, where0, col0) sqrt(cs_ml_mahalanobis2(Q, fit$center, fit$cov)) # the fitted center and scatter
# %% Flag anomalies
RULE <- "cutoff"
cutoff_ <- NULL
if (is.null(cutoff_)) cutoff_ <- DEFAULT_CUTOFF # set by the including template (e.g. the χ² cutoff for MCD)
flagged <- cs_ml_flag(scores, RULE, 0.05, cutoff_)
flags <- flagged$flag
threshold <- flagged$threshold
ord <- order(-scores, rows) # highest score first, ties by row
out <- cs_ml_out_dir("target/academy-parity/run-8142/discover.robust_cov/usarrests/out-r")
nanoparquet::write_parquet(data.frame(row = as.integer(rows), score = scores, anomaly = flags), file.path(out, "labels.parquet"))
# %% Result
values <- c(list(n = length(rows), n_flagged = sum(flags), threshold = threshold,
score_check = cs_ml_checksum(scores, rows), score_max = max(scores), score_mean = mean(scores)),
extra_values)
for (rank in seq_len(min(10L, length(ord)))) {
values[[sprintf("top_row[%d]", rank)]] <- rows[ord[rank]]
values[[sprintf("top_score[%d]", rank)]] <- scores[ord[rank]]
}
top <- utils::head(ord, 20L)
# %% Why these rows (numeric features: robust z and the ECOD tail-score share; Phase 11 DS1)
NUMERIC <- c("Murder", "Assault", "UrbanPop", "Rape")
why <- NULL
if (length(NUMERIC)) {
F_ <- as.matrix(as.data.frame(lapply(df[rows + 1L, NUMERIC, drop = FALSE], function(x) as.numeric(as.character(x)))))
med_ <- apply(F_, 2, function(c) if (any(!is.na(c))) stats::median(c[!is.na(c)]) else 0)
for (j in seq_len(ncol(F_))) F_[is.na(F_[, j]), j] <- med_[j]
why <- cs_ml_anomaly_explain(F_, top - 1L)
for (rank in seq_len(min(10L, length(top)))) {
values[[sprintf("why_feature[%d]", rank)]] <- why$feature[rank]
values[[sprintf("why_z[%d]", rank)]] <- why$z[rank]
values[[sprintf("why_share[%d]", rank)]] <- why$share[rank]
}
# Score drop: move one feature to its median, leave the rest of the row alone, and rescore.
drop_ <- cs_ml_score_drops(X, top - 1L, match(NUMERIC, cs_ml_design_names(fitted)) - 1L, scores, rescore)
for (rank in seq_len(min(10L, length(top)))) {
values[[sprintf("drop_feature[%d]", rank)]] <- drop_$feature[rank]
values[[sprintf("drop_score[%d]", rank)]] <- drop_$drop[rank]
}
}
table_rows <- lapply(seq_along(top), function(rank) {
i <- top[rank]
r <- list(rank = rank, row = rows[i] + 1L, score = scores[i])
if (!is.null(why)) {
j <- why$feature[rank] + 1L
sh <- why$share[rank]
r$why <- paste0(sprintf("%s = %s (robust z %+.1f)", NUMERIC[j], format(signif(F_[i, j], 4)), why$z[rank]),
if (is.nan(sh)) "" else sprintf("; %.0f%% of its tail score", 100 * sh))
d_ <- drop_$drop[rank]
r$drop <- if (d_ > 0) sprintf("%s: falls %s at its median", NUMERIC[drop_$feature[rank] + 1L], format(signif(d_, 3))) else "no single feature lowers it"
}
for (f in FEATURES) {
v <- df[[f]][rows[i] + 1L]
r[[f]] <- if (is.na(v)) NULL else if (is.numeric(v)) v else as.character(v)
}
r
})
cs_publish(list(
title = "Robust covariance (MCD) outliers",
engine = do.call(cs_engine_info, as.list(ENGINE_PACKAGES)),
n = length(rows),
summary = sprintf("%d of %d rows (%.1f%%) are flagged as anomalies (%s ≥ %s).", sum(flags), length(rows),
100 * mean(flags), SCORE_LABEL, format(signif(threshold, 3))),
statistics = list(list(key = "n_flagged", label = "Anomalies", value = sum(flags), format = "integer"),
list(key = "threshold", label = "Threshold", value = threshold)),
tables = list(list(
key = "top", title = "Most anomalous rows",
columns = c(list(list(key = "rank", label = "Rank", type = "integer"), list(key = "row", label = "Row", type = "integer"),
list(key = "score", label = SCORE_LABEL, type = "number")),
if (!is.null(why)) list(list(key = "why", label = "Most unusual"), list(key = "drop", label = "Biggest score drop")) else list(),
lapply(FEATURES, function(f) list(key = f, label = f))),
rows = table_rows
)),
charts = list(cs_chart("scores", "anomaly-scores", paste(SCORE_LABEL, "distribution"), list(
score = cs_col(SCORE_LABEL, scores, "numeric"),
anomaly = cs_col("Anomaly", flags, "boolean")
), controls = list(threshold = threshold))),
values = values,
warnings = warnings,
artifacts = list(list(key = "labels", path = file.path(out, "labels.parquet"), format = "parquet"))
))
Sources
- Rousseeuw PJ, Van Driessen K (1999). A fast algorithm for the minimum covariance determinant estimator. Technometrics 41(3):212–223.
- Hubert M, Debruyne M (2010). Minimum covariance determinant. WIREs Computational Statistics 2:36–43.
From the CodeSplash method registry · discover.robust_cov v1.1.0.