Skip to content

About

Perceptron virtual sensor for unsupervised fault detection in a simulated thermal tank process (FastAPI + Docker + pytest).

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Perceptron Virtual Sensor

A "virtual sensor" fault detector for a simulated tank/boiler process (a university "Projeto Integrador" / joint capstone project): a small Perceptron learns to predict two temperature readings (T6, T5) from six other process signals during normal operation. When a real fault changes the physical relationship between those signals, the model's prediction error jumps - that jump is the fault signal, without ever training on faulty data.

This repository is a refactor of an exploratory Jupyter notebook (kept, sanitized, in notebooks/original_exploration.ipynb) into a small production-style service, following the architecture from Udemy's "ML in Production: From Data Scientist to ML Engineer" course - the same pattern used in the sibling mvpower-rrcf-anomaly-detector and gan-thermal-fault-detector projects:

  • Poetry for dependency management and packaging.
  • Pydantic / pydantic-settings for typed configuration.
  • Loguru for structured logging (console + rotating file).
  • A src/ package layout, with data loading, the model, training and evaluation cleanly separated.
  • FastAPI serving the trained model as a microservice, containerized with Docker.
  • pytest unit tests for feature/target splitting and the training loop.

Architecture

Reference_data_1min.xlsx --> split_validation (held out BEFORE scaling)
                                     |                    |
                              remainder (85%)        validation (15%)
                                     |                    |
                          StandardScaler.fit_transform     |
                                     |                    |
                        70/30 train/test split              |
                                     |                    |
                        configs/config.yaml            scaler.transform
                       (architecture, training)              |
                                     |                    |
                              training.py               evaluation.py
                          (fixes: optimizer.zero_grad()  (fault-free
                           was missing every batch)       baseline MSE)
                                     |                    |
                                     v                    v
                           artifacts/ (perceptron.pt, scaler.joblib,
                              metadata.json: columns + fault_threshold)
                                     |
                                     v
                              +-------------------+
                              |  api/main.py       |  FastAPI:
                              +-------------------+  POST /predict
                                                       POST /detect

Datos_MF_TANK_1min.xlsx, Datos_MF_BOI_1min.xlsx and Datos_MF_BOI_TANK_1min.xlsx (tank fault, boiler fault, and both together) are scored the same way as the notebook did, purely for the training-time report in scripts/run_pipeline.py's logs - they play no role in choosing the API's fault_threshold (see "Design choices beyond the notebook" below).

What changed vs. the original notebook

The original notebook is preserved (outputs stripped) in notebooks/original_exploration.ipynb for provenance.

  1. optimizer.zero_grad() was never called. The notebook's training loop ran pred = rede(dado), loss.backward(), optimizer.step() every batch without ever resetting gradients first, so every batch's gradient added onto every previous batch's instead of replacing it. The loss curve still trended down (Adam's adaptive per-parameter learning rate partly masks the effect), but each step used the wrong gradient. Fixed in training.py; tests/test_training.py has a regression test asserting zero_grad is called once per batch.

Unchanged from the notebook: the Perceptron architecture (6 -> 8 -> 4 -> 2, ReLU activations), all training hyperparameters (35 epochs, batch size 1024, Adam lr 0.0002, betas (0.5, 0.999), MSE loss), the 6000-row warm-up skip, the 15%/70% validation/train-test split fractions, and scaling the reference run with a single StandardScaler fit only on the training remainder (the notebook already held validation out before fitting the scaler - no leakage to fix there). The malfunction files' padded column names (e.g. ' TIME ') and one file's fully duplicated columns (a source-workbook artifact, not something the notebook or this code introduced) are handled exactly as the notebook did: strip whitespace, then select the modeled columns by exact name.

Design choices beyond the notebook

The notebook only ever compared four datasets' mean MSE by eye - useful for exploration, useless for an API that needs a yes/no answer per sample. Two things were added, clearly separated from the ported logic:

  • evaluation.fault_threshold_multiplier (default 2.0): a sample is flagged as faulty when its squared prediction error exceeds this multiple of the fault-free validation set's mean squared error. This threshold is computed once at training time and saved into artifacts/metadata.json.
  • The notebook's own numbers are a useful sanity check for this choice: the tank-fault and combined boiler+tank runs show roughly double the fault-free validation MSE, while the boiler-only fault is barely distinguishable from baseline with these six input signals - i.e., this model/feature set mostly detects tank faults; catching boiler-only faults would need different inputs or a dedicated model, which is out of scope here.

Project layout

configs/config.yaml                   # columns, split fractions, model & training hyperparameters
data/raw/                             # place Reference_data_1min.xlsx and Datos_MF_*.xlsx here (not committed)
src/perceptron_virtual_sensor/
  config.py                          # Pydantic settings (data dir from env) + YAML config loader
  logging_config.py                  # Loguru setup
  data/datasets.py                   # loading, validation split, scaling, torch Dataset
  models/perceptron.py               # the Perceptron
  training.py                        # training loop
  evaluation.py                      # per-dataset and per-sample error
  pipeline.py                        # orchestrates training, saves/loads artifacts, predict/detect
  schemas.py                         # API request/response models
  api/main.py                        # FastAPI app (`/health`, `/features`, `POST /predict`, `POST /detect`)
scripts/run_pipeline.py              # CLI entrypoint: train, evaluate, save artifacts
tests/                                # pytest unit tests
notebooks/original_exploration.ipynb  # sanitized original notebook, for provenance

Running locally

poetry install
cp .env.example .env   # adjust PVS_DATA_DIR if your data lives elsewhere

# copy Reference_data_1min.xlsx and the three Datos_MF_*.xlsx files into data/raw/

# Train + evaluate, saving artifacts/
poetry run python scripts/run_pipeline.py

# API (serves the saved artifacts)
poetry run uvicorn perceptron_virtual_sensor.api.main:app --reload
# then: GET  http://localhost:8000/features
#       POST http://localhost:8000/predict  {"features": {"m2": 0, "m3": 0, "T4": 60, "T8": 60, "T9": 10, "Text": 10}}
#       POST http://localhost:8000/detect   {"features": {...}, "actual": {"T6": 60, "T5": 60}}

The four source .xlsx files are university project data, not included in this repository - data/raw/ is gitignored.

Tests

poetry run pytest

Docker

docker build -t perceptron-virtual-sensor-tank .
docker run -p 8000:8000 perceptron-virtual-sensor-tank

Build an image only after running scripts/run_pipeline.py at least once locally, so artifacts/ has a trained model to bake in.

Skills demonstrated

Virtual/soft-sensor fault detection with a small feedforward network (PyTorch), correct StandardScaler usage without validation leakage, and taking a model from a notebook to a config-driven, tested, containerized microservice with a training/serving split.

About

Perceptron virtual sensor for unsupervised fault detection in a simulated thermal tank process (FastAPI + Docker + pytest).

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages