Skip to content

CDiscover · discover.lof

Local outlier factor

Which rows sit in sparser neighborhoods than their neighbors?

Local outlier factor (LOF): each row's local density compared with that of its k nearest neighbors (Euclidean distance on standardized features). LOF near 1 is ordinary; well above 1 is an outlier. Neighborhoods include every row within the k-distance (Breunig et al.; the definition of dbscan::lof), computed the same way in both engines. Local outlier probabilities (LoOP) turn the same neighborhoods into a 0–1 score.

Verified in Python and R Python and R agree to 10 decimals

A real result

Example “Usarrests”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

Local outlier factorRecorded · Python and R agreeRecorded 2026-11-25 · 77 values compared
R

5 of 50 rows (10.0%) are flagged as anomalies (LOF ≥ 1.22).

Anomalies
5
Threshold
1.217

Plots

LOF distributionHow unusual are the most anomalous rows compared with the rest, and where is the cut?
View data
AnomalyLOF
false1.002
true1.605
false0.9810
false1.135
false1.102
false1.083
false1.083
true1.487
false1.111
false0.9526
true1.217
false0.9530
false1.001
false1.000
false0.9976
false0.9666
false1.200
false0.9827
false0.9738
false0.9238
false1.153
false1.020
false1.028
false1.062
false1.174
false1.028
false0.9751
false1.116
false0.9854
false1.210
false1.008
false0.9705
false1.199
false1.107
false0.9691
false1.041
false1.208
false0.9829
false1.203
false1.049
false0.9884
false1.128
false0.9870
false1.119
true1.262
false0.9961
false1.143
true1.231
false1.009
false0.9702

Most anomalous rows

RankRowLOFMost unusualBiggest score dropMurderAssaultUrbanPopRape
121.605Rape = 44.5 (robust z +2.8); 40% of its tail scoreRape: falls 0.562 at its median102634844.500
281.487Assault = 238 (robust z +0.7); 28% of its tail scoreAssault: falls 0.505 at its median5.9002387215.800
3451.262UrbanPop = 32 (robust z -1.9); 36% of its tail scoreUrbanPop: falls 0.219 at its median2.200483211.200
4481.231UrbanPop = 39 (robust z -1.5); 37% of its tail scoreUrbanPop: falls 0.149 at its median5.70081399.300
5111.217Assault = 46 (robust z -1.0); 46% of its tail scoreAssault: falls 0.163 at its median5.300468320.200
6301.210UrbanPop = 89 (robust z +1.3); 60% of its tail scoreUrbanPop: falls 0.229 at its median7.4001598918.800
7371.208Rape = 29.3 (robust z +1.1); 40% of its tail scoreRape: falls 0.235 at its median4.9001596729.300
8391.203Rape = 8.3 (robust z -1.4); 36% of its tail scoreRape: falls 0.0595 at its median3.400174878.300
9171.200UrbanPop = 52 (robust z -0.8); 31% of its tail scoreUrbanPop: falls 0.136 at its median9.7001095216.300
10331.199Assault = 337 (robust z +1.6); 43% of its tail scoreAssault: falls 0.117 at its median133374516.100
11251.174Rape = 28.2 (robust z +0.9); 38% of its tail scoreRape: falls 0.0998 at its median91787028.200
12211.153UrbanPop = 85 (robust z +1.1); 43% of its tail scoreUrbanPop: falls 0.199 at its median4.4001498516.300
13471.143Rape = 26.2 (robust z +0.7); 29% of its tail scoreRape: falls 0.122 at its median41457326.200
1441.135UrbanPop = 50 (robust z -0.9); 40% of its tail scoreUrbanPop: falls 0.0831 at its median8.8001905019.500
15421.128Murder = 13.2 (robust z +1.1); 37% of its tail scoreUrbanPop: falls 0.121 at its median13.2001885926.900
16441.119UrbanPop = 80 (robust z +0.8); 28% of its tail scoreRape: falls 0.0871 at its median3.2001208022.900
17281.116Rape = 46 (robust z +3.0); 45% of its tail scoreRape: falls 0.0905 at its median12.2002528146
1891.111Assault = 335 (robust z +1.6); 35% of its tail scoreUrbanPop: falls 0.0585 at its median15.4003358031.900
19341.107Rape = 7.3 (robust z -1.5); 27% of its tail scoreUrbanPop: falls 0.0493 at its median0.800045447.300
2051.102Rape = 40.6 (robust z +2.4); 29% of its tail scoreUrbanPop: falls 0.0557 at its median92769140.600
Python

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

RankRowLOFMost unusualBiggest score dropMurderAssaultUrbanPopRape
121.605Rape = 44.5 (robust z +2.8); 40% of its tail scoreRape: falls 0.562 at its median102634844.500
281.487Assault = 238 (robust z +0.7); 28% of its tail scoreAssault: falls 0.505 at its median5.9002387215.800
3451.262UrbanPop = 32 (robust z -1.9); 36% of its tail scoreUrbanPop: falls 0.219 at its median2.200483211.200
4481.231UrbanPop = 39 (robust z -1.5); 37% of its tail scoreUrbanPop: falls 0.149 at its median5.70081399.300
5111.217Assault = 46 (robust z -1.0); 46% of its tail scoreAssault: falls 0.163 at its median5.300468320.200
6301.210UrbanPop = 89 (robust z +1.3); 60% of its tail scoreUrbanPop: falls 0.229 at its median7.4001598918.800
7371.208Rape = 29.3 (robust z +1.1); 40% of its tail scoreRape: falls 0.235 at its median4.9001596729.300
8391.203Rape = 8.3 (robust z -1.4); 36% of its tail scoreRape: falls 0.0595 at its median3.400174878.300
9171.200UrbanPop = 52 (robust z -0.8); 31% of its tail scoreUrbanPop: falls 0.136 at its median9.7001095216.300
10331.199Assault = 337 (robust z +1.6); 43% of its tail scoreAssault: falls 0.117 at its median133374516.100
11251.174Rape = 28.2 (robust z +0.9); 38% of its tail scoreRape: falls 0.0998 at its median91787028.200
12211.153UrbanPop = 85 (robust z +1.1); 43% of its tail scoreUrbanPop: falls 0.199 at its median4.4001498516.300
13471.143Rape = 26.2 (robust z +0.7); 29% of its tail scoreRape: falls 0.122 at its median41457326.200
1441.135UrbanPop = 50 (robust z -0.9); 40% of its tail scoreUrbanPop: falls 0.0831 at its median8.8001905019.500
15421.128Murder = 13.2 (robust z +1.1); 37% of its tail scoreUrbanPop: falls 0.121 at its median13.2001885926.900
16441.119UrbanPop = 80 (robust z +0.8); 28% of its tail scoreRape: falls 0.0871 at its median3.2001208022.900
17281.116Rape = 46 (robust z +3.0); 45% of its tail scoreRape: falls 0.0905 at its median12.2002528146
1891.111Assault = 335 (robust z +1.6); 35% of its tail scoreUrbanPop: falls 0.0585 at its median15.4003358031.900
19341.107Rape = 7.3 (robust z -1.5); 27% of its tail scoreUrbanPop: falls 0.0493 at its median0.800045447.300
2051.102Rape = 40.6 (robust z +2.4); 29% of its tail scoreUrbanPop: falls 0.0557 at its median92769140.600

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 unscaled cutoffml_pima · features: glu, bp, bmi, age
  • Penguins mixedml_penguins · features: island, bill_len, bill_dep, flipper_len, body_mass
  • Iris duplicate rowml_iris · features: sepal_length, sepal_width, petal_length, petal_width
  • Usarrests loopml_usarrests · features: Murder, Assault, UrbanPop, Rape
  • Pima loop cutoffml_pima · features: glu, bp, bmi, age
  • Iris loop duplicates lambdaml_iris · features: sepal_length, sepal_width, petal_length, petal_width
  • Regress infml_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–200 columns
Columns used to describe each row. Numbers are standardized; categories become indicator columns.

Choices you make

model

Neighbors (k)default 20

Neighbors used to judge local density. Small values find tiny clusters of outliers; large values are smoother.

Scoredefault lof

LOF compares densities as a ratio; LoOP turns the same comparison into a 0–1 outlier probability.

  • Local outlier factor (LOF)(default) — Density ratio: about 1 is ordinary, well above 1 is an outlier.
  • Local outlier probability (LoOP) — Kriegel et al.'s 0–1 score from the same neighborhoods; values near 1 are clear outliers.
Significance (λ)default 3

How many standard deviations count as clearly outlying when LoOP scales its scores (3 is the usual choice).

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 the cutoff; for LOF, 1 means about as dense as the neighbors and values well above 1 stand out.
Share flaggeddefault 0.05

Share of rows to flag as anomalies (0.05 flags the most unusual 5%).

Score cutoffdefault —

Rows at or above this are flagged. Empty uses 1.5 for LOF (1 is typical density) and 0.5 for LoOP.

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.
neighbors
How many nearest rows each row's local density is compared with; small values find tight local outliers.

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 numpy; R uses codesplashr.

Default traps between the two languages

  • LoOP (Kriegel et al. 2009) runs on the same tie-inclusive neighborhoods through the twin codesplash.ml.anomaly_ext.loop ↔ cs_ml_loop (erf via the χ²₁ distribution in R); PyNomaly takes exactly k neighbors, so it agrees when no distances tie.
  • Both engines run the LOF twin (codesplash.ml.anomaly.lof ↔ codesplashr::cs_ml_lof) with Breunig et al.'s neighborhoods — every point within the k-distance, ties included — the definition of dbscan::lof(minPts = k + 1). dbscan decides exact distance ties after its own floating-point summation (iris differs by 5e-4 in mean LOF); scikit-learn's LocalOutlierFactor uses exactly k neighbors. All three agree when no distances tie. Duplicate points give LOF = 1, as in dbscan.
Python

The exact script CodeSplash ran for example “Usarrests” · 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"}],
})
R

The exact script CodeSplash ran for example “Usarrests” · 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"))
))

Sources

  • Kriegel H-P, Kröger P, Schubert E, Zimek A (2009). LoOP: local outlier probabilities. CIKM 2009, 1649–1652.
  • Breunig MM, Kriegel H-P, Ng RT, Sander J (2000). LOF: identifying density-based local outliers. SIGMOD 2000, 93–104.

From the CodeSplash method registry · discover.lof v1.3.0.