---
url: /dev/tutorials/anomaly-detection.md
description: >-
  Anomaly detection on multi-table data: a relational isolation forest flags
  entities, such as customers, whose related rows look unlike anyone else's.
---

# Find unusual entities

**An unusual entity often looks ordinary in its own table and unusual only
in its related rows: a customer with a few very large orders, an account
with far too many transactions, or a machine with a mix of readings nobody
else has. `RelationalIsolationForest` describes each entity by
aggregates of its related rows, such as `max(orders.amount)`, and isolates
the ones that few random questions set apart.** It needs no label.

## A shop with a few big spenders

Six of the 300 customers below place orders twenty times larger than the
others. Nothing in the customers table says so.

```python
import numpy as np
from sklink import Database

rng = np.random.default_rng(0)
n_orders = rng.integers(1, 6, 300)
owner = np.repeat(np.arange(300), n_orders)
unusual = np.zeros(300, dtype=bool)
unusual[rng.choice(300, 6, replace=False)] = True
amount = rng.normal(50, 10, owner.size) * np.where(unusual[owner], 20, 1)

db = Database(
    {
        "customers": {"customer_id": np.arange(300), "age": rng.integers(18, 80, 300)},
        "orders": {
            "order_id": np.arange(owner.size),
            "customer_id": owner,
            "amount": amount,
        },
    },
    primary_keys={"customers": "customer_id", "orders": "order_id"},
    relationships=[("orders.customer_id", "customers.customer_id")],
)
X = np.arange(300)[:, None]  # one row per customer: its key
```

## Fit and rank

`score_samples` is lower for more unusual customers. `predict` returns `-1`
for outliers and `1` for the others, with a threshold set by
`contamination`, the share of outliers you expect.

```python
from sklink.ensemble import RelationalIsolationForest

model = RelationalIsolationForest(
    db, entity="customers", key=0, contamination=0.02, random_state=0
).fit(X)
ranked = np.argsort(model.score_samples(X))
print("most unusual:", ranked[:6].tolist())
print("planted:     ", sorted(np.flatnonzero(unusual).tolist()))
print("flagged:", int((model.predict(X) == -1).sum()))
```

```text
most unusual: [33, 2, 30, 32, 108, 23]
planted:      [2, 23, 30, 32, 33, 108]
flagged: 6
```

With `contamination="auto"` (the default), the threshold is the one of the
original isolation forest paper, which usually flags more customers than
were planted; rank by
`score_samples` when you only need the most unusual ones.

## What it looks at

The forest splits the same features as
[`RelationalKMeans`](./clustering): the outputs of
[`RelationalFeaturizer`](./relational-features) with `conditional=False`, with one indicator per
category and missing values at the mean. `embedding_feature_names_` lists
them:

```python
print(len(model.embedding_feature_names_), "features, such as")
print([n for n in model.embedding_feature_names_ if "amount" in n][:4])
```

```text
7 features, such as
['max(orders.amount)', 'mean(orders.amount)', 'min(orders.amount)', 'std(orders.amount)']
```

Every feature can isolate a customer, so a table with many columns gives
the trees more chances to split on noise. Narrow the features with
`include` or `exclude`, for example `include=["orders.*"]`. With a `time`
column, each customer is described only by the rows before their cutoff, as
in [Time and cutoffs](./time-and-cutoffs), so you can score each day's
customers on their history.

## Parameters at a glance

| Parameter | Default | What it does |
| --- | --- | --- |
| `n_estimators` | `100` | Number of isolation trees |
| `max_samples` | `"auto"` | Samples drawn for each tree (`min(256, n_samples)`) |
| `contamination` | `"auto"` | Expected share of outliers, for `predict` |
| `max_features` | `1.0` | Features drawn for each tree |
| `max_relationship_depth` | `2` | Relationships followed from the entity table |
| `include`, `exclude` | `None` | Patterns that select the features |

Next, group the other customers with [clustering](./clustering), or see which
aggregates describe them in [relational features](./relational-features).
