16 · Point-level versus event-level evaluation for detection

Run it in Colab View the .ipynb

You are reading this notebook. To run it, open it in Colab with the button above - no install, no GPU needed for most of them - or clone the repository and open it in Jupyter.

  1. 1. Purpose
  2. 2. Conceptual explanation
    1. 2.1 Two units of analysis
    2. 2.2 Why point metrics mislead on contiguous events
    3. 2.3 Events, half-open intervals and post-processing
    4. 2.4 Matching rules
    5. 2.5 The event-level metrics
    6. 2.6 Point-adjust, and why it is not used here
    7. 2.7 Connection to other domains
    8. 2.8 Industry example
    9. 2.9 Limits and misconceptions
  3. 3. Worked examples
    1. 3.1 Hand-built detectors: the two metrics disagree
    2. 3.2 Point-adjust on real labels
  4. 4. Guided lab: flowguard.evaluation and the point-versus-event table
  5. 5. Independent challenge
    1. The challenge brief
      1. Part A - choose an operating point under an alert budget (graded by checks + rubric)
      2. Part B - a matching rule for intermittent network outages (rubric only)
  6. 6. Progressive hints (open in order, only when stuck)
  7. 7. Assessment
    1. Assessment questions
      1. Reasoning questions
      2. Design-choice explanation (write 6-10 sentences)
      3. Rubric (for questions and the design explanation)
      4. Interview rep (Python, 12 minutes, no notes)
  8. 8. Reflection and review
  9. Verification record
  10. Record your progress

Week 3 · day 4 · 2 h essential path + up to 1 h optional · lab files: labs/w3d4_point_vs_event_evaluation/

Objective. Implement and interpret point-wise metrics, event matching, detection delay and false alarms per hour; explain when each misleads.

# --- Setup: works on your laptop AND in Google Colab ----------------------------
# In Colab this clones the course repository and installs the requirements (about a
# minute, first run only). On your own machine it just finds the repository. Every
# command in this notebook runs from the repository root. Safe to re-run.
import os
import subprocess
import sys
from pathlib import Path

if "google.colab" in sys.modules:
    if not Path("/content/mlengineering").exists():
        subprocess.run(["git", "clone", "--depth", "1",
                        "https://github.com/berdakh/mlengineering.git",
                        "/content/mlengineering"], check=True)
    os.chdir("/content/mlengineering")
    subprocess.run([sys.executable, "-m", "pip", "install", "-q",
                    "-r", "requirements.txt"], check=True)

REPO_ROOT = next(p for p in [Path.cwd(), *Path.cwd().parents]
                 if (p / "src" / "mlcourse").is_dir())
os.chdir(REPO_ROOT)
sys.path.insert(0, str(REPO_ROOT / "src"))
print("repo root:", REPO_ROOT)

Status: see STATUS.md. Handbook: H6.5, H7.3. Solutions live in solutions/labs/w3d4_point_vs_event_evaluation/; open them after your own attempt.

1. Purpose

Objective. Implement and interpret point-wise metrics, event matching, detection delay and false alarms per hour of normal operation, and explain when each one misleads.

Why an applied ML engineer needs it. The person who receives a detector’s output does not experience rows. They experience alarms: a pager going off, a ticket opened, a pump stopped for inspection. Whether the detector is worth deploying depends on three numbers they can feel: how many faults it catches, how long after onset, and how often it cries wolf. Point-level precision and recall answer none of these directly, and on contiguous events they can rank detectors in the wrong order. In this session the same flags will score point F1 0.826 and produce 469 separate alarms for seven faults.

Deliverable. flowguard.evaluation (tested), and lab/EVENT_EVAL.md: the point-versus-event table for the w2d6 baselines on real SKAB data, with the project’s reporting decision.

Prerequisites. w2d6 (baselines, point metrics, frozen dev thresholds) and the split discipline of w3d2. The lab ships snapshots of flowguard.data, splits (manifest v2, overlap groups kept together), baselines, metrics and benchmark. SKAB downloaded: python project/get_skab.py. If you have evaluated any event detector before (spikes, seizures, intrusions), section 2.7 says what transfers.

Time budget (2 h essential).

Activity Minutes
Read sections 2-3, run both worked examples 30
Lab tasks 1-2: write your own cases, then extract_events and point_adjust 20
Lab task 3: matching, recall, precision 25
Lab task 4: delay and false alarms per hour 20
Lab task 5: run the tables, write EVENT_EVAL.md 15
Assessment questions 1-3 10
Optional extension (up to 1 h): challenge part A (alert budget) and part B (another domain); interview rep 60

2. Conceptual explanation

2.1 Two units of analysis

A detector emits a score per row. A threshold turns scores into flags. Up to here everything is per row, and point metrics (precision, recall, F1, PR-AUC) count rows. But faults are not rows: in SKAB each labelled experiment contains exactly one contiguous anomalous segment of 188 to 586 rows. The operator does not act on rows either; they act on alarms, which are runs of flags.

Diagram 1 of notebook 16

Everything after the flags is part of the detector, not of the metric: merge_gap and min_duration are hyperparameters, chosen on development data like the threshold (w3d3).

2.2 Why point metrics mislead on contiguous events

Three mechanisms, each visible in the worked example:

  1. Long events dominate. Point recall weights an event by its length. If one event holds 82 % of the anomalous rows, a detector that finds only that event scores point recall 0.82 and event recall 1/10.
  2. Timing is invisible. Flagging the last 80 % of every event and flagging the first 5 rows of every event both find all events. Point F1 rates the late detector 0.89 and the early one 0.07. For a fault alarm the early one is the useful one.
  3. Fragmentation is invisible. Flagging every other row of every event gives a moderate point recall and a stream of hundreds of alarms. Point precision does not see the operator’s load.

The opposite failure also exists: a handful of stray flags in normal operation barely moves point precision when anomalous rows are plentiful (35 % of SKAB rows), but each stray run is a separate false alarm, and false alarms are what make operators switch detectors off.

2.3 Events, half-open intervals and post-processing

An event is a half-open pair (start, end): rows start .. end-1. Half-open intervals make lengths end - start, make adjacent events (a, b), (b, c) not overlap, and make slicing x[start:end] exact. The lab’s conventions (module docstring of evaluation.py) are:

  • runs of flags separated by at most merge_gap zeros are merged (hysteresis in time);
  • merged runs shorter than min_duration rows are dropped (confirmation);
  • merge first, then filter: filtering first would delete the short fragments that merging was meant to join (one of the mutants does exactly this).

A minimum duration has a price that must be reported: an alarm that needs d rows of confirmation is raised d - 1 rows after its first flag. The lab adds that wait to the detection delay.

2.4 Matching rules

Matching decides which alarms “detect” which events. Every published scheme makes choices that change the numbers:

Choice Options This course’s default
What counts as detecting any overlap; IoU above a threshold; alarm starts inside the event; starts within a tolerance window around the onset start inside, early_tolerance = 0 rows
Several alarms in one event each a true positive; first is a hit, the rest are redundant; extras are false alarms first is a hit, rest redundant
Alarm running from normal operation into an event detects it; false alarm false alarm
Alarm before the labelled onset detection with negative delay; false alarm unless within the tolerance false alarm

The reasoning: an alarm is news at the moment it starts. An alarm that started during normal operation and stays on told the operator “something is wrong” before anything was wrong; when the fault does start, the alarm carries no new information. Any-overlap would credit it with a detection at delay zero. The tolerance exists because onsets are labelled imprecisely: SKAB marks a changepoint, and maintenance logs in industry lag the true onset. A tolerance must be set from what is known about label timing, stated, and kept fixed.

Diagram 2 of notebook 16

2.5 The event-level metrics

For one protocol, pooled over the test experiments:

  • Event recall = detected events / true events.
  • Event precision = hits / (hits + false alarms). Redundant alarms are excluded from both counts.
  • Detection delay per true event: time from the true onset to the moment the hit is raised, inf for a missed event. Report the median and a high percentile over all events, missed ones counted as infinite. Averaging only over detected events rewards a detector for missing hard cases (a censoring error; one mutant drops the missed delays).
  • False alarms per hour of normal operation = false alarms / hours outside true events. Hours come from timestamps, never from row counts: SKAB is “about 1 Hz” but has gaps up to 247 s. Decide explicitly what to do with gaps (the lab caps nothing by default and reports the alternatives).

Because false alarms are counts over an exposure, the honest report is the pair (count, hours) and an upper confidence bound, not just the rate. For zero false alarms in T hours the one-sided 95 % upper bound on a Poisson rate is -ln(0.05) / T ≈ 3 / T (the “rule of three”); in general it is chi2.ppf(0.95, 2(n+1)) / (2T). With 1.22 hours of normal operation in the SKAB test experiments, zero false alarms is compatible with 2.46 per hour.

2.6 Point-adjust, and why it is not used here

A large part of the time-series anomaly-detection literature evaluates with point-adjust: if any row of a true event is flagged, every row of that event is counted as detected, and point F1 is computed afterwards. On long events this rewards a detector for a single lucky flag. The worked example shows it on the real SKAB labels: flagging 1 % of rows at random gives point F1 0.021 raw and 0.984 after point-adjust, above every non-adjusted entry of the SKAB leaderboard (best 0.78). The phenomenon has been documented in the literature (Kim et al., AAAI 2022, “Towards a Rigorous Evaluation of Time-Series Anomaly Detection”; cited from memory, not re-opened this session). The course implements point_adjust only to demonstrate the effect. Point-adjusted numbers are never reported.

2.7 Connection to other domains

Biomedical event detection (spikes or seizures in EEG, arrhythmias in ECG) is scored the same way: overlap criteria, false detections per hour, latency to onset. Three things differ in industrial monitoring:

  • Event rates. Equipment faults are rare relative to normal hours; budgets are stated as “one false alarm per shift” or “per week”. A per-hour rate measured on a few hours cannot certify such budgets (challenge part A makes you compute how many hours you would need).
  • Labels come from logs. Onsets are recorded by a technician or a ticket system, late and with jitter; ends are often unknown. The tolerance window and “detected after the label” logic have to be built for that (challenge part B).
  • Alarm fatigue is the dominant cost. A detector that triggers often is switched off, after which its recall is zero. Clinical seizure detection has the same problem; in industry it is usually the binding constraint.

2.8 Industry example

A water utility monitors pumping stations. A leak-detection model is evaluated by the data team at point-level F1 0.81. Deployed, it pages the on-call engineer 30 times a night, mostly fragments of the same few events plus brief pressure transients. After two weeks the alert is muted. Re-evaluated by events, the same model finds 9 of 10 leaks at a median delay of 4 minutes but raises 12 false alarms per hour; with a 10-minute confirmation and merging of gaps under 5 minutes it raises 0.3 per hour and finds 8 of 10 at 14 minutes. That second configuration ships. (Illustrative composite, not a documented incident.)

2.9 Limits and misconceptions

  • “Event metrics fix leakage.” They do not. On SKAB the elapsed-time “detector” finds 3 of 7 test events within 14 s under the strict rule and 7 of 7 under any-overlap, because onsets cluster near row 570 (see the lab’s clock row). Held-out conditions fix leakage; metrics do not.
  • “Higher event recall is better.” Not without the false-alarm rate and delay next to it: flagging everything has event recall 1.0 under any-overlap.
  • “p90 delay is a robust statistic.” With seven events it is the worst case.
  • “A per-hour rate is a measurement.” It is a count divided by an exposure; with few hours, the upper bound is the number to act on.
  • “Post-processing is evaluation.” It is part of the detector and must be tuned on dev only.

3. Worked examples

Both are complete and run from the repository root.

3.1 Hand-built detectors: the two metrics disagree

example/toy_point_vs_event.py builds a SYNTHETIC recording (6 h at one row per 2 s, ten events, one of them long) and five hand-built detectors with known behaviour.

!python labs/w3d4_point_vs_event_evaluation/example/toy_point_vs_event.py

Output (run 2026-11-22):

rows 10800, sampling 2 s, anomalous rows 1470 (13.6%), events 10; the long event holds 82% of the anomalous rows

                                point P point R point F1 events found alarms false alarms/h median delay s
late (last 80 % of each event)      1.0     0.8    0.889        10/10     10            0.0           12.0
onset only (first 5 rows)           1.0   0.034    0.066        10/10     10            0.0            0.0
long event only                     1.0   0.816    0.899         1/10      1            0.0            0.0
chattering (50 % of event rows)     1.0   0.521    0.685        10/10    389            0.0            1.0
onset only + 20 stray flags       0.714   0.034    0.065        10/10     30           3.86            0.0

Bar charts of point F1 and event recall for five hand-built detectors: the detector that finds only the long event has the highest point F1 and the lowest event recall

Figure 1 (SYNTHETIC). Read across a row: “long event only” is the best detector by point F1 and the worst by events; “onset only” is the reverse. The chattering detector’s 389 alarms do not appear in either bar chart; that column of the table is what an operator would notice first.

Interpretation. Point F1 ranks by “share of anomalous rows covered”, which is the right question for a segmentation task and the wrong one for an alarm. “Onset only + 20 stray flags” still has point precision 0.71 while raising 3.86 false alarms per hour.

3.2 Point-adjust on real labels

example/point_adjust_random.py flags rows at random with rate q on all 34 labelled SKAB experiments (real labels, random detector) and scores the flags raw and after point-adjust.

!python labs/w3d4_point_vs_event_evaluation/example/point_adjust_random.py

Output (run 2026-11-22):

34 experiments, 37401 rows, prevalence 0.349, event length 188-586 rows (median 399)

| flag rate q | raw P | raw R | raw F1 | PA P | PA R | PA F1 | events counted | expected events |
|---|---|---|---|---|---|---|---|---|
| 0.0005 | 0.292 | 0.001 | 0.001 | 0.994 | 0.206 | 0.341 | 7/34 | 5.9 |
| 0.0020 | 0.459 | 0.002 | 0.004 | 0.995 | 0.532 | 0.693 | 18/34 | 18.1 |
| 0.0100 | 0.371 | 0.011 | 0.021 | 0.981 | 0.986 | 0.984 | 33/34 | 33.1 |
| 0.0500 | 0.364 | 0.051 | 0.090 | 0.918 | 1.000 | 0.957 | 34/34 | 34.0 |
| 0.2000 | 0.350 | 0.200 | 0.254 | 0.729 | 1.000 | 0.843 | 34/34 | 34.0 |

Reference points on the same rows: flag everything gives F1 0.518; the best F1 on the SKAB README leaderboard (not point-adjusted) is 0.78.

Line chart of point F1 against the random flag rate: raw F1 stays near zero while point-adjusted F1 rises to about 0.99 at one percent of rows flagged

Figure 2 (real SKAB labels, random flags). The orange curve is the same random detector after point-adjust. It crosses the best published non-adjusted F1 at well under 1 % of rows flagged.

Interpretation. “Expected events” is 34 - Σ (1-q)^len: the chance that at least one of an event’s rows is flagged. With events of ~400 rows, q = 0.01 hits almost every event, so point-adjust credits every row of nearly every event. The leaderboard figure (0.78) was read from the SKAB README at the pinned commit.

4. Guided lab: flowguard.evaluation and the point-versus-event table

Work in labs/w3d4_point_vs_event_evaluation/lab/. Given and complete: data.py, splits.py, baselines.py, metrics.py, benchmark.py, _seconds and evaluate_experiments in evaluation.py, and the scripts event_table.py and tradeoff_curve.py. Yours: every TODO in evaluation.py, your own cases in tests/test_evaluation.py, and EVENT_EVAL.md.

Check at any time (offline, synthetic sequences, under 2 s):

!python wb.py check w3d4

All 54 checks fail on the starter.

Task 1 - your cases first (10 min). Before writing any code, add at least five cases to tests/test_evaluation.py, drawn on paper first (a row of 0/1 for the truth, a row for the alarms): an event touching the first and last rows; two alarms inside one event; an alarm starting two rows before an event; a missed event; a recording sampled every 2 s; a logging gap of 300 s inside normal operation. Write the answer you expect under the docstring conventions.

Checkpoint. Your tests fail with NotImplementedError, not with import errors.

Task 2 - events from flags, and point-adjust (10 min). Implement extract_events (merge, then minimum duration) and point_adjust.

Checkpoint. python -m pytest labs/w3d4_point_vs_event_evaluation/checks/test_extract_events.py labs/w3d4_point_vs_event_evaluation/checks/test_point_adjust.py -q passes.

Debugging. An event that runs to the last row disappears: you only close a run when a 0 follows it; append a sentinel. Off-by-one ends: you used the index of the last 1 as end; end is exclusive.

Task 3 - matching (25 min). Implement match_events, event_recall, event_precision. Process alarms in order of start; for each, find the true event it detects (if any) under the tolerance rule.

Checkpoint. test_matching.py passes. The tests that matter most: an alarm that starts in normal operation and runs into an event is a false alarm and does not detect it; two alarms in one event give one hit and one redundant.

Debugging. Recall above 1.0: you count hits per alarm instead of per event. Precision changes when you add a redundant alarm: redundant alarms must not enter either count.

Task 4 - time (20 min). Implement detection_delay, delay_summary, normal_hours, false_alarms_per_hour. Delays use times, include the confirmation rows of a minimum duration, are never negative, and are inf when missed.

Checkpoint. test_time.py passes, including the 2 s sampling case and the gap case.

Debugging. Hours too small by a factor of about 1.1 on SKAB: you counted rows. Median delay suspiciously small: you dropped missed events before taking the median.

Task 5 - run and read (15 min).

!python labs/w3d4_point_vs_event_evaluation/lab/event_table.py
!python labs/w3d4_point_vs_event_evaluation/lab/event_table.py --min-duration 10 --merge-gap 30
!python labs/w3d4_point_vs_event_evaluation/lab/tradeoff_curve.py

Expected with the reference implementation (yours must match exactly; the metrics are deterministic). The scripts read the split from lab/splits/v2.json, the manifest repaired and frozen in w3d1 (7 test, 27 development experiments): the test set is never redrawn once results have been seen, so every Week 3 lesson reports on the same seven experiments.

experiments: dev 27, test 7 (other/1, other/14, valve1/10, valve1/13, valve1/5, valve1/8, valve2/0)
test rows evaluated: 6659 (2487 anomalous, 7 events); burn-in 100 rows; min_duration=1, merge_gap=0

| detector | point P | point R | point F1 | F1 after point-adjust | events found | alarms | false alarms | redundant | event P | false alarms / h | median delay s | p90 delay s |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| random | 0.373 | 1.000 | 0.544 | 0.544 | 1/7 | 9 | 8 | 0 | 0.111 | 6.6 | missed | missed |
| elapsed time t (no sensors) | 0.732 | 0.992 | 0.842 | 0.846 | 3/7 | 7 | 4 | 0 | 0.429 | 3.3 | missed | missed |
| flow_rate abs z, burn-in | 0.840 | 0.813 | 0.826 | 0.928 | 7/7 | 469 | 290 | 172 | 0.024 | 238.6 | 4 | 43 |
| max abs z, burn-in | 0.591 | 0.897 | 0.713 | 0.763 | 6/7 | 275 | 217 | 52 | 0.027 | 178.5 | 5 | missed |
| Mahalanobis, burn-in | 0.696 | 0.766 | 0.729 | 0.857 | 6/7 | 245 | 129 | 110 | 0.044 | 106.1 | 16 | missed |
| logistic regression (supervised) | 0.825 | 0.846 | 0.835 | 0.918 | 7/7 | 462 | 319 | 136 | 0.021 | 262.4 | 4 | 31 |

normal operation in the evaluated test rows: 1.22 h (wall clock, gaps included)

With --min-duration 10 --merge-gap 30 the single-sensor detector drops to 17 alarms (14 false, 11.5 per hour) but finds only 3 of 7 events: at the low best-F1 threshold (2.40) the merged alarm often starts before the onset and becomes a false alarm. Mahalanobis, worst of the three sensor detectors on point F1, is the best post-processed one: 5 of 7 events, 5 false alarms (4.1 per hour), median delay 52 s. Post-processing parameters and the threshold have to be chosen together.

Three stacked panels for test experiment valve1/10: flow rate with the labelled anomalous segment shaded, the burn-in z-score with the threshold, and the alarms before and after post-processing

Figure 3 (real SKAB, test experiment valve1/10). One fault. The raw flags (bottom row) are 28 separate alarms: one hit, 13 redundant, 14 false. After merging gaps of up to 30 rows and requiring 10 rows of confirmation, two remain: the hit and one false alarm, which you can see coming from an isolated burst of high z-scores in normal operation.

Two panels against false alarms per hour on a log scale: event recall rises with the false-alarm rate, and median delay falls; the post-processed curve reaches much higher recall at low false-alarm rates

Figure 4 (real SKAB, 27 development experiments). The curve an operating point is chosen from. The dashed line is a budget of one false alarm per 8 hours. Note that with post-processing recall is not monotone in the threshold: at low thresholds the merged alarm starts before the onset and becomes a false alarm. Missing delays in the right panel are where the median event was missed.

Things you should be able to see for yourself, before reading the reference EVENT_EVAL.md:

  • the detector whose rank changes most between point F1 and the event columns, and why;
  • what point-adjust does to every row, including the random one;
  • how many test events the clock “detects”, and what the any-overlap rule would have said;
  • why no false-alarm rate in this table supports an operational claim.

Completion criteria. All 54 lab checks pass; your own tests in lab/tests pass and include the six cases of task 1; EVENT_EVAL.md contains both tables, the clock analysis, and a one-sentence reporting decision and matching rule for the project.

# Run the automated checks on your guided lab.
# A fresh starter is expected to FAIL; passing means guided practice, not mastery.
from mlcourse.checks import check

check("w3d4")

5. Independent challenge

challenge/README.md, two parts:

  • A - an alert budget. Choose threshold, min_duration and merge_gap on development data so the detector raises at most one false alarm per eight hours, evaluate once on test, and write the sentence you would send the reliability engineer. Graded by checks (selection logic, exact Poisson bound) and a rubric (the claim must be one the data supports).
  • B - another domain. Intermittent network outages of 3-20 s with ticket-log labels that lag by 0-8 s (SYNTHETIC). The SKAB rule gets both detectors wrong; design, implement and defend a rule.
!python wb.py check w3d4 --challenge

The challenge brief

Work without the hints first. About 60-75 minutes for both parts. Finish the lab before starting: the challenge imports your flowguard.evaluation from ../lab/src (or from challenge/src if you copy the package there).

Part A - choose an operating point under an alert budget (graded by checks + rubric)

Scenario. The reliability engineer will accept the detector only if it raises at most one false alarm per eight hours of normal operation. Within that budget they want as many faults found as possible, as early as possible.

  1. In operating_point.py implement
    • rate_upper_bound(n_false_alarms, hours, confidence=0.95): the exact one-sided upper confidence bound for a Poisson rate, in false alarms per hour;
    • choose_operating_point(dev_tidy, dev_scores, budget_per_hour, thresholds, min_durations, merge_gaps, burn_in, early_tolerance): evaluate every grid setting on the development data it is given and return the choice described in the file’s docstring. Selection rule: a setting is feasible if its dev false-alarm rate is within the budget; among feasible settings take the highest event recall, then the lowest median delay, then the lowest false-alarm rate. If nothing is feasible, return the setting with the lowest false-alarm rate (ties: highest recall) and say so with feasible = False.
  2. Run the report on the real data (it calls your two functions; nothing else is needed):

    python labs/w3d4_point_vs_event_evaluation/challenge/budget_report.py
    
  3. Write REPORT.md (half a page): the chosen setting, dev and test results, and the exact sentence you would send to the engineer about whether the budget is met.

Acceptance criteria

  • python wb.py check w3d4 --challenge passes.
  • The function receives development data only. The test experiments are touched once, by the report.
  • REPORT.md states counts and exposure (false alarms, hours) and an upper bound, not only a rate.
  • The claim about the budget is one the data supports. (Decide what that is before you write it.)

Part B - a matching rule for intermittent network outages (rubric only)

outages.py simulates 24 hours of a monitored link (SYNTHETIC): forty outages of 3-20 s, labels taken from a ticket log that lags the real outage by 0-8 s, and two detectors with known behaviour. Run it:

!python labs/w3d4_point_vs_event_evaluation/challenge/outages.py

Under the rule you built for SKAB the table is badly wrong about both detectors.

  1. Explain in OUTAGE_RULE.md what in this domain breaks the SKAB rule. Be specific about label timing, event length and event rate.
  2. Design a rule for this domain and implement it in outage_rule.py::score_outages, built from your flowguard.evaluation functions.
  3. Defend each choice in OUTAGE_RULE.md, including what your rule can no longer measure and one way a detector could exploit it.

Acceptance criteria

  • The script prints your rule’s results for both detectors.
  • Each parameter of the rule is justified from a property of the domain, not from the resulting score.
  • You state the resolution limit of the delay you report.
  • You name at least one way to game your rule and how you would notice.

Self-assess with the rubric in solutions/labs/w3d4_point_vs_event_evaluation/assessment_answers.md only after writing both documents.

# Run the automated checks on your independent challenge.
# A fresh starter is expected to FAIL; passing means guided practice, not mastery.
from mlcourse.checks import check

check("w3d4", challenge=True)

6. Progressive hints (open in order, only when stuck)

  1. Concept
  2. Approach
  3. Partial implementation

Reference solutions: solutions/labs/w3d4_point_vs_event_evaluation/. If you open a hint, the work counts as guided, not independent.

Open one hint at a time, only after a real attempt.

Hint 1 concept * Everything this module decides about an alarm is decided from **its start row**. If you find yourself asking "does the alarm overlap the event?", re-read the matching rule: overlap is not the question. * An event and an alarm are the same data structure: a half-open `(start, end)`. Lengths are `end - start`; adjacent runs `(2, 5)` and `(5, 8)` share no row. * Post-processing order matters: merge runs that are close, *then* drop runs that are short. Short fragments of one fault are exactly what merging is for. * A missed event has a delay too: infinity. Summaries are taken over **all** events. * Time comes from timestamps. Rows are a proxy for time only when sampling is regular and gap-free, which SKAB is not. * Challenge A: a rate from a few hours of data is a count over an exposure. The number to compare with a budget is the upper confidence bound, not the point estimate. * Challenge B: start from what is known about how the *labels* are produced (lag, jitter, event length, event spacing), not from what makes a detector score well.
Hint 2 approach **`extract_events`.** Pad the flags with a 0 on both sides, take `np.diff`, and read starts where the difference is +1 and ends where it is -1 (in padded coordinates the end index is already exclusive). Then walk the list once: if the gap `next.start - current.end <= merge_gap`, extend `current`; finally keep runs with `end - start >= min_duration`. **`point_adjust`.** For each true event, if `y_pred[start:end].any()`, set `y_pred[start:end] = 1` on a copy. Do not modify the input. **`match_events`.** Sort alarms by start. For each alarm find the true event whose window `[start - early_tolerance, end)` contains the alarm's start (events do not overlap, so there is at most one; `np.searchsorted` on event starts finds it in O(log n)). If none: false alarm. If that event already has a hit: redundant. Otherwise: hit, and record which alarm. Return per-alarm labels and the per-event hit index (or `None`). **Recall and precision** are counts from that result. Decide the NaN cases from the docstring before writing them. **`detection_delay`.** For each true event: if no hit, `inf`. Otherwise the hit is raised at `alarm_start + (min_duration - 1)` rows (the confirmation wait); convert that row and the event start to seconds with `_seconds(times)` and take `max(0, raised - onset)`. **`normal_hours`.** Sum the time differences between consecutive rows that are both outside every true event; optionally cap each difference at `max_gap`. Divide by 3600. **Challenge A.** Loop over the grid with `itertools.product`, call `evaluate_experiments` on the dev data for each setting, keep a list of results, then sort by the stated keys. The Poisson upper bound is `chi2.ppf(confidence, 2 * (n + 1)) / (2 * hours)`.
Hint 3 partial ```python def extract_events(binary, min_duration=1, merge_gap=0): b = np.asarray(binary, dtype=int) d = np.diff(np.concatenate([[0], b, [0]])) runs = list(zip(np.flatnonzero(d == 1), np.flatnonzero(d == -1))) merged = [] for s, e in runs: if merged and s - merged[-1][1] <= merge_gap: merged[-1] = (merged[-1][0], e) else: merged.append((s, e)) return [(int(s), int(e)) for s, e in merged if e - s >= min_duration] def match_events(true_events, pred_events, early_tolerance=0): starts = np.array([s for s, _ in true_events]) first_detection = [None] * len(true_events) labels = [None] * len(pred_events) # one label per alarm, in the order given for j in sorted(range(len(pred_events)), key=lambda j: pred_events[j][0]): # earliest first a_start = pred_events[j][0] k = int(np.searchsorted(starts, a_start + early_tolerance, side="right")) - 1 inside = k >= 0 and true_events[k][0] - early_tolerance <= a_start < true_events[k][1] if not inside: labels[j] = "false_alarm" elif first_detection[k] is None: first_detection[k] = ... # what does detection_delay need to know? labels[j] = "hit" else: labels[j] = "redundant" return {"first_detection": first_detection, "pred_label": labels} ``` Still yours: the return structure of `match_events`, the NaN conventions, `detection_delay` with the confirmation wait, `delay_summary` with infinite delays, `normal_hours` from timestamps with gaps.

7. Assessment

assessment.md (section 7 of this notebook): six reasoning questions, one design-choice explanation, a rubric, and one interview rep (Python: interval merging and overlap). Automated checks: checks/ (54 tests) and checks_challenge/ (13 tests), validated against the reference solution and against eleven plausible wrong submissions. Passing them means your functions follow the conventions; it does not mean your matching rule is the right one for a new domain.

Assessment questions

Answer in writing before opening solutions/labs/w3d4_point_vs_event_evaluation/assessment_answers.md. About 15 minutes for the questions; the interview rep is separate.

Reasoning questions

  1. Two detectors on the same seven test events. A: point F1 0.84, 6/7 events, 239 false alarms per hour. B: point F1 0.83, 7/7 events, 262 false alarms per hour. A colleague says “A is better, higher F1 and fewer false alarms”. Give two reasons this conclusion is not supported, one about the metric and one about the data.
  2. Under any-overlap matching the elapsed-time detector “finds” 7 of 7 SKAB test events; under the course’s start-based rule it finds 3. Which number is closer to what an operator would experience, and what property of the clock’s alarms makes the two rules disagree?
  3. A paper reports point-adjusted F1 0.96 on SKAB. Without access to the code, what single additional number would let you judge whether 0.96 means anything? Explain.
  4. Why must min_duration and merge_gap be chosen on development experiments, and what goes wrong in the reported delay if the confirmation wait is not added to it?
  5. A detector raised zero false alarms in 1.22 hours of held-out normal operation. State the strongest claim about its false-alarm rate that the data support at 95 % confidence, and the number of hours with zero false alarms needed to claim “at most one per 8 hours”.
  6. Median detection delay is computed over the detected events only and reported as 40 s; two of seven events were missed. What is the median over all events, and why is the second number the one to report?

Design-choice explanation (write 6-10 sentences)

Your team is about to adopt a matching rule for a new detector of compressor surges, labelled from maintenance tickets that are entered by hand, typically 5-30 minutes after the event starts. Propose a rule (what counts as a detection, early tolerance, treatment of repeated alarms, what counts as a false alarm, how hours are counted) and justify each element from a property of the labels or of the operator’s use of the alarm. Name one thing your rule can no longer measure.

Rubric (for questions and the design explanation)

Level Description
Demonstrated Distinguishes rows from alarms in every answer; quantifies with counts and exposures; ties each rule element to a property of labels or use; states what the chosen rule cannot measure.
Partial Correct mechanics (e.g. rule of three, censored delays) but justifications are generic (“to be fair”, “standard practice”) or one element is chosen by its effect on the score.
Not yet Treats point F1 or point-adjusted F1 as evidence of detection quality, or reports rates without exposure, or averages delays over detected events only without saying so.

Interview rep (Python, 12 minutes, no notes)

Implement, with tests you write yourself:

Interval = tuple[int, int]   # half-open [start, end)

def merge_intervals(intervals: list[Interval]) -> list[Interval]:
    """Union as sorted disjoint intervals. Touching intervals merge; empty ones are ignored."""

def overlap_length(a: list[Interval], b: list[Interval]) -> int:
    """Total length covered by both a and b (each may contain overlapping intervals)."""

State the time complexity of each. Then answer aloud: how would overlap_length let you compute the point-level recall of a set of alarms against a set of true events without materialising per-row arrays?

Self-score against the interview rubric in the answers file; a reference implementation with tests is in solutions/labs/w3d4_point_vs_event_evaluation/interview_rep/.

8. Reflection and review

You should now be able to do, alone: turn scores into alarms with explicit post-processing; state a matching rule and its consequences; compute event recall, event precision, censored delays and false alarms per hour from timestamps; explain why point-adjusted numbers are uninformative; express a false-alarm rate as count, exposure and upper bound; choose an operating point from dev data under a budget.

Reflection prompt (5 lines, python wb.py note w3d4 "..."): think of an event detector you have built or read about (in a paper, a product, or this course). Which matching rule did it use, was it written down before the results, and would any-overlap have changed a headline number?

Retrieval question for later (w3d7 review, and again in Week 7): a detector raised zero false alarms in 2 hours of held-out normal operation. The requirement is at most one per 8 hours. What can you claim, and how many hours of clean operation would you need to claim the requirement is met at 95 % confidence?

Next. w3d5 uncertainty puts intervals on these counts: seven events and 1.22 hours are the reason every number in today’s table needs one.

Verification record

Authored 2026-11-21/22, executed on Python 3.13.18, NumPy 2.5.3, pandas 3.0.5, scikit-learn 1.9.1, matplotlib 3.11.2 (figures only), SKAB at commit b2c0d46.

  • python tools/verify_checks.py labs/w3d4_point_vs_event_evaluation: reference passes lab (54) and challenge (13); 7 lab and 4 challenge mutants rejected.
  • Shipped starter: 54 of 54 lab checks fail; challenge 9 fail, 4 error.
  • Both worked examples, event_table.py (two settings), tradeoff_curve.py, the challenge budget_report.py and outages.py, and figures/make_figures.py were run on the reference solution; outputs above are copied from those runs. Interview-rep reference: 5 tests pass.
  • 2026-11-22: real-data scripts switched to the frozen w3d1 manifest (lab/splits/v2.json) and every real-SKAB number and figure in this unit regenerated from a fresh run.
  • Not verified: the Kim et al. citation (from memory); time budgets.

Record your progress

Tick only what is true. Passing the supplied checks is guided practice; mark independent only for work done without hints or solutions.

from mlcourse.progress import mark, note

# mark("w3d4", "reading")
# mark("w3d4", "guided")
# mark("w3d4", "independent")
# note("w3d4", "what tripped me up today")

Back to top

Applied ML Engineering course materials. Code is MIT licensed; prose is CC BY 4.0. The SKAB dataset is GPL-3.0 and is downloaded from its source, not redistributed here.