Skip to content

39. Unsupervised learning — Mini-project

A plant runs four sensors (S1 to S4) on its production line. Each one reports temperature, humidity and vibration every 10 minutes. Nobody has labeled the faulty readings. The maintenance team asks for a short weekly report:

  • Which readings should a technician check first?
  • How many unusual readings does each sensor have?
  • Do two independent detectors agree?
  • Is any sensor drifting into a new, abnormal state?

Write a script, anomaly_watch.py, that answers these questions with the unsupervised tools of module 39: context features, one Isolation Forest and one Local Outlier Factor per sensor, a comparison with a simple spike rule, and a chart.

data/sensors.csv has 8,064 rows: 4 sensors × 2,016 readings from 2024-05-01 00:00 to 2024-05-14 23:50 (see the data dictionary).

Column Meaning
timestamp ISO datetime, every 10 minutes
sensor_id S1 to S4
temperature_c °C, 22 blank cells
humidity_pct %, 29 blank cells
vibration_mm_s mm/s, 30 blank cells
status ok, warn or fail, from a fixed threshold rule

What the data dictionary tells you, and the models do not know:

  • Temperature follows a daily cycle: lowest around 03:00, highest around 15:00.
  • Each sensor has its own normal level. S4 runs warmest (mean 26 °C).
  • S3 drifts upward by about 0.35 °C per day (calibration drift).
  • S4’s vibration rises from May 12 on: the bearing wears out.
  • About 1% of the readings are spikes: 40 temperature spikes of +9 to +18 °C and 41 vibration spikes of 3 to 5 times the normal value.

Your script must:

  1. Load the data, parse timestamp, drop the rows with a blank in any of the three numeric columns and print how many rows remain.
  2. Add a context feature temp_dev: the temperature minus the median temperature of the same sensor at the same hour of day. Use temp_dev, humidity_pct and vibration_mm_s as model features.
  3. For each sensor separately, fit:
    • IsolationForest(n_estimators=200, contamination=0.01, random_state=42) on the features, and keep its flags and score_samples;
    • LocalOutlierFactor(n_neighbors=20, contamination=0.01) on the scaled features, and keep its flags.
  4. Mark a reading as confirmed when both detectors flag it.
  5. Compute a reference spike rule per sensor: a temperature more than 6 °C above, or a vibration more than 2.2 times, the rolling median of the 13 readings around it (rolling(13, center=True, min_periods=1)).
  6. Print a summary table with one row per sensor: rows, Isolation Forest flags, LOF flags, confirmed flags, rule spikes and the rule spikes that Isolation Forest found.
  7. Print the 10 confirmed readings with the lowest Isolation Forest score, with their timestamp, sensor, raw values and status.
  8. Fit one pooled Isolation Forest on the raw three columns of all sensors together and print its flags per sensor. Explain in a comment why the per-sensor models are better.
  9. Detect slow changes, which single-reading detectors cannot see. Per sensor, compute the daily median temperature and vibration. Print one row per sensor with the temperature trend (°C per day: the slope of a straight line through the daily medians, np.polyfit(day, median, 1)[0]) and the vibration ratio (mean daily median of May 12–14 divided by that of May 1–7).
  10. Plot S4’s vibration over time with the per-sensor flags in one panel and the pooled flags in a second panel.
  11. End with assert checks: every sensor has 1% of its rows flagged by Isolation Forest, and the per-sensor Isolation Forests together find at least 80% of the rule spikes.
  1. Load and clean. Read the CSV with parse_dates=["timestamp"]. Drop rows with blanks in the three numeric columns with dropna(subset=...) and reset the index.

  2. Add the context feature. Take the hour with .dt.hour. Group by ["sensor_id", "hour"] and transform("median") the temperature. Subtract it from the temperature.

  3. Loop over the sensors. for sensor_id, part in readings.groupby("sensor_id"): gives one DataFrame per sensor. Make a copy, fit both detectors, compute the rule and append the copy to a list. pd.concat joins the list at the end.

  4. Summarize. Use groupby("sensor_id").agg(...) with named aggregations. Booleans sum to counts.

  5. Rank. Filter the confirmed readings and use nsmallest(10, "iso_score").

  6. Compare with a pooled model. Fit one Isolation Forest on all rows and count its flags per sensor. Look at which sensor collects the flags, and why.

  7. Look for slow changes. Group by sensor and timestamp.dt.day, take the medians, then fit one line per sensor with np.polyfit. A trend near 0 and a ratio near 1 mean “stable”.

  8. Plot. Two stacked panels with plt.subplots(2, 1, sharex=True). Draw the S4 vibration as a line and the flagged points as red dots.

  9. Check. Add the asserts, run the script and read the report as the maintenance team would.

A skeleton to start from:

anomaly_watch.py (starter)
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.ensemble import IsolationForest
from sklearn.neighbors import LocalOutlierFactor
from sklearn.preprocessing import StandardScaler
RAW = ["temperature_c", "humidity_pct", "vibration_mm_s"]
FEATURES = ["temp_dev", "humidity_pct", "vibration_mm_s"]
# --- Load and clean ---
# TODO: read, parse dates, drop blanks, print the row count
# --- Context feature ---
# TODO: temp_dev = temperature - median temperature of the same sensor and hour
# --- Per-sensor detectors and rule ---
# TODO: loop over sensors; IsolationForest, LOF (scaled), rule; concat
# --- Report ---
# TODO: summary table, top 10 confirmed readings
# --- Pooled model, slow changes and chart ---
# TODO: pooled IsolationForest on RAW; flags per sensor
# TODO: temperature trend and vibration ratio per sensor
# TODO: two-panel S4 chart
# --- Self-checks ---
# TODO: assert checks
Criterion Points Full points when
Clean data 1 Blanks dropped, timestamps parsed, row count printed
Context feature 2 temp_dev uses the same sensor and the same hour
Per-sensor models 3 Both detectors fitted per sensor, with the given settings; LOF on scaled features
Rule comparison 2 Rule computed per sensor; found spikes counted per sensor
Report 2 Summary table and top-10 table, readable without the code
Pooled comparison 2 Pooled flags per sensor printed, with a correct explanation
Chart 2 Two panels, flags clearly visible, titled and labeled
Self-checks 1 The two required asserts pass
Total 15 12 or more: you are ready for module 40
  1. Add novelty=True to the LOF, train it on May 1–7 and score May 8–14 only. Does the S4 wear show up as a run of novelties?
  2. Count the Isolation Forest flags of S4 per day. From which day do they increase, and does it match the start of the wear (May 12)?
  3. Replace the fixed contamination=0.01 with the default "auto" and compare the number of flags per sensor.
  4. Cluster the confirmed anomalies of all sensors with k-means on temp_dev and vibration_mm_s. Do you get one “temperature spike” and one “vibration spike” group?
  5. Write the top-10 table to output/anomalies.csv so that the maintenance team can open it in a spreadsheet.

Try the project yourself first. Then compare. Your names can differ; your numbers must not.

Reference solution
anomaly_watch.py (part 1)
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn.ensemble import IsolationForest
from sklearn.neighbors import LocalOutlierFactor
from sklearn.preprocessing import StandardScaler
pd.set_option("display.width", 100)
pd.set_option("display.max_columns", 12)
pd.set_option("display.precision", 3)
RAW = ["temperature_c", "humidity_pct", "vibration_mm_s"]
FEATURES = ["temp_dev", "humidity_pct", "vibration_mm_s"]
# --- Load and clean ---
readings = pd.read_csv("data/sensors.csv", parse_dates=["timestamp"])
readings = readings.dropna(subset=RAW).reset_index(drop=True)
print("rows after dropping blanks:", len(readings))
# --- Context feature: warmer or colder than usual for this sensor and hour ---
readings["hour"] = readings["timestamp"].dt.hour
usual = readings.groupby(["sensor_id", "hour"])["temperature_c"].transform("median")
readings["temp_dev"] = readings["temperature_c"] - usual
Output
rows after dropping blanks: 7983
anomaly_watch.py (part 2)
# --- Per-sensor detectors and rule ---
parts = []
for _sensor_id, part in readings.groupby("sensor_id"):
part = part.copy()
iso = IsolationForest(n_estimators=200, contamination=0.01, random_state=42)
part["iso_flag"] = iso.fit_predict(part[FEATURES]) == -1
part["iso_score"] = iso.score_samples(part[FEATURES])
scaled = StandardScaler().fit_transform(part[FEATURES])
lof = LocalOutlierFactor(n_neighbors=20, contamination=0.01)
part["lof_flag"] = lof.fit_predict(scaled) == -1
local = part[RAW].rolling(13, center=True, min_periods=1).median()
part["rule_spike"] = (part["temperature_c"] - local["temperature_c"] > 6) | (
part["vibration_mm_s"] / local["vibration_mm_s"] > 2.2
)
parts.append(part)
watch = pd.concat(parts).sort_values(["timestamp", "sensor_id"])
watch["confirmed"] = watch["iso_flag"] & watch["lof_flag"]
watch["rule_found"] = watch["rule_spike"] & watch["iso_flag"]
summary = watch.groupby("sensor_id").agg(
rows=("iso_flag", "size"),
iso=("iso_flag", "sum"),
lof=("lof_flag", "sum"),
confirmed=("confirmed", "sum"),
rule_spikes=("rule_spike", "sum"),
rule_found=("rule_found", "sum"),
)
print(summary)
print(f"rule spikes found by Isolation Forest: {summary['rule_found'].sum()}"
f" of {summary['rule_spikes'].sum()}")
Output
rows iso lof confirmed rule_spikes rule_found
sensor_id
S1 1989 20 20 14 14 14
S2 2001 20 20 18 23 20
S3 1995 20 20 15 24 19
S4 1998 20 20 15 19 15
rule spikes found by Isolation Forest: 68 of 80
anomaly_watch.py (part 3)
# --- Readings to check first ---
top = watch[watch["confirmed"]].nsmallest(10, "iso_score")
print(top[["timestamp", "sensor_id"] + RAW + ["status"]].to_string(index=False))
Output
timestamp sensor_id temperature_c humidity_pct vibration_mm_s status
2024-05-05 04:20:00 S3 20.83 57.1 8.55 warn
2024-05-01 00:40:00 S2 38.03 59.0 2.39 warn
2024-05-13 03:40:00 S1 33.33 57.6 2.98 warn
2024-05-12 07:20:00 S2 33.62 56.1 4.21 warn
2024-05-05 23:10:00 S3 21.60 56.6 8.31 warn
2024-05-05 18:40:00 S3 23.19 49.9 8.55 warn
2024-05-11 12:40:00 S3 26.29 48.8 9.99 warn
2024-05-10 23:40:00 S2 37.38 58.4 2.61 warn
2024-05-02 13:20:00 S2 44.89 51.6 2.96 fail
2024-05-10 19:00:00 S3 25.76 46.8 9.40 warn
anomaly_watch.py (part 4)
# --- Pooled model: one shared "normal" for all four sensors ---
pooled = IsolationForest(n_estimators=200, contamination=0.01, random_state=42)
watch["pooled_flag"] = pooled.fit_predict(watch[RAW]) == -1
print(watch.groupby("sensor_id")["pooled_flag"].sum())
# The pooled model flags mostly S4: its high temperature and its late wear make
# whole stretches of S4 unusual compared with the other sensors. Per-sensor
# models judge each reading against its own sensor's normal behavior.
Output
sensor_id
S1 5
S2 10
S3 6
S4 59
Name: pooled_flag, dtype: int64
anomaly_watch.py (part 5)
# --- Slow changes: drift and wear show in daily medians, not in single readings ---
daily = watch.groupby(["sensor_id", watch["timestamp"].dt.day]).agg(
temp=("temperature_c", "median"), vib=("vibration_mm_s", "median")
)
rows = []
for sensor_id, days in daily.groupby(level="sensor_id"):
day = days.index.get_level_values("timestamp").to_numpy()
trend = np.polyfit(day, days["temp"].to_numpy(), 1)[0]
ratio = days.loc[day >= 12, "vib"].mean() / days.loc[day <= 7, "vib"].mean()
rows.append((sensor_id, trend, ratio))
changes = pd.DataFrame(rows, columns=["sensor_id", "temp_trend_c_per_day", "vib_ratio"])
print(changes.round(3).to_string(index=False))
Output
sensor_id temp_trend_c_per_day vib_ratio
S1 -0.002 1.009
S2 0.004 1.006
S3 0.341 1.004
S4 -0.002 2.189
anomaly_watch.py (part 6)
# --- Chart: S4 vibration, per-sensor flags versus pooled flags ---
s4 = watch[watch["sensor_id"] == "S4"]
fig, axes = plt.subplots(2, 1, figsize=(9, 5), sharex=True, sharey=True)
for ax, flag, title in (
(axes[0], "iso_flag", "Per-sensor Isolation Forest"),
(axes[1], "pooled_flag", "Pooled Isolation Forest (all sensors)"),
):
ax.plot(s4["timestamp"], s4["vibration_mm_s"], linewidth=0.6)
hits = s4[s4[flag]]
ax.scatter(hits["timestamp"], hits["vibration_mm_s"], color="tab:red", s=16,
zorder=3, label=f"{len(hits)} flags")
ax.set(title=title, ylabel="vibration (mm/s)")
ax.legend(loc="upper left", fontsize=8)
fig.autofmt_xdate()
fig.tight_layout()
plt.show()
# --- Self-checks ---
iso_share = watch.groupby("sensor_id")["iso_flag"].mean()
assert iso_share.round(2).eq(0.01).all()
assert summary["rule_found"].sum() >= 0.8 * summary["rule_spikes"].sum()
Two stacked time series of S4 vibration over two weeks. The line stays near 3 mm/s until May 11, then climbs to about 10 mm/s by May 14, with tall spikes throughout. Top panel: 20 red flags on most tall spikes, on a few readings with normal vibration and on the last day; the spikes on May 7 and May 10 have no flag. Bottom panel: 59 red flags on every spike above 10 mm/s and in a dense band over the wear period after May 13.
Per-sensor flags pick single readings. The pooled model flags S4's whole wear period.

How it works:

  1. Context feature. transform("median") returns, for each reading, the typical temperature of its sensor at its hour. temp_dev removes the daily cycle and the sensor’s own level, so a warm afternoon is no longer suspicious and a warm night is.
  2. Per-sensor loop. groupby("sensor_id") gives each sensor its own data. Each detector learns that sensor’s normal state. With contamination=0.01, each Isolation Forest flags 1% of its own rows (20 of about 2,000).
  3. Two detectors. Isolation Forest works on raw units; LOF needs scaled features because it uses distances. Readings that both flag (confirmed) are the safest to check first.
  4. Reference rule. The rule uses the local rolling median, which the models never see. Isolation Forest finds 68 of the 80 rule spikes. It misses 3 on S2, 5 on S3 and 4 on S4. Part of this is the quota: contamination=0.01 allows 20 flags per sensor, but S2 has 23 rule spikes and S3 has 24, so at least 3 and 4 of them must be missed whatever the model does (all 20 S2 flags are rule spikes). A higher contamination would find more spikes and also flag more normal readings. The 12 flags outside the rule are of two kinds: 5 on S4 during its wear (vibration of 5 to 13 mm/s, status warn or fail; the vibration rises slowly, so the rolling median rises with it and the rule stays silent), and 7 readings at the edge of normal on S1 and S3, such as very humid nights.
  5. Pooled model. Trained on all sensors, Isolation Forest puts 59 of its 80 flags on S4: compared with the other three sensors, S4’s late wear period looks abnormal as a whole. That is useful as a “this machine is different” signal, but useless for finding single faulty readings. The chart shows both views. It also shows a weakness of the per-sensor model: it misses the S4 spikes on May 7 (13.7 mm/s) and May 10 (10.9 mm/s), and a 36.8 °C temperature spike on May 3. The likely cause is that its training data contains the wear period, which teaches it that 10 mm/s is normal for S4. A check supports this: the same Isolation Forest trained on May 1–7 only flags all three, but it also flags 119 S4 readings, nearly the whole wear period. Stretch goal 1 explores this trade-off. The red dots at normal vibration levels in the top panel are temperature or humidity anomalies.
  6. Slow changes. S3’s daily median temperature rises by about 0.34 °C per day, the calibration drift from the data dictionary; the other sensors stay near 0. S4’s vibration in its last three days is about 2.2 times its first-week level, the bearing wear. No single reading of S3 is abnormal, so the detectors cannot see the drift; a trend over days can. This answers the brief’s last question: S3 drifts and S4 wears.
  7. Asserts. The first one checks the contamination quota per sensor; the second one checks that the detectors find most known spikes.