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.
Dataset
Section titled “Dataset”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.
Requirements
Section titled “Requirements”Your script must:
- Load the data, parse
timestamp, drop the rows with a blank in any of the three numeric columns and print how many rows remain. - Add a context feature
temp_dev: the temperature minus the median temperature of the same sensor at the same hour of day. Usetemp_dev,humidity_pctandvibration_mm_sas model features. - For each sensor separately, fit:
IsolationForest(n_estimators=200, contamination=0.01, random_state=42)on the features, and keep its flags andscore_samples;LocalOutlierFactor(n_neighbors=20, contamination=0.01)on the scaled features, and keep its flags.
- Mark a reading as confirmed when both detectors flag it.
- 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)). - 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.
- Print the 10 confirmed readings with the lowest Isolation Forest score, with their timestamp, sensor, raw values and
status. - 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.
- 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). - Plot S4’s vibration over time with the per-sensor flags in one panel and the pooled flags in a second panel.
- End with
assertchecks: 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.
Step plan
Section titled “Step plan”-
Load and clean. Read the CSV with
parse_dates=["timestamp"]. Drop rows with blanks in the three numeric columns withdropna(subset=...)and reset the index. -
Add the context feature. Take the hour with
.dt.hour. Group by["sensor_id", "hour"]andtransform("median")the temperature. Subtract it from the temperature. -
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.concatjoins the list at the end. -
Summarize. Use
groupby("sensor_id").agg(...)with named aggregations. Booleans sum to counts. -
Rank. Filter the confirmed readings and use
nsmallest(10, "iso_score"). -
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.
-
Look for slow changes. Group by sensor and
timestamp.dt.day, take the medians, then fit one line per sensor withnp.polyfit. A trend near 0 and a ratio near 1 mean “stable”. -
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. -
Check. Add the asserts, run the script and read the report as the maintenance team would.
A skeleton to start from:
import matplotlib.pyplot as pltimport pandas as pdfrom sklearn.ensemble import IsolationForestfrom sklearn.neighbors import LocalOutlierFactorfrom 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 checksRubric
Section titled “Rubric”| 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 |
Stretch goals
Section titled “Stretch goals”- Add
novelty=Trueto 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? - 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)?
- Replace the fixed
contamination=0.01with the default"auto"and compare the number of flags per sensor. - Cluster the confirmed anomalies of all sensors with k-means on
temp_devandvibration_mm_s. Do you get one “temperature spike” and one “vibration spike” group? - Write the top-10 table to
output/anomalies.csvso that the maintenance team can open it in a spreadsheet.
Reference solution
Section titled “Reference solution”Try the project yourself first. Then compare. Your names can differ; your numbers must not.
Reference solution
import matplotlib.pyplot as pltimport numpy as npimport pandas as pdfrom sklearn.ensemble import IsolationForestfrom sklearn.neighbors import LocalOutlierFactorfrom 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.hourusual = readings.groupby(["sensor_id", "hour"])["temperature_c"].transform("median")readings["temp_dev"] = readings["temperature_c"] - usualrows after dropping blanks: 7983# --- 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()}") rows iso lof confirmed rule_spikes rule_foundsensor_idS1 1989 20 20 14 14 14S2 2001 20 20 18 23 20S3 1995 20 20 15 24 19S4 1998 20 20 15 19 15rule spikes found by Isolation Forest: 68 of 80# --- Readings to check first ---top = watch[watch["confirmed"]].nsmallest(10, "iso_score")print(top[["timestamp", "sensor_id"] + RAW + ["status"]].to_string(index=False)) timestamp sensor_id temperature_c humidity_pct vibration_mm_s status2024-05-05 04:20:00 S3 20.83 57.1 8.55 warn2024-05-01 00:40:00 S2 38.03 59.0 2.39 warn2024-05-13 03:40:00 S1 33.33 57.6 2.98 warn2024-05-12 07:20:00 S2 33.62 56.1 4.21 warn2024-05-05 23:10:00 S3 21.60 56.6 8.31 warn2024-05-05 18:40:00 S3 23.19 49.9 8.55 warn2024-05-11 12:40:00 S3 26.29 48.8 9.99 warn2024-05-10 23:40:00 S2 37.38 58.4 2.61 warn2024-05-02 13:20:00 S2 44.89 51.6 2.96 fail2024-05-10 19:00:00 S3 25.76 46.8 9.40 warn# --- 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]) == -1print(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.sensor_idS1 5S2 10S3 6S4 59Name: pooled_flag, dtype: int64# --- 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))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# --- 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()
How it works:
- Context feature.
transform("median")returns, for each reading, the typical temperature of its sensor at its hour.temp_devremoves the daily cycle and the sensor’s own level, so a warm afternoon is no longer suspicious and a warm night is. - Per-sensor loop.
groupby("sensor_id")gives each sensor its own data. Each detector learns that sensor’s normal state. Withcontamination=0.01, each Isolation Forest flags 1% of its own rows (20 of about 2,000). - 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. - 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.01allows 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, statuswarnorfail; 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. - 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.
- 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.
- Asserts. The first one checks the contamination quota per sensor; the second one checks that the detectors find most known spikes.