CDiscover · discover.ocsvm
One-class SVM
Which rows fall outside the boundary that encloses most of the data?
Learns a smooth boundary (RBF kernel) around the bulk of the rows; rows outside it score as anomalies. ν bounds the share of rows treated as outliers while learning. Both engines call LIBSVM (scikit-learn ↔ e1071) on the same scaled design and kernel width, so scores agree closely; the flagging rule is shared with the other detectors. The SVDD view reports the same boundary as the smallest sphere in feature space that encloses the bulk (support vector data description).
A real result
Example “Pima”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
27 of 532 rows (5.1%) are flagged as anomalies (One-class SVM score ≥ 6.22e-05).
- Anomalies
- 27
- Threshold
- 6.217e-5
Plots
View data
| Anomaly | One-class SVM score |
|---|---|
| false | −0.5286 |
| false | −0.0418 |
| false | −0.3742 |
| false | −0.1168 |
| false | −0.3205 |
| false | −0.6584 |
| false | −0.4743 |
| false | −5.478e-5 |
| false | −0.0242 |
| false | −0.6677 |
| true | 0.1363 |
| false | −0.7790 |
| true | 0.0002 |
| false | −0.0002 |
| false | −0.1001 |
| false | −0.1698 |
| false | −0.1427 |
| false | −0.6612 |
| false | −0.7404 |
| false | −0.1418 |
| false | −0.3107 |
| false | −0.5438 |
| false | −0.3718 |
| false | −0.2284 |
| false | −0.4660 |
| false | −0.4329 |
| false | −0.3381 |
| false | −0.2765 |
| false | −0.7064 |
| false | −0.8842 |
| false | −0.1249 |
| false | −0.5039 |
| false | −0.5228 |
| false | −0.2672 |
| false | −0.6600 |
| true | 0.0004 |
| false | −0.2038 |
| false | −0.0569 |
| false | −0.2050 |
| false | −0.3041 |
| false | −0.6747 |
| false | −0.4018 |
| false | −0.6309 |
| false | −0.1680 |
| false | −0.3066 |
| false | −0.3530 |
| false | −0.7007 |
| false | −0.0002 |
| false | −0.3471 |
| false | −0.0003 |
| false | −0.2637 |
| false | −0.4869 |
| false | −1.170 |
| false | −0.4593 |
| false | −0.3679 |
| false | −0.2207 |
| false | −0.3180 |
| false | −0.2365 |
| false | −0.4202 |
| true | 0.0002 |
First 60 of 532 rows.
Most anomalous rows
| Rank | Row | One-class SVM score | Most unusual | Biggest score drop | npreg | glu | bp | skin | bmi | ped | age |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 1 | 157 | 0.5142 | skin = 99 (robust z +6.7); 34% of its tail score | skin: falls 0.681 at its median | 2 | 197 | 70 | 99 | 34.700 | 0.5750 | 62 |
| 2 | 398 | 0.3378 | ped = 2.42 (robust z +7.6); 26% of its tail score | no single feature lowers it | 0 | 180 | 78 | 63 | 59.400 | 2.420 | 25 |
| 3 | 279 | 0.1742 | bmi = 67.1 (robust z +5.2); 33% of its tail score | ped: falls 0.0249 at its median | 0 | 129 | 110 | 46 | 67.100 | 0.3190 | 26 |
| 4 | 11 | 0.1363 | ped = 2.288 (robust z +7.1); 29% of its tail score | ped: falls 0.259 at its median | 0 | 137 | 40 | 35 | 43.100 | 2.288 | 33 |
| 5 | 257 | 0.0962 | bp = 30 (robust z -3.5); 30% of its tail score | age: falls 0.00225 at its median | 1 | 88 | 30 | 42 | 55 | 0.4960 | 26 |
| 6 | 255 | 0.0004 | bmi = 53.2 (robust z +3.1); 27% of its tail score | glu: falls 0.0456 at its median | 0 | 162 | 76 | 56 | 53.200 | 0.7590 | 25 |
| 7 | 449 | 0.0004 | npreg = 11 (robust z +3.0); 20% of its tail score | bmi: falls 0.393 at its median | 11 | 103 | 68 | 40 | 46.200 | 0.1260 | 42 |
| 8 | 36 | 0.0004 | npreg = 13 (robust z +3.7); 25% of its tail score | bmi: falls 0.228 at its median | 13 | 145 | 82 | 19 | 22.200 | 0.2450 | 57 |
| 9 | 492 | 0.0004 | bmi = 57.3 (robust z +3.7); 33% of its tail score | bmi: falls 0.109 at its median | 3 | 123 | 100 | 35 | 57.300 | 0.8800 | 22 |
| 10 | 327 | 0.0003 | bp = 88 (robust z +1.3); 18% of its tail score | glu: falls 0.299 at its median | 0 | 78 | 88 | 29 | 36.900 | 0.4340 | 21 |
| 11 | 147 | 0.0003 | glu = 56 (robust z -2.0); 42% of its tail score | glu: falls 0.464 at its median | 2 | 56 | 56 | 28 | 24.200 | 0.3320 | 22 |
| 12 | 526 | 0.0003 | glu = 181 (robust z +2.2); 19% of its tail score | glu: falls 0.279 at its median | 0 | 181 | 88 | 44 | 43.300 | 0.2220 | 26 |
| 13 | 347 | 0.0003 | ped = 1.476 (robust z +4.0); 29% of its tail score | ped: falls 0.699 at its median | 8 | 118 | 72 | 19 | 23.100 | 1.476 | 46 |
| 14 | 432 | 0.0003 | age = 60 (robust z +3.6); 19% of its tail score | skin: falls 0.205 at its median | 6 | 129 | 90 | 7 | 19.600 | 0.5820 | 60 |
| 15 | 440 | 0.0002 | bp = 90 (robust z +1.5); 22% of its tail score | glu: falls 0.179 at its median | 4 | 84 | 90 | 23 | 39.500 | 0.1590 | 25 |
| 16 | 60 | 0.0002 | bp = 106 (robust z +2.9); 26% of its tail score | bp: falls 0.398 at its median | 8 | 167 | 106 | 46 | 37.600 | 0.1650 | 43 |
| 17 | 13 | 0.0002 | age = 59 (robust z +3.5); 28% of its tail score | age: falls 0.359 at its median | 1 | 189 | 60 | 23 | 30.100 | 0.3980 | 59 |
| 18 | 530 | 0.0002 | age = 63 (robust z +3.9); 29% of its tail score | skin: falls 0.332 at its median | 10 | 101 | 76 | 48 | 32.900 | 0.1710 | 63 |
| 19 | 296 | 0.0002 | ped = 2.329 (robust z +7.2); 35% of its tail score | ped: falls 0.337 at its median | 4 | 197 | 70 | 39 | 36.700 | 2.329 | 31 |
| 20 | 520 | 0.0002 | npreg = 13 (robust z +3.7); 26% of its tail score | npreg: falls 0.802 at its median | 13 | 153 | 88 | 37 | 40.600 | 1.174 | 39 |
27 of 532 rows (5.1%) are flagged as anomalies (One-class SVM score ≥ 6.22e-05).
- Anomalies
- 27
- Threshold
- 6.217e-5
To keep this page light, the plots are shown once, under the R tab.
Most anomalous rows
| Rank | Row | One-class SVM score | Most unusual | Biggest score drop | npreg | glu | bp | skin | bmi | ped | age |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 1 | 157 | 0.5142 | skin = 99 (robust z +6.7); 34% of its tail score | skin: falls 0.681 at its median | 2 | 197 | 70 | 99 | 34.700 | 0.5750 | 62 |
| 2 | 398 | 0.3378 | ped = 2.42 (robust z +7.6); 26% of its tail score | no single feature lowers it | 0 | 180 | 78 | 63 | 59.400 | 2.420 | 25 |
| 3 | 279 | 0.1742 | bmi = 67.1 (robust z +5.2); 33% of its tail score | ped: falls 0.0249 at its median | 0 | 129 | 110 | 46 | 67.100 | 0.3190 | 26 |
| 4 | 11 | 0.1363 | ped = 2.288 (robust z +7.1); 29% of its tail score | ped: falls 0.259 at its median | 0 | 137 | 40 | 35 | 43.100 | 2.288 | 33 |
| 5 | 257 | 0.0962 | bp = 30 (robust z -3.5); 30% of its tail score | age: falls 0.00225 at its median | 1 | 88 | 30 | 42 | 55 | 0.4960 | 26 |
| 6 | 255 | 0.0004 | bmi = 53.2 (robust z +3.1); 27% of its tail score | glu: falls 0.0456 at its median | 0 | 162 | 76 | 56 | 53.200 | 0.7590 | 25 |
| 7 | 449 | 0.0004 | npreg = 11 (robust z +3.0); 20% of its tail score | bmi: falls 0.393 at its median | 11 | 103 | 68 | 40 | 46.200 | 0.1260 | 42 |
| 8 | 36 | 0.0004 | npreg = 13 (robust z +3.7); 25% of its tail score | bmi: falls 0.228 at its median | 13 | 145 | 82 | 19 | 22.200 | 0.2450 | 57 |
| 9 | 492 | 0.0004 | bmi = 57.3 (robust z +3.7); 33% of its tail score | bmi: falls 0.109 at its median | 3 | 123 | 100 | 35 | 57.300 | 0.8800 | 22 |
| 10 | 327 | 0.0003 | bp = 88 (robust z +1.3); 18% of its tail score | glu: falls 0.299 at its median | 0 | 78 | 88 | 29 | 36.900 | 0.4340 | 21 |
| 11 | 147 | 0.0003 | glu = 56 (robust z -2.0); 42% of its tail score | glu: falls 0.464 at its median | 2 | 56 | 56 | 28 | 24.200 | 0.3320 | 22 |
| 12 | 526 | 0.0003 | glu = 181 (robust z +2.2); 19% of its tail score | glu: falls 0.279 at its median | 0 | 181 | 88 | 44 | 43.300 | 0.2220 | 26 |
| 13 | 347 | 0.0003 | ped = 1.476 (robust z +4.0); 29% of its tail score | ped: falls 0.699 at its median | 8 | 118 | 72 | 19 | 23.100 | 1.476 | 46 |
| 14 | 432 | 0.0003 | age = 60 (robust z +3.6); 19% of its tail score | skin: falls 0.205 at its median | 6 | 129 | 90 | 7 | 19.600 | 0.5820 | 60 |
| 15 | 440 | 0.0002 | bp = 90 (robust z +1.5); 22% of its tail score | glu: falls 0.179 at its median | 4 | 84 | 90 | 23 | 39.500 | 0.1590 | 25 |
| 16 | 60 | 0.0002 | bp = 106 (robust z +2.9); 26% of its tail score | bp: falls 0.398 at its median | 8 | 167 | 106 | 46 | 37.600 | 0.1650 | 43 |
| 17 | 13 | 0.0002 | age = 59 (robust z +3.5); 28% of its tail score | age: falls 0.359 at its median | 1 | 189 | 60 | 23 | 30.100 | 0.3980 | 59 |
| 18 | 530 | 0.0002 | age = 63 (robust z +3.9); 29% of its tail score | skin: falls 0.332 at its median | 10 | 101 | 76 | 48 | 32.900 | 0.1710 | 63 |
| 19 | 296 | 0.0002 | ped = 2.329 (robust z +7.2); 35% of its tail score | ped: falls 0.337 at its median | 4 | 197 | 70 | 39 | 36.700 | 2.329 | 31 |
| 20 | 520 | 0.0002 | npreg = 13 (robust z +3.7); 26% of its tail score | npreg: falls 0.802 at its median | 13 | 153 | 88 | 37 | 40.600 | 1.174 | 39 |
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
- Pimaml_pima · features: npreg, glu, bp, skin, bmi, ped, age
- Usarrests cutoffml_usarrests · features: Murder, Assault, UrbanPop, Rape
- Usarrests svddml_usarrests · features: Murder, Assault, UrbanPop, Rape
- Pima svdd cutoffml_pima · features: npreg, glu, bp, skin, bmi, ped, age
- Regress infml_pima · features: npreg, glu, bp, skin, bmi, ped, 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
- Featuresnumeric / categorical / boolean · 1–1000 columns
- Variables that describe normal rows (standardized; categories as 0/1 columns; missing numbers → median).
Choices you make
model
- Viewdefault ocsvm
The same fitted boundary, read as a separating hyperplane (one-class SVM) or as an enclosing sphere (SVDD).
- One-class SVM(default) — Score = minus the decision value; 0 is the boundary.
- Sphere (SVDD) — Score = squared distance to the sphere's center minus its squared radius in feature space; 0 is the boundary. Also reports the radius and C = 1/(νn).
- Outlier share while learning (ν)default 0.05
Upper bound on the training rows left outside the boundary (and lower bound on support vectors).
- Kernel width (γ)default —
Larger γ = tighter boundary around each row; smaller = smoother.
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) — Flag a fixed share of rows.
- Score cutoff — Flag rows whose score passes a value (0 = on the boundary).
- Share flaggeddefault 0.05
Share of rows to flag (the highest scores).
- Score cutoffdefault 0
Rows scoring at or above this are flagged; 0 is the learned boundary.
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.
- gamma
- Half the average squared difference between pairs of sites, by distance. Low at short range when nearby sites resemble each other.
- n_support
- How many independent units the analysis used; it sets precision and power.
- outside_boundary
- Learns a smooth boundary around most rows; rows outside it score as anomalies.
- nu
- Upper bound on the share of training rows treated as outliers (and lower bound on support vectors); the value this run used.
Per group, level or term: svdd[<quantity>], 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 within simulation error (relative tolerance 1e-4). Python uses scikit-learn; R uses e1071.
Default traps between the two languages
- SVDD view (Tax & Duin 2004): with the RBF kernel, k(x, x) = 1, so the SVDD with C = 1/(νn) has the one-class SVM's solution scaled, β = α / (νn); score = ‖φ(x) − a‖² − R² = −2 f(x) / (νn), radius R² = 1 − 2ρ / (νn) + βᵀKβ. Same ranking and flags as the one-class SVM view.
- Both engines run LIBSVM's ν one-class solver (scikit-learn's bundled LIBSVM ↔ e1071's) with the same kernel width, tolerance and shrinking; the bundled versions can stop a few solver steps apart, so scores agree to about 1e-5 rather than exactly. Score = −decision value (higher = more anomalous; 0 is the boundary).
The exact script CodeSplash ran for example “Pima” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# One-class SVM
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.ocsvm 1.2.0 · spec 1be6576db7edad53
# Dataset: ml_pima (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
from sklearn.svm import OneClassSVM
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_pima.parquet", columns=["npreg", "glu", "bp", "skin", "bmi", "ped", "age"]), ["npreg", "glu", "bp", "skin", "bmi", "ped", "age"])
FEATURES = ["npreg", "glu", "bp", "skin", "bmi", "ped", "age"]
df = pd.read_parquet("tests/parity/fixtures/ml_pima.parquet", columns=FEATURES)
warnings = []
design = csml.Design.for_frame(
df,
FEATURES,
kinds={
"npreg": "numeric",
"glu": "numeric",
"bp": "numeric",
"skin": "numeric",
"bmi": "numeric",
"ped": "numeric",
"age": "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 (LIBSVM ν one-class; score = −decision value, 0 = the boundary)
NU = 0.05
GAMMA = None
if GAMMA is None:
var = float(X.var())
GAMMA = 1.0 / (X.shape[1] * var) if var > 0 else 1.0
model = OneClassSVM(kernel="rbf", nu=NU, gamma=GAMMA, tol=1e-3, shrinking=True).fit(X)
scores = -np.asarray(model.decision_function(X), dtype=np.float64)
SCORE_LABEL = "One-class SVM score"
ENGINE_PACKAGES = ("scikit-learn", "numpy", "pandas")
extra_values = {"gamma": float(GAMMA), "nu": float(NU), "n_support": int(len(model.support_)), "outside_boundary": int(np.sum(scores > 0))}
rescore = lambda Q, where, col: -np.asarray(model.decision_function(Q), dtype=np.float64) # the fitted boundary, no refit
# %% Flag anomalies
RULE = "share"
_cutoff = 0
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.ocsvm/pima/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 = ["npreg", "glu", "bp", "skin", "bmi", "ped", "age", ]
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": "One-class SVM",
"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 “Pima” · R version 4.5.1 (2025-06-13)
# One-class SVM
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.ocsvm 1.2.0 · spec 1be6576db7edad53
# Dataset: ml_pima (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_pima.parquet", col_select = c("npreg", "glu", "bp", "skin", "bmi", "ped", "age"))), c("npreg", "glu", "bp", "skin", "bmi", "ped", "age"))
FEATURES <- c("npreg", "glu", "bp", "skin", "bmi", "ped", "age")
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_pima.parquet", col_select = FEATURES))
warnings <- list()
design <- cs_ml_design(
df, FEATURES,
kinds = list(
npreg = "numeric",
glu = "numeric",
bp = "numeric",
skin = "numeric",
bmi = "numeric",
ped = "numeric",
age = "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 (LIBSVM ν one-class; score = −decision value, 0 = the boundary)
NU <- 0.05
GAMMA <- NULL
if (is.null(GAMMA)) {
v <- mean((X - mean(X))^2) # population variance of every entry (scikit-learn's "scale")
GAMMA <- if (v > 0) 1 / (ncol(X) * v) else 1
}
model <- e1071::svm(x = X, type = "one-classification", kernel = "radial", gamma = GAMMA, nu = NU,
scale = FALSE, tolerance = 1e-3, shrinking = TRUE)
dv <- attr(stats::predict(model, X, decision.values = TRUE), "decision.values")
scores <- -as.numeric(dv)
SCORE_LABEL <- "One-class SVM score"
ENGINE_PACKAGES <- c("e1071", "nanoparquet")
extra_values <- list(gamma = GAMMA, nu = NU, n_support = nrow(model$SV), outside_boundary = sum(scores > 0))
rescore <- function(Q, where0, col0) -as.numeric(attr(stats::predict(model, Q, decision.values = TRUE), "decision.values")) # the fitted boundary, no refit
# %% Flag anomalies
RULE <- "share"
cutoff_ <- 0
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.ocsvm/pima/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("npreg", "glu", "bp", "skin", "bmi", "ped", "age")
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 = "One-class SVM",
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
- Tax DMJ, Duin RPW (2004). Support vector data description. Machine Learning 54(1):45–66.
- Schölkopf B, Platt JC, Shawe-Taylor J, Smola AJ, Williamson RC (2001). Estimating the support of a high-dimensional distribution. Neural Computation 13(7):1443–1471.
- Chang CC, Lin CJ (2011). LIBSVM: a library for support vector machines. ACM TIST 2(3):27.
From the CodeSplash method registry · discover.ocsvm v1.2.0.