AI Anomaly Detection Assistant Project

Artificial Intelligence project 18

AI Anomaly Detection Assistant Project

Build a complete anomaly detection assistant workflow with reproducible Python code, transparent inputs, reviewable output, and responsible-use limits.

Explore AI training in VizagView all project ideas

AI objective

Rank unusual sensor combinations against a clean reference window and flag the lowest-scoring records.

Data or knowledge source

One thousand seeded normal sensor records plus 30 clearly labelled injected anomalies across temperature, vibration, and pressure.

Requirements

  • Python 3.10 or later
  • A terminal or command prompt
  • python -m pip install numpy pandas scikit-learn
  • About 45-60 minutes to build and review

How the system works

Fit scaling and Isolation Forest only on the reference window, set a threshold from its score distribution, then score all records.

Validation checklist

  • Reference data is separated before fitting
  • Scaling is fitted only on the reference
  • Threshold corresponds to an explicit reference false-positive rate
  • Injected labels are used only for evaluation

Complete Python code

Save the program as ai_anomaly_detection_assistant.py. The code runs locally and requires no paid API key or model download.

"""Detect unusual synthetic sensor records with Isolation Forest."""

from __future__ import annotations

import numpy as np
import pandas as pd
from sklearn.ensemble import IsolationForest
from sklearn.preprocessing import StandardScaler


def make_demo_sensors(normal_rows: int = 1000, anomalies: int = 30, seed: int = 42) -> pd.DataFrame:
    rng = np.random.default_rng(seed)
    normal = np.column_stack([rng.normal(65, 3, normal_rows), rng.normal(2.2, 0.35, normal_rows), rng.normal(40, 4, normal_rows)])
    unusual = np.column_stack([rng.normal(88, 3, anomalies), rng.normal(5.4, 0.5, anomalies), rng.normal(62, 5, anomalies)])
    values = np.vstack([normal, unusual])
    return pd.DataFrame({"temperature": values[:, 0], "vibration": values[:, 1], "pressure": values[:, 2], "injected_anomaly": [False] * normal_rows + [True] * anomalies})


def detect_anomalies(data: pd.DataFrame, reference_rows: int = 800, reference_false_positive_rate: float = 0.02) -> pd.DataFrame:
    features = ["temperature", "vibration", "pressure"]
    reference = data.iloc[:reference_rows]
    scaler = StandardScaler().fit(reference[features])
    model = IsolationForest(n_estimators=250, contamination="auto", random_state=42).fit(scaler.transform(reference[features]))
    reference_scores = model.decision_function(scaler.transform(reference[features]))
    threshold = float(np.quantile(reference_scores, reference_false_positive_rate))
    result = data.copy()
    result["anomaly_score"] = model.decision_function(scaler.transform(result[features]))
    result["is_anomaly"] = result["anomaly_score"] < threshold
    return result


def main() -> None:
    result = detect_anomalies(make_demo_sensors())
    print(result.groupby("injected_anomaly")["is_anomaly"].agg(["count", "sum", "mean"]).round(3))
    print("Anomalies are review candidates, not automatic evidence of equipment failure.")


if __name__ == "__main__":
    main()

Run the project

  1. Create and activate a virtual environment.
  2. Install dependencies with python -m pip install numpy pandas scikit-learn when packages are required.
  3. Run python ai_anomaly_detection_assistant.py.
  4. Review confidence, fallbacks, sources, or error metrics rather than accepting output automatically.
  5. Test additional normal, edge, unsupported, and adversarial inputs.

Expected output

Anomaly score and flag per record plus review rates for normal and injected rows.

Accuracy, privacy, and responsible-use limits

An anomaly is a review candidate, not proof of failure, fraud, or danger. Real alerts need stable reference periods, domain thresholds, incident labels, and monitored false positives.

Ways to extend the project

Add time-aware features, machine-specific baselines, root-cause context, alert suppression, precision-recall evaluation, and investigator feedback.

Continue learning Artificial Intelligence

Try the next project, return to the Softenant project library, or explore the AI training in Vizag for guided NLP, retrieval, evaluation, automation, and responsible AI practice.