Sub topic 15
Explaining Why a Point Was Flagged
Isolation Forest returns a score. It does not return a reason. An analyst who gets a flagged transaction or sensor reading will ask which values made it unusual. This chapter shows how to answer that with three techniques, and where each one breaks down.
I assume you have read the earlier chapters on path length, the anomaly score, and score_samples. You should be comfortable with NumPy indexing and with the fitted attributes of a scikit-learn ensemble.
What the score tells you, and what it hides
A short average path length means random splits separated the point quickly. The score is one number per point, so it says nothing about which feature caused the isolation. Suppose a point has three features and only the second is extreme. The score is high, but nothing in it points at feature two.
Explanation therefore needs a second step. You ask a narrower question about the already-flagged point: which features, if they looked normal, would make the point score as ordinary?
A reference setup
The examples below share one model. The training data has three standard normal features. The query point is ordinary in features 0 and 2 and extreme in feature 1.
import numpy as np
from sklearn.ensemble import IsolationForest
rng = np.random.RandomState(0)
X_train = rng.normal(size=(1000, 3))
feature_names = ["f0", "f1", "f2"]
clf = IsolationForest(random_state=0).fit(X_train)
x = np.array([[0.2, 5.0, -0.1]])
print("label:", clf.predict(x)[0])
print("score_samples:", clf.score_samples(x)[0])The label is -1 and the score is well below the scores of typical training points.
Method 1: compare each feature with its baseline
The cheapest explanation ignores the forest. Compute how far each feature of the point sits from the training distribution. A robust version uses the median and the median absolute deviation (MAD), so that the outliers already in the training data do not distort the baseline.
def robust_z(X_ref, x):
med = np.median(X_ref, axis=0)
mad = np.median(np.abs(X_ref - med), axis=0)
mad = np.where(mad == 0, 1e-9, mad)
return 0.6745 * (np.asarray(x).ravel() - med) / mad
for name, z in zip(feature_names, robust_z(X_train, x)):
print(f"{name}: robust z = {z:+.2f}")The factor 0.6745 makes the MAD comparable to a standard deviation for normal data. This method is fast and easy to explain. It only sees one feature at a time, though. A point can be flagged because of an unusual combination of features, such as a young customer with a very high income, while each value looks normal on its own. In that case every z-score is small and the method explains nothing.
Method 2: replacement attribution
This method asks the model directly. For each feature, replace the point's value with values drawn from the training data and measure how much the abnormality drops. A large drop means that feature was driving the flag. Because it calls only score_samples, it works for any fitted detector.
def replacement_attribution(clf, X_ref, x, n_draws=200, seed=0):
rng = np.random.RandomState(seed)
x = np.asarray(x, dtype=float).reshape(1, -1)
base = -clf.score_samples(x)[0] # higher = more anomalous
drops = np.zeros(x.shape[1])
for j in range(x.shape[1]):
variants = np.repeat(x, n_draws, axis=0)
variants[:, j] = rng.choice(X_ref[:, j], size=n_draws)
drops[j] = base - (-clf.score_samples(variants)).mean()
return base, drops
base, drops = replacement_attribution(clf, X_train, x)
print("abnormality of the point:", round(base, 3))
for name, d in zip(feature_names, drops):
print(f"{name}: abnormality drop = {d:+.3f}")Feature f1 should show a large positive drop. The other two should be near zero, and may be slightly positive or negative from sampling noise.
Because the replacement values are drawn independently of the other features, the method can create unrealistic combinations. If two features are strongly correlated, swapping one of them produces a point that is itself abnormal. That distorts the attribution. Replacing features in correlated groups, or conditioning the draws on the other features, reduces the problem.
Method 3: inspect the paths inside the trees
You can also read the forest itself. Every tree in clf.estimators_ is a scikit-learn tree. For a given point, decision_path lists the nodes it visited, and tree_.feature gives the feature tested at each node. An anomaly has short paths, so the splits near the root matter most. If those splits keep using the same feature, that feature is the likely cause.
def path_feature_share(clf, x):
x = np.asarray(x, dtype=np.float32).reshape(1, -1)
counts = np.zeros(x.shape[1])
for tree, feats in zip(clf.estimators_, clf.estimators_features_):
node_ids = tree.decision_path(x[:, feats]).indices
split_feats = tree.tree_.feature[node_ids]
for f in split_feats[split_feats >= 0]: # leaves are marked -2
counts[feats[f]] += 1
return counts / counts.sum()
share_x = path_feature_share(clf, x)
share_ref = np.mean([path_feature_share(clf, row) for row in X_train[:200]], axis=0)
for name, sx, sr in zip(feature_names, share_x, share_ref):
print(f"{name}: share on path {sx:.2f} vs typical {sr:.2f}")Compare the point's share with the typical share. With three features, a typical share is close to one third. A feature that takes a much larger share on the flagged point's path is where the isolating cuts happened. The estimators_features_ array maps each tree's local feature index back to the original column. This matters when max_features is below 1.0 and each tree sees only a subset of columns.
Research methods such as DIFFI (Depth-based Isolation Forest Feature Importance) refine this idea. They weight each split by how much it shortened the path compared with an expected path. The count above is a simplified version.
SHAP as a ready-made option
The shap library's TreeExplainer supports scikit-learn's IsolationForest. It returns Shapley values for the score, which are additive contributions per feature that sum to the difference from the average score. This gives a principled attribution and plots for free. It costs extra computation, and some versions of the library handle IsolationForest less well than others, so check your installed version against its documentation before relying on it.
Choosing a method
| Method | Needs the model internals | Sees feature interactions | Cost | Main weakness |
|---|---|---|---|---|
| Baseline comparison | No | No | Very low | Misses unusual combinations |
| Replacement attribution | No | Partly | Moderate | Unrealistic replacement points |
| Path inspection | Yes | Indirectly | Low to moderate | Shows where cuts happened, not effect size |
| SHAP TreeExplainer | Yes | Yes | Higher | Library and version dependence |
A practical routine is to run the baseline comparison first. If it explains the flag, you are done. If every z-score is small, move to replacement attribution or SHAP, because the cause is probably an interaction.
Pitfalls
- Unstable attributions. The forest is random, so two fits with different seeds can give different rankings for borderline features. Fix
random_statefor reporting, and check that the top feature stays the same across a few seeds before you trust it. - Scale and units. Attributions are measured in score units, which are comparable across features of one model. Raw feature values are not. When you show an analyst "value 5.0", also show the typical range.
- Many weak features. If the abnormality is spread across many features, no single feature stands out. Report that outcome as it is, instead of forcing a top three.
- Drift. An explanation uses the training data as its reference. If the data has drifted, the reference no longer describes normal, and the explanations drift with it.
Putting it together
For one flagged record, a compact report can pair each feature's value with its robust z-score and its replacement drop. This gives the reader both a simple check and a model-based one, and they usually agree on the top feature.
base, drops = replacement_attribution(clf, X_train, x)
zs = robust_z(X_train, x)
order = np.argsort(-drops)
for j in order:
print(f"{feature_names[j]}: value={x[0, j]:+.2f}, "
f"robust z={zs[j]:+.2f}, drop={drops[j]:+.3f}")When the two columns disagree, that disagreement is informative. A large drop with a small z-score points to an interaction or a sparse region, which is worth a closer look.
Exercise
A flagged record has small robust z-scores on every feature, yet its score_samples value is far below typical. Name one likely cause and one method from this chapter that could expose it.
Show answer
The point is probably unusual as a combination of features, for example two correlated features that normally move together but here do not. Per-feature baselines cannot see this. Replacement attribution (replacing one feature at a time and measuring the drop in abnormality), or SHAP values, can show which features drive the score. Replacing features in correlated groups gives a cleaner result.
Exercise
In pathfeatureshare, why must the code index the result with feats[f] instead of using f directly?
Show answer
Each tree is fitted on a subset of columns when maxfeatures is below 1.0, so the feature index stored in tree.feature is local to that subset. The array estimatorsfeatures maps the local index back to the original column. Using f directly would credit the wrong feature.