---
url: /stable/case-studies/machine-condition-intervals.md
description: >-
  Quantile relational gradient boosting on sensor readings and repair logs:
  forecast next month's vibration with an interval, then calibrate its coverage.
---

# Case study: machine condition with prediction intervals

**A maintenance team plans a month ahead. For every machine, it wants the
vibration level expected over the next 30 days, and a range that will hold
the real value for most machines. Sensor readings and repair logs are
separate tables, so the forecast reads each machine's history as of the
planning date.** This case study fits relational gradient boosting with the
quantile loss, checks how often its intervals hold the truth on later months,
and widens them by the amount a calibration period asks for.

## The tables

Each machine belongs to a machine model, a row of `models`, with a rated
temperature. Every other day, a
sensor records its temperature and vibration. Wear builds up with age, raises
both readings, and makes repairs likely; a repair removes most of the wear.

```python
import numpy as np
import pandas as pd

rng = np.random.default_rng(0)
start = pd.Timestamp("2024-01-01")
models = pd.DataFrame(
    {
        "model_id": [0, 1, 2, 3],
        "maker": ["A", "A", "B", "C"],
        "rated_temp": [70.0, 80.0, 75.0, 90.0],
    }
)
n = 300
machines = pd.DataFrame(
    {
        "machine_id": np.arange(n),
        "model_id": rng.choice(4, n),
        "site": rng.choice(["north", "south", "east"], n),
        "age_years": rng.integers(1, 15, n),
    }
)
readings, repairs = [], []
for machine, model, age in zip(
    machines["machine_id"], machines["model_id"], machines["age_years"]
):
    rated = models["rated_temp"][model]
    wear = 0.0
    for day in range(0, 365, 2):
        wear += rng.gamma(1.0, 0.004 + 0.0015 * age)
        at = start + pd.Timedelta(days=day, hours=int(rng.integers(0, 24)))
        temperature = rated - 10 + 25 * wear + rng.normal(0, 3)
        vibration = 1 + 2 * wear + rng.normal(0, 0.3)
        readings.append((machine, at, temperature, vibration))
        if rng.random() < 0.002 + 0.2 * max(0.0, wear - 1.0):
            kind = rng.choice(["electrical", "mechanical", "software"])
            hours = rng.gamma(2.0, 4.0 + 6.0 * wear)
            repairs.append((machine, start + pd.Timedelta(days=day), kind, hours))
            wear *= 0.3
readings = pd.DataFrame(
    readings, columns=["machine_id", "read_at", "temperature", "vibration"]
)
readings.insert(0, "reading_id", np.arange(len(readings)))
repairs = pd.DataFrame(
    repairs, columns=["machine_id", "started_at", "kind", "downtime_hours"]
)
repairs.insert(0, "repair_id", np.arange(len(repairs)))
print(readings.shape, repairs.shape)
```

```text
(54900, 5) (690, 5)
```

```python
from sklink import Database

db = Database(
    tables={
        "models": models,
        "machines": machines,
        "readings": readings,
        "repairs": repairs,
    },
    primary_keys={
        "models": "model_id",
        "machines": "machine_id",
        "readings": "reading_id",
        "repairs": "repair_id",
    },
    relationships=[
        ("machines.model_id", "models.model_id"),
        ("readings.machine_id", "machines.machine_id"),
        ("repairs.machine_id", "machines.machine_id"),
    ],
    time_columns={"readings": "read_at", "repairs": "started_at"},
)
```

## The target: next month's vibration

One row of `X` is a machine on the first day of a month. The target is the
mean vibration of its readings in the 30 days after that date. The last
reading before the date is kept aside as the naive forecast to beat.

```python
cutoffs = pd.date_range("2024-03-01", "2024-11-01", freq="MS")
X = machines[["machine_id"]].merge(pd.DataFrame({"cutoff": cutoffs}), how="cross")
rows = pd.MultiIndex.from_frame(X)
pairs = X.merge(readings[["machine_id", "read_at", "vibration"]], on="machine_id")
following = pairs[
    (pairs["read_at"] >= pairs["cutoff"])
    & (pairs["read_at"] < pairs["cutoff"] + pd.Timedelta(days=30))
]
y = (
    following.groupby(["machine_id", "cutoff"])["vibration"]
    .mean()
    .reindex(rows)
    .to_numpy()
)
earlier = pairs[pairs["read_at"] < pairs["cutoff"]].sort_values("read_at")
last = (
    earlier.groupby(["machine_id", "cutoff"])["vibration"]
    .last()
    .reindex(rows)
    .to_numpy()
)
print(X.shape, np.quantile(y, [0.1, 0.5, 0.9]).round(2))
```

```text
(2700, 2) [1.87 2.57 3.32]
```

## Three periods

The models learn from March to July. August and September are a calibration
period, used only to measure how wide the intervals must be. October and
November are the test. Each period's 30-day targets end before the next
period starts, so no label leaks across.

```python
train = (X["cutoff"] < "2024-08-01").to_numpy()
calibration = ((X["cutoff"] >= "2024-08-01") & (X["cutoff"] < "2024-10-01")).to_numpy()
test = (X["cutoff"] >= "2024-10-01").to_numpy()
print(train.sum(), calibration.sum(), test.sum())
```

```text
1500 600 600
```

## One model per quantile

`loss="quantile"` with `alpha=0.1`, `0.5` and `0.9` gives a lower bound, a
median forecast and an upper bound. With `time="cutoff"`, each model reads
only the readings and repairs from before each machine's date.

```python
from sklink.ensemble import RelationalGradientBoostingRegressor

common = {"entity": "machines", "key": "machine_id", "time": "cutoff"}
quantiles = {}
for alpha in (0.1, 0.5, 0.9):
    model = RelationalGradientBoostingRegressor(
        db, loss="quantile", alpha=alpha, random_state=0, **common
    )
    quantiles[alpha] = model.fit(X[train], y[train])
```

The median forecast is compared with the naive one, the last reading:

```python
from sklearn.metrics import mean_absolute_error

median = quantiles[0.5].predict(X[test])
print(f"MAE median forecast {mean_absolute_error(y[test], median):.2f}")
print(f"MAE last reading    {mean_absolute_error(y[test], last[test]):.2f}")
```

```text
MAE median forecast 0.30
MAE last reading    0.45
```

## How often do the intervals hold?

An interval from the 10th to the 90th percentile should hold the true value
for about 80% of the machines. Quantile models fitted on a few months often
fall short, so coverage is first measured on the calibration months, which
the models have not seen.

```python
def interval(rows):
    return quantiles[0.1].predict(X[rows]), quantiles[0.9].predict(X[rows])


low_cal, high_cal = interval(calibration)
inside = (y[calibration] >= low_cal) & (y[calibration] <= high_cal)
print(f"coverage {inside.mean():.2f}, mean width {np.mean(high_cal - low_cal):.2f}")
```

```text
coverage 0.72, mean width 0.83
```

## Calibrate the width on a later period

Conformalized quantile regression corrects the width without refitting. On
the calibration period, it measures by how much each true value falls
outside its interval, takes the finite-sample 80% quantile of that score,
and widens every interval by it. Assuming the calibration months resemble
the test months, this brings coverage back near 80%. The test months are
looked at once, before and after the correction.

```python
score = np.maximum(low_cal - y[calibration], y[calibration] - high_cal)
n_cal = len(score)
margin = np.quantile(
    score, min(1.0, np.ceil(0.8 * (n_cal + 1)) / n_cal), method="higher"
)
low, high = interval(test)
for name, widen in [("raw", 0.0), ("calibrated", margin)]:
    inside = (y[test] >= low - widen) & (y[test] <= high + widen)
    width = np.mean(high - low + 2 * widen)
    print(f"{name:<10} coverage {inside.mean():.2f}, mean width {width:.2f}")
```

```text
raw        coverage 0.71, mean width 0.88
calibrated coverage 0.80, mean width 1.01
```

## What drives the forecast

The importances of the median model show which histories it reads, here
grouped by expression.

```python
from sklink.inspection import aggregate_importances

for expression, share in list(aggregate_importances(quantiles[0.5]).items())[:4]:
    print(f"{share:.2f} {expression}")
```

```text
0.17 last(readings.vibration)
0.14 time_since_last(repairs.started_at)
0.10 mean(readings.vibration)
0.08 std(readings.temperature)
```

## What to take from it

* **Any loss of the boosting works on related tables**, including the
  quantile loss for intervals and the absolute error for robust forecasts;
  see [relational gradient boosting](../tutorials/relational-gradient-boosting).
* **Check coverage on later dates.** An interval is only as good as the
  share of true values it holds on data the model has not seen.
* **Calibrate on its own period.** Two months between training and test are
  enough to correct the width, and the correction is a few lines of NumPy.
