CDiscover · discover.cblof
Cluster-based local outlier factor (CBLOF)
Which rows sit far from the large clusters, or in small remote clusters?
CBLOF (He et al. 2003): k-means splits the rows into clusters, the largest clusters that together hold most rows count as normal, and every row is scored by its distance to its own center (rows in a large cluster) or to the nearest large center (rows in a small cluster), optionally times its cluster's size. Both engines use the same k-means starts and the same scoring twin.
A real result
Example “Usarrests k4”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
5 of 50 rows (10.0%) are flagged as anomalies (CBLOF ≥ 1.46).
- Anomalies
- 5
- Threshold
- 1.462
Plots
View data
| Anomaly | CBLOF |
|---|---|
| false | 0.3554 |
| true | 2.312 |
| false | 0.8529 |
| false | 1.398 |
| false | 1.401 |
| false | 1.117 |
| false | 1.075 |
| false | 1.252 |
| false | 1.454 |
| false | 1.102 |
| false | 1.305 |
| false | 0.6099 |
| false | 1.114 |
| false | 0.8170 |
| false | 0.5541 |
| false | 0.6319 |
| true | 1.528 |
| false | 0.9259 |
| false | 0.5937 |
| false | 1.006 |
| false | 0.8800 |
| false | 0.3891 |
| false | 1.039 |
| false | 0.9826 |
| false | 1.252 |
| false | 0.8110 |
| false | 0.8968 |
| true | 1.462 |
| false | 0.5895 |
| false | 1.156 |
| false | 0.5654 |
| false | 1.038 |
| false | 1.425 |
| false | 1.087 |
| false | 0.5325 |
| false | 0.5049 |
| false | 1.268 |
| false | 0.6111 |
| true | 1.604 |
| false | 0.6084 |
| false | 0.5087 |
| false | 0.9840 |
| false | 1.193 |
| false | 0.8700 |
| true | 1.489 |
| false | 1.047 |
| false | 0.8927 |
| false | 1.080 |
| false | 1.056 |
| false | 1.094 |
Most anomalous rows
| Rank | Row | CBLOF | Most unusual | Biggest score drop | Murder | Assault | UrbanPop | Rape |
|---|---|---|---|---|---|---|---|---|
| 1 | 2 | 2.312 | Rape = 44.5 (robust z +2.8); 40% of its tail score | Rape: falls 1.28 at its median | 10 | 263 | 48 | 44.500 |
| 2 | 39 | 1.604 | Rape = 8.3 (robust z -1.4); 36% of its tail score | Rape: falls 0.457 at its median | 3.400 | 174 | 87 | 8.300 |
| 3 | 17 | 1.528 | UrbanPop = 52 (robust z -0.8); 31% of its tail score | Murder: falls 0.503 at its median | 9.700 | 109 | 52 | 16.300 |
| 4 | 45 | 1.489 | UrbanPop = 32 (robust z -1.9); 36% of its tail score | UrbanPop: falls 0.394 at its median | 2.200 | 48 | 32 | 11.200 |
| 5 | 28 | 1.462 | Rape = 46 (robust z +3.0); 45% of its tail score | no single feature lowers it | 12.200 | 252 | 81 | 46 |
| 6 | 9 | 1.454 | Assault = 335 (robust z +1.6); 35% of its tail score | Murder: falls 0.163 at its median | 15.400 | 335 | 80 | 31.900 |
| 7 | 33 | 1.425 | Assault = 337 (robust z +1.6); 43% of its tail score | Rape: falls 0.113 at its median | 13 | 337 | 45 | 16.100 |
| 8 | 5 | 1.401 | Rape = 40.6 (robust z +2.4); 29% of its tail score | UrbanPop: falls 0.237 at its median | 9 | 276 | 91 | 40.600 |
| 9 | 4 | 1.398 | UrbanPop = 50 (robust z -0.9); 40% of its tail score | UrbanPop: falls 0.291 at its median | 8.800 | 190 | 50 | 19.500 |
| 10 | 11 | 1.305 | Assault = 46 (robust z -1.0); 46% of its tail score | Assault: falls 0.601 at its median | 5.300 | 46 | 83 | 20.200 |
| 11 | 37 | 1.268 | Rape = 29.3 (robust z +1.1); 40% of its tail score | Rape: falls 0.684 at its median | 4.900 | 159 | 67 | 29.300 |
| 12 | 25 | 1.252 | Rape = 28.2 (robust z +0.9); 38% of its tail score | Rape: falls 0.293 at its median | 9 | 178 | 70 | 28.200 |
| 13 | 8 | 1.252 | Assault = 238 (robust z +0.7); 28% of its tail score | Assault: falls 0.824 at its median | 5.900 | 238 | 72 | 15.800 |
| 14 | 43 | 1.193 | Murder = 12.7 (robust z +1.0); 33% of its tail score | UrbanPop: falls 0.0645 at its median | 12.700 | 201 | 80 | 25.500 |
| 15 | 30 | 1.156 | UrbanPop = 89 (robust z +1.3); 60% of its tail score | UrbanPop: falls 0.432 at its median | 7.400 | 159 | 89 | 18.800 |
| 16 | 6 | 1.117 | Rape = 38.7 (robust z +2.2); 45% of its tail score | Rape: falls 0.119 at its median | 7.900 | 204 | 78 | 38.700 |
| 17 | 13 | 1.114 | UrbanPop = 83 (robust z +1.0); 36% of its tail score | no single feature lowers it | 10.400 | 249 | 83 | 24 |
| 18 | 10 | 1.102 | Murder = 17.4 (robust z +1.9); 55% of its tail score | Rape: falls 0.0967 at its median | 17.400 | 211 | 60 | 25.800 |
| 19 | 50 | 1.094 | Rape = 15.6 (robust z -0.5); 34% of its tail score | UrbanPop: falls 0.345 at its median | 6.800 | 161 | 60 | 15.600 |
| 20 | 34 | 1.087 | Rape = 7.3 (robust z -1.5); 27% of its tail score | no single feature lowers it | 0.8000 | 45 | 44 | 7.300 |
- No boundary met the α or β rule, so every cluster counts as large (each row is scored by the distance to its own center).
5 of 50 rows (10.0%) are flagged as anomalies (CBLOF ≥ 1.46).
- Anomalies
- 5
- Threshold
- 1.462
To keep this page light, the plots are shown once, under the R tab.
Most anomalous rows
| Rank | Row | CBLOF | Most unusual | Biggest score drop | Murder | Assault | UrbanPop | Rape |
|---|---|---|---|---|---|---|---|---|
| 1 | 2 | 2.312 | Rape = 44.5 (robust z +2.8); 40% of its tail score | Rape: falls 1.28 at its median | 10 | 263 | 48 | 44.500 |
| 2 | 39 | 1.604 | Rape = 8.3 (robust z -1.4); 36% of its tail score | Rape: falls 0.457 at its median | 3.400 | 174 | 87 | 8.300 |
| 3 | 17 | 1.528 | UrbanPop = 52 (robust z -0.8); 31% of its tail score | Murder: falls 0.503 at its median | 9.700 | 109 | 52 | 16.300 |
| 4 | 45 | 1.489 | UrbanPop = 32 (robust z -1.9); 36% of its tail score | UrbanPop: falls 0.394 at its median | 2.200 | 48 | 32 | 11.200 |
| 5 | 28 | 1.462 | Rape = 46 (robust z +3.0); 45% of its tail score | no single feature lowers it | 12.200 | 252 | 81 | 46 |
| 6 | 9 | 1.454 | Assault = 335 (robust z +1.6); 35% of its tail score | Murder: falls 0.163 at its median | 15.400 | 335 | 80 | 31.900 |
| 7 | 33 | 1.425 | Assault = 337 (robust z +1.6); 43% of its tail score | Rape: falls 0.113 at its median | 13 | 337 | 45 | 16.100 |
| 8 | 5 | 1.401 | Rape = 40.6 (robust z +2.4); 29% of its tail score | UrbanPop: falls 0.237 at its median | 9 | 276 | 91 | 40.600 |
| 9 | 4 | 1.398 | UrbanPop = 50 (robust z -0.9); 40% of its tail score | UrbanPop: falls 0.291 at its median | 8.800 | 190 | 50 | 19.500 |
| 10 | 11 | 1.305 | Assault = 46 (robust z -1.0); 46% of its tail score | Assault: falls 0.601 at its median | 5.300 | 46 | 83 | 20.200 |
| 11 | 37 | 1.268 | Rape = 29.3 (robust z +1.1); 40% of its tail score | Rape: falls 0.684 at its median | 4.900 | 159 | 67 | 29.300 |
| 12 | 25 | 1.252 | Rape = 28.2 (robust z +0.9); 38% of its tail score | Rape: falls 0.293 at its median | 9 | 178 | 70 | 28.200 |
| 13 | 8 | 1.252 | Assault = 238 (robust z +0.7); 28% of its tail score | Assault: falls 0.824 at its median | 5.900 | 238 | 72 | 15.800 |
| 14 | 43 | 1.193 | Murder = 12.7 (robust z +1.0); 33% of its tail score | UrbanPop: falls 0.0645 at its median | 12.700 | 201 | 80 | 25.500 |
| 15 | 30 | 1.156 | UrbanPop = 89 (robust z +1.3); 60% of its tail score | UrbanPop: falls 0.432 at its median | 7.400 | 159 | 89 | 18.800 |
| 16 | 6 | 1.117 | Rape = 38.7 (robust z +2.2); 45% of its tail score | Rape: falls 0.119 at its median | 7.900 | 204 | 78 | 38.700 |
| 17 | 13 | 1.114 | UrbanPop = 83 (robust z +1.0); 36% of its tail score | no single feature lowers it | 10.400 | 249 | 83 | 24 |
| 18 | 10 | 1.102 | Murder = 17.4 (robust z +1.9); 55% of its tail score | Rape: falls 0.0967 at its median | 17.400 | 211 | 60 | 25.800 |
| 19 | 50 | 1.094 | Rape = 15.6 (robust z -0.5); 34% of its tail score | UrbanPop: falls 0.345 at its median | 6.800 | 161 | 60 | 15.600 |
| 20 | 34 | 1.087 | Rape = 7.3 (robust z -1.5); 27% of its tail score | no single feature lowers it | 0.8000 | 45 | 44 | 7.300 |
- No boundary met the α or β rule, so every cluster counts as large (each row is scored by the distance to its own center).
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
- Usarrests k4ml_usarrests · features: Murder, Assault, UrbanPop, Rape
- Pima defaultml_pima · features: glu, bp, bmi, age
- Iris weighted cutoffml_iris · features: sepal_length, sepal_width, petal_length, petal_width
- Penguins mixed betaml_penguins · features: island, bill_len, bill_dep, flipper_len, body_mass
- Degenerate infml_usarrests · features: Murder, Assault, UrbanPop, Rape
- Degenerate n3ml_usarrests · features: Murder, Assault, UrbanPop, Rape
In the guides
Where it sits in the decision guides
- Anomaly detection · DS & ML Decision Guide · Discover — find structure without labels
What you need
- Featuresnumeric / categorical / boolean · 1–500 columns
- Columns used to describe each row. Numbers are standardized; categories become indicator columns.
Choices you make
model
- Clusters (k)default 8
Clusters k-means makes before they are split into large (normal) and small ones.
- Share in large clusters (α)default 0.9
The large clusters together hold at least this share of rows (with β, picks the split).
- Size jump (β)default 5
A split also counts where the last large cluster is at least β times the next one.
- Multiply by cluster sizedefault off
He et al.'s original score multiplies the distance by the cluster's size; off gives the plain distance.
- k-means startsdefault 10
k-means runs from different k-means++ starts; the one with the smallest within-cluster sum of squares is kept.
preprocess
- Standardize featuresdefault on
Mean 0, SD 1 (population SD) so no feature dominates the distances.
options
- Flag anomalies bydefault share
Flag a fixed share of the most unusual rows, or every row whose score passes a cutoff.
- Share of rows (the highest scores)(default) — Flags a set share of rows with the highest scores; pick it when you know how many you can review.
- Score cutoff — Flags rows at or above a cutoff; leave it empty for median + 3 MADs of the scores.
- Share flaggeddefault 0.05
Share of rows to flag as anomalies (0.05 flags the most unusual 5%).
- Score cutoffdefault —
Rows scoring at or above this are flagged; empty uses the median plus 3 scaled MADs.
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.
- clusters
- The largest clusters that together hold a share α of rows, or end where size drops by β times, count as normal.
- n_large
- The largest clusters that together hold a share α of rows, or end where size drops by β times, count as normal.
- small_rows
- The largest clusters that together hold a share α of rows, or end where size drops by β times, count as normal.
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>]
Python and R
Python and R agree to 10 decimals (relative tolerance 1e-9). Python uses scikit-learn; R uses codesplashr.
Default traps between the two languages
- k-means is the shared twin (best of n starts from host k-means++ starts on the shared stream; scikit-learn ↔ stats::kmeans Lloyd), clusters renumbered by size (ties by first row). Clusters are sorted by size and the large/small boundary is the first that meets both the α and β rules, else α, else β, as in PyOD's CBLOF; when none does, every cluster counts as large (PyOD stops with an error) and the result says so.
The exact script CodeSplash ran for example “Usarrests k4” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Cluster-based local outlier factor (CBLOF)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.cblof 1.0.0 · spec 7368b18436d8bebb
# 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.errors import cs_error
from codesplash.ml import anomaly as csanom
from codesplash.ml import anomaly_ext as csax
from codesplash.ml import cluster as csc
from codesplash.ml import embed as csembed
from codesplash.stats.rng import Rng
# %% 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))
# %% Clusters (shared k-means twin: host k-means++ starts on the shared stream, Lloyd to convergence)
K = 4
SEED = 42
if len(df) <= K:
cs_error("CS_E_TOO_FEW_ROWS", what=f"CBLOF with {K} clusters", min=K + 1, n=len(df))
_raw, _centers, _ = csc.kmeans_fit(X, K, Rng(SEED), n_init=10)
labels = csc.canonical(_raw) # 1..k by size, ties by first row
k_found = int(labels.max())
centers = np.vstack([_centers[int(_raw[np.flatnonzero(labels == c)[0]])] for c in range(1, k_found + 1)])
sizes = np.bincount(labels, minlength=k_found + 1)[1:]
# %% Scores (He et al. 2003; the large/small split as in PyOD's CBLOF)
n_large, _split = csax.cblof_split(labels, 0.9, 5)
if not _split:
warnings.append("No boundary met the α or β rule, so every cluster counts as large (each row is scored by the distance to its own center).")
WEIGHTED = False
scores = csax.cblof_scores(X, labels, centers, sizes, n_large, WEIGHTED)
SCORE_LABEL = "CBLOF"
ENGINE_PACKAGES = ("scikit-learn", "numpy", "pandas")
extra_values = {"clusters": k_found, "n_large": int(n_large), "small_rows": int(np.sum(labels > n_large))}
DEFAULT_CUTOFF = csax.auto_cutoff(scores, "kth") # median + 3 scaled MADs
def rescore(Q, where, col):
lab = csax.nearest_center(Q, centers) # the fitted clusters, no refit
return csax.cblof_scores(Q, lab, centers, sizes, n_large, WEIGHTED)
# %% 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.cblof/usarrests_k4/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": "Cluster-based local outlier factor (CBLOF)",
"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 k4” · R version 4.5.1 (2025-06-13)
# Cluster-based local outlier factor (CBLOF)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.cblof 1.0.0 · spec 7368b18436d8bebb
# 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
# %% Clusters (shared k-means twin: host k-means++ starts on the shared stream, Lloyd to convergence)
K <- 4
SEED <- 42
if (nrow(df) <= K) cs_error("CS_E_TOO_FEW_ROWS", what = sprintf("CBLOF with %d clusters", K), min = K + 1L, n = nrow(df))
.km <- cs_ml_kmeans_fit(X, K, cs_rng(SEED), n_init = 10)
labels <- as.integer(cs_ml_canonical(.km$labels)) # 1..k by size, ties by first row
k_found <- max(labels)
centers <- do.call(rbind, lapply(seq_len(k_found), function(c) .km$centers[.km$labels[which(labels == c)[1]] + 1L, ]))
sizes <- tabulate(labels, nbins = k_found)
# %% Scores (He et al. 2003; the large/small split as in PyOD's CBLOF)
.split <- cs_ml_cblof_split(labels, 0.9, 5)
n_large <- .split$n_large
if (!.split$split) warnings <- c(warnings, "No boundary met the α or β rule, so every cluster counts as large (each row is scored by the distance to its own center).")
WEIGHTED <- FALSE
scores <- cs_ml_cblof_scores(X, labels, centers, sizes, n_large, WEIGHTED)
SCORE_LABEL <- "CBLOF"
ENGINE_PACKAGES <- c("codesplashr", "nanoparquet")
extra_values <- list(clusters = k_found, n_large = n_large, small_rows = sum(labels > n_large))
DEFAULT_CUTOFF <- cs_ml_ax_auto_cutoff(scores, "kth") # median + 3 scaled MADs
rescore <- function(Q, where0, col0) {
lab <- cs_ml_nearest_center(Q, centers) # the fitted clusters, no refit
cs_ml_cblof_scores(Q, lab, centers, sizes, n_large, WEIGHTED)
}
# %% 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.cblof/usarrests_k4/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 = "Cluster-based local outlier factor (CBLOF)",
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
- He Z, Xu X, Deng S (2003). Discovering cluster-based local outliers. Pattern Recognition Letters 24(9–10):1641–1650.
From the CodeSplash method registry · discover.cblof v1.0.0.