edSlash Labs  /  Machine Learning Lab  /  Unsupervised Learning  /  Anomaly Detection
Algorithm 05 · Unsupervised learning · Outlier detection

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.

Beginner friendly

The big idea

Find data that looks different from most of the data.

Unusual pattern = possible anomalyAn anomaly is a point or event that differs strongly from expected behaviour.

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.

Normal data

The common pattern the model learns or uses as a reference.

Anomaly

A point or event that is unusual compared with the rest.

Anomaly score

A number that shows how unusual a point appears.

Threshold

A cutoff used to decide which scores should be flagged.

Remember: an anomaly is not automatically fraud or a mistake. It is a signal that something is unusual and may need human checking.

1. How does Anomaly Detection work?

The model learns what is common, then looks for observations that stand apart.

A simple workflow

Collect data

Gather examples such as payments, sensor readings, website activity, or network traffic.

Learn the usual pattern

Use a method to understand common behaviour or how easily points can be separated.

Give each point a score

More unusual points receive a stronger anomaly score.

Apply a threshold

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.

Unusual does not mean wrong. The learner may have had a valid reason. The system should flag the event for review, not decide the reason by itself.

2. Live Anomaly Detection playground

Change the contamination level and watch the model flag unusual points.

Interactive experiment

Data map

Blue dots are treated as normal. Orange dots are flagged as anomalies.

NormalFlagged anomalyUnscored point

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.

Data points60
Flagged—
Contamination8%
Model trees60
Data is ready. Select “Detect anomalies” to score the points.
Try 3%, 8%, and 15% contamination. Notice how the number of flagged points changes.

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 playground

Local 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.

Which one should you use? It depends on the data, the shape of normal behaviour, the number of features, and how many false alarms you can accept.

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.

Short path → more unusualLong path → more like the crowded, common data

Anomaly score

The model combines path lengths from many trees. A commonly used score is:

s(x, n) = 2−E(h(x))/c(n)Higher scores are more likely to be anomalies.

What do the symbols mean?

SymbolMeaning
h(x)Path length needed to isolate point x in a tree.
E(h(x))Average path length across the trees.
nNumber 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.
The formula is a score, not a probability that a person has committed fraud. The cutoff depends on the problem and the cost of false alarms.

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.

PaymentAmountTimePattern
P-01₹42010:15Usual
P-02₹65013:20Usual
P-03₹51018:05Usual
P-04₹78019:10Usual
P-05₹48,00003:12Unusual

How the model helps

Learn normal behaviour

The model sees many past payments, including their amounts and times.

Score a new payment

A very large payment at an unusual time may receive a high anomaly score.

Flag for review

The payment is sent for an extra check, such as confirming with the customer.

Make a careful decision

A human or a separate safety process decides what action is appropriate.

This example is only an illustration. A large payment is not automatically fraud; a real system uses more context and careful checks.

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.

Useful Python terms: 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.

0 of 10 answered

Mini challenge

Use the playground. Try 3%, 8%, and 15% contamination. Can you explain why the number of flagged points changes?

Can you explain why a flagged point should be checked instead of being treated as proof of fraud?