Multivariate Anomaly Detection on Time-Series Data in Python: Using Isolation Forests to Detect Credit Card Fraud

Multivariate Anomaly Detection on Time-Series Data in Python: Using Isolation Forests to Detect Credit Card Fraud

Isolation Forest detects unusual observations by measuring how quickly random trees isolate them. This updated tutorial uses a deterministic transaction fixture, an explicit contamination assumption, current scikit-learn APIs, and known injected anomalies for evaluation.

Fit the detector

model = IsolationForest(
    n_estimators=250,
    contamination=EXPECTED_ANOMALY_SHARE,
    random_state=RANDOM_SEED,
)
predictions = model.fit_predict(features)

The model is unsupervised during fitting. Fixture labels are used only afterward to calculate precision, recall, and a confusion matrix.

Isolation Forest anomalies

An anomaly is not automatically fraud. Real fraud detection needs time-aware validation, investigation feedback, threshold selection based on operational costs, monitoring for drift, and controls that prevent automated adverse decisions without review.

Florian Follonier

Florian Follonier · Cloud Solution Architect at Microsoft

Florian Follonier (PhD) is a Cloud Solution Architect at Microsoft based in Zurich and the author of relataly.com, writing hands-on tutorials on machine learning, Python, RAG, and AI agents.

2 Commentsarchived from the original site

  • Philip
    Does this method also detect collective anomalies or only point anomalies ?
  • Florian Follonier
    That’s a great question! In my opinion, it depends on the features. In the example, features cover a single data point t. So the isolation tree will check if this point deviates from the norm. If you you are looking for temporal patterns that unfold over multiple datapoints, you could try to add features that capture these historical data points, t, t-1, t-n. Or you need to use a different algorithm, e.g., an LSTM neural net.