Anomaly Detection
Learn how machine learning spots unusual events, suspicious activity, and data points that do not follow the normal pattern. Explore an Isolation Forest playground and see how the contamination setting changes the result.
The big idea
Find data that looks different from most of the data.
Anomaly Detection is a machine learning task. It looks for rare or unusual observations. These observations may be errors, fraud, faults, attacks, or simply rare events that need a closer look.
Many anomaly detection methods can learn from mostly normal data, even when we do not have labels saying which examples are bad.
At a glance
Four useful ideas to remember.
The common pattern the model learns or uses as a reference.
A point or event that is unusual compared with the rest.
A number that shows how unusual a point appears.
A cutoff used to decide which scores should be flagged.
1. How does Anomaly Detection work?
The model learns what is common, then looks for observations that stand apart.
A simple workflow
Gather examples such as payments, sensor readings, website activity, or network traffic.
Use a method to understand common behaviour or how easily points can be separated.
More unusual points receive a stronger anomaly score.
Flag points whose scores cross the chosen cutoff. Check them before taking action.
Imagine a school attendance chart
Most learners arrive between 8:00 and 8:20. One learner arrives at 11:30. That time is unusual compared with the usual pattern.
2. Live Anomaly Detection playground
Change the contamination level and watch the model flag unusual points.
Data map
Blue dots are treated as normal. Orange dots are flagged as anomalies.
Teaching demo: this playground uses a small Isolation Forest model built in JavaScript. It is a simplified example, not a production fraud detector.
Expected share of unusual points. Higher values flag more points.
3. Common Anomaly Detection methods
Different methods find unusual data in different ways.
Isolation Forest
Builds many random decision trees. Unusual points are often separated from the rest using fewer splits, so they get higher anomaly scores.
Used in the playgroundLocal Outlier Factor (LOF)
Compares how crowded the area around a point is with the areas around its neighbours. A point in a much less crowded area may be unusual.
One-Class SVM
Learns a boundary around most of the training data. Points outside that learned region may be treated as anomalies.
Simple statistical rules
Uses measures such as z-scores or the interquartile range to find values far from the usual range.
4. The mathematics behind Isolation Forest
The main idea is to measure how quickly a point can be separated from other points.
Path length
A tree repeatedly splits data using a randomly chosen feature and split value. The number of splits needed to isolate a point is its path length.
Anomaly score
The model combines path lengths from many trees. A commonly used score is:
What do the symbols mean?
| Symbol | Meaning |
|---|---|
| h(x) | Path length needed to isolate point x in a tree. |
| E(h(x)) | Average path length across the trees. |
| n | Number of points used to build a tree. |
| c(n) | Expected path length used to normalise the score. |
| s(x, n) | Anomaly score. A higher score means the point is easier to isolate. |
5. Worked example: unusual card payments
See how a model can help a bank find payments that need a closer look.
Example payment data
The table shows a made-up customer's usual payments and one unusual payment.
| Payment | Amount | Time | Pattern |
|---|---|---|---|
| P-01 | ₹420 | 10:15 | Usual |
| P-02 | ₹650 | 13:20 | Usual |
| P-03 | ₹510 | 18:05 | Usual |
| P-04 | ₹780 | 19:10 | Usual |
| P-05 | ₹48,000 | 03:12 | Unusual |
How the model helps
The model sees many past payments, including their amounts and times.
A very large payment at an unusual time may receive a high anomaly score.
The payment is sent for an extra check, such as confirming with the customer.
A human or a separate safety process decides what action is appropriate.
6. Anomaly Detection in Python
Scikit-learn provides IsolationForest for finding unusual observations.
Using Isolation Forest
Copy this example into a Python notebook.
# Install the libraries if needed:
# pip install numpy scikit-learn
import numpy as np
from sklearn.ensemble import IsolationForest
from sklearn.preprocessing import StandardScaler
# Example data: two numerical features
X = np.array([
[2.0, 2.1], [2.2, 1.8], [1.8, 2.3],
[2.4, 2.0], [1.9, 1.7], [2.1, 2.4],
[8.5, 9.0], [-5.0, 8.0]
])
# Scale features when their ranges are very different
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
# contamination is the expected share of anomalies
model = IsolationForest(
n_estimators=100,
contamination=0.10,
random_state=42
)
# Train and predict
model.fit(X_scaled)
predictions = model.predict(X_scaled)
# In scikit-learn: -1 = anomaly, 1 = normal
print("Predictions:", predictions)
print("Anomaly rows:", np.where(predictions == -1)[0])
# Lower decision_function values are more unusual
scores = model.decision_function(X_scaled)
print("Scores:", scores)
The example uses a tiny made-up dataset. Real models need enough representative data and careful testing.
n_estimators is the number of trees. contamination sets the expected share of outliers. predict() returns 1 for normal points and -1 for anomalies. decision_function() gives a score where lower values are more unusual.7. Where is Anomaly Detection used?
It helps people notice unusual events in many types of data.
Banking and payments
Flag unusual payment patterns that may need fraud checks.
Cybersecurity
Spot unusual network activity or strange login behaviour.
Factories
Find unusual machine readings that may warn of equipment problems.
Healthcare
Highlight unusual measurements for a trained professional to review.
Strengths and limitations
Know what the method can—and cannot—tell you.
Strengths
- Can work when anomaly labels are rare or missing.
- Can examine many features at once.
- Isolation Forest can work well on large datasets.
- Can help prioritise cases for human review.
Limitations
- Normal behaviour can change over time.
- Too many flags create false alarms.
- Rare but valid events may be flagged.
- Results depend on useful features and settings.
- A score does not explain the cause by itself.
8. Knowledge check
Answer one question at a time. Your score and explanations will appear after the final question.
Mini challenge
Use the playground. Try 3%, 8%, and 15% contamination. Can you explain why the number of flagged points changes?