Build a Sensor Anomaly Pipeline

Build a Python pipeline that cleans sensor data and detects anomalies.

Introduction

30 Second Summary

A machine can keep running while its readings quietly drift away from normal. Those warning signs only help when the data reveals them clearly.

In this project, you will build SensorGuard, a reproducible Python data pipeline that turns messy equipment readings into validated data. You will measure a simple threshold against an IsolationForest detector to see which anomalies each approach catches.

What You'll Build

You will run SensorGuard and see suspicious equipment readings stand out as red markers in a finished anomaly report.

By the end of this project, you'll have:

  • A raw-to-clean data trail where you can inspect missing readings, repair invalid values, and query the validated records in SQLite.
  • Measured detector results that use precision and recall to reveal why a temperature-only rule misses important events.
  • A public GitHub project containing runnable source code, generated data, a queryable database, visual reports, and documentation you can show a reviewer.
  • Secret Mission: Shift the sensor's normal temperature range and measure how distribution drift changes the detector's alert volume.

Are there any prerequisites?

You do not need previous data engineering or machine learning experience. Google Colab provides the browser workspace for the project, so you can begin without configuring a local development environment.

Before We Start

This is your moment to commit to what SensorGuard will do before the hands-on work begins. A clear purpose makes every later engineering choice easier to explain.

Set Up a Reproducible Browser Workspace

SensorGuard depends on the same library behavior every time you run it. A browser-based Google Colab runtime keeps local setup differences out of the pipeline.

Version drift can change data handling or model results. You will pin Python 3.12.13 through Colab runtime 2026.07.

You will also install the package versions that the later pipeline expects. Your GitHub account will be ready for publishing in Step 5.

In this step, get ready to:
  • Prepare your Google account for Colab.
  • Prepare your GitHub account for publishing.
  • Configure runtime 2026.07 with the pinned packages.
Sign In to Your Browser Tools

Google Colab handles the notebook in your browser. GitHub gives you a publishing destination later.

Your sign-in credentials stay on each provider's own login page. You never paste them into the notebook.

  • Open Google Colab in your browser.
  • Click Sign in in the top-right corner.
  • Complete the Google sign-in prompts.
  • Open the GitHub signup page in a second browser tab.
  • Authenticate with your existing GitHub account if you already have one.
  • Create a GitHub account through the signup flow if you need one.
  • Confirm the GitHub page shows you as signed in.

That clears the account setup. Colab can save your notebook under your Google account.

Having Trouble Signing In?

Use each provider's account-recovery flow if your login is rejected. Keep passwords or recovery codes out of the notebook.

If the browser keeps returning you to the login page, help me troubleshoot the Colab or GitHub sign-in flow.

Create the Notebook and Pin the Runtime

Colab runtimes bundle Python with preinstalled libraries. Choosing a dated runtime gives this project a known starting point before package pinning.

  • Click File in the Colab top menu.
  • Click New notebook.
  • Click Runtime in the blank notebook's top menu.
  • Click Change runtime type.
  • Open the Runtime Version dropdown to inspect the current selection.

✔️ I see runtime 2026.07 selected

The selected runtime already matches the project.

  • Leave 2026.07 selected.
  • Close the dialog after confirming the selection.

ⓧ I see an older runtime

An older runtime can load different package defaults. Switch to the project's pinned runtime before installing anything.

  • Select 2026.07 from the Runtime Version dropdown.
  • Confirm the runtime change using the dialog's confirmation control.

ⓧ I cannot find runtime 2026.07

The project depends on this dated runtime for Python 3.12.13. Do not continue with a different runtime.

  • Reload the Colab browser page.
  • Click Runtime in the top menu.
  • Click Change runtime type.
  • Check the Runtime Version dropdown for 2026.07 again.

Runtime Still Missing?

Confirm that your Google account is signed in before reopening the runtime menu.

If the option is still absent, help me find the pinned Colab runtime.

The 2026.07 runtime provides Python 3.12.13. Your notebook now has the required language version.

Install and Verify the Pinned Packages

A package pin fixes the exact library release used by the notebook. This makes later outputs easier to reproduce.

SensorGuard uses pandas for tables. It uses scikit-learn for anomaly detection.

Matplotlib produces the visual reports.

  • Install the pinned packages in the first code cell by pasting this command:
!pip install pandas==3.0.6 scikit-learn==1.9.1 matplotlib==3.11.2

What Does This Command Do?

  • The leading ! runs a terminal command from the Colab code cell.
  • pandas==3.0.6 installs the table-processing library at the required version.
  • scikit-learn==1.9.1 installs the machine-learning library at the required version.
  • matplotlib==3.11.2 installs the plotting library at the required version.

The first installation can take a few minutes while Colab resolves the packages. Scrolling output during this wait is expected.

  • Run the installation cell by pressing Shift+Enter.
  • Wait for the installation cell to finish.
  • Confirm that the output ends without an installation failure.

Package Installation Failed?

  • Rerun the installation cell once if the Colab runtime disconnected.
  • Check that the command still contains all three exact package pins.
  • If the installation still fails, help me diagnose the pinned package installation.

An import check proves that Python can load each installed package. The version attributes confirm that Colab is using the releases you requested.

  • Verify the imports plus package versions in the next code cell by pasting this code:
import matplotlib
import pandas as pd
import sklearn

# Confirm that the notebook loaded every pinned dependency
print(pd.__version__, sklearn.__version__, matplotlib.__version__)

What Does This Check?

  • The import statements test whether all three packages can load in the current runtime.
  • __version__ reads the installed release from each package.
  • The final print places the three versions on one line for a quick comparison.

Before you run this cell, which three version numbers should appear in order?

  • Run the version-check cell by pressing Shift+Enter.

You should see 3.0.6 1.9.1 3.11.2 on the final line. That locks in every dependency SensorGuard needs.

Versions Do Not Match?

  • Rerun the installation cell if any printed version differs from the expected output.
  • Rerun the version-check cell after the installation finishes.
  • If an import still fails, help me compare my Colab package versions.

Your browser workspace is pinned and tested. Next, you will generate the raw sensor stream that SensorGuard analyzes.

Generate a Raw Sensor Stream

Your pinned Google Colab workspace is ready. SensorGuard now needs a repeatable stream of equipment readings to process.

A raw feed can look usable while hiding missing values or physically impossible readings. In this step, you will generate those failures deliberately so every later check has a known target.

In this step, get ready to:
  • Build a deterministic generator for 240 hourly sensor records.
  • Report deliberate quality failures before cleaning begins.
  • Save the raw records as a CSV file with a matching visual report.
Build the telemetry generator

Synthetic telemetry is generated data that imitates readings from real equipment. A deterministic generator produces the same records every time.

  • In the Colab notebook from earlier, add a code cell beneath the package version check.
  • Paste this first source segment into the new cell:
import math
import sqlite3

import matplotlib.pyplot as plt
import pandas as pd
from sklearn.ensemble import IsolationForest

ANOMALY_INDICES = {40, 120, 180, 220}
FEATURE_COLUMNS = [
    "temperature_c",
    "vibration_mm_s",
    "pressure_bar",
    "temperature_change",
]


def generate_raw_data():
    timestamps = pd.date_range(
        start="2026-01-01",
        periods=240,
        freq="h",
    )
    records = []

    for index, timestamp in enumerate(timestamps):
        temperature = 50 + (0.02 * index) + (1.5 * math.sin(index / 8))
        vibration = 2 + (0.001 * index) + (0.15 * math.cos(index / 6))
        pressure = 30 + (0.3 * math.sin(index / 10))

What does this source segment do?

  • The math functions create gradual movement in each sensor signal.
  • The pandas date range supplies 240 hourly timestamps.
  • The ANOMALY_INDICES set records where known unusual events occur.
  • The FEATURE_COLUMNS list defines the signals that later stages can evaluate together.
  • Continue the same generate_raw_data() function by pasting this second segment directly below the pressure calculation:

        if index == 40:
            temperature += 20
        elif index == 120:
            vibration += 5
        elif index == 180:
            temperature += 15
            vibration += 4
        elif index == 220:
            temperature -= 20

        if index == 15:
            temperature = None
        if index == 75:
            vibration = -1

        records.append(
            {
                "timestamp": timestamp,
                "temperature_c": temperature,
                "vibration_mm_s": vibration,
                "pressure_bar": pressure,
                "ground_truth_anomaly": int(index in ANOMALY_INDICES),
            }
        )

    return records

How are the test problems created?

  • The index checks inject four unusual sensor events into known rows.
  • The None value creates a missing temperature.
  • The -1 value creates a physically invalid vibration reading.
  • The ground_truth_anomaly field labels the four injected events for later evaluation.
  • Run the source cell once to confirm the generator is syntactically complete.

Good. The execution indicator finishes without a Python error because the generator is now fully defined.

Seeing a Python error?

Check that the second segment remains indented inside generate_raw_data(). Confirm that return records lines up with the for statement.

Run the package installation cell from earlier if the error mentions a missing imported library.

Help me repair the indentation in my telemetry generator.

Expose the bad readings

A data quality check turns a vague suspicion into measurable counts. SensorGuard checks the raw records before any repair can hide the original problems.

  • Return to the source cell from the previous substep.
  • Place your cursor below return records.
  • Paste the quality-report function at that location:
def quality_report(records):
    missing_temperature = sum(
        row["temperature_c"] is None for row in records
    )
    invalid_vibration = sum(
        row["vibration_mm_s"] is not None
        and row["vibration_mm_s"] < 0
        for row in records
    )
    return {
        "missing_temperature": missing_temperature,
        "invalid_vibration": invalid_vibration,
    }

What does the quality report measure?

  • The first count finds records whose temperature_c value is missing.
  • The second count finds records whose vibration_mm_s value falls below zero.
  • The returned dictionary gives each failure type a separate count.
  • Run the source cell to load the new function into the active runtime.

The source cell completes without an error. The quality check is now ready to inspect generated records.

  • Add a temporary code cell beneath the source cell.
  • Paste this focused quality check into the temporary cell:
raw_records = generate_raw_data()
print("Raw data quality:", quality_report(raw_records))

What does this check do?

The first line generates the complete raw stream. The second line passes those records into quality_report() so the deliberate failures become visible.

Before you run this check, do you expect both quality counts to be zero?

  • Run the temporary quality-check cell.

You will see Raw data quality: {'missing_temperature': 1, 'invalid_vibration': 1}. Those nonzero counts prove that the raw feed contains problems despite its otherwise consistent structure.

Do the counts look different?

Confirm that index 15 sets temperature to None. Confirm that index 75 sets vibration to -1.

Check that the temporary cell calls the current generate_raw_data() function before it prints the report.

Help me debug unexpected SensorGuard quality counts.

Plot and export the raw stream

Numbers reveal how many failures exist. Matplotlib shows where the sensor signals behave unusually across time.

  • In the source cell, place your cursor below the quality_report() function.
  • Paste the plotting function at that location:
def plot_raw_data(raw_frame):
    figure, axes = plt.subplots(
        2,
        1,
        figsize=(12, 6),
        sharex=True,
        layout="constrained",
    )
    axes[0].plot(
        raw_frame["timestamp"],
        raw_frame["temperature_c"],
        label="Temperature",
    )
    axes[1].plot(
        raw_frame["timestamp"],
        raw_frame["vibration_mm_s"],
        color="orange",
        label="Vibration",
    )
    axes[0].set(title="Raw temperature", ylabel="Temperature (C)")
    axes[1].set(
        title="Raw vibration",
        xlabel="Timestamp",
        ylabel="Vibration (mm/s)",
    )
    axes[0].legend()
    axes[1].legend()
    figure.savefig("raw_telemetry.png", dpi=150, bbox_inches="tight")
    plt.show()

What does the plot show?

  • The two axes share one timestamp scale so the sensor events can be compared by time.
  • The upper plot displays temperature_c.
  • The lower plot displays vibration_mm_s.
  • The figure is saved as raw_telemetry.png before it is displayed in the notebook.

The generator plus its checks are ready. A temporary main() block now connects them into one runnable pipeline slice.

  • Place your cursor below the plot_raw_data() function in the source cell.
  • Paste the temporary main block at the bottom of the source cell:
def main():
    raw_records = generate_raw_data()
    print("Raw data quality:", quality_report(raw_records))

    raw_frame = pd.DataFrame(raw_records)
    raw_frame.to_csv("raw_telemetry.csv", index=False)
    plot_raw_data(raw_frame)


if __name__ == "__main__":
    main()

How does the pipeline run?

  • The main() function generates the raw records before printing their quality counts.
  • The DataFrame gives the records a table structure for exporting plus plotting.
  • The to_csv() call writes all 240 records to raw_telemetry.csv.
  • The final condition runs main() when the full source cell executes.

Before you run the completed cell, do you expect the chart to make both quality failures equally obvious?

  • Run the completed source cell.

You will see the raw quality report followed by two shared-timestamp plots. The temperature plot shows the generated trend while the vibration plot includes a sharp drop below its normal range.

  • Use the notebook's file browser to confirm the generated artifacts.

You will see raw_telemetry.csv plus raw_telemetry.png in the active Colab runtime. The CSV contains 240 raw records.

Missing a plot or output file?

Confirm that plot_raw_data(raw_frame) remains inside main() with one indentation level. Check that the final main() call remains beneath its condition.

Rerun the source cell after correcting the code. Refresh the notebook's file browser if the two filenames do not appear immediately.

Help me restore the missing SensorGuard plots or files.

✔️ Awesome, I've got everything!

Your source cell is complete. Confirm that the notebook has saved before moving on.

ⓧ I'd like to double check the full code

import math
import sqlite3

import matplotlib.pyplot as plt
import pandas as pd
from sklearn.ensemble import IsolationForest

ANOMALY_INDICES = {40, 120, 180, 220}
FEATURE_COLUMNS = [
    "temperature_c",
    "vibration_mm_s",
    "pressure_bar",
    "temperature_change",
]


def generate_raw_data():
    timestamps = pd.date_range(
        start="2026-01-01",
        periods=240,
        freq="h",
    )
    records = []

    for index, timestamp in enumerate(timestamps):
        temperature = 50 + (0.02 * index) + (1.5 * math.sin(index / 8))
        vibration = 2 + (0.001 * index) + (0.15 * math.cos(index / 6))
        pressure = 30 + (0.3 * math.sin(index / 10))

        if index == 40:
            temperature += 20
        elif index == 120:
            vibration += 5
        elif index == 180:
            temperature += 15
            vibration += 4
        elif index == 220:
            temperature -= 20

        if index == 15:
            temperature = None
        if index == 75:
            vibration = -1

        records.append(
            {
                "timestamp": timestamp,
                "temperature_c": temperature,
                "vibration_mm_s": vibration,
                "pressure_bar": pressure,
                "ground_truth_anomaly": int(index in ANOMALY_INDICES),
            }
        )

    return records


def quality_report(records):
    missing_temperature = sum(
        row["temperature_c"] is None for row in records
    )
    invalid_vibration = sum(
        row["vibration_mm_s"] is not None
        and row["vibration_mm_s"] < 0
        for row in records
    )
    return {
        "missing_temperature": missing_temperature,
        "invalid_vibration": invalid_vibration,
    }


def plot_raw_data(raw_frame):
    figure, axes = plt.subplots(
        2,
        1,
        figsize=(12, 6),
        sharex=True,
        layout="constrained",
    )
    axes[0].plot(
        raw_frame["timestamp"],
        raw_frame["temperature_c"],
        label="Temperature",
    )
    axes[1].plot(
        raw_frame["timestamp"],
        raw_frame["vibration_mm_s"],
        color="orange",
        label="Vibration",
    )
    axes[0].set(title="Raw temperature", ylabel="Temperature (C)")
    axes[1].set(
        title="Raw vibration",
        xlabel="Timestamp",
        ylabel="Vibration (mm/s)",
    )
    axes[0].legend()
    axes[1].legend()
    figure.savefig("raw_telemetry.png", dpi=150, bbox_inches="tight")
    plt.show()


def main():
    raw_records = generate_raw_data()
    print("Raw data quality:", quality_report(raw_records))

    raw_frame = pd.DataFrame(raw_records)
    raw_frame.to_csv("raw_telemetry.csv", index=False)
    plot_raw_data(raw_frame)


if __name__ == "__main__":
    main()

Your raw stream now exposes the exact failures that could weaken later analysis. Next, you will repair those records before loading trusted data into a database.

Clean, Validate, and Load the Data

Your Google Colab notebook already exposes the raw stream's data quality failures. Its quality report shows one missing temperature plus one impossible vibration reading.

Those bad readings must be repaired before analysis can trust them. This step applies ETL to produce validated records for queryable storage in SQLite.

In this step, get ready to:
  • Replace bad sensor values without changing the anomaly labels.
  • Engineer temperature_change for each cleaned record.
  • Load 240 validated rows into a queryable SQLite table.
Repair the invalid readings

Mean imputation fills a bad reading with the average of the valid readings from the same sensor. Each replacement uses a copied record so the injected anomaly label stays attached.

  • Switch back to the sensorguard.py source cell from the previous step.
  • Find def plot_raw_data(raw_frame): near the middle of the cell.
  • Paste the following function directly above that line:
def clean_records(records):
    valid_temperatures = [
        row["temperature_c"]
        for row in records
        if row["temperature_c"] is not None
    ]
    valid_vibrations = [
        row["vibration_mm_s"]
        for row in records
        if row["vibration_mm_s"] is not None
        and row["vibration_mm_s"] >= 0
    ]
    temperature_mean = sum(valid_temperatures) / len(valid_temperatures)
    vibration_mean = sum(valid_vibrations) / len(valid_vibrations)

    cleaned = []
    for row in records:
        clean_row = row.copy()
        if clean_row["temperature_c"] is None:
            clean_row["temperature_c"] = temperature_mean
        if (
            clean_row["vibration_mm_s"] is None
            or clean_row["vibration_mm_s"] < 0
        ):
            clean_row["vibration_mm_s"] = vibration_mean
        cleaned.append(clean_row)

    return cleaned

What does this code do?

  • The valid_temperatures list excludes the missing temperature before calculating its mean.
  • The valid_vibrations list excludes the negative vibration before calculating its mean.
  • The row.copy() call preserves every original field in a new record.
  • The two conditional checks replace only readings that fail the quality rules.

The cleaner now needs a runtime check. Calling it from main() lets the existing quality report measure the repaired records.

  • Scroll to main() at the bottom of the source cell.
  • Find plot_raw_data(raw_frame).
  • Paste the following lines directly below it:
    cleaned_records = clean_records(raw_records)
    print("Cleaned data quality:", quality_report(cleaned_records))

How does the check work?

The first line passes all 240 raw records through clean_records(). The next line applies the same quality rules to the repaired records.

  • Run the sensorguard.py source cell using the play icon on its left.

You'll see Cleaned data quality: {'missing_temperature': 0, 'invalid_vibration': 0} after the plots. Both deliberate quality failures are now repaired.

Still seeing a nonzero quality count?

Check that clean_records() appears above plot_raw_data(). Confirm that the two new lines sit inside main() with four spaces of indentation.

Run the entire source cell again after correcting the placement.

Help me debug the cleaned quality report.

Engineer a change feature and load SQLite

Feature engineering turns existing readings into signals that expose useful patterns. The absolute temperature change captures how sharply each reading moves from the previous hour.

  • Scroll to the end of clean_records().
  • Find its current final line:
    return cleaned

Why does this line move?

This return currently sends the repaired records back to main(). Moving it below the feature loop gives every record a temperature_change value first.

  • Replace that line with the following feature calculation:
    for index, row in enumerate(cleaned):
        if index == 0:
            row["temperature_change"] = 0.0
        else:
            row["temperature_change"] = abs(
                row["temperature_c"]
                - cleaned[index - 1]["temperature_c"]
            )

    return cleaned

How is the feature calculated?

  • The first record receives 0.0 because it has no previous reading.
  • Every later record stores the absolute difference from the previous cleaned temperature.
  • The final return sends records containing the repaired values plus the new feature.

The cleaned records are ready for SQL aggregation. The next function replaces the telemetry table with the current cleaned dataset each time the pipeline runs.

  • Find def main(): near the bottom of the source cell.
  • Paste the following function directly above that line:
def persist_with_sql(clean_frame):
    connection = sqlite3.connect("sensorguard.db")
    clean_frame.to_sql(
        name="telemetry",
        con=connection,
        if_exists="replace",
        index=False,
    )
    summary = pd.read_sql(
        """
        SELECT ground_truth_anomaly, COUNT(*) AS row_count
        FROM telemetry
        GROUP BY ground_truth_anomaly
        ORDER BY ground_truth_anomaly
        """,
        connection,
    )
    connection.close()
    return summary

What does the database function do?

  • The connection creates or opens sensorguard.db in the active runtime.
  • The to_sql() call replaces telemetry with the current cleaned DataFrame.
  • The grouped query counts normal rows separately from injected anomaly rows.
  • Closing the connection finishes the database operation before returning the summary.
  • Run the updated sensorguard.py source cell to register the new functions.

The plots display again. The cleaned quality report remains at zero for both checks.

A short verification cell can now build the cleaned pandas DataFrame. It also proves that the database preserves all 240 labels.

  • Create a new code cell directly below the sensorguard.py source cell.
  • Paste the following verification code into the new cell:
raw_records = generate_raw_data()
cleaned_records = clean_records(raw_records)
clean_frame = pd.DataFrame(cleaned_records)
sql_summary = persist_with_sql(clean_frame)
print("SQL row counts:")
print(sql_summary)

What does this check prove?

  • The first three lines reproduce the raw records as a cleaned 240-row DataFrame.
  • The database function writes that DataFrame into the telemetry table.
  • The final two lines expose the grouped counts returned by the SQL query.
  • Run the verification cell using the play icon on its left.

You'll see 236 rows where ground_truth_anomaly is 0. You'll also see 4 rows where it is 1.

That is the storage milestone complete: sensorguard.db now contains every cleaned record without losing the four injected anomaly labels.

Missing the SQL summary?

Confirm that you reran the source cell after adding persist_with_sql(). Check that the function appears above main().

If the two counts do not total 240, rerun the source cell before rerunning the verification cell.

Help me debug the SQLite row counts.

Wire the full pipeline together

The source cell should reproduce the database without relying on a separate verification cell. Adding the storage path to main() makes every complete run repeatable.

  • Return to main() in the sensorguard.py source cell.
  • Find print("Cleaned data quality:", quality_report(cleaned_records)).
  • Paste the following lines directly below it:
    clean_frame = pd.DataFrame(cleaned_records)
    sql_summary = persist_with_sql(clean_frame)
    print("SQL row counts:")
    print(sql_summary)

How does this complete the pipeline?

The cleaned records become a DataFrame before entering persist_with_sql(). The returned summary becomes visible during every full pipeline run.

  • Predict the two grouped row counts before rerunning the pipeline.
  • Run the complete sensorguard.py source cell using the play icon on its left.

You'll see zero missing temperatures plus zero invalid vibrations in the cleaned report. The SQL summary shows 236 normal rows plus 4 injected anomaly rows.

The source cell also recreates sensorguard.db with a six-column telemetry table. The sixth column is temperature_change.

Does the full run stop before the SQL output?

Check the indentation of the new lines inside main(). Confirm that persist_with_sql() appears before main().

Rerun the entire source cell after fixing the placement.

Help me debug the completed cleaning and SQL pipeline.

The complete source below is a reference for your final comparison.

✔️ Awesome, I've got everything!

Your source now cleans the raw readings, engineers the change feature, writes the SQLite table, and prints the grouped counts.

ⓧ I'd like to double check the full code

import math
import sqlite3

import matplotlib.pyplot as plt
import pandas as pd
from sklearn.ensemble import IsolationForest

ANOMALY_INDICES = {40, 120, 180, 220}
FEATURE_COLUMNS = [
    "temperature_c",
    "vibration_mm_s",
    "pressure_bar",
    "temperature_change",
]


def generate_raw_data():
    timestamps = pd.date_range(
        start="2026-01-01",
        periods=240,
        freq="h",
    )
    records = []

    for index, timestamp in enumerate(timestamps):
        temperature = 50 + (0.02 * index) + (1.5 * math.sin(index / 8))
        vibration = 2 + (0.001 * index) + (0.15 * math.cos(index / 6))
        pressure = 30 + (0.3 * math.sin(index / 10))

        if index == 40:
            temperature += 20
        elif index == 120:
            vibration += 5
        elif index == 180:
            temperature += 15
            vibration += 4
        elif index == 220:
            temperature -= 20

        if index == 15:
            temperature = None
        if index == 75:
            vibration = -1

        records.append(
            {
                "timestamp": timestamp,
                "temperature_c": temperature,
                "vibration_mm_s": vibration,
                "pressure_bar": pressure,
                "ground_truth_anomaly": int(index in ANOMALY_INDICES),
            }
        )

    return records


def quality_report(records):
    missing_temperature = sum(
        row["temperature_c"] is None for row in records
    )
    invalid_vibration = sum(
        row["vibration_mm_s"] is not None
        and row["vibration_mm_s"] < 0
        for row in records
    )
    return {
        "missing_temperature": missing_temperature,
        "invalid_vibration": invalid_vibration,
    }


def clean_records(records):
    valid_temperatures = [
        row["temperature_c"]
        for row in records
        if row["temperature_c"] is not None
    ]
    valid_vibrations = [
        row["vibration_mm_s"]
        for row in records
        if row["vibration_mm_s"] is not None
        and row["vibration_mm_s"] >= 0
    ]
    temperature_mean = sum(valid_temperatures) / len(valid_temperatures)
    vibration_mean = sum(valid_vibrations) / len(valid_vibrations)

    cleaned = []
    for row in records:
        clean_row = row.copy()
        if clean_row["temperature_c"] is None:
            clean_row["temperature_c"] = temperature_mean
        if (
            clean_row["vibration_mm_s"] is None
            or clean_row["vibration_mm_s"] < 0
        ):
            clean_row["vibration_mm_s"] = vibration_mean
        cleaned.append(clean_row)

    for index, row in enumerate(cleaned):
        if index == 0:
            row["temperature_change"] = 0.0
        else:
            row["temperature_change"] = abs(
                row["temperature_c"]
                - cleaned[index - 1]["temperature_c"]
            )

    return cleaned


def plot_raw_data(raw_frame):
    figure, axes = plt.subplots(
        2,
        1,
        figsize=(12, 6),
        sharex=True,
        layout="constrained",
    )
    axes[0].plot(
        raw_frame["timestamp"],
        raw_frame["temperature_c"],
        label="Temperature",
    )
    axes[1].plot(
        raw_frame["timestamp"],
        raw_frame["vibration_mm_s"],
        color="orange",
        label="Vibration",
    )
    axes[0].set(title="Raw temperature", ylabel="Temperature (C)")
    axes[1].set(
        title="Raw vibration",
        xlabel="Timestamp",
        ylabel="Vibration (mm/s)",
    )
    axes[0].legend()
    axes[1].legend()
    figure.savefig("raw_telemetry.png", dpi=150, bbox_inches="tight")
    plt.show()


def persist_with_sql(clean_frame):
    connection = sqlite3.connect("sensorguard.db")
    clean_frame.to_sql(
        name="telemetry",
        con=connection,
        if_exists="replace",
        index=False,
    )
    summary = pd.read_sql(
        """
        SELECT ground_truth_anomaly, COUNT(*) AS row_count
        FROM telemetry
        GROUP BY ground_truth_anomaly
        ORDER BY ground_truth_anomaly
        """,
        connection,
    )
    connection.close()
    return summary


def main():
    raw_records = generate_raw_data()
    print("Raw data quality:", quality_report(raw_records))

    raw_frame = pd.DataFrame(raw_records)
    raw_frame.to_csv("raw_telemetry.csv", index=False)
    plot_raw_data(raw_frame)

    cleaned_records = clean_records(raw_records)
    print("Cleaned data quality:", quality_report(cleaned_records))

    clean_frame = pd.DataFrame(cleaned_records)
    sql_summary = persist_with_sql(clean_frame)
    print("SQL row counts:")
    print(sql_summary)


if __name__ == "__main__":
    main()

Your pipeline now produces trusted telemetry in a queryable database. Next, you'll test a simple detector against the four preserved anomaly labels.

Measure the Baseline Detector

Your pipeline now repairs the bad readings and stores 240 validated rows in SQLite. You have trusted data for measuring a detector.

A temperature-only threshold sees one sensor signal. Precision and recall measure how its alerts compare with all four known anomalies.

In this step, get ready to:
  • Create anomaly predictions using a temperature threshold of 60.
  • Calculate true positives, false positives, false negatives, precision, and recall.
  • Run the baseline against the four injected anomalies and identify its blind spots.
Create temperature-only predictions

A baseline is a simple method that gives you a reference point for later models. This baseline labels a reading as anomalous when its temperature exceeds 60.

  • Find the closing return summary line in persist_with_sql().
  • Place the baseline function below persist_with_sql() by pasting this code:
def naive_predictions(clean_frame):
    return [
        int(temperature > 60)
        for temperature in clean_frame["temperature_c"]
    ]

What does this function do?

  • The function reads every value from the temperature_c column.
  • The comparison produces 1 for temperatures above the threshold.
  • Every other temperature receives 0.
  • Run the sensorguard.py source cell to check that Python accepts the function.

You should see the raw plots and SQL row counts complete without a syntax error.

Seeing a syntax error?

Check that naive_predictions() sits below the closing line of persist_with_sql(). Make sure its body remains indented by four spaces.

Still stuck? Help me check the indentation in my naive_predictions function.

Calculate the evaluation metrics

The known anomaly labels let you compare predictions with the events deliberately injected into the telemetry. Start by counting the three outcomes that determine precision and recall.

  • Place a new compute_metrics() function below naive_predictions() by pasting this first section:
def compute_metrics(true_labels, predicted_labels):
    true_positives = sum(
        truth == 1 and prediction == 1
        for truth, prediction in zip(true_labels, predicted_labels)
    )
    false_positives = sum(
        truth == 0 and prediction == 1
        for truth, prediction in zip(true_labels, predicted_labels)
    )
    false_negatives = sum(
        truth == 1 and prediction == 0
        for truth, prediction in zip(true_labels, predicted_labels)
    )

What do these counts measure?

  • A true positive is a labeled anomaly that the baseline catches.
  • A false positive is a normal reading that the baseline flags.
  • A false negative is a labeled anomaly that the baseline misses.
  • Run the sensorguard.py source cell to verify that the three counting expressions are valid.

You should see the existing quality report and SQL summary finish successfully.

Does the counting section fail?

Check that each sum() expression has a closing parenthesis. Confirm that all three expressions remain inside compute_metrics().

Need another pair of eyes? Help me debug the metric-counting expressions.

The three counts can now be converted into rates. Precision measures alert correctness. Recall measures anomaly coverage.

  • Continue compute_metrics() directly below the false_negatives calculation by pasting this code:
    precision = (
        true_positives / (true_positives + false_positives)
        if true_positives + false_positives
        else 0.0
    )
    recall = (
        true_positives / (true_positives + false_negatives)
        if true_positives + false_negatives
        else 0.0
    )
    return {
        "true_positives": true_positives,
        "false_positives": false_positives,
        "false_negatives": false_negatives,
        "precision": round(precision, 2),
        "recall": round(recall, 2),
    }

How are the rates calculated?

  • Precision divides true positives by every alert raised by the detector.
  • Recall divides true positives by every labeled anomaly in the data.
  • The conditional expressions prevent division by zero when a detector raises no alerts or encounters no labeled anomalies.
  • The returned dictionary rounds both rates to two decimal places for a readable comparison.
  • Run the sensorguard.py source cell to confirm that the completed function is valid.

You should see the existing pipeline finish without an indentation or syntax error.

Is the completed function failing?

Make sure the precision calculation, recall calculation, and returned dictionary all have four spaces of indentation. Check that the closing brace aligns with return.

Still seeing a problem? Help me inspect my compute_metrics function.

Run the baseline and inspect its misses

The two functions become useful when the cleaned labels and predictions meet inside main(). This run measures the threshold against every injected anomaly.

  • Find print(sql_summary) near the end of main().
  • Place the baseline evaluation below print(sql_summary) by pasting this code:
    clean_frame["naive_anomaly"] = naive_predictions(clean_frame)
    true_labels = list(clean_frame["ground_truth_anomaly"])
    print(
        "Naive detector:",
        compute_metrics(true_labels, clean_frame["naive_anomaly"]),
    )

What does the baseline evaluation do?

  • The naive_anomaly column stores one threshold prediction for each cleaned row.
  • The true_labels list preserves the four injected anomaly labels used as the comparison.
  • The final call prints the three counts plus precision and recall.

Before you run the cell, ask yourself whether one temperature threshold can catch all four anomaly patterns.

  • Run the completed sensorguard.py source cell.

The baseline output should show 2 true positives, 0 false positives, and 2 false negatives. You should also see precision of 1.0 and recall of 0.5.

Why does perfect precision still leave gaps?

Precision of 1.0 means every alert raised by the threshold matches a labeled anomaly. Recall of 0.5 means it catches only two of the four labeled anomalies.

The threshold catches the high-temperature events at indices 40 and 180. It misses the vibration-only event at index 120.

It also misses the unusually low temperature at index 220. This intended shortfall proves that alert correctness and anomaly coverage answer different questions.

🙋‍♀️ Baseline metrics look different?

Check that naive_predictions() uses temperature > 60. Confirm that true_labels comes from the ground_truth_anomaly column.

Check that the baseline evaluation runs after clean_frame is created. Help me trace why my baseline metrics differ from the expected result.

✔️ Awesome, I've got everything!

Your source now creates the baseline labels and prints the measured detector performance. Keep the updated sensorguard.py source in your notebook.

ⓧ I'd like to double check the full code

import math
import sqlite3

import matplotlib.pyplot as plt
import pandas as pd
from sklearn.ensemble import IsolationForest

ANOMALY_INDICES = {40, 120, 180, 220}
FEATURE_COLUMNS = [
    "temperature_c",
    "vibration_mm_s",
    "pressure_bar",
    "temperature_change",
]


def generate_raw_data():
    timestamps = pd.date_range(
        start="2026-01-01",
        periods=240,
        freq="h",
    )
    records = []

    for index, timestamp in enumerate(timestamps):
        temperature = 50 + (0.02 * index) + (1.5 * math.sin(index / 8))
        vibration = 2 + (0.001 * index) + (0.15 * math.cos(index / 6))
        pressure = 30 + (0.3 * math.sin(index / 10))

        if index == 40:
            temperature += 20
        elif index == 120:
            vibration += 5
        elif index == 180:
            temperature += 15
            vibration += 4
        elif index == 220:
            temperature -= 20

        if index == 15:
            temperature = None
        if index == 75:
            vibration = -1

        records.append(
            {
                "timestamp": timestamp,
                "temperature_c": temperature,
                "vibration_mm_s": vibration,
                "pressure_bar": pressure,
                "ground_truth_anomaly": int(index in ANOMALY_INDICES),
            }
        )

    return records


def quality_report(records):
    missing_temperature = sum(
        row["temperature_c"] is None for row in records
    )
    invalid_vibration = sum(
        row["vibration_mm_s"] is not None
        and row["vibration_mm_s"] < 0
        for row in records
    )
    return {
        "missing_temperature": missing_temperature,
        "invalid_vibration": invalid_vibration,
    }


def clean_records(records):
    valid_temperatures = [
        row["temperature_c"]
        for row in records
        if row["temperature_c"] is not None
    ]
    valid_vibrations = [
        row["vibration_mm_s"]
        for row in records
        if row["vibration_mm_s"] is not None
        and row["vibration_mm_s"] >= 0
    ]
    temperature_mean = sum(valid_temperatures) / len(valid_temperatures)
    vibration_mean = sum(valid_vibrations) / len(valid_vibrations)

    cleaned = []
    for row in records:
        clean_row = row.copy()
        if clean_row["temperature_c"] is None:
            clean_row["temperature_c"] = temperature_mean
        if (
            clean_row["vibration_mm_s"] is None
            or clean_row["vibration_mm_s"] < 0
        ):
            clean_row["vibration_mm_s"] = vibration_mean
        cleaned.append(clean_row)

    for index, row in enumerate(cleaned):
        if index == 0:
            row["temperature_change"] = 0.0
        else:
            row["temperature_change"] = abs(
                row["temperature_c"]
                - cleaned[index - 1]["temperature_c"]
            )

    return cleaned


def plot_raw_data(raw_frame):
    figure, axes = plt.subplots(
        2,
        1,
        figsize=(12, 6),
        sharex=True,
        layout="constrained",
    )
    axes[0].plot(
        raw_frame["timestamp"],
        raw_frame["temperature_c"],
        label="Temperature",
    )
    axes[1].plot(
        raw_frame["timestamp"],
        raw_frame["vibration_mm_s"],
        color="orange",
        label="Vibration",
    )
    axes[0].set(title="Raw temperature", ylabel="Temperature (C)")
    axes[1].set(
        title="Raw vibration",
        xlabel="Timestamp",
        ylabel="Vibration (mm/s)",
    )
    axes[0].legend()
    axes[1].legend()
    figure.savefig("raw_telemetry.png", dpi=150, bbox_inches="tight")
    plt.show()


def persist_with_sql(clean_frame):
    connection = sqlite3.connect("sensorguard.db")
    clean_frame.to_sql(
        name="telemetry",
        con=connection,
        if_exists="replace",
        index=False,
    )
    summary = pd.read_sql(
        """
        SELECT ground_truth_anomaly, COUNT(*) AS row_count
        FROM telemetry
        GROUP BY ground_truth_anomaly
        ORDER BY ground_truth_anomaly
        """,
        connection,
    )
    connection.close()
    return summary


def naive_predictions(clean_frame):
    return [
        int(temperature > 60)
        for temperature in clean_frame["temperature_c"]
    ]


def compute_metrics(true_labels, predicted_labels):
    true_positives = sum(
        truth == 1 and prediction == 1
        for truth, prediction in zip(true_labels, predicted_labels)
    )
    false_positives = sum(
        truth == 0 and prediction == 1
        for truth, prediction in zip(true_labels, predicted_labels)
    )
    false_negatives = sum(
        truth == 1 and prediction == 0
        for truth, prediction in zip(true_labels, predicted_labels)
    )
    precision = (
        true_positives / (true_positives + false_positives)
        if true_positives + false_positives
        else 0.0
    )
    recall = (
        true_positives / (true_positives + false_negatives)
        if true_positives + false_negatives
        else 0.0
    )
    return {
        "true_positives": true_positives,
        "false_positives": false_positives,
        "false_negatives": false_negatives,
        "precision": round(precision, 2),
        "recall": round(recall, 2),
    }


def main():
    raw_records = generate_raw_data()
    print("Raw data quality:", quality_report(raw_records))

    raw_frame = pd.DataFrame(raw_records)
    raw_frame.to_csv("raw_telemetry.csv", index=False)
    plot_raw_data(raw_frame)

    cleaned_records = clean_records(raw_records)
    print("Cleaned data quality:", quality_report(cleaned_records))

    clean_frame = pd.DataFrame(cleaned_records)
    sql_summary = persist_with_sql(clean_frame)
    print("SQL row counts:")
    print(sql_summary)

    clean_frame["naive_anomaly"] = naive_predictions(clean_frame)
    true_labels = list(clean_frame["ground_truth_anomaly"])
    print(
        "Naive detector:",
        compute_metrics(true_labels, clean_frame["naive_anomaly"]),
    )


if __name__ == "__main__":
    main()

You found the detector's blind spot: its alerts are accurate, but half of the known anomalies remain invisible. Next up, you will evaluate several sensor signals together and produce anomaly scores a reviewer can inspect.

Build the ML Detector and Publish the Project

Your Google Colab notebook now proves that the temperature threshold has perfect precision. Its recall stays at 0.5 because two unusual events remain invisible.

An IsolationForest can evaluate several sensor signals together. You will add that detector before publishing the complete pipeline on GitHub.

In this step, get ready to:
  • Train a multivariate detector using the cleaned sensor features.
  • Export scored telemetry plus a visual anomaly report.
  • Publish the runnable pipeline with its documentation.
Train the multivariate detector

The baseline checks one temperature rule. The new model uses temperature, vibration, pressure, plus temperature change to identify unusual combinations.

Why IsolationForest?

A threshold works well when one known boundary defines the problem. IsolationForest can score patterns across every column in FEATURE_COLUMNS.

The project still uses the injected labels to measure the result. This gives you a direct comparison with the baseline.

  • Return to the sensorguard.py source in your Colab notebook.
  • Add build_model() after compute_metrics() by pasting this function:
def build_model(clean_frame):
    model = IsolationForest(
        n_estimators=100,
        contamination=len(ANOMALY_INDICES) / len(clean_frame),
        random_state=42,
    )
    raw_predictions = model.fit_predict(clean_frame[FEATURE_COLUMNS])
    predictions = [
        int(prediction == -1) for prediction in raw_predictions
    ]
    anomaly_scores = [
        -score
        for score in model.decision_function(clean_frame[FEATURE_COLUMNS])
    ]
    return model, predictions, anomaly_scores

What does this code do?

  • The model uses 100 estimators to compare each reading across the four selected features.
  • The contamination value tells the model that four rows out of 240 are expected to be unusual.
  • The fixed random state makes repeated runs reproducible.
  • The prediction conversion turns model outliers into binary anomaly labels.
  • The score inversion makes larger values represent more unusual readings.
  • Find the baseline metrics block inside main().
  • Extend main() immediately below that block by pasting:
    model, predictions, anomaly_scores = build_model(clean_frame)
    clean_frame["ml_anomaly"] = predictions
    clean_frame["anomaly_score"] = anomaly_scores
    print(
        "IsolationForest detector:",
        compute_metrics(true_labels, clean_frame["ml_anomaly"]),
    )
    print("IsolationForest trees:", model.n_estimators)

How does the model reach the report?

  • The returned predictions become the ml_anomaly column.
  • The inverted scores become the anomaly_score column.
  • The existing metric function compares the model labels with the injected ground truth.
  • The final print confirms that the fitted model contains 100 estimators.

Before you run the cell, do you expect a multivariate model to catch patterns that the temperature threshold missed?

  • Select the source cell's run icon to execute the expanded pipeline.

You will see a new line beginning with IsolationForest detector:. You will also see IsolationForest trees: 100.

That closes the baseline blind spot. SensorGuard can now evaluate all four sensor features through one reproducible model.

Missing the detector metrics?

Check that build_model() appears above main().

Check that the new model block remains indented inside main().

Need another pair of eyes? Help me debug the missing IsolationForest output.

Export the scored anomaly report

Model metrics summarize performance with numbers. A chart makes the flagged readings visible to someone reviewing the project.

  • Add plot_detection() after build_model() by pasting this function:
def plot_detection(clean_frame):
    detected = clean_frame[clean_frame["ml_anomaly"] == 1]
    figure, axis = plt.subplots(
        figsize=(12, 5),
        layout="constrained",
    )
    axis.plot(
        clean_frame["timestamp"],
        clean_frame["temperature_c"],
        label="Temperature",
    )
    axis.scatter(
        detected["timestamp"],
        detected["temperature_c"],
        color="red",
        s=50,
        label="ML anomaly",
    )
    axis.set(
        title="SensorGuard anomaly report",
        xlabel="Timestamp",
        ylabel="Temperature (C)",
    )
    axis.legend()
    figure.savefig("anomaly_report.png", dpi=150, bbox_inches="tight")
    plt.show()

What does this chart show?

  • The filtered detected frame contains only rows where ml_anomaly equals 1.
  • The line shows cleaned temperature across the full timeline.
  • The red markers identify readings selected by the ML detector.
  • The figure is saved as anomaly_report.png before it is displayed.
  • Find print("IsolationForest trees:", model.n_estimators) inside main().
  • Extend the export stage directly below that line by pasting:
    clean_frame.to_csv("clean_telemetry.csv", index=False)
    anomalies = clean_frame[clean_frame["ml_anomaly"] == 1]
    anomalies.to_csv("anomalies.csv", index=False)
    plot_detection(clean_frame)

    print(
        "Created raw_telemetry.csv, clean_telemetry.csv, "
        "anomalies.csv, sensorguard.db, raw_telemetry.png, "
        "and anomaly_report.png"
    )

What gets exported?

  • The cleaned CSV contains every validated row plus the baseline label, ML label, plus anomaly score.
  • The anomaly CSV contains only rows selected by the ML detector.
  • The chart function creates the final PNG report.
  • The closing message lists every artifact created by the complete pipeline.

Before you run the completed cell, which outputs do you expect to contain only ML-flagged rows?

  • Select the source cell's run icon to execute the completed pipeline.
  • Expand the notebook's file browser after the cell finishes.

You will see the raw plots followed by the SensorGuard anomaly report. The final chart contains red markers for readings where ml_anomaly equals 1.

The file browser now contains raw_telemetry.csv, clean_telemetry.csv, anomalies.csv, sensorguard.db, raw_telemetry.png, plus anomaly_report.png.

Missing the anomaly report?

Check that plot_detection(clean_frame) appears after the anomaly CSV export inside main().

Check that the chart function filters the exact ml_anomaly column created by the model block.

Still missing an output? Help me debug my SensorGuard export stage.

Use this comparison to confirm that your Colab source matches the complete pipeline before publishing it.

✔️ Awesome, I've got everything!

Your source now trains the ML detector, exports its scores, plus creates the final anomaly chart.

ⓧ I'd like to double check the full code

import math
import sqlite3

import matplotlib.pyplot as plt
import pandas as pd
from sklearn.ensemble import IsolationForest

ANOMALY_INDICES = {40, 120, 180, 220}
FEATURE_COLUMNS = [
    "temperature_c",
    "vibration_mm_s",
    "pressure_bar",
    "temperature_change",
]


def generate_raw_data():
    timestamps = pd.date_range(
        start="2026-01-01",
        periods=240,
        freq="h",
    )
    records = []

    for index, timestamp in enumerate(timestamps):
        temperature = 50 + (0.02 * index) + (1.5 * math.sin(index / 8))
        vibration = 2 + (0.001 * index) + (0.15 * math.cos(index / 6))
        pressure = 30 + (0.3 * math.sin(index / 10))

        if index == 40:
            temperature += 20
        elif index == 120:
            vibration += 5
        elif index == 180:
            temperature += 15
            vibration += 4
        elif index == 220:
            temperature -= 20

        if index == 15:
            temperature = None
        if index == 75:
            vibration = -1

        records.append(
            {
                "timestamp": timestamp,
                "temperature_c": temperature,
                "vibration_mm_s": vibration,
                "pressure_bar": pressure,
                "ground_truth_anomaly": int(index in ANOMALY_INDICES),
            }
        )

    return records


def quality_report(records):
    missing_temperature = sum(
        row["temperature_c"] is None for row in records
    )
    invalid_vibration = sum(
        row["vibration_mm_s"] is not None
        and row["vibration_mm_s"] < 0
        for row in records
    )
    return {
        "missing_temperature": missing_temperature,
        "invalid_vibration": invalid_vibration,
    }


def clean_records(records):
    valid_temperatures = [
        row["temperature_c"]
        for row in records
        if row["temperature_c"] is not None
    ]
    valid_vibrations = [
        row["vibration_mm_s"]
        for row in records
        if row["vibration_mm_s"] is not None
        and row["vibration_mm_s"] >= 0
    ]
    temperature_mean = sum(valid_temperatures) / len(valid_temperatures)
    vibration_mean = sum(valid_vibrations) / len(valid_vibrations)

    cleaned = []
    for row in records:
        clean_row = row.copy()
        if clean_row["temperature_c"] is None:
            clean_row["temperature_c"] = temperature_mean
        if (
            clean_row["vibration_mm_s"] is None
            or clean_row["vibration_mm_s"] < 0
        ):
            clean_row["vibration_mm_s"] = vibration_mean
        cleaned.append(clean_row)

    for index, row in enumerate(cleaned):
        if index == 0:
            row["temperature_change"] = 0.0
        else:
            row["temperature_change"] = abs(
                row["temperature_c"]
                - cleaned[index - 1]["temperature_c"]
            )

    return cleaned


def plot_raw_data(raw_frame):
    figure, axes = plt.subplots(
        2,
        1,
        figsize=(12, 6),
        sharex=True,
        layout="constrained",
    )
    axes[0].plot(
        raw_frame["timestamp"],
        raw_frame["temperature_c"],
        label="Temperature",
    )
    axes[1].plot(
        raw_frame["timestamp"],
        raw_frame["vibration_mm_s"],
        color="orange",
        label="Vibration",
    )
    axes[0].set(title="Raw temperature", ylabel="Temperature (C)")
    axes[1].set(
        title="Raw vibration",
        xlabel="Timestamp",
        ylabel="Vibration (mm/s)",
    )
    axes[0].legend()
    axes[1].legend()
    figure.savefig("raw_telemetry.png", dpi=150, bbox_inches="tight")
    plt.show()


def persist_with_sql(clean_frame):
    connection = sqlite3.connect("sensorguard.db")
    clean_frame.to_sql(
        name="telemetry",
        con=connection,
        if_exists="replace",
        index=False,
    )
    summary = pd.read_sql(
        """
        SELECT ground_truth_anomaly, COUNT(*) AS row_count
        FROM telemetry
        GROUP BY ground_truth_anomaly
        ORDER BY ground_truth_anomaly
        """,
        connection,
    )
    connection.close()
    return summary


def naive_predictions(clean_frame):
    return [
        int(temperature > 60)
        for temperature in clean_frame["temperature_c"]
    ]


def compute_metrics(true_labels, predicted_labels):
    true_positives = sum(
        truth == 1 and prediction == 1
        for truth, prediction in zip(true_labels, predicted_labels)
    )
    false_positives = sum(
        truth == 0 and prediction == 1
        for truth, prediction in zip(true_labels, predicted_labels)
    )
    false_negatives = sum(
        truth == 1 and prediction == 0
        for truth, prediction in zip(true_labels, predicted_labels)
    )
    precision = (
        true_positives / (true_positives + false_positives)
        if true_positives + false_positives
        else 0.0
    )
    recall = (
        true_positives / (true_positives + false_negatives)
        if true_positives + false_negatives
        else 0.0
    )
    return {
        "true_positives": true_positives,
        "false_positives": false_positives,
        "false_negatives": false_negatives,
        "precision": round(precision, 2),
        "recall": round(recall, 2),
    }


def build_model(clean_frame):
    model = IsolationForest(
        n_estimators=100,
        contamination=len(ANOMALY_INDICES) / len(clean_frame),
        random_state=42,
    )
    raw_predictions = model.fit_predict(clean_frame[FEATURE_COLUMNS])
    predictions = [
        int(prediction == -1) for prediction in raw_predictions
    ]
    anomaly_scores = [
        -score
        for score in model.decision_function(clean_frame[FEATURE_COLUMNS])
    ]
    return model, predictions, anomaly_scores


def plot_detection(clean_frame):
    detected = clean_frame[clean_frame["ml_anomaly"] == 1]
    figure, axis = plt.subplots(
        figsize=(12, 5),
        layout="constrained",
    )
    axis.plot(
        clean_frame["timestamp"],
        clean_frame["temperature_c"],
        label="Temperature",
    )
    axis.scatter(
        detected["timestamp"],
        detected["temperature_c"],
        color="red",
        s=50,
        label="ML anomaly",
    )
    axis.set(
        title="SensorGuard anomaly report",
        xlabel="Timestamp",
        ylabel="Temperature (C)",
    )
    axis.legend()
    figure.savefig("anomaly_report.png", dpi=150, bbox_inches="tight")
    plt.show()


def main():
    raw_records = generate_raw_data()
    print("Raw data quality:", quality_report(raw_records))

    raw_frame = pd.DataFrame(raw_records)
    raw_frame.to_csv("raw_telemetry.csv", index=False)
    plot_raw_data(raw_frame)

    cleaned_records = clean_records(raw_records)
    print("Cleaned data quality:", quality_report(cleaned_records))

    clean_frame = pd.DataFrame(cleaned_records)
    sql_summary = persist_with_sql(clean_frame)
    print("SQL row counts:")
    print(sql_summary)

    clean_frame["naive_anomaly"] = naive_predictions(clean_frame)
    true_labels = list(clean_frame["ground_truth_anomaly"])
    print(
        "Naive detector:",
        compute_metrics(true_labels, clean_frame["naive_anomaly"]),
    )

    model, predictions, anomaly_scores = build_model(clean_frame)
    clean_frame["ml_anomaly"] = predictions
    clean_frame["anomaly_score"] = anomaly_scores
    print(
        "IsolationForest detector:",
        compute_metrics(true_labels, clean_frame["ml_anomaly"]),
    )
    print("IsolationForest trees:", model.n_estimators)

    clean_frame.to_csv("clean_telemetry.csv", index=False)
    anomalies = clean_frame[clean_frame["ml_anomaly"] == 1]
    anomalies.to_csv("anomalies.csv", index=False)
    plot_detection(clean_frame)

    print(
        "Created raw_telemetry.csv, clean_telemetry.csv, "
        "anomalies.csv, sensorguard.db, raw_telemetry.png, "
        "and anomaly_report.png"
    )


if __name__ == "__main__":
    main()
Publish the repository

The pipeline now produces evidence a reviewer can inspect. A public repository packages that evidence with setup instructions plus an explanation of the baseline comparison.

  • Switch back to GitHub in your browser.
  • Select New repository.
  • Enter sensorguard-anomaly-pipeline in the Repository name field.
  • Select Public.
  • Enable Add README.
  • Select Create repository.

You will arrive at the new repository page with a starter README.md file. The repository is now ready to receive the runnable source.

  • Select Add file above the repository file list.
  • Select Create new file.
  • Enter sensorguard.py in the filename field.
  • Switch back to the completed Colab source cell.
  • Copy the complete SensorGuard source.
  • Return to the GitHub file editor.
  • Paste the source into the file editor.
  • Select Commit changes.

The repository file list now contains sensorguard.py beside the starter README. Your runnable pipeline is published.

Source file missing from GitHub?

Check that the filename is exactly sensorguard.py.

Return to the file editor if the commit was not completed.

Need help with the browser workflow? Help me publish sensorguard.py in my GitHub repository.

The README explains why the project matters before a reviewer reads the source. You will build it in three short sections so each part is easy to check.

  • Select README.md from the repository file list.
  • Choose the file's edit control.
  • Select the starter README text.
  • Delete the selected text.
  • Add the project summary by pasting this first section:
# SensorGuard

SensorGuard is a reproducible data and machine-learning pipeline that generates equipment telemetry, validates and cleans bad records, stores trusted data in SQLite, and detects unusual readings with IsolationForest.

## What it demonstrates

- Python data validation and feature engineering
- CSV and SQLite data pipelines
- SQL aggregation
- Baseline comparison using precision and recall
- Multivariate anomaly detection
- Reproducible visual reports

What does this section communicate?

The opening sentence states what SensorGuard does. The capability list gives reviewers a quick view of the engineering skills demonstrated by the project.

  • Use the editor's rendered preview to review the first README section.

You will see a SensorGuard heading followed by a project summary plus six demonstrated capabilities.

README formatting look flat?

Check that the title starts with one hash character.

Check that every capability starts with a hyphen.

Need help with the Markdown structure? Help me fix the first section of my SensorGuard README.

  • Return to the README editing view.
  • Append the setup instructions plus output reference by pasting:


## Setup

Use Python 3.12.13 and install the pinned dependencies:

```bash
pip install pandas==3.0.6 scikit-learn==1.9.1 matplotlib==3.11.2
```

## Run

```bash
python sensorguard.py
```

## Outputs

- `raw_telemetry.csv`: generated telemetry before cleaning
- `clean_telemetry.csv`: validated data with predictions and scores
- `anomalies.csv`: records flagged by the ML detector
- `sensorguard.db`: SQLite database containing the cleaned telemetry table
- `raw_telemetry.png`: raw temperature and vibration plots
- `anomaly_report.png`: final anomaly visualization

Why include these details?

The setup section records the pinned environment. The run section gives a direct execution command.

The output list connects each generated filename to its purpose. A reviewer can reproduce the pipeline without guessing which artifacts matter.

  • Use the rendered preview to review the setup section.

You will see two formatted command blocks followed by a six-item output list.

Commands not showing as blocks?

Check the opening plus closing code fences around each command.

Check that the output filenames remain wrapped in backticks.

Need help with the rendered README? Help me fix the command blocks in my SensorGuard README.

  • Return to the README editing view.
  • Append the evaluation plus reproducibility notes by pasting:


## Evaluation

The project first tests a temperature-only threshold. That baseline misses the vibration-only and low-temperature events. IsolationForest then evaluates temperature, vibration, pressure, and temperature change together.

The data is synthetic and deterministic, so the pipeline can be reproduced without external credentials or dataset licensing.

What does the ending prove?

The evaluation note explains the baseline's blind spot. It also identifies the additional signals evaluated by the ML detector.

The closing note states where the data comes from. It makes the project's reproducibility boundary clear.

  • Use the rendered preview to review the completed README.

You will see an Evaluation heading followed by the baseline comparison plus the reproducibility note.

Evaluation section missing?

Check that the new section begins after the final output item.

Check that ## Evaluation appears on its own line.

Need help checking the final section? Help me fix the Evaluation section in my README.

Compare the complete README before you commit the replacement.

✔️ Awesome, I've got everything!

Your README covers setup, execution, outputs, evaluation, plus reproducibility.

ⓧ I'd like to double check the full code

# SensorGuard

SensorGuard is a reproducible data and machine-learning pipeline that generates equipment telemetry, validates and cleans bad records, stores trusted data in SQLite, and detects unusual readings with IsolationForest.

## What it demonstrates

- Python data validation and feature engineering
- CSV and SQLite data pipelines
- SQL aggregation
- Baseline comparison using precision and recall
- Multivariate anomaly detection
- Reproducible visual reports

## Setup

Use Python 3.12.13 and install the pinned dependencies:

```bash
pip install pandas==3.0.6 scikit-learn==1.9.1 matplotlib==3.11.2
```

## Run

```bash
python sensorguard.py
```

## Outputs

- `raw_telemetry.csv`: generated telemetry before cleaning
- `clean_telemetry.csv`: validated data with predictions and scores
- `anomalies.csv`: records flagged by the ML detector
- `sensorguard.db`: SQLite database containing the cleaned telemetry table
- `raw_telemetry.png`: raw temperature and vibration plots
- `anomaly_report.png`: final anomaly visualization

## Evaluation

The project first tests a temperature-only threshold. That baseline misses the vibration-only and low-temperature events. IsolationForest then evaluates temperature, vibration, pressure, and temperature change together.

The data is synthetic and deterministic, so the pipeline can be reproduced without external credentials or dataset licensing.

Before you commit the README, which two files should appear together when you return to the repository page?

  • Select Commit changes to save the completed README.
  • Select Commit changes again if GitHub requests confirmation.
  • Return to the repository file list after the commit finishes.

You will see sensorguard.py plus README.md in the public sensorguard-anomaly-pipeline repository. The README displays the setup, run command, outputs, evaluation, plus reproducibility note.

You have published a complete data pipeline with measured baseline limitations, multivariate anomaly scores, plus inspectable output artifacts. A reviewer can now understand the project before opening the source.

Secret mission

Stress-Test the Detector with Sensor Drift

Shift SensorGuard's normal temperature range after row 160. Reuse the fitted detector to measure how distribution drift changes its alert volume.

Clean Up Your Resources

Clean Up Your Resources

Decide whether to keep your SensorGuard resources, pause your work, or delete the persistent copies. Google Colab free compute and GitHub Free keep this project path at $0.

Resources you used:

  • Your SensorGuard notebook in Google Drive.
  • Your public sensorguard-anomaly-pipeline GitHub repository containing sensorguard.py, drift_test.py, and README.md.
  • The sensorguard.py and drift_test.py source files in the temporary Colab runtime.
  • Your generated CSV files in the temporary Colab runtime: raw_telemetry.csv, clean_telemetry.csv, and anomalies.csv.
  • Your SQLite database in the temporary Colab runtime: sensorguard.db.
  • Your PNG reports in the temporary Colab runtime: raw_telemetry.png and anomaly_report.png.

Keep everything running

No action needed. Choose this if you want to rerun the pipeline or compare more drift magnitudes.

  • Keep the SensorGuard notebook in Google Drive.
  • Keep the public sensorguard-anomaly-pipeline repository on GitHub.
  • Use the notebook to regenerate temporary output files after a runtime reset.
  • Use drift_test.py to compare alert volumes with different shift_c values.

Pause - I'll come back to this later

Pausing ends your current browser session while leaving the persistent source available. Temporary runtime files may disappear after Colab releases the session.

  • Close the Google Colab tab.
  • Leave the SensorGuard notebook in Google Drive.
  • Leave the public sensorguard-anomaly-pipeline repository unchanged.
  • Rerun the notebook when you return to regenerate the CSV, SQLite, and PNG outputs.

Delete - I don't want to use this again

Deleting the persistent copies is permanent. The generated outputs remain reproducible only while you retain the source.

  • Return to the Colab notebook from earlier.
  • Delete sensorguard.py, drift_test.py, raw_telemetry.csv, clean_telemetry.csv, anomalies.csv, sensorguard.db, raw_telemetry.png, and anomaly_report.png from the Colab runtime file browser.
  • Delete the SensorGuard notebook from Google Drive.
  • Return to the public sensorguard-anomaly-pipeline repository on GitHub.
  • Delete the repository from its repository settings.
  • Confirm that the SensorGuard notebook no longer appears in Google Drive.
  • Confirm that sensorguard-anomaly-pipeline no longer appears in your GitHub repositories.

Nice Work!

Nice Work!

Congratulations! SensorGuard is now a reproducible data pipeline for anomaly detection.

What you learned:

  • Generated deterministic synthetic telemetry with deliberate quality failures. Validated the bad readings with explicit quality checks. Stored 240 cleaned rows in SQLite.
  • Measured a temperature-only baseline with precision. Exposed its missed events through recall. Trained an IsolationForest detector across four sensor features.
  • Published sensorguard.py in the public GitHub repository sensorguard-anomaly-pipeline. Documented the setup in README.md for a reviewer to reproduce.
  • Secret Mission: Reused the fitted model on temperature-shifted telemetry. Compared baseline alerts with drift alerts to measure distribution drift. Added a monitoring note that defines when investigation or possible retraining makes sense.

Ready to quiz yourself?