Skip to content

CDiscover · discover.iforest

Isolation forest

Which rows are unusual compared with the rest of the data?

Isolation forest anomaly scores (isotree): rows that random splits isolate quickly score high. Numeric, categorical (one-hot) and true/false features; missing numbers are handled by the model. Python and R run the same isotree core with the same seed, so the scores are identical.

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

A real result

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

Isolation forestRecorded · Python and R agreeRecorded 2026-11-25 · 76 values compared
R

27 of 532 rows (5.1%) are flagged as anomalies (Isolation score ≥ 0.544).

Anomalies
27
Threshold
0.5439

Plots

Isolation score distributionHow unusual are the most anomalous rows compared with the rest, and where is the cut?
View data
AnomalyIsolation score
false0.4081
false0.5287
false0.4413
false0.4636
false0.4169
false0.4347
false0.4074
false0.4973
false0.5010
false0.4784
true0.5893
false0.4503
false0.5303
true0.5869
false0.4832
false0.4453
false0.4789
false0.5061
false0.4188
false0.4556
false0.4309
false0.4163
false0.4443
false0.4376
false0.3962
false0.4868
false0.4475
false0.4318
false0.4052
false0.3880
false0.4534
false0.4077
false0.4203
false0.4442
false0.4156
true0.5612
false0.4338
false0.4865
false0.4497
false0.4056
false0.5027
false0.4411
false0.4342
false0.4533
false0.4100
false0.4241
false0.3961
false0.5211
false0.4149
true0.5698
false0.4223
false0.3942
false0.4276
false0.3996
false0.3894
false0.4685
false0.4098
false0.4536
false0.4511
false0.5424

First 60 of 532 rows.

Most anomalous rows

RankRowIsolation scoreMost unusualBiggest score dropnpregglubpskinbmipedage
13980.6665ped = 2.42 (robust z +7.6); 26% of its tail scoreped: falls 0.0805 at its median0180786359.4002.42025
21570.6541skin = 99 (robust z +6.7); 34% of its tail scoreskin: falls 0.126 at its median2197709934.7000.575062
32790.5900bmi = 67.1 (robust z +5.2); 33% of its tail scorebmi: falls 0.104 at its median01291104667.1000.319026
4110.5893ped = 2.288 (robust z +7.1); 29% of its tail scoreped: falls 0.0926 at its median0137403543.1002.28833
54320.5892age = 60 (robust z +3.6); 19% of its tail scorebmi: falls 0.0492 at its median612990719.6000.582060
62210.5880bp = 110 (robust z +3.2); 28% of its tail scorebp: falls 0.0554 at its median91711102445.4000.721054
7140.5869npreg = 12 (robust z +3.4); 19% of its tail scorenpreg: falls 0.0653 at its median129262727.6000.926044
84170.5850age = 58 (robust z +3.4); 21% of its tail scoreage: falls 0.0749 at its median0173783246.5001.15958
94910.5701bp = 106 (robust z +2.9); 26% of its tail scorebp: falls 0.0591 at its median10681062335.5000.285047
10500.5698ped = 1.394 (robust z +3.7); 21% of its tail scoreped: falls 0.0674 at its median1199764342.9001.39422
113060.5633ped = 1.213 (robust z +3.0); 19% of its tail scoreped: falls 0.0492 at its median91848515301.21349
122720.5613npreg = 17 (robust z +5.1); 36% of its tail scorenpreg: falls 0.0954 at its median17163724140.9000.817047
13360.5612npreg = 13 (robust z +3.7); 25% of its tail scorenpreg: falls 0.0451 at its median13145821922.2000.245057
142960.5607ped = 2.329 (robust z +7.2); 35% of its tail scoreped: falls 0.101 at its median4197703936.7002.32931
151400.5587skin = 60 (robust z +3.0); 29% of its tail scoreskin: falls 0.0604 at its median0100886046.8000.962031
164030.5566age = 81 (robust z +6.0); 44% of its tail scoreage: falls 0.105 at its median9134743325.9000.460081
172550.5536bmi = 53.2 (robust z +3.1); 27% of its tail scorebmi: falls 0.0537 at its median0162765653.2000.759025
183580.5532age = 65 (robust z +4.2); 31% of its tail scoreage: falls 0.0785 at its median51031083739.2000.305065
192220.5529ped = 1.893 (robust z +5.6); 31% of its tail scoreped: falls 0.0861 at its median01806639421.89325
202180.5519ped = 1.39 (robust z +3.7); 27% of its tail scoreped: falls 0.0804 at its median4111724737.1001.39056
Python

27 of 532 rows (5.1%) are flagged as anomalies (Isolation score ≥ 0.544).

Anomalies
27
Threshold
0.5439

To keep this page light, the plots are shown once, under the R tab.

Most anomalous rows

RankRowIsolation scoreMost unusualBiggest score dropnpregglubpskinbmipedage
13980.6665ped = 2.42 (robust z +7.6); 26% of its tail scoreped: falls 0.0805 at its median0180786359.4002.42025
21570.6541skin = 99 (robust z +6.7); 34% of its tail scoreskin: falls 0.126 at its median2197709934.7000.575062
32790.5900bmi = 67.1 (robust z +5.2); 33% of its tail scorebmi: falls 0.104 at its median01291104667.1000.319026
4110.5893ped = 2.288 (robust z +7.1); 29% of its tail scoreped: falls 0.0926 at its median0137403543.1002.28833
54320.5892age = 60 (robust z +3.6); 19% of its tail scorebmi: falls 0.0492 at its median612990719.6000.582060
62210.5880bp = 110 (robust z +3.2); 28% of its tail scorebp: falls 0.0554 at its median91711102445.4000.721054
7140.5869npreg = 12 (robust z +3.4); 19% of its tail scorenpreg: falls 0.0653 at its median129262727.6000.926044
84170.5850age = 58 (robust z +3.4); 21% of its tail scoreage: falls 0.0749 at its median0173783246.5001.15958
94910.5701bp = 106 (robust z +2.9); 26% of its tail scorebp: falls 0.0591 at its median10681062335.5000.285047
10500.5698ped = 1.394 (robust z +3.7); 21% of its tail scoreped: falls 0.0674 at its median1199764342.9001.39422
113060.5633ped = 1.213 (robust z +3.0); 19% of its tail scoreped: falls 0.0492 at its median91848515301.21349
122720.5613npreg = 17 (robust z +5.1); 36% of its tail scorenpreg: falls 0.0954 at its median17163724140.9000.817047
13360.5612npreg = 13 (robust z +3.7); 25% of its tail scorenpreg: falls 0.0451 at its median13145821922.2000.245057
142960.5607ped = 2.329 (robust z +7.2); 35% of its tail scoreped: falls 0.101 at its median4197703936.7002.32931
151400.5587skin = 60 (robust z +3.0); 29% of its tail scoreskin: falls 0.0604 at its median0100886046.8000.962031
164030.5566age = 81 (robust z +6.0); 44% of its tail scoreage: falls 0.105 at its median9134743325.9000.460081
172550.5536bmi = 53.2 (robust z +3.1); 27% of its tail scorebmi: falls 0.0537 at its median0162765653.2000.759025
183580.5532age = 65 (robust z +4.2); 31% of its tail scoreage: falls 0.0785 at its median51031083739.2000.305065
192220.5529ped = 1.893 (robust z +5.6); 31% of its tail scoreped: falls 0.0861 at its median01806639421.89325
202180.5519ped = 1.39 (robust z +3.7); 27% of its tail scoreped: falls 0.0804 at its median4111724737.1001.39056

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
  • Penguins mixed missingml_penguins · features: island, bill_len, bill_dep, flipper_len, body_mass, sex
  • Airquality extendedml_airquality · features: Ozone, solar radiation, Wind, Temp
  • Pdna mixed nullablepdna_penguins · features: island, bill_len, bill_dep, flipper_len, body_mass, sex

In the guides

Where it sits in the decision guides

  • Automated EDA (profiling, anomaly detection) · DS & ML Decision Guide · Describe — summarize and visualize
  • 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

Treesdefault 100

Number of isolation trees. More gives steadier scores.

Rows per treedefault 256

Sub-sample size for each tree (capped at the number of rows).

Advanced

Split dimensionsdefault 1

1 = the classic isolation forest; more = extended isolation forest (oblique splits).

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 above the score you set; pick it when you know a meaningful threshold.
Share flaggeddefault 0.05

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

Score cutoffdefault 0.6

Standardized isolation scores near 0.5 are ordinary; values well above 0.5 are anomalous.

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.

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

Default traps between the two languages

  • Python and R call the same isotree C++ core with the same seed, one thread and the same design matrix; scores agree to rounding.
Python

The exact script CodeSplash ran for example “Pima” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0

# Isolation forest
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.iforest 1.2.0 · spec 59a1df5b296d40c4
# 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 isotree import IsolationForest

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 = "none"  # isotree handles missing numbers itself
SCALE = "none"
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
model = IsolationForest(
    ntrees=100,
    sample_size=min(256, len(df)),
    ndim=1,
    missing_action="impute",
    nthreads=1,  # pinned: identical trees in Python and R
    random_seed=42,
)
model.fit(X)
scores = np.asarray(model.predict(X), dtype=np.float64)  # standardized isolation score
SCORE_LABEL = "Isolation score"
ENGINE_PACKAGES = ("isotree", "numpy", "pandas")
extra_values = {}

rescore = lambda Q, where, col: np.asarray(model.predict(Q), dtype=np.float64)  # the fitted trees, no refit

# %% Flag anomalies
RULE = "share"
_cutoff = 0.6
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.iforest/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": "Isolation forest",
    "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 “Pima” · R version 4.5.1 (2025-06-13)

# Isolation forest
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.iforest 1.2.0 · spec 59a1df5b296d40c4
# 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)
suppressPackageStartupMessages(library(isotree))

# %% Data
IMPUTE <- "none"  # isotree handles missing numbers itself
SCALE <- "none"
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
model <- isotree::isolation.forest(
  X,
  ntrees = 100,
  sample_size = min(256, nrow(df)),
  ndim = 1,
  missing_action = "impute",
  nthreads = 1,  # pinned: identical trees in Python and R
  seed = 42
)
scores <- as.numeric(predict(model, X, type = "score"))  # standardized isolation score
SCORE_LABEL <- "Isolation score"
ENGINE_PACKAGES <- c("isotree", "nanoparquet")
extra_values <- list()

rescore <- function(Q, where0, col0) as.numeric(predict(model, Q, type = "score"))  # the fitted trees, no refit

# %% Flag anomalies
RULE <- "share"
cutoff_ <- 0.6
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.iforest/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 = "Isolation forest",
  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

  • Liu FT, Ting KM, Zhou Z-H (2008). Isolation forest. ICDM 2008, 413–422.
  • Hariri S, Kind MC, Brunner RJ (2021). Extended isolation forest. IEEE TKDE 33(4):1479–1489.

From the CodeSplash method registry · discover.iforest v1.2.0.