Skip to content

Residual score for sensor anomalies

Compute a residual score while keeping drift and alert limits visible.

Data Dora, your practice guide

Data Dora
Compute a residual score while keeping drift and alert limits visible.
Predict the reading, then compare it with the measurement.

Python 3 in your browser (JupyterLite)

Python · no install

Tier 2 · Web · paste-in setup · No account

Last tested October 2026.

Open the notebook in your browser and run each Python cell; no install or account is needed.

Three ways to run: use JupyterLite here with no install; run main.py locally from the downloadable lab folder; or open the same notebook in Google Colab.

Open in your browser (new tab)

Steps

The tool may have moved on since the screenshots were taken — the text steps are the contract.

  1. 1 Step 1

    Do
    Run the Step 1 notebook cell and inspect the drifting synthetic series with its planted outlier.
    You will see

    Run the cell. You should see:

    • SYNTHETIC drifting temperature, seed=1414; Normal readings use fixed offsets; one planted +2.00 C outlier at t=7.; t value_C; 0 20.00; 1 20.30
    Why it matters
    The known planted event permits a direct check of detector behavior.
    Code for step 1
    import platform
    import pyodide
    print(f'Runtime: Python {platform.python_version()} / Pyodide {pyodide.__version__}')
    
    """Rolling residual detector on explicitly synthetic sensor data."""
    import random
    import statistics
    
    SEED = 1414
    BASE = [20 + 0.2 * i for i in range(12)]
    NORMAL = [round(v + d, 2) for v, d in zip(BASE,
              [0.00, 0.10, -0.10, 0.00, 0.10, -0.10, 0.00, 2.00, 0.10, 0.00, -0.10, 0.00])]
    THRESHOLD_C = 0.8
    
    
    def baseline(values, index):
        if index < 3:
            return None
        return statistics.median(values[index - 3:index])
    
    
    def scored(values):
        return [(i, values[i], baseline(values, i),
                 None if i < 3 else values[i] - baseline(values, i))
                for i in range(len(values))]
    
    
    def noisy_series():
        rng = random.Random(SEED)
        # Preserve the same planted outlier; independent noise affects ordinary rows.
        return [NORMAL[i] if i == 7 else round(BASE[i] + rng.choice([-1.1, 0.0, 1.1]), 2)
                for i in range(len(NORMAL))]
    
    
    def table(rows):
        return [f"{i:>2} {v:>7.2f} {('n/a' if b is None else f'{b:.2f}'):>8} "
                f"{('n/a' if r is None else f'{r:+.2f}'):>8} "
                f"{'FLAG' if r is not None and abs(r) > THRESHOLD_C else '-'}"
                for i, v, b, r in rows]
    
    
    def flagged(rows):
        return [i for i, _, _, r in rows if r is not None and abs(r) > THRESHOLD_C]
    
    
    def run_step(n):
        normal_rows, noise_rows = scored(NORMAL), scored(noisy_series())
        if n == 1:
            lines = ["SYNTHETIC drifting temperature, seed=1414",
                     "Normal readings use fixed offsets; one planted +2.00 C outlier at t=7.",
                     "t value_C", *[f"{i:>2} {v:>7.2f}" for i, v in enumerate(NORMAL[:9])],
                     "These are generated inputs, not sensor measurements."]
        elif n == 2:
            lines = ["Trailing 3-reading median baseline; current point excluded",
                     "t value_C baseline_C residual_C flag", *table(normal_rows[3:9]),
                     "The baseline rises with the underlying drift."]
        elif n == 3:
            lines = ["Residual = observed - trailing median baseline",
                     "t value_C baseline_C residual_C flag", *table(normal_rows[5:11]),
                     "At t=7 the residual is much larger than nearby values."]
        elif n == 4:
            lines = [f"Fixed alert rule: |residual| > {THRESHOLD_C:.2f} C",
                     "t value_C baseline_C residual_C flag", *table(normal_rows[5:11]),
                     f"flagged timestamps={flagged(normal_rows)}",
                     "The planted event is t=7; post-event baseline may also be affected."]
        elif n == 5:
            lines = [f"Higher ordinary noise: random choices from -1.10, 0, +1.10 C; seed={SEED}",
                     "same planted t=7 value and same 0.80 C threshold",
                     "t value_C baseline_C residual_C flag", *table(noise_rows[3:10]),
                     f"flagged timestamps={flagged(noise_rows)}"]
        elif n == 6:
            normal_flags, noise_flags = flagged(normal_rows), flagged(noise_rows)
            lines = ["RESULT CARD: synthetic rolling-median residuals; seed=1414",
                     f"baseline threshold={THRESHOLD_C:.2f} C",
                     f"quiet-series flags={normal_flags}",
                     f"higher-noise flags={noise_flags}",
                     f"higher-noise ordinary false positives={[i for i in noise_flags if i != 7]}",
                     "More noise changes the alert count under the unchanged threshold.",
                     "This synthetic run does not establish field false-alarm rates."]
        else:
            raise ValueError(n)
        lines.append(f"STEP {n} complete")
        output = "\n".join(lines)
        print(output)
        return output
    
    
    
    run_step(1);
    Real JupyterLite notebook output for step 1 of Residual score for sensor anomalies.
    Step 1 · Python 3 in your browser (JupyterLite); numbered callout added to a real capture.
  2. 2 Step 2

    Do
    Run the Step 2 notebook cell to inspect the trailing median baseline.
    You will see

    Run the cell. You should see:

    • Trailing 3-reading median baseline; current point excluded; t value_C baseline_C residual_C flag; 8 21.70 21.20 +0.50 -; The baseline rises with the underlying drift.
    Why it matters
    A trailing baseline uses past readings and can follow slow drift.
    Code for step 2
    run_step(2);
    Real JupyterLite notebook output for step 2 of Residual score for sensor anomalies.
    Step 2 · Python 3 in your browser (JupyterLite); numbered callout added to a real capture.
  3. 3 Step 3

    Do
    Run the Step 3 notebook cell to subtract the baseline and read residuals.
    You will see

    Run the cell. You should see:

    • Residual = observed - trailing median baseline; t value_C baseline_C residual_C flag; 10 21.90 21.80 +0.10 -; At t=7 the residual is much larger than nearby values.
    Why it matters
    Residuals expose departures from the local expected value.
    Code for step 3
    run_step(3);
    Real JupyterLite notebook output for step 3 of Residual score for sensor anomalies.
    Step 3 · Python 3 in your browser (JupyterLite); numbered callout added to a real capture.
  4. 4 Step 4

    Do
    Run the Step 4 notebook cell to apply the fixed 0.80 C threshold and note the flag.
    You will see

    Run the cell. You should see:

    • Fixed alert rule: |residual| > 0.80 C; t value_C baseline_C residual_C flag; flagged timestamps=[7]; The planted event is t=7; post-event baseline may also be affected.
    Why it matters
    A fixed threshold converts scores into inspectable decisions.
    Code for step 4
    run_step(4);
    Real JupyterLite notebook output for step 4 of Residual score for sensor anomalies.
    Step 4 · Python 3 in your browser (JupyterLite); numbered callout added to a real capture.
  5. 5 Step 5

    Do
    Run the Step 5 notebook cell to raise ordinary noise without changing the threshold.
    You will see

    Run the cell. You should see:

    • Higher ordinary noise: random choices from -1.10, 0, +1.10 C; seed=1414; same planted t=7 value and same 0.80 C threshold; 9 21.80 22.30 -0.50 -; flagged timestamps=[4, 6, 7, 8]
    Why it matters
    Noise can produce ordinary false alerts under the same rule.
    Code for step 5
    run_step(5);
    Real JupyterLite notebook output for step 5 of Residual score for sensor anomalies.
    Step 5 · Python 3 in your browser (JupyterLite); numbered callout added to a real capture.
  6. 6 Step 6

    Do
    Run the Step 6 notebook cell and compare flag counts and false positives.
    You will see

    Run the cell. You should see:

    • RESULT CARD: synthetic rolling-median residuals; seed=1414; baseline threshold=0.80 C; More noise changes the alert count under the unchanged threshold.; This synthetic run does not establish field false-alarm rates.
    Why it matters
    A detector threshold needs evidence from the operating noise level.
    Code for step 6
    run_step(6);
    Real JupyterLite notebook output for step 6 of Residual score for sensor anomalies.
    Step 6 · Python 3 in your browser (JupyterLite); numbered callout added to a real capture.

Chapter checks

These questions refer to the chapter’s examples. Use the return links to review their answers.

  1. Why should a seasonal IoT signal usually be scored on residuals instead of raw readings?

    Return to the chapter’s knowledge check
  2. The matching seasonal baseline is 18 kW and the observed load is 31 kW. The alert band is ±4 kW, but the reading arrived 2 minutes after a 1-minute action deadline. What is the defensible result?

    Return to the chapter’s knowledge check

Caution

Before you start

Read this before you start.

This synthetic run does not establish field false-alarm rates or deployed detector performance.

Technical details
Version tested
Version tested: Python 3.12.7 / Pyodide 0.27.6 in JupyterLite 0.6.4; Chromium real browser capture, 2026-10-09. Date: 2026-10-09.
QR code that opens the Residual score for sensor anomalies lab page
Open this lab online: https://iotclass.org/labs/residual-sensor-anomalies.html

Return to Time-Series Anomalies: Baselines and Residuals · Browse Labs