Spotting anomalies, and what a flag means
Isolation forest, LOF, ECOD, one-class SVM and robust covariance each define "unusual" differently. Learn to compare them and to treat a flag as a question.
What runs in CodeSplash
- Isolation forest Verified in Python and R
- Local outlier factor Verified in Python and R
- ECOD anomaly scores Verified in Python and R
- One-class SVM Verified in Python and R
- Robust covariance (MCD) outliers Verified in Python and R
- Autoencoder (neural map and reconstruction anomalies) Verified in Python and R
You will be able to
- Distinguish the idea of unusual used by each detector
- Explain why a fixed share always flags rows, and when to use a cutoff instead
- Use the Review tab to turn flags into decisions
Unusual compared with what?
ReadAn outlier in one column is a matter of counting. An anomaly across several columns depends on your idea of "normal".
Each detector here has its own idea, and each returns an anomaly scoreAnomaly scoreHow unusual a row is compared with the rest; a ranking for review, not proof of a problem.. A high score means "unusual by this definition", not "wrong", "fraud" or "error". The score tells you where to look. You still decide what you found.
Five ideas of unusual
Read| Detector | A row is unusual if… |
|---|---|
| Isolation forestIsolation forestFlags rows that random splits separate quickly, because unusual rows take few cuts to isolate. | Random splits separate it quickly |
| LOFLocal outlier factorCompares a row's local density with its neighbors'; a value well above 1 means it sits in a sparser spot than they do. | It sits in a sparser neighborhood than its neighbors do |
| ECODECODScores each row by how far into the tails of each column's own distribution it falls, with no settings to tune. | Its values lie far in the tails of several columns |
| One-class SVMOne-class SVMLearns a smooth boundary around most rows; rows outside it score as anomalies. | It falls outside a smooth boundary around most rows |
| Robust covarianceMinimum covariance determinantMean and covariance from the tightest half of the rows, so outliers cannot hide themselves by inflating the spread. | It's far from the center, measured by the tight core of the data |
Set a threshold
ExploreAExplorable · Isolation forest: where to draw the line
Why are anomalies easy to isolate, and how many should you flag?
Cut at random until a point stands alone. On average, how many cuts does a planted anomaly take? (A normal point takes about 7.)
Commit your prediction above to see the result
Make your prediction to see the result.
Move the threshold and watch precision trade against recall on the planted anomalies. Then switch on Anomalies clump together. Rows that clump take more splits to isolate, so the forest misses them more often.
Real data has no planted truth, so you can't read recall from the card. This is why review matters.
Make a guess
PredictPredict first
Pima has 532 rows. Isolation forest and ECOD both run with their defaults on the same seven columns. How many rows will each one flag?
Make your guess between 0 and 532 rows, then reveal.
Reveal
Isolation forest flags 27 and ECOD flags 27. It's the same count because the default rule is share: flag the most unusual 5%, whether or not anything is unusual. On perfectly normal data it still flags 5%.
Masking
ReadA cluster of outliers can pull the mean toward itself and inflate the covariance. The classical distance then calls them ordinary. This is maskingMaskingA group of outliers pulls the mean and inflates the covariance, so distance measures call those same outliers ordinary..
The robust method estimates center and shape from the tightest half of the rows, so outliers can't distort it. On US arrests, classical Mahalanobis distance flags 2 states while robust distance flags 15.
That doesn't make those states wrong. With only 50 rows, the tight core describes a subset of states, and the method assumes roughly elliptical data. Read it as a sensitivity check.
A learned boundary
ReadA one-class SVM draws a smooth boundary around most rows, and ν sets an upper bound on the share it may leave outside while learning. On Pima with ν = 0.05, 34 rows lie outside the boundary, while the share rule still flags 27.
So the method and the flag rule are separate decisions. The boundary says who's outside. The rule says how many you want to look at.
Read the card
In the app5 of 50 rows (10.0%) are flagged as anomalies (LOF ≥ 1.22).
- Anomalies
- 5
- Threshold
- 1.217
Plots
View data
| Anomaly | LOF |
|---|---|
| false | 1.002 |
| true | 1.605 |
| false | 0.9810 |
| false | 1.135 |
| false | 1.102 |
| false | 1.083 |
| false | 1.083 |
| true | 1.487 |
| false | 1.111 |
| false | 0.9526 |
| true | 1.217 |
| false | 0.9530 |
| false | 1.001 |
| false | 1.000 |
| false | 0.9976 |
| false | 0.9666 |
| false | 1.200 |
| false | 0.9827 |
| false | 0.9738 |
| false | 0.9238 |
| false | 1.153 |
| false | 1.020 |
| false | 1.028 |
| false | 1.062 |
| false | 1.174 |
| false | 1.028 |
| false | 0.9751 |
| false | 1.116 |
| false | 0.9854 |
| false | 1.210 |
| false | 1.008 |
| false | 0.9705 |
| false | 1.199 |
| false | 1.107 |
| false | 0.9691 |
| false | 1.041 |
| false | 1.208 |
| false | 0.9829 |
| false | 1.203 |
| false | 1.049 |
| false | 0.9884 |
| false | 1.128 |
| false | 0.9870 |
| false | 1.119 |
| true | 1.262 |
| false | 0.9961 |
| false | 1.143 |
| true | 1.231 |
| false | 1.009 |
| false | 0.9702 |
Most anomalous rows
| Rank | Row | LOF | Most unusual | Biggest score drop | Murder | Assault | UrbanPop | Rape |
|---|---|---|---|---|---|---|---|---|
| 1 | 2 | 1.605 | Rape = 44.5 (robust z +2.8); 40% of its tail score | Rape: falls 0.562 at its median | 10 | 263 | 48 | 44.500 |
| 2 | 8 | 1.487 | Assault = 238 (robust z +0.7); 28% of its tail score | Assault: falls 0.505 at its median | 5.900 | 238 | 72 | 15.800 |
| 3 | 45 | 1.262 | UrbanPop = 32 (robust z -1.9); 36% of its tail score | UrbanPop: falls 0.219 at its median | 2.200 | 48 | 32 | 11.200 |
| 4 | 48 | 1.231 | UrbanPop = 39 (robust z -1.5); 37% of its tail score | UrbanPop: falls 0.149 at its median | 5.700 | 81 | 39 | 9.300 |
| 5 | 11 | 1.217 | Assault = 46 (robust z -1.0); 46% of its tail score | Assault: falls 0.163 at its median | 5.300 | 46 | 83 | 20.200 |
| 6 | 30 | 1.210 | UrbanPop = 89 (robust z +1.3); 60% of its tail score | UrbanPop: falls 0.229 at its median | 7.400 | 159 | 89 | 18.800 |
| 7 | 37 | 1.208 | Rape = 29.3 (robust z +1.1); 40% of its tail score | Rape: falls 0.235 at its median | 4.900 | 159 | 67 | 29.300 |
| 8 | 39 | 1.203 | Rape = 8.3 (robust z -1.4); 36% of its tail score | Rape: falls 0.0595 at its median | 3.400 | 174 | 87 | 8.300 |
| 9 | 17 | 1.200 | UrbanPop = 52 (robust z -0.8); 31% of its tail score | UrbanPop: falls 0.136 at its median | 9.700 | 109 | 52 | 16.300 |
| 10 | 33 | 1.199 | Assault = 337 (robust z +1.6); 43% of its tail score | Assault: falls 0.117 at its median | 13 | 337 | 45 | 16.100 |
| 11 | 25 | 1.174 | Rape = 28.2 (robust z +0.9); 38% of its tail score | Rape: falls 0.0998 at its median | 9 | 178 | 70 | 28.200 |
| 12 | 21 | 1.153 | UrbanPop = 85 (robust z +1.1); 43% of its tail score | UrbanPop: falls 0.199 at its median | 4.400 | 149 | 85 | 16.300 |
| 13 | 47 | 1.143 | Rape = 26.2 (robust z +0.7); 29% of its tail score | Rape: falls 0.122 at its median | 4 | 145 | 73 | 26.200 |
| 14 | 4 | 1.135 | UrbanPop = 50 (robust z -0.9); 40% of its tail score | UrbanPop: falls 0.0831 at its median | 8.800 | 190 | 50 | 19.500 |
| 15 | 42 | 1.128 | Murder = 13.2 (robust z +1.1); 37% of its tail score | UrbanPop: falls 0.121 at its median | 13.200 | 188 | 59 | 26.900 |
| 16 | 44 | 1.119 | UrbanPop = 80 (robust z +0.8); 28% of its tail score | Rape: falls 0.0871 at its median | 3.200 | 120 | 80 | 22.900 |
| 17 | 28 | 1.116 | Rape = 46 (robust z +3.0); 45% of its tail score | Rape: falls 0.0905 at its median | 12.200 | 252 | 81 | 46 |
| 18 | 9 | 1.111 | Assault = 335 (robust z +1.6); 35% of its tail score | UrbanPop: falls 0.0585 at its median | 15.400 | 335 | 80 | 31.900 |
| 19 | 34 | 1.107 | Rape = 7.3 (robust z -1.5); 27% of its tail score | UrbanPop: falls 0.0493 at its median | 0.8000 | 45 | 44 | 7.300 |
| 20 | 5 | 1.102 | Rape = 40.6 (robust z +2.4); 29% of its tail score | UrbanPop: falls 0.0557 at its median | 9 | 276 | 91 | 40.600 |
The exact R script · R R version 4.5.1 (2025-06-13)
# Local outlier factor
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.lof 1.3.0 · spec 504fa0f9da461112
# 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 <- "standard"
# Infinite values stop the run before the design (registry/errors.yaml)
cs_check_finite_columns(as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_usarrests.parquet", col_select = c("Murder", "Assault", "UrbanPop", "Rape"))), c("Murder", "Assault", "UrbanPop", "Rape"))
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
# %% Scores
if (nrow(df) < 2L) cs_error("CS_E_TOO_FEW_ROWS", what = "Local outlier scores", min = 2L, n = nrow(df))
k <- min(5, nrow(df) - 1L)
# Breunig et al.'s LOF (the definition of dbscan::lof(X, minPts = k + 1)), computed by the twin so
# that exact distance ties are decided identically in Python and R.
scores <- cs_ml_lof(X, k)
SCORE_LABEL <- "LOF"
ENGINE_PACKAGES <- c("codesplashr", "nanoparquet")
extra_values <- list(neighbors = k)
.lof_parts <- cs_ml_lof_parts(X, k)
rescore <- function(Q, where0, col0) cs_ml_lof_query(X, k, .lof_parts, Q, where0) # the other rows' densities held fixed
DEFAULT_CUTOFF <- 1.5
# %% Flag anomalies
RULE <- "share"
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.1, 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.lof/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 = "Local outlier factor",
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"))
))
5 of 50 rows (10.0%) are flagged as anomalies (LOF ≥ 1.22).
- Anomalies
- 5
- Threshold
- 1.217
To keep this page light, the plots are shown once, under the R tab.
Most anomalous rows
| Rank | Row | LOF | Most unusual | Biggest score drop | Murder | Assault | UrbanPop | Rape |
|---|---|---|---|---|---|---|---|---|
| 1 | 2 | 1.605 | Rape = 44.5 (robust z +2.8); 40% of its tail score | Rape: falls 0.562 at its median | 10 | 263 | 48 | 44.500 |
| 2 | 8 | 1.487 | Assault = 238 (robust z +0.7); 28% of its tail score | Assault: falls 0.505 at its median | 5.900 | 238 | 72 | 15.800 |
| 3 | 45 | 1.262 | UrbanPop = 32 (robust z -1.9); 36% of its tail score | UrbanPop: falls 0.219 at its median | 2.200 | 48 | 32 | 11.200 |
| 4 | 48 | 1.231 | UrbanPop = 39 (robust z -1.5); 37% of its tail score | UrbanPop: falls 0.149 at its median | 5.700 | 81 | 39 | 9.300 |
| 5 | 11 | 1.217 | Assault = 46 (robust z -1.0); 46% of its tail score | Assault: falls 0.163 at its median | 5.300 | 46 | 83 | 20.200 |
| 6 | 30 | 1.210 | UrbanPop = 89 (robust z +1.3); 60% of its tail score | UrbanPop: falls 0.229 at its median | 7.400 | 159 | 89 | 18.800 |
| 7 | 37 | 1.208 | Rape = 29.3 (robust z +1.1); 40% of its tail score | Rape: falls 0.235 at its median | 4.900 | 159 | 67 | 29.300 |
| 8 | 39 | 1.203 | Rape = 8.3 (robust z -1.4); 36% of its tail score | Rape: falls 0.0595 at its median | 3.400 | 174 | 87 | 8.300 |
| 9 | 17 | 1.200 | UrbanPop = 52 (robust z -0.8); 31% of its tail score | UrbanPop: falls 0.136 at its median | 9.700 | 109 | 52 | 16.300 |
| 10 | 33 | 1.199 | Assault = 337 (robust z +1.6); 43% of its tail score | Assault: falls 0.117 at its median | 13 | 337 | 45 | 16.100 |
| 11 | 25 | 1.174 | Rape = 28.2 (robust z +0.9); 38% of its tail score | Rape: falls 0.0998 at its median | 9 | 178 | 70 | 28.200 |
| 12 | 21 | 1.153 | UrbanPop = 85 (robust z +1.1); 43% of its tail score | UrbanPop: falls 0.199 at its median | 4.400 | 149 | 85 | 16.300 |
| 13 | 47 | 1.143 | Rape = 26.2 (robust z +0.7); 29% of its tail score | Rape: falls 0.122 at its median | 4 | 145 | 73 | 26.200 |
| 14 | 4 | 1.135 | UrbanPop = 50 (robust z -0.9); 40% of its tail score | UrbanPop: falls 0.0831 at its median | 8.800 | 190 | 50 | 19.500 |
| 15 | 42 | 1.128 | Murder = 13.2 (robust z +1.1); 37% of its tail score | UrbanPop: falls 0.121 at its median | 13.200 | 188 | 59 | 26.900 |
| 16 | 44 | 1.119 | UrbanPop = 80 (robust z +0.8); 28% of its tail score | Rape: falls 0.0871 at its median | 3.200 | 120 | 80 | 22.900 |
| 17 | 28 | 1.116 | Rape = 46 (robust z +3.0); 45% of its tail score | Rape: falls 0.0905 at its median | 12.200 | 252 | 81 | 46 |
| 18 | 9 | 1.111 | Assault = 335 (robust z +1.6); 35% of its tail score | UrbanPop: falls 0.0585 at its median | 15.400 | 335 | 80 | 31.900 |
| 19 | 34 | 1.107 | Rape = 7.3 (robust z -1.5); 27% of its tail score | UrbanPop: falls 0.0493 at its median | 0.8000 | 45 | 44 | 7.300 |
| 20 | 5 | 1.102 | Rape = 40.6 (robust z +2.4); 29% of its tail score | UrbanPop: falls 0.0557 at its median | 9 | 276 | 91 | 40.600 |
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Local outlier factor
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.lof 1.3.0 · spec 504fa0f9da461112
# 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 embed as csembed
# %% Data
IMPUTE = "median"
SCALE = "standard"
# Infinite values stop the run before the design (registry/errors.yaml)
cs.check_finite_columns(pd.read_parquet("tests/parity/fixtures/ml_usarrests.parquet", columns=["Murder", "Assault", "UrbanPop", "Rape"]), ["Murder", "Assault", "UrbanPop", "Rape"])
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))
# %% Scores
if len(df) < 2:
cs.cs_error("CS_E_TOO_FEW_ROWS", what="Local outlier scores", min=2, n=len(df))
k = min(5, len(df) - 1)
# Breunig et al.'s LOF: neighborhoods include every point within the k-distance (dbscan::lof's
# definition). sklearn.neighbors.LocalOutlierFactor(n_neighbors=k) gives the same scores unless
# distances tie.
scores = csanom.lof(X, k)
SCORE_LABEL = "LOF"
ENGINE_PACKAGES = ("numpy", "pandas")
extra_values = {"neighbors": k}
_lof_parts = csanom.lof_parts(X, k)
rescore = lambda Q, where, col: csanom.lof_query(X, k, _lof_parts, Q, where) # the other rows' densities held fixed
DEFAULT_CUTOFF = 1.5
# %% Flag anomalies
RULE = "share"
_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.1, _cutoff)
order = np.lexsort((rows, -scores)) # highest score first, ties by row
out = csml.out_dir("target/academy-parity/run-8142/discover.lof/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": "Local outlier factor",
"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"}],
})
LOF compares each state's density with its neighbors'. It flags 5 of 50 here, with the largest score 1.60. It can find a row that's unusual only locally: normal for the data as a whole, odd next to its neighbors.
The score histogram shows flagged rows stacked in red, with the threshold marked.
View data
| anomaly score | flagged |
|---|---|
| 0.4217 | false |
| 0.4499 | false |
| 0.5103 | false |
| 0.5028 | false |
| 0.4336 | false |
| 0.5026 | false |
| 0.5002 | false |
| 0.5199 | false |
| 0.4377 | false |
| 0.5178 | false |
| 0.4528 | false |
| 0.4401 | false |
| 0.4395 | false |
| 0.4971 | false |
| 0.4508 | false |
| 0.4541 | false |
| 0.4738 | false |
| 0.4640 | false |
| 0.4289 | false |
| 0.4376 | false |
| 0.4474 | false |
| 0.5025 | false |
| 0.4309 | false |
| 0.4250 | false |
| 0.4255 | false |
| 0.5547 | false |
| 0.4777 | false |
| 0.4272 | false |
| 0.4347 | false |
| 0.4316 | false |
| 0.4482 | false |
| 0.4415 | false |
| 0.4450 | false |
| 0.5123 | false |
| 0.5606 | false |
| 0.4290 | false |
| 0.4287 | false |
| 0.4343 | false |
| 0.4322 | false |
| 0.4788 | false |
| 0.4677 | false |
| 0.4839 | false |
| 0.4386 | false |
| 0.5540 | false |
| 0.4545 | false |
| 0.4542 | false |
| 0.4528 | false |
| 0.4476 | false |
| 0.4649 | false |
| 0.5142 | false |
| 0.4437 | false |
| 0.4764 | false |
| 0.4597 | false |
| 0.4426 | false |
| 0.5354 | false |
| 0.4325 | false |
| 0.4305 | false |
| 0.4485 | false |
| 0.5064 | false |
| 0.4441 | false |
First 60 of 1200 rows.
A long separate tail suggests real anomalies. A smooth curve with a threshold cut through it suggests you're ranking normal rows.
Compare, then review
ReflectRows that several detectors agree on deserve attention first. Rows only one detector flags tell you what kind of oddity it's sensitive to.
The Review tab lists flagged rows with the highest score first, lets you confirm or dismiss each with a note, and saves the decisions to the dataset as a column. Those decisions are labels. In time, they could train a supervised model.
Who in your organization would review these rows, and what would they need to see?
Check your understanding
CheckpointCheck yourself
You run a detector with the default fixed share on clean, normal data. What happens?
Show the answer
Answer: b
A share rule always flags that share. Use a cutoff, and look at the score distribution, to ask whether anything is unusual.
Check yourself
A row sits just outside a very tight cluster, and is still close to the data's overall center. Which detector is most likely to catch it?
Show the answer
Answer: a
Its values aren't extreme in any single column, so ECOD sees little. LOF notices it's in a sparser spot than its dense neighbors.
Check yourself
A group of 20 outliers makes classical Mahalanobis distance look normal for each of them. What's this called?
Show the answer
Answer: b
The outliers inflate the covariance that's meant to expose them. Robust estimates, such as minimum covariance determinant, are built to resist that.
Do it on your own data
In the appChoose Spot anomalies, run two detectors on the same features, and open Review on the one you trust more. Save to dataset adds each row's score and flag as a new dataset version.
import pandas as pd
from sklearn.covariance import MinCovDet
from sklearn.ensemble import IsolationForest
from sklearn.neighbors import LocalOutlierFactor
from sklearn.preprocessing import StandardScaler
df = pd.read_csv("usarrests.csv")
X = StandardScaler().fit_transform(df[["Murder", "Assault", "UrbanPop", "Rape"]])
forest = IsolationForest(n_estimators=100, random_state=1).fit(X)
print("iforest", -forest.score_samples(X)[:3].round(3))
lof = LocalOutlierFactor(n_neighbors=5).fit(X)
print("lof", -lof.negative_outlier_factor_[:3].round(3))
print("robust", MinCovDet(random_state=1).fit(X).mahalanobis(X)[:3].round(2))df <- read.csv("usarrests.csv")
X <- scale(df[, c("Murder", "Assault", "UrbanPop", "Rape")])
round(head(dbscan::lof(X, minPts = 6), 3), 3)
mcd <- robustbase::covMcd(X)
round(head(mahalanobis(X, mcd$center, mcd$cov), 3), 2)Note that minPts in R's lof counts the row itself, so 6 there corresponds to 5 neighbors. Scores from the Python libraries are on different scales than the app's unless you standardize them the same way, so compare ranks.
Recap
Recap- Each detector defines unusual differently, so compare them.
- A share rule always flags that share, and a cutoff lets the data speak.
- A flag is a question for a person, and their answers are labels you can keep.
Concepts in this lesson