Sub topic 12
Evaluating with ROC AUC and average precision
This chapter assumes you can fit an IsolationForest and read score_samples (covered earlier in the tutorial). It also assumes you know what precision, recall, true positives and false positives mean. Here you will measure how well a detector ranks anomalies above normal points, using two metrics from scikit-learn.
Why evaluation needs care
Anomaly detection is usually an unsupervised task, so most real datasets come with no labels. Evaluation is only possible when you have some labeled data. That might be a historical set of confirmed fraud cases, a benchmark dataset, or a synthetic test where you inject outliers yourself.
Two properties of the problem shape the choice of metric:
- Anomalies are rare. A detector that labels everything "normal" can reach 99% accuracy when 1% of points are anomalies. Accuracy tells you almost nothing here.
predictdepends oncontamination. Its labels reflect a threshold you chose, not the quality of the underlying scores. To judge the model itself, evaluate the continuous scores before any threshold is applied.
ROC AUC and average precision both work on scores. They ask how well the scores rank true anomalies above normal points.
The sign convention
In scikit-learn, score_samples returns values where lower means more abnormal. roc_auc_score and average_precision_score expect the opposite. They treat a higher score as stronger evidence for the positive class, and here the positive class is "anomaly".
So negate the scores before evaluating:
anomaly_scores = -clf.score_samples(X) # higher = more anomalousdecision_function also uses "lower is more abnormal". It equals score_samples shifted by the offset_ attribute, so negating it gives the same ranking and the same metric values.
ROC AUC
The ROC curve plots the true positive rate (recall) against the false positive rate as the threshold sweeps from the highest score to the lowest. ROC AUC is the area under that curve.
It has a useful probabilistic reading. ROC AUC is the probability that a randomly chosen anomaly receives a higher anomaly score than a randomly chosen normal point.
- 1.0 means every anomaly outranks every normal point.
- 0.5 means the ranking is no better than random.
- Below 0.5 means the ranking is inverted, which usually points to a sign error.
ROC AUC does not depend on the class ratio, because the false positive rate is computed only over normal points. That makes it stable, but it also hides a weakness. With 10,000 normal points and 20 anomalies, a false positive rate of 1% still means 100 false alarms, which swamp the 20 real anomalies. ROC AUC barely registers this, and a review team reading the alerts would.
Average precision
Average precision (AP) summarizes the precision-recall curve. Precision is the fraction of flagged points that are true anomalies. Recall is the fraction of true anomalies that were flagged. As you lower the threshold, recall rises and precision usually falls.
scikit-learn computes AP as a weighted sum over the curve's thresholds:
AP = sum over n of (Rn − R(n−1)) × P_n
Here Pn and Rn are precision and recall at the n-th threshold. This avoids the linear interpolation used in some trapezoid-based definitions, which can be too optimistic.
AP depends strongly on prevalence, the fraction of anomalies in the data. A random ranking has an expected AP equal to the prevalence. With 5% anomalies, random scoring gives an AP near 0.05, so an AP of 0.40 is a large improvement. Always compare AP against that baseline.
| Property | ROC AUC | Average precision |
|---|---|---|
| Random baseline | 0.5 | Prevalence of anomalies |
| Sensitive to class imbalance | Little | Strongly |
| Penalizes false alarms among top-ranked points | Weakly | Strongly |
| Good for | Overall ranking quality, comparing across datasets | Rare anomalies, alert-review workflows |
A complete evaluation
The script below trains on normal data only and evaluates on a held-out set with labeled anomalies. It reports both metrics, shows the sign mistake, and computes precision among the top-ranked points.
import numpy as np
from sklearn.ensemble import IsolationForest
from sklearn.metrics import roc_auc_score, average_precision_score
rng = np.random.RandomState(0)
# Training data: normal behavior only
X_train = rng.normal(size=(1000, 2))
# Held-out test data: 500 normal points and 25 anomalies
X_test_normal = rng.normal(size=(500, 2))
X_test_outliers = rng.uniform(low=-6.0, high=6.0, size=(25, 2))
X_test = np.vstack([X_test_normal, X_test_outliers])
y_true = np.r_[np.zeros(len(X_test_normal)), np.ones(len(X_test_outliers))] # 1 = anomaly
clf = IsolationForest(n_estimators=200, random_state=0).fit(X_train)
raw = clf.score_samples(X_test) # lower = more abnormal
anomaly_scores = -raw # higher = more anomalous
print("ROC AUC:", round(roc_auc_score(y_true, anomaly_scores), 3))
print("Average precision:", round(average_precision_score(y_true, anomaly_scores), 3))
print("Random AP baseline:", round(y_true.mean(), 3))
print("AUC with wrong sign:", round(roc_auc_score(y_true, raw), 3))
# Precision among the k highest-scoring points
k = 25
top_k = np.argsort(anomaly_scores)[::-1][:k]
print(f"Precision@{k}:", y_true[top_k].mean())Some uniform outliers land inside the normal cluster, so you should not expect perfect scores. The wrong-sign line prints roughly one minus the correct AUC.
Precision at k and the review budget
Many deployments have a fixed review capacity. For example, analysts can inspect 50 alerts a day. In that setting the useful question is how many of the top 50 are real. This is precision@k, shown at the end of the script above. It needs no threshold, only a count, and it matches how the detector is used. Pair it with recall@k, which is the share of all known anomalies that appear in the top k.
AP and precision@k agree in spirit. Both reward models that push true anomalies to the very top of the ranking.
Choosing a threshold from labels
If you have labels, you can use them to set the threshold instead of guessing contamination. precision_recall_curve returns precision and recall at every candidate threshold, so you can pick the one that meets a business requirement, such as "recall of at least 0.8 with the best precision".
from sklearn.metrics import precision_recall_curve
precision, recall, thresholds = precision_recall_curve(y_true, anomaly_scores)
# precision and recall have one more entry than thresholds, so drop the last
ok = recall[:-1] >= 0.8
best = np.argmax(precision[:-1] * ok)
print("Threshold:", thresholds[best])
print("Precision:", precision[best], "Recall:", recall[best])Choose this threshold on a validation set, and report final metrics on a separate test set. A threshold tuned and scored on the same data gives an optimistic picture.
Common errors
- Wrong sign. Covered above. Negate
score_samplesordecision_function. - Evaluating
predictoutput. Passing the -1/1 labels toroc_auc_scorecollapses the ranking to two values and discards information. It also encodes anomalies as -1, which is the wrong direction. Use the continuous scores. - Label coding. Metrics treat 1 as the positive class by default.
IsolationForestuses -1 for outliers, so convert your ground truth to 1 = anomaly, 0 = normal, or passpos_labelexplicitly. - Evaluating on training data with leaked anomalies. If the training set contains the labeled anomalies and you score the same points, the numbers describe how well the model fits that sample. They do not describe generalization to new data. Hold out a test set.
- Comparing AP across datasets with different prevalence. An AP of 0.3 is excellent at 1% prevalence and poor at 30%. Report the baseline next to it.
- Tiny numbers of positives. With 5 labeled anomalies, one extra anomaly ranked differently changes AP a lot. Use repeated runs with different
random_statevalues or bootstrap resampling to see the spread. - Label quality. Labeled anomalies often reflect only the cases someone detected. Unlabeled true anomalies count as false positives, which pushes your measured precision down.
When there are no labels
Without labels, ROC AUC and AP cannot be computed. You still have options:
- Inject synthetic anomalies into a validation set and measure how well the model recovers them. The result depends on how realistic your injected anomalies are, so treat it as a sanity check.
- Review a sample of the top-ranked points manually and estimate precision@k from that review.
- Monitor the score distribution and the alert rate over time. A sudden shift suggests drift or a pipeline change.
- Use the quantile threshold from the earlier chapter, for example
np.quantile(anomaly_scores, 0.95), to flag a fixed share of points. This controls alert volume but says nothing about correctness.
Exercise
A fraud dataset has 0.5% fraudulent transactions. Your detector reaches ROC AUC 0.93 and average precision 0.04. Is AP of 0.04 good or bad, and why can the two metrics look so different?
Show answer
An AP of 0.04 is about eight times the random baseline of 0.005, so it is better than chance, but it is low in absolute terms: most flagged transactions are still false alarms. The metrics differ because ROC AUC uses the false positive rate, which divides by the large number of normal points, so a small rate of false alarms still looks good. AP uses precision, which counts false alarms against the few true frauds, so it exposes how many of the top-ranked alerts are wrong.
Exercise
You call roc_auc_score(y_true, clf.score_samples(X)) and get 0.08. What does this indicate, and what is the fix?
Show answer
The ranking is inverted, because score_samples is lower for anomalies while roc_auc_score expects higher scores for the positive class. The detector is actually good, with an AUC near 0.92. Fix it by passing -clf.score_samples(X).
Exercise
Your analysts can review 100 alerts per day. Which metric best matches this constraint, and how do you compute it?
Show answer
Precision@100. Sort points by anomaly score (after negating score_samples) in descending order, take the first 100, and compute the mean of y_true over those points. Recall@100 shows the share of all true anomalies that those 100 alerts catch.