Sub topic 12
Evaluating with ROC AUC and average precision
This chapter assumes you can fit an IsolationForest, read score_samples, and have a feature matrix where some rows are known anomalies. Labels are rarely available in production, but a labeled sample lets you compare models and settings before you deploy.
Why accuracy is the wrong metric
Anomalies are rare. If 5% of rows are anomalies, a model that flags nothing is 95% accurate and useless. Use metrics that score the ranking of points instead of a single hard cut.
Both metrics below take a continuous score where higher means more anomalous. score_samples returns the opposite, because lower values are more abnormal. Negate it first.
ROC AUC
The ROC curve plots the true positive rate against the false positive rate as the threshold moves from strict to loose. ROC AUC is the area under that curve. It equals the probability that a random anomaly gets a higher score than a random normal point. A value of 0.5 is random ranking and 1.0 is perfect ranking.
Average precision
Average precision summarizes the precision-recall curve. Precision is the share of flagged points that are true anomalies. Recall is the share of true anomalies that were flagged. Average precision rewards a model that puts true anomalies at the very top of the ranking.
When anomalies are very rare, prefer average precision. ROC AUC can look high because the false positive rate is divided by a large number of normal points, so many false alarms barely move it. Precision is not diluted that way. The baseline for average precision is the anomaly rate, not 0.5.
Worked example
import numpy as np
from sklearn.ensemble import IsolationForest
from sklearn.metrics import roc_auc_score, average_precision_score
rng = np.random.RandomState(0)
X_normal = rng.normal(size=(1000, 2))
X_outliers = rng.uniform(low=-6.0, high=6.0, size=(50, 2))
X = np.vstack([X_normal, X_outliers])
y_true = np.r_[np.zeros(len(X_normal)), np.ones(len(X_outliers))] # 1 = anomaly
clf = IsolationForest(random_state=0).fit(X)
anomaly_scores = -clf.score_samples(X) # flip sign so higher = more anomalous
print("ROC AUC:", roc_auc_score(y_true, anomaly_scores))
print("Average precision:", average_precision_score(y_true, anomaly_scores))
# Unsupervised threshold: flag the 5% most abnormal points
threshold = np.quantile(anomaly_scores, 0.95)
flagged = anomaly_scores >= thresholdThe anomaly rate here is 50 / 1050, about 4.8%. An average precision near that value would mean no skill. Anything well above it means the forest ranks real anomalies first.
Some uniform outliers land inside the Gaussian cluster, so neither metric reaches 1.0. That is expected.
Evaluation workflow
Common errors
- Forgetting to negate the score. Passing
score_samplesdirectly gives an AUC below 0.5, which means the ranking is inverted. - Using
predictoutput as the score. Labels of 1 and -1 collapse the ranking into two values and discard information. Also,predictreturns -1 for anomalies, whiley_truehere uses 1. - Tuning on the test labels. If you pick
max_samplesorcontaminationusing the same labels you report, the result is optimistic. Hold out a separate labeled set. - Reading the metrics as threshold quality. Both metrics ignore the threshold. After you pick one, check precision and recall at that cut.
- Labels that are incomplete. Unlabeled real anomalies count as false positives, which lowers precision for a model that is actually correct.
Exercise
A dataset has 2% anomalies. Your detector gets ROC AUC 0.95 but average precision 0.20. Is this a contradiction, and which number better reflects the cost of reviewing alerts?
Show answer
It is not a contradiction. With few anomalies, many normal points can outrank some anomalies without lowering the false positive rate much, so ROC AUC stays high. Average precision of 0.20 against a 0.02 baseline shows the model has skill, but only about one in five top-ranked alerts is a true anomaly. Average precision better reflects the review cost.
Exercise
You compute rocaucscore(ytrue, clf.scoresamples(X)) and get 0.03. What went wrong and what is the fix?
Show answer
scoresamples is lower for anomalies, but rocaucscore expects higher scores for the positive class. The ranking is inverted. Use -clf.scoresamples(X), which should give about 0.97.