diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..be9392d --- /dev/null +++ b/.dockerignore @@ -0,0 +1,14 @@ +.git +.venv +venv +mlruns +data/external +data/processed +data/audit +**/__pycache__ +**/*.pyc +.pytest_cache +.ruff_cache +notebooks +docs/reports +*.egg-info diff --git a/.editorconfig b/.editorconfig index 824d0e3..182c842 100644 --- a/.editorconfig +++ b/.editorconfig @@ -10,3 +10,8 @@ trim_trailing_whitespace = true [*.md] trim_trailing_whitespace = false + +[Makefile] +indent_style = tab +end_of_line = lf +insert_final_newline = true diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..7ebd74b --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +Makefile text eol=lf +.github/workflows/*.yml text eol=lf diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..bcf29b8 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,23 @@ +name: CI + +on: + push: + pull_request: + +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.13" + cache: pip + - name: Install + run: | + python -m pip install --upgrade pip + python -m pip install -e ".[dev]" + - name: Ruff + run: python -m ruff check src tests + - name: Pytest + run: python -m pytest -q diff --git a/.gitignore b/.gitignore index 9cc4c2d..40b1d31 100644 --- a/.gitignore +++ b/.gitignore @@ -26,11 +26,12 @@ data/audit/* # Experiment tracking mlruns/ -# Local model outputs +# Local model outputs (repo-root artifacts, not src/har/models/) *.pkl *.joblib *.onnx onnx/ +/models/ # Packaging *.egg-info/ diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..0cc4a1b --- /dev/null +++ b/Makefile @@ -0,0 +1,32 @@ +PYTHON ?= python +CONFIG ?= configs/protocol_b_watch_stat_xgb.yaml +RAW_ROOT ?= data/external/wisdm-dataset +PROCESSED_DIR ?= data/processed +HOST ?= 0.0.0.0 +PORT ?= 8000 + +.PHONY: install test audit prepare train eval figures serve + +install: + $(PYTHON) -m pip install -e ".[dev]" + +test: + $(PYTHON) -m pytest -q + +audit: + $(PYTHON) -m har.data.audit --raw-root $(RAW_ROOT) + +prepare: + $(PYTHON) -m har.data.repair --raw-root $(RAW_ROOT) --processed-dir $(PROCESSED_DIR) + +train: + $(PYTHON) -m har.train --config $(CONFIG) + +eval: + $(PYTHON) -m har.evaluate --from-reports docs/reports + +figures: + $(PYTHON) -m har.eval.plots --from-reports docs/reports --out docs/figures --sync-mlflow + +serve: + $(PYTHON) -m uvicorn har.serve.app:app --host $(HOST) --port $(PORT) diff --git a/README.md b/README.md index 6f23d43..0830b50 100644 --- a/README.md +++ b/README.md @@ -1,140 +1,70 @@ -# Activity Recognition with WISDM + XGBoost +# Subject-independent HAR on WISDM -Notebook-first human activity recognition project using WISDM accelerometer data. +A student phone-only XGBoost notebook reported **0.8559 accuracy** on WISDM (`notebooks/archive/student_evaluation.txt`). That split shuffled overlapping windows with the same people in train and test. On repaired 20 Hz phone data, the same flattened 5 s windows score **0.8925 macro-F1** under that leaky split (`configs/protocol_a2_phone_raw_flat_xgb.yaml`) and **0.2924** when subjects are held out (`configs/protocol_b_phone_raw_flat_xgb.yaml`). The honest 18-class number that matters is watch statistical XGBoost: **0.7031 macro-F1** under 5-fold GroupKFold (`configs/protocol_b_watch_stat_xgb.yaml`). -The pipeline includes: -- data ingestion from raw + ARFF exports -- preprocessing and exploratory analysis -- XGBoost model training and evaluation -- confusion matrix and class-wise metric review +Primary metric is **macro-F1**. Accuracy is secondary. Every cell names a protocol and a config. Numbers are full 51-subject UCI 507, repaired to 20 Hz. -## Repository Structure +## Dataset -```text -. -├─ assets/ -│ └─ images/ -│ ├─ PhoneConf2.png -│ └─ PhoneEval2.png -├─ data/ -│ ├─ activity_key.txt -│ ├─ external/ # local source dataset (gitignored) -│ └─ processed/ # generated CSVs (gitignored) -├─ docs/ -│ └─ reports/ -│ └─ evaluation.txt -├─ notebooks/ -│ └─ archive/ # student notebooks -│ ├─ DataLoader.ipynb -│ ├─ analysis.ipynb -│ └─ PhoneXGB2.ipynb -├─ src/ -│ └─ har/ # installable package -├─ tests/ -├─ .editorconfig -├─ .gitignore -├─ pyproject.toml -├─ requirements.txt -├─ requirements-dev.txt -├─ LICENSE -└─ README.md -``` - -## Tech Stack - -- Python 3.10+ -- Jupyter Notebook -- pandas, numpy, scipy -- scikit-learn -- xgboost -- matplotlib, seaborn -- FastAPI, ONNX Runtime, MLflow (package runtime; not used by archived notebooks) - -## Setup - -```bash -python -m venv .venv -source .venv/Scripts/activate # Windows Git Bash -python -m pip install --upgrade pip -python -m pip install -r requirements.txt -``` - -For development tooling (pytest, ruff, pre-commit): - -```bash -python -m pip install -r requirements-dev.txt -``` - -## Data Layout and Paths - -Raw WISDM files are gitignored. Expected tree after download or a manual extract: - -```text -data/external/wisdm-dataset/raw/phone/accel/data_1600_accel_phone.txt -``` +[WISDM Smartphone and Smartwatch Activity and Biometrics Dataset (UCI 507)](https://archive.ics.uci.edu/dataset/507/wisdm+smartphone+and+smartwatch+activity+and+biometrics+dataset): 51 subjects (1600-1650), 18 activities (A-S skipping N), phone in pocket and watch on the dominant hand, accelerometer and gyroscope. -```bash -python -m har.data.download # skips if that file already exists; not used in CI -python -m har.data.audit # writes gitignored CSVs under data/audit/ and docs/data_card.md -python -m har.data.repair # resample/align to 20 Hz; writes gitignored parquet under data/processed/ -python -m har.train --config configs/protocol_a2_phone_raw_flat_xgb.yaml # A2 leaky XGBoost; overnight on full WISDM, not CI - -python -m mlflow ui --backend-store-uri mlruns # Run Mlflow -``` +This dump matches Weiss row counts exactly (**15,630,426**). The archived notebook concatenated **15,649,253** rows. Audit summary: `docs/data_card.md`. -Zip URL and checksum field live in `configs/audit.yaml`. See `data/README.md`. +| Stream | Rows | +|--------|------| +| phone accel | 4,804,403 | +| phone gyro | 3,608,635 | +| watch accel | 3,777,046 | +| watch gyro | 3,440,342 | -Archived notebooks still expect a processed CSV: +Raw sessions are not 20 Hz throughout. Implied Hz clusters at **20** (2,838 sessions), **25** (543), **50** (322), and **100** (14). A 200-row official ARFF window is 10 s at 20 Hz and about 4 s at 50 Hz, so windowing by row count mixes time scales. -1. `notebooks/archive/DataLoader.ipynb` writes `data/processed/raw.csv` and `arff.csv`. -2. `notebooks/archive/analysis.ipynb` reads `data/processed/arff.csv`. -3. `notebooks/archive/PhoneXGB2.ipynb` reads `data/processed/raw.csv`. +![Implied sampling-rate modes in raw WISDM](docs/figures/sampling_rate_modes.png) -The archive loader hardcoded `../data/external/wisdm-dataset/wisdm-dataset`. The UCI zip extracts one level shallower (`data/external/wisdm-dataset`). +**35** subject x activity x stream cells are empty. Phone accel gaps include 1609 B, 1616 B and F, 1642 C and F, plus other holes in the 18-class grid. See `docs/data_card.md` for the full list. -## Notebook Workflow +There are no demographics, so there is no fairness slice. -1. Run `notebooks/archive/DataLoader.ipynb`. -2. Run `notebooks/archive/analysis.ipynb`. -3. Run `notebooks/archive/PhoneXGB2.ipynb`. +## Method -## Formatting and Quality +Repair (`python -m har.data.repair`, `configs/default.yaml`) interpolates each `(subject, activity, device)` session onto a shared **20 Hz** grid, aligns accel and gyro by coverage intersection (not an exact-timestamp join), leaves phone-accel reorient **off**, and does not trim the start of the trial. -- `.editorconfig` for whitespace and newlines -- `ruff` via `pyproject.toml` (line length 100). Dev extras are pytest, ruff, and pre-commit. - -```bash -python -m ruff check src tests -python -m ruff format --check src tests -``` +Windows are **5.0 s** with a **1.0 s** hop, built inside one session. They never slide across subject or activity boundaries. Default features are 104-dimensional statistical summaries (per-axis moments, magnitude, pairwise correlations). Flattened raw windows exist only to compare against the student representation. -## Baseline Result +Models on the honest ladder: stratified dummy, logistic regression, random forest, XGBoost (200 trees, `max_depth` 6). Protocol A clones the student 982-tree family. A two-stage group-then-expert head was tried and did not beat flat 18-way macro-F1. Gradient boosting on repaired session features beat the other classical models, so no 1D CNN or TCN is shipped. -From `docs/reports/evaluation.txt` (Protocol A, leaky window split, phone-only): -- best run accuracy is around `0.8559` -- class-level metrics highlight weaker classes such as stairs/kicking compared to sitting/writing +Protocols (`docs/protocol.md`): -See `docs/protocol.md` for A1 (80-sample clone) vs A2 (session-safe leaky) and `docs/limitations.md` for why that number is not subject-independent. MLflow writes `mlruns/` (gitignored). Fixture tests train dummy and a tiny XGBoost; they do not download WISDM. +| Protocol | Split | Role | +|----------|--------|------| +| A1 | leaky `train_test_split` on 80-sample / hop-40 windows | Closest clone of `notebooks/archive/PhoneXGB2.ipynb` | +| A2 | leaky split on 5 s / 1 s flattened windows | Same representation as honest B flatten | +| B | 5-fold GroupKFold on `subject_id` | Main table | +| C | 46/5 grouped holdout, 3 repeats from one seed | Phone holdout check; not 51-fold LOSO | -## Honest results (Task 9) +Scalers, encoders, and early stopping fit on training subjects only, except Protocol A, which copies the notebook and early-stops on the test set. -Primary metric is **macro-F1**. Accuracy is secondary. Every cell names protocol and config. Numbers below are full 51-subject WISDM on repaired 20 Hz parquet. On the same flattened phone windows, leaky A2 is 0.8925 macro-F1 and subject-grouped B is 0.2924. A1 (80-sample clone) is 0.8490 / 0.8475, next to the student 0.8559 accuracy. +## Results -### Protocol A1 vs the student notebook (phone, leaky, 80-sample flatten) +### Leaky clone vs the student notebook (phone, flattened) | Protocol | Config | Model | macro-F1 | Accuracy | |----------|--------|-------|----------|----------| -| Student notebook | `docs/reports/evaluation.txt` | xgboost | (not reported) | 0.8559 | -| A1 leaky | `configs/protocol_a1_phone_raw_flat_xgb.yaml` (`docs/reports/protocol_a1_phone_raw_flat_xgb.json`) | xgboost (student 982 trees) | 0.8490 | 0.8475 | +| Student notebook | `notebooks/archive/student_evaluation.txt` | xgboost | (not reported) | 0.8559 | +| A1 leaky | `configs/protocol_a1_phone_raw_flat_xgb.yaml` (`docs/reports/protocol_a1_phone_raw_flat_xgb.json`) | xgboost (982 trees) | 0.8490 | 0.8475 | -A1 is the clone. It is not the same window geometry as A2. +A1 is the 80-sample clone. It is not the same window geometry as A2. Do not treat A2 vs 0.8559 as a leakage-only delta: the student matrix was unrepaired and concat-windowed. -### Protocol A vs B, same representation (phone, 5 s / 1 s, `raw_flat`) +### Same representation, leaky vs grouped (phone, 5 s / 1 s, `raw_flat`) | Protocol | Config | Model | macro-F1 | Accuracy | |----------|--------|-------|----------|----------| -| A2 leaky | `configs/protocol_a2_phone_raw_flat_xgb.yaml` (`docs/reports/protocol_a2_phone_raw_flat_xgb.json`) | xgboost (student 982 trees) | 0.8925 | 0.8913 | -| B GroupKFold | `configs/protocol_b_phone_raw_flat_xgb.yaml` (`docs/reports/protocol_b_phone_raw_flat_xgb.json`) | xgboost (student 982 trees) | 0.2924 | 0.3047 | +| A2 leaky | `configs/protocol_a2_phone_raw_flat_xgb.yaml` (`docs/reports/protocol_a2_phone_raw_flat_xgb.json`) | xgboost (982 trees) | 0.8925 | 0.8913 | +| B GroupKFold | `configs/protocol_b_phone_raw_flat_xgb.yaml` (`docs/reports/protocol_b_phone_raw_flat_xgb.json`) | xgboost (982 trees) | 0.2924 | 0.3047 | + +![Same flattened 5 s phone windows under a leaky split versus GroupKFold](docs/figures/leakage_macro_f1.png) + +That drop is the leakage finding. ### Protocol B, statistical features, GroupKFold 5 @@ -143,17 +73,23 @@ A1 is the clone. It is not the same window geometry as A2. | phone | `configs/protocol_b_phone_stat_dummy.yaml` (`docs/reports/protocol_b_phone_stat_dummy.json`) | dummy | 0.0151 | 0.0551 | | phone | `configs/protocol_b_phone_stat_logreg.yaml` (`docs/reports/protocol_b_phone_stat_logreg.json`) | logreg | 0.2767 | 0.2799 | | phone | `configs/protocol_b_phone_stat_rf.yaml` (`docs/reports/protocol_b_phone_stat_rf.json`) | rf | 0.3131 | 0.3252 | -| phone | `configs/protocol_b_phone_stat_xgb.yaml` (`docs/reports/protocol_b_phone_stat_xgb.json`) | xgboost (honest 200 trees) | 0.3272 | 0.3382 | -| watch | `configs/protocol_b_watch_stat_xgb.yaml` (`docs/reports/protocol_b_watch_stat_xgb.json`) | xgboost (honest 200 trees) | 0.7031 | 0.7013 | -| both (concat windows, 6 channels; not 12-channel fusion) | `configs/protocol_b_concat_stat_xgb.yaml` (`docs/reports/protocol_b_concat_stat_xgb.json`) | xgboost (honest 200 trees) | 0.5236 | 0.5267 | +| phone | `configs/protocol_b_phone_stat_xgb.yaml` (`docs/reports/protocol_b_phone_stat_xgb.json`) | xgboost (200 trees) | 0.3272 | 0.3382 | +| watch | `configs/protocol_b_watch_stat_xgb.yaml` (`docs/reports/protocol_b_watch_stat_xgb.json`) | xgboost (200 trees) | 0.7031 | 0.7013 | +| both (stacked 6-channel windows, not 12-channel fusion) | `configs/protocol_b_concat_stat_xgb.yaml` (`docs/reports/protocol_b_concat_stat_xgb.json`) | xgboost (200 trees) | 0.5236 | 0.5267 | -### Protocol C (46/5 x 3 repeats from one seed, not 51-fold LOSO) +![Protocol B model and device ladder on statistical features](docs/figures/protocol_b_ladder.png) + +Statistical phone XGBoost (0.3272) beats flattened raw under the same protocol (0.2924). Watch is the device that actually classifies 18 activities. Concat is extra rows from both devices, still 6 channels per window. + +### Protocol C (phone statistical XGBoost, 46/5 x 3) | Protocol | Config | Model | macro-F1 | Accuracy | |----------|--------|-------|----------|----------| -| C grouped_holdout | `configs/protocol_c_phone_stat_xgb.yaml` (`docs/reports/protocol_c_phone_stat_xgb.json`) | xgboost (honest 200 trees) | 0.2985 | 0.3140 | +| C grouped_holdout | `configs/protocol_c_phone_stat_xgb.yaml` (`docs/reports/protocol_c_phone_stat_xgb.json`) | xgboost (200 trees) | 0.2985 | 0.3140 | + +Headline `macro_f1` is the unweighted mean of repeats. It tracks Protocol B phone (0.3272), not Protocol A. -### Protocol B ablations (phone statistical XGBoost, Task 10) +### Protocol B ablations (phone statistical XGBoost) Full table and per-group F1: `docs/reports/ablations.md`. Same GroupKFold and 200-tree family as `configs/protocol_b_phone_stat_xgb.yaml`. @@ -167,14 +103,105 @@ Full table and per-group F1: `docs/reports/ablations.md`. Same GroupKFold and 20 | Magnitude only | `configs/ablations/magnitude.yaml` | 0.3142 | 0.4516 | | Hierarchical | `configs/ablations/hierarchical.yaml` | 0.3271 | 0.5855 | -RQ1: reorient and 15 s trim do not beat the unreoriented, untrimmed control on 18-class phone GroupKFold. RQ5: the two-stage head does not beat flat 18-way on macro-F1; eating group F1 rises from 0.4945 to 0.5855. +![Phone statistical XGBoost ablations under Protocol B](docs/figures/ablations_macro_f1.png) -Rebuild the compact ladder table: +rWISDM-style reorient and a 15 s start trim do not beat the unreoriented, untrimmed 5 s control on 18-class phone GroupKFold. The two-stage head does not beat flat 18-way on macro-F1; eating group F1 rises from 0.4945 to 0.5855. 10 s windows are the only row that clearly beats 5 s (0.3422). Defaults stay 5 s, `reorient: false`, `trim_start_s: 0.0`. + +Rebuild the compact ladder and the README figures: ```bash python -m har.evaluate --from-reports docs/reports +python -m har.eval.plots --from-reports docs/reports --out docs/figures --sync-mlflow ``` +## Failure cases + +Pocket phone IMU under Protocol B (`configs/protocol_b_phone_stat_xgb.yaml`) can tell locomotion as a group (F1 0.8873) and still cannot name eating or sitting. Per-class F1: eating pasta 0.0749, soup 0.0807, chips 0.0964, drinking 0.1050, sandwich 0.1064, sitting 0.1943. Stairs (0.6588) and kicking (0.6470) are the weakest locomotion classes; they are not the worst overall. + +Watch on the dominant hand (`configs/protocol_b_watch_stat_xgb.yaml`) flips that picture: locomotion 0.9292, hand 0.8788, eating 0.8450, posture 0.6606. Stairs is 0.7028 and kicking 0.7831. The hard class is sandwich (0.2816). Do not serve a phone window to a watch bundle. + +![Per-class F1 for phone versus watch statistical XGBoost under Protocol B](docs/figures/per_class_f1_phone_watch.png) + +![Activity-group F1 for phone versus watch statistical XGBoost under Protocol B](docs/figures/per_group_f1_phone_watch.png) + +Confusion among walking / jogging / stairs, and among the eating cluster, is the pattern the leaky notebook already flagged. Under a subject-independent split those errors survive; the 0.89 leaky score does not. + +## Reproduce + +Python 3.10+. Raw WISDM is gitignored. Expected sentinel after extract: + +```text +data/external/wisdm-dataset/raw/phone/accel/data_1600_accel_phone.txt +``` + +```bash +python -m venv .venv +source .venv/Scripts/activate # Windows Git Bash; otherwise source .venv/bin/activate +python -m pip install --upgrade pip +make install +``` + +Zip URL lives in `configs/audit.yaml`. Layout notes: `data/README.md`. + +```bash +python -m har.data.download # skips if the sentinel exists; not used in CI +make audit # data/audit/*.csv and docs/data_card.md +make prepare # 20 Hz parquet under data/processed/ (gitignored) +make train CONFIG=configs/protocol_b_watch_stat_xgb.yaml +make eval +make figures +make test # fixtures only; no WISDM +``` + +Full 51-subject XGBoost is an overnight local run, not CI. GitHub Actions runs ruff and pytest on committed fixtures. + +```bash +python -m ruff check src tests +python -m ruff format --check src tests +python -m mlflow ui --backend-store-uri mlruns +``` + +MLflow runs are named after the config stem (`protocol_b_watch_stat_xgb`, `ablation_window_10s`, ...). Each run logs `fold_macro_f1` by fold, `group_f1_*`, a per-class F1 bar, and a confusion matrix. The README charts in `docs/figures/` are built from `docs/reports/` so they stay aligned with the tables. + +![MLflow experiment view: accuracy, fold metrics, and per-group F1 across runs](docs/figures/mlflow_charts_1.png) + +![MLflow experiment view: macro-F1, fold variance, and activity-group F1](docs/figures/mlflow_charts_2.png) + +Archived notebooks under `notebooks/archive/` still expect `data/processed/raw.csv` / `arff.csv` from the old loader. They are not the training path. + +## API + +CPU service for one 5 s, 20 Hz window (`T=100`, `C=6`). Default bundle is watch statistical XGBoost. Details: `serving/README.md`, `docs/model_card.md`. + +```bash +python -m har.models.export --config configs/protocol_b_watch_stat_xgb.yaml --out models/watch_stat_xgb.onnx +export HAR_MODEL_PATH=models/watch_stat_xgb.onnx +make serve +``` + +```http +GET /health -> {"status": "ok", "model_id": "..."} +GET /labels -> {"codes": [...], "names": {...}, "groups": {...}} +POST /predict +``` + +```bash +python -c "import json,urllib.request; body=json.dumps({'device':'watch','hz':20,'channels':['ax','ay','az','gx','gy','gz'],'samples':[[0,0,0,0,0,0]]*100}).encode(); req=urllib.request.Request('http://127.0.0.1:8000/predict', data=body, headers={'Content-Type':'application/json'}); print(json.load(urllib.request.urlopen(req)))" +``` + +Wrong `T`, `C`, `device`, or `hz` is 422. `abstained` is true when `max(proba)` is below the bundle threshold (default 0.0, never abstain). + +## Limits and next steps + +- No subject demographics; cannot slice by sex, handedness, or phone model. +- Concat is stacked 6-channel windows, not time-aligned 12-channel phone+watch fusion. +- Protocol C is 46/5 x 3, not 51-fold LOSO. Nested XGBoost validation is one held-out **train** subject, not a separate val cohort. +- Served ONNX is a refit on all windows (one subject held out only for early stopping). Cite GroupKFold numbers from the metrics JSON, not from export. +- Abstain is uncalibrated. Statistical features still run in Python; only the tree head is ONNX. +- 10 s windows beat 5 s on phone GroupKFold by about 1.5 macro-F1 points. Changing the default is a product choice, not a free lunch on latency. + +More on protocol, defects of the archived notebooks, and the served bundle: `docs/protocol.md`, `docs/limitations.md`, `docs/model_card.md`. + ## License MIT License. See `LICENSE`. diff --git a/configs/protocol_a2_phone_raw_flat_xgb.yaml b/configs/protocol_a2_phone_raw_flat_xgb.yaml index b39659f..331608d 100644 --- a/configs/protocol_a2_phone_raw_flat_xgb.yaml +++ b/configs/protocol_a2_phone_raw_flat_xgb.yaml @@ -1,6 +1,6 @@ # protocol_a2_phone_raw_flat_xgb: session-safe 5 s windows + leaky split on repaired phone parquet. # Same student XGBoost family as A1. Isolates subject/overlap leakage from an -# honest GroupKFold on the same features (Task 9), not parse bugs. The matrix +# honest GroupKFold on the same features, not parse bugs. The matrix # is already aligned and resampled; full WISDM is an overnight run, not CI. seed: 42 data: diff --git a/data/README.md b/data/README.md index 130ea7d..bbcdde9 100644 --- a/data/README.md +++ b/data/README.md @@ -19,7 +19,7 @@ data/external/wisdm-dataset/ arffmagic-master/ ``` -Checksum of the zip is recorded in `configs/audit.yaml` as `data.zip_sha256` (null until the first scripted download). +Checksum of the zip is recorded in `configs/audit.yaml` as `data.zip_sha256`. It is null for a manual extract; this dump is identified by Weiss row counts in `docs/data_card.md` (15,630,426 total, exact match). Fill `zip_sha256` after a scripted download. ## Get the files diff --git a/docs/build-log.md b/docs/build-log.md index f88210c..285bbe9 100644 --- a/docs/build-log.md +++ b/docs/build-log.md @@ -1,6 +1,6 @@ # Build log (blog / video) -Source notes for public writing. Not a second spec. After each plan task, append a section. Commands are copy-pasteable. +Source notes for public writing. Commands are copy-pasteable. --- @@ -387,3 +387,123 @@ python -c "import tomllib; from pathlib import Path; p=tomllib.loads(Path('pypro test ! -e src/har/models/tcn.py && test ! -e configs/phone_tcn.yaml && echo skipped # skipped ``` + +--- + +## Task 12: Export, API, Docker, calibration + +**Commit:** pending (you add the commit) + +**Story beat:** The product surface is a CPU FastAPI that scores one 5 s window. XGBoost trees ship as ONNX; features stay in Python. + +**Shipped:** +- `src/har/models/export.py`: `ModelBundle`, joblib and ONNX (`onnxmltools` + sidecar JSON), `predict_window`, `export_from_config`, `python -m har.models.export` +- `src/har/serve/schema.py`, `src/har/serve/app.py`: `GET /health`, `GET /labels`, `POST /predict` +- `serving/Dockerfile`, `serving/README.md`, `.dockerignore` +- `tests/test_serve.py` (stub 422/happy path, device/hz/channel names, body cap, joblib and ONNX roundtrip, fixture export with YAML `cuda` forced to CPU, `HAR_MODEL_PATH` startup for both artifacts, 100-request p95 bound) +- `docs/model_card.md` (Task 11 skip paragraph plus serving contract and p95) +- `httpx==0.28.1` on the dev extra for FastAPI `TestClient` +- `onnx==1.22.0`, `onnxmltools==1.16.0`, `skl2onnx==1.20.0` on runtime deps (`onnx` 1.22 has a wheel; 1.17 did not) + +**Decision:** Prefer ONNX for the served XGBoost head. `onnx==1.17.0` had no wheel and tried a source build; `onnx==1.22.0` is `cp312-abi3` and works on Python 3.13. `onnxmltools.convert_xgboost` matches sklearn `predict_proba` on a fixture. joblib remains for stubs. Abstain is `max(proba) < threshold` with default 0.0 (never abstain). The bundle to train for serving is watch statistical XGBoost (`configs/protocol_b_watch_stat_xgb.yaml`). Export refuses `data.device: both` and `hierarchical`. Export always fits with `device: cpu` even if the YAML says `cuda`. `activity_code` is argmax over the 18-way padded `proba`. + +**Gotcha:** +- `POST /predict` `samples` length is `T=100` at 5 s / 20 Hz, not one row. A one-row JSON body is 422. +- GroupKFold metrics in the model card are not the export fit. Export refits on all windows (one subject held out only for early stopping). +- Wrong `T` or `C` is 422; so is `device` or `hz` mismatch. Do not send phone windows to a watch bundle. +- Module-level `har.serve.app:app` loads `HAR_MODEL_PATH` on startup. An `.onnx` path also needs the sidecar `.json`. +- joblib pickle must be exported with the same CPython minor as `serving/Dockerfile` (3.13). ONNX does not have that pickle constraint. +- Bodies over 1 MiB return 413. `samples` is capped at 512 rows. + +**Demo clip:** +```bash +python -m pytest tests/test_serve.py -q +# 19 passed +python -c "from pathlib import Path; print(Path('docs/model_card.md').read_text().splitlines()[6][:80])" +# Trees on repaired session features were enough. Protocol B GroupKFold phone sta +python -m har.models.export --config configs/protocol_b_watch_stat_xgb.yaml --out models/watch_stat_xgb.onnx +# writes gitignored onnx + json; then: +# HAR_MODEL_PATH=models/watch_stat_xgb.onnx uvicorn har.serve.app:app --host 0.0.0.0 --port 8000 +``` + +--- + +## Task 13: CI and Makefile + +**Commit:** pending (you add the commit) + +**Story beat:** An empty GitHub clone can lint and test without WISDM. Full data stays a local `make audit` / `make prepare` step. + +**Shipped:** +- `.github/workflows/ci.yml`: checkout, Python 3.12, `pip install -e ".[dev]"`, `ruff check src tests`, `pytest -q` +- `Makefile` targets: `install`, `test`, `audit`, `prepare`, `train`, `eval`, `serve` +- `tests/fixtures/tiny_wisdm/`: subjects 1600 and 1601, activities A and B, phone accel+gyro, 20 Hz, 3 s per activity +- `tests/test_tiny_wisdm.py`, `tests/test_ci.py` +- `.gitattributes` keeps `Makefile` as LF so Windows checkout does not break GNU make + +**Decision:** CI does not call `har.data.download` and does not read `data/external/`. Pytest uses committed fixtures and tmp_path trees. `make test` is pytest only; ruff lives in the workflow. `make serve` does not set `HAR_MODEL_PATH`; export it first as in `serving/README.md`. Default `CONFIG` is watch statistical XGBoost. + +**Gotcha:** A CRLF `Makefile` on Linux is `missing separator`. Keep it LF. CI Python is 3.12; local and the serve image are 3.13. First GitHub run is the real empty-clone check. `make audit` / `make prepare` still need a local WISDM dump. + +**Demo clip:** +```bash +python -m ruff check src tests +# All checks passed! +python -m pytest tests/test_tiny_wisdm.py tests/test_ci.py tests/test_download.py -q +# 12 passed +python -m pytest -q +# 138 passed +make -n test +# python -m pytest -q +``` + +--- + +## Case-study README and metric freeze + +**Commit:** pending (you add the commit) + +**Story beat:** The README now reads as a short paper. Lead with leaky 0.8925 vs grouped 0.2924 on the same phone flatten, then watch 0.7031 as the number to cite. + +**Shipped:** +- `README.md` rewritten around protocol + config cells, audit highlights, method, failure cases, reproduce, API +- `docs/model_card.md`, `docs/data_card.md`, `docs/protocol.md`, `docs/limitations.md` as standalone cards (no work-tracker labels) +- `docs/reports/evaluation.txt` moved to `notebooks/archive/student_evaluation.txt` +- `src/har/data/audit.py` data-card limits name repair as shipped (`python -m har.data.repair`) +- `docs/reports/ablations.md` title and section headings without work-tracker labels + +**Decision:** Public writing cites `configs/*.yaml` and `docs/reports/*.json`. The student 0.8559 accuracy stays in the archive next to the notebooks, not in `docs/reports/`. Concat stays labeled as stacked 6-channel windows. Watch sandwich (L) 0.2816 is the actual hard watch class; phone eating per-class F1 0.07-0.11 is worse than stairs/kicking. + +**Gotcha:** `docs/data_card.md` is regenerated by `python -m har.data.audit`. Edit `write_data_card`, not only the markdown, or the next audit overwrites the limits paragraph. + +**Demo clip:** +```bash +python -m pytest tests/test_audit.py tests/test_ci.py -q +python -c "from pathlib import Path; t=Path('README.md').read_text(); assert '0.8925' in t and '0.2924' in t and '0.7031' in t; print(t.splitlines()[2][:140])" +``` + +--- + +## Install pin and portable serve recipe + +**Commit:** pending (you add the commit) + +**Story beat:** `make install` and GitHub Actions can resolve. Docker no longer bind-mounts a path from this machine. + +**Shipped:** +- `pyproject.toml` `pyarrow==19.0.1` so it sits under MLflow 2.22.5's `pyarrow<20` +- `serving/README.md` mounts `$PWD/models:/models` +- `serving/Dockerfile` comment: inference-only image, not a pin workaround +- `.github/workflows/ci.yml` Python 3.13 (same as local and the serve image) +- `data/README.md`: null `zip_sha256` means identity is Weiss row counts in the data card +- `tests/test_ci.py` locks the pyarrow ceiling and the portable mount + +**Decision:** Keep MLflow 2.22.5. Drop pyarrow to 19.0.1 (what this venv already ran). Do not bump MLflow just to keep pyarrow 23. + +**Gotcha:** A venv that already has pyarrow 23 will look fine until a clean `pip install -e ".[dev]"`. `pip check` on a mixed venv is not enough. + +**Demo clip:** +```bash +python -m pytest tests/test_ci.py -q +``` + diff --git a/docs/data_card.md b/docs/data_card.md index 05f50fa..683a761 100644 --- a/docs/data_card.md +++ b/docs/data_card.md @@ -1,8 +1,8 @@ # WISDM data card -Generated by `python scripts/audit.py`. Sampling rate is implied Hz: `1e9 / median_dt_ns` from timestamp diffs inside a session. Absolute Unix epoch is not used. +Audit of the raw [WISDM Smartphone and Smartwatch Activity and Biometrics Dataset (UCI 507)](https://archive.ics.uci.edu/dataset/507/wisdm+smartphone+and+smartwatch+activity+and+biometrics+dataset) dump on disk. This card describes raw sessions, not the repaired 20 Hz parquet. Regenerate with `python -m har.data.audit` (or `python scripts/audit.py`). -Dataset: [WISDM Smartphone and Smartwatch Activity and Biometrics Dataset (UCI 507)](https://archive.ics.uci.edu/dataset/507/wisdm+smartphone+and+smartwatch+activity+and+biometrics+dataset). +Sampling rate is implied Hz: `1e9 / median_dt_ns` from timestamp diffs inside a session. Absolute Unix epoch is unused. ## Row counts vs Weiss @@ -110,6 +110,6 @@ Session implied Hz clustered around the observed peaks: 20, 25, 50, and 100. Do ## Limits - No demographics (gender, handedness, height, phone model) in this dump, so no fairness slices. -- Start-of-trial seconds may not match the labeled activity; trim is a later repair flag. -- Accel and gyro clocks are not assumed to share sample instants; alignment is a later repair step. +- Start-of-trial seconds may not match the labeled activity. Repair can drop them (`trim_start_s`); the default tree is untrimmed. +- Accel and gyro clocks do not share sample instants. Repair interpolates both onto a shared 20 Hz grid per session (`python -m har.data.repair`). diff --git a/docs/figures/ablations_macro_f1.png b/docs/figures/ablations_macro_f1.png new file mode 100644 index 0000000..060388b Binary files /dev/null and b/docs/figures/ablations_macro_f1.png differ diff --git a/docs/figures/leakage_macro_f1.png b/docs/figures/leakage_macro_f1.png new file mode 100644 index 0000000..6a31493 Binary files /dev/null and b/docs/figures/leakage_macro_f1.png differ diff --git a/docs/figures/mlflow_charts_1.png b/docs/figures/mlflow_charts_1.png new file mode 100644 index 0000000..a09095f Binary files /dev/null and b/docs/figures/mlflow_charts_1.png differ diff --git a/docs/figures/mlflow_charts_2.png b/docs/figures/mlflow_charts_2.png new file mode 100644 index 0000000..dfc8868 Binary files /dev/null and b/docs/figures/mlflow_charts_2.png differ diff --git a/docs/figures/per_class_f1_phone_watch.png b/docs/figures/per_class_f1_phone_watch.png new file mode 100644 index 0000000..635e3cb Binary files /dev/null and b/docs/figures/per_class_f1_phone_watch.png differ diff --git a/docs/figures/per_group_f1_phone_watch.png b/docs/figures/per_group_f1_phone_watch.png new file mode 100644 index 0000000..299a104 Binary files /dev/null and b/docs/figures/per_group_f1_phone_watch.png differ diff --git a/docs/figures/protocol_b_ladder.png b/docs/figures/protocol_b_ladder.png new file mode 100644 index 0000000..1a81853 Binary files /dev/null and b/docs/figures/protocol_b_ladder.png differ diff --git a/docs/figures/sampling_rate_modes.png b/docs/figures/sampling_rate_modes.png new file mode 100644 index 0000000..bb95ba1 Binary files /dev/null and b/docs/figures/sampling_rate_modes.png differ diff --git a/docs/limitations.md b/docs/limitations.md index a9409e3..1270b22 100644 --- a/docs/limitations.md +++ b/docs/limitations.md @@ -1,6 +1,6 @@ -# Limitations of the archived student pipeline +# Limitations -This is a description of the 2024 notebook pipeline in `notebooks/archive/`, not of the rebuilt `src/har/` package. Keep these defects in mind when you read `docs/reports/evaluation.txt` (phone accuracy `0.855905403547367`). That number is Protocol A (leaky). It is not a subject-independent HAR result. +The 2024 notebook pipeline in `notebooks/archive/` reported phone accuracy `0.855905403547367` (`notebooks/archive/student_evaluation.txt`). That number is Protocol A (leaky). It is not a subject-independent HAR result. The defects below are why. The rebuilt `src/har/` package avoids them on Protocols B and C; remaining limits of that work are at the end. ## Subject leakage @@ -24,7 +24,7 @@ A scaler fit on the full matrix before the split sees test windows. Fit scalers, ## Weak tree features -XGBoost is given `80 x 6 = 480` raw samples. The official ARFF already had distribution bins, peaks, MFCCs, and axis correlations. Flattened raw windows remain the A1/A2 reproduction. Statistical features are the Protocol B default, compared later (RQ3). +XGBoost is given `80 x 6 = 480` raw samples. The official ARFF already had distribution bins, peaks, MFCCs, and axis correlations. Flattened raw windows remain the A1/A2 reproduction. Statistical features are the Protocol B default. ## Exact-timestamp accel/gyro merge @@ -32,16 +32,25 @@ IMU clocks rarely share sample instants. An inner join on the raw timestamp drop ## Unused deep-learning imports -The phone notebook imports Keras CNN pieces. TensorFlow was in `requirements.txt` and is not a v1 runtime dependency. No CNN ships until a logged table shows XGBoost losing on GroupKFold macro-F1. +The phone notebook imports Keras CNN pieces. TensorFlow was in `requirements.txt` and is not a runtime dependency. Trees on repaired session features beat dummy, logreg, RF, and flattened raw under GroupKFold, so no CNN ships. ## Watch data unused -The student result is phone-only with no stated product choice. The dump has watch accel and gyro. Phone vs watch vs fusion is RQ4, under a subject-independent protocol. +The student result is phone-only with no stated product choice. The dump has watch accel and gyro. Under Protocol B, watch statistical XGBoost is 0.7031 macro-F1 and phone is 0.3272 on the same feature family. ## Evaluation writeup -`docs/reports/evaluation.txt` is a generic metric walkthrough, not a model card. It does not name the split, the window identity rules, or the timestamp handling. Rebuilt numbers live next to a protocol name in the README and in MLflow. +`notebooks/archive/student_evaluation.txt` is a generic metric walkthrough, not a model card. It does not name the split, the window identity rules, or the timestamp handling. Frozen numbers live next to a protocol name in the README and in MLflow. -## What this rebuild does not claim yet +## What the honest numbers do not mean -Task 9 filled the Protocol B/C table in the README from `docs/reports/`. A2 is `docs/reports/protocol_a2_phone_raw_flat_xgb.json`. Do not treat A2 vs 0.8559 as a leakage-only delta: the student matrix was unrepaired and concat-windowed. Do not treat statistical GroupKFold XGBoost as the same-representation A vs B gap; that cell is `protocol_b_phone_raw_flat_xgb.json`. +A2 is `docs/reports/protocol_a2_phone_raw_flat_xgb.json`. Do not treat A2 vs 0.8559 as a leakage-only delta: the student matrix was unrepaired and concat-windowed. Do not treat statistical GroupKFold XGBoost as the same-representation A vs B gap; that cell is `docs/reports/protocol_b_phone_raw_flat_xgb.json`. + +## Remaining limits of this release + +- No demographics, so no fairness analysis. +- Concat (`configs/protocol_b_concat_stat_xgb.yaml`) stacks 6-channel windows from both devices. It is not time-aligned 12-channel fusion. +- Protocol C is 46/5 x 3, not 51-fold LOSO. +- Phone eating and sitting stay weak even after repair. Watch sandwich (L) is 0.2816 F1 under Protocol B. +- The served ONNX bundle is a refit, not a GroupKFold fold. Abstain is uncalibrated (threshold 0.0). +- Mixed raw sampling rates are repaired to 20 Hz; residual orientation flips inside a session are not fully modeled (`reorient` default off; the ablation did not help 18-class phone GroupKFold). diff --git a/docs/model_card.md b/docs/model_card.md new file mode 100644 index 0000000..686b773 --- /dev/null +++ b/docs/model_card.md @@ -0,0 +1,44 @@ +# Model card: WISDM HAR + +Intended use: a CPU API that maps one 5 s, 20 Hz IMU window (phone or watch, 6 channels) to one of 18 WISDM activities. Not a medical or safety device. + +## Training data + +Repaired WISDM 20 Hz parquet from UCI 507. No demographics, so no fairness slice. Timestamp deltas are treated as nanoseconds; absolute epoch is unused. Coverage holes, mixed sampling rates, and row counts: `docs/data_card.md`. Split rules: `docs/protocol.md`. Notebook defects that inflated the old 0.8559 accuracy: `docs/limitations.md`. + +## Why trees + +Trees on repaired session features were enough. Protocol B GroupKFold phone statistical XGBoost macro-F1 is 0.3272 (`configs/protocol_b_phone_stat_xgb.yaml`), which beats dummy 0.0151 (`configs/protocol_b_phone_stat_dummy.yaml`), logreg 0.2767 (`configs/protocol_b_phone_stat_logreg.yaml`), RF 0.3131 (`configs/protocol_b_phone_stat_rf.yaml`), and flattened raw 0.2924 (`configs/protocol_b_phone_raw_flat_xgb.yaml`). Watch statistical XGBoost is 0.7031 (`configs/protocol_b_watch_stat_xgb.yaml`). Hierarchical is 0.3271 (`configs/ablations/hierarchical.yaml`) and does not beat the flat tree. There is no TCN, no `configs/phone_tcn.yaml`, and no PyTorch extra. + +## Served model + +| Field | Value | +|-------|--------| +| Recommended bundle | Watch statistical XGBoost from `configs/protocol_b_watch_stat_xgb.yaml` | +| Protocol (metrics) | B, 5-fold GroupKFold on `subject_id` | +| Protocol B macro-F1 | 0.7031 (`docs/reports/protocol_b_watch_stat_xgb.json`) | +| Protocol B accuracy | 0.7013 | +| Features | statistical, 104 dims, 5.0 s window, 20 Hz, `T=100`, `C=6` | +| Artifact | ONNX (`python -m har.models.export --out models/watch_stat_xgb.onnx`) plus sidecar JSON. joblib is a fallback. | +| ONNX | XGBoost trees via `onnxmltools==1.16.0` / `onnx==1.22.0`. Statistical features stay in Python. `onnxruntime==1.20.1` runs the graph. | +| Abstain | `max(proba) < threshold`; default threshold 0.0 (never abstain). Not temperature-scaled. | +| p95 CPU latency | 2.7 ms over 100 `POST /predict` calls (FastAPI TestClient, 200-tree XGBoost, statistical 100x6 window, this CPU). Not Docker/uvicorn and not a 51-subject watch model. Pytest checks a stub path stays under 500 ms. | + +Export fits on all windows from that config (one train subject used only for early stopping). That served fit is not a GroupKFold fold. Cite Protocol B numbers from the metrics JSON, not from the export command. + +Phone statistical XGBoost is 0.3272 macro-F1 under the same protocol. Concat fusion is 0.5236 and is stacked 6-channel windows, not 12-channel alignment. Do not send a phone window to a watch bundle; the API returns 422 on `device` mismatch. + +## Metrics to cite next to any number + +- Primary: macro-F1. Also per-class F1, per-group F1 (locomotion, posture, hand, eating), balanced accuracy. +- Leaky student-style accuracy is Protocol A only. Do not put it next to this API. + +## Failure modes + +Watch group F1 from `docs/reports/protocol_b_watch_stat_xgb.json`: locomotion 0.9292, posture 0.6606, hand 0.8788, eating 0.8450. Sandwich (L) is the weak watch class (per-class F1 0.2816). Stairs 0.7028 and kicking 0.7831. + +Phone eating and posture stay hard (eating group F1 0.4945 on `configs/protocol_b_phone_stat_xgb.yaml`; sitting 0.1943; eating per-class F1 0.07-0.11). Stairs 0.6588 and kicking 0.6470 are the weakest locomotion classes on phone. Hierarchical raises eating group F1 on phone (0.5855) but not 18-way macro-F1. + +## How to serve + +See `serving/README.md`. Endpoints: `GET /health`, `GET /labels`, `POST /predict`. Wrong window length or channel count is 422. diff --git a/docs/protocol.md b/docs/protocol.md index 8741ecb..aa13e28 100644 --- a/docs/protocol.md +++ b/docs/protocol.md @@ -12,16 +12,16 @@ Windows are built inside one `(subject_id, device, activity)` session. Scalers, |----------|--------|-------------| | A leaky | `train_test_split` on windows, `random_state=42`, 20% test | Student-style leaky number. Label every figure **leaky**. | | A1 | A, plus 80-sample flatten / hop 40 (row count, not seconds) | Closest clone of `notebooks/archive/PhoneXGB2.ipynb`. Config: `configs/protocol_a1_phone_raw_flat_xgb.yaml`. | -| A2 | A, plus session-safe 5 s / 1 s hop on the same repaired matrix | Leaky vs GroupKFold on one representation (RQ2). Config: `configs/protocol_a2_phone_raw_flat_xgb.yaml`. | +| A2 | A, plus session-safe 5 s / 1 s hop on the same repaired matrix | Leaky vs GroupKFold on one representation. Config: `configs/protocol_a2_phone_raw_flat_xgb.yaml`. | | B | 5-fold GroupKFold on `subject_id` | Main comparison table. Configs: `configs/protocol_b_*.yaml`. | | C | Grouped holdout: 5 test subjects, rest train, 3 repeats from one seed (46/5 x 3). Not 51-fold LOSO. | Variance across people. Config: `configs/protocol_c_phone_stat_xgb.yaml`. | -| D | Train phone, test watch (and reverse) on the same subjects | Hardware transfer. Later. | +| D | Train phone, test watch (and reverse) on the same subjects | Hardware transfer. Not run. | -Task 10 ablations overlay Protocol B phone statistical XGBoost. Table: `docs/reports/ablations.md`. Window length, 15 s trim, phone-accel reorient, magnitude-only features, and a group-then-expert head. Trim and reorient are applied at train time so `data/processed/` stays the trim-0 / unreoriented tree. +Ablations overlay Protocol B phone statistical XGBoost. Table: `docs/reports/ablations.md`. Window length, 15 s trim, phone-accel reorient, magnitude-only features, and a group-then-expert head. Trim and reorient are applied at train time so `data/processed/` stays the trim-0 / unreoriented tree. Known clone deltas vs the archive notebook: timestamp deltas as nanoseconds (not `unit="us"`), accel/gyro interpolated onto a shared grid (not an exact-timestamp join), session-safe windows (not `get_frames` on a concat table), no scaler fit on all rows, and flatten layout `(N, T, C)` C-order rather than `(N, 6, 80)`. YAML files request `device: cuda`; `fit_xgboost` falls back to CPU if CUDA is not visible. -Target after A2 exists: leaky accuracy in the same ballpark as 0.86 is possible but not required. Protocol B on the **same** flattened features should drop. That drop is the finding (RQ2). Config: `configs/protocol_b_phone_raw_flat_xgb.yaml` (student XGBoost params, GroupKFold). +Leaky accuracy in the same ballpark as 0.86 is possible on A1/A2 but not required. Protocol B on the **same** flattened features should drop. That drop is the finding. Config: `configs/protocol_b_phone_raw_flat_xgb.yaml` (student XGBoost params, GroupKFold). **Concat** in this repo is phone and watch windows stacked as extra rows. Each window is still 6 channels. `data.device: both` loads both devices. It is not a 12-channel time-aligned phone+watch fusion. Config: `configs/protocol_b_concat_stat_xgb.yaml`. @@ -34,8 +34,8 @@ Filenames are `protocol_{rung}_{device}_{features}_{model}.yaml`. `stat` means ` | Config | Role | Run on disk | |--------|------|-------------| | `protocol_a1_phone_raw_flat_xgb.yaml` | Student clone, 80-sample flatten, leaky | yes | -| `protocol_a2_phone_raw_flat_xgb.yaml` | 5 s flatten, leaky (RQ2 leaky side) | yes | -| `protocol_b_phone_raw_flat_xgb.yaml` | Same flatten as A2, GroupKFold (RQ2 honest side) | yes | +| `protocol_a2_phone_raw_flat_xgb.yaml` | 5 s flatten, leaky (leaky side of the same-representation pair) | yes | +| `protocol_b_phone_raw_flat_xgb.yaml` | Same flatten as A2, GroupKFold (honest side) | yes | | `protocol_b_phone_stat_dummy.yaml` | Chance floor | yes | | `protocol_b_phone_stat_logreg.yaml` | Linear baseline | yes | | `protocol_b_phone_stat_rf.yaml` | Tree baseline | yes | @@ -48,13 +48,13 @@ Not missing, on purpose: - No watch A1/A2. The student notebook is phone-only. - No watch dummy/logreg/RF. One 18-class chance floor is enough. -- No watch raw_flat. RQ3 (features vs flatten) is the phone A2 vs B flatten pair plus phone statistical B. +- No watch raw_flat. Feature vs flatten is the phone A2 vs B flatten pair plus phone statistical B. - No Protocol C on watch or concat. C checks that phone holdout tracks phone GroupKFold. Watch GroupKFold already has 5 subject folds. - No 12-channel aligned fusion. That is a new pipeline, not a YAML rename. ## Student hyperparameters (Protocol A, and Protocol B raw_flat only) -From `docs/reports/evaluation.txt`. They are pinned in the A1/A2 YAML files. `fit_xgboost` does not inject them. Do not reuse them as the honest-protocol default without a subject-grouped search. +From `notebooks/archive/student_evaluation.txt`. They are pinned in the A1/A2 YAML files. `fit_xgboost` does not inject them. Do not reuse them as the honest-protocol default without a subject-grouped search. ```text colsample_bytree: 0.9396893641976711 diff --git a/docs/reports/ablations.md b/docs/reports/ablations.md index d22451d..88e4fdb 100644 --- a/docs/reports/ablations.md +++ b/docs/reports/ablations.md @@ -1,4 +1,4 @@ -# Protocol B ablations (Task 10) +# Protocol B ablations Phone, repaired 20 Hz parquet, GroupKFold 5, statistical features unless noted. Primary metric is **macro-F1**. Control is `configs/protocol_b_phone_stat_xgb.yaml` (`docs/reports/protocol_b_phone_stat_xgb.json`): 5.0 s / 1.0 s hop, XYZ, no reorient, trim 0 s, flat 18-way XGBoost (200 trees). @@ -28,14 +28,14 @@ Per-group F1 (locomotion / posture / hand / eating): | Magnitude | 0.8698 | 0.2580 | 0.6103 | 0.4516 | | Hierarchical | 0.8964 | 0.3178 | 0.6380 | 0.5855 | -## RQ1 (repair knobs on this 18-class phone split) +## Repair knobs on this 18-class phone split Resample-to-20 Hz and accel/gyro align are already in the control parquet. On top of that: - rWISDM-style phone-accel reorient does not raise Protocol B macro-F1 (0.3230 vs 0.3272). Default `reorient: false` stays. This ablation reorients already-aligned phone accel (`channels[:, :3]`); `prepare.py` would reorient raw accel before interpolating onto the gyro grid. - Dropping the first 15 s does not raise macro-F1 (0.3247) and lowers eating group F1. Default `trim_start_s: 0.0` stays. -## RQ5 (two-stage head) +## Two-stage head Hierarchical does **not** beat flat 18-way on macro-F1 (0.3271 vs 0.3272). It does raise eating group F1 (0.5855 vs 0.4945) and hand group F1 (0.6380 vs 0.6002), while posture drops (0.3178 vs 0.3709). Eating class F1 moves H +0.047, I +0.027, J +0.062, K -0.031, L +0.029. diff --git a/docs/reports/evaluation.txt b/notebooks/archive/student_evaluation.txt similarity index 100% rename from docs/reports/evaluation.txt rename to notebooks/archive/student_evaluation.txt diff --git a/pyproject.toml b/pyproject.toml index f5f92b6..8bb4170 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -12,7 +12,7 @@ license = { text = "MIT" } dependencies = [ "pandas==2.2.3", "numpy==2.2.6", - "pyarrow==23.0.1", + "pyarrow==19.0.1", "scipy==1.15.3", "scikit-learn==1.7.2", "xgboost==2.1.4", @@ -20,7 +20,11 @@ dependencies = [ "fastapi==0.115.14", "uvicorn==0.34.3", "onnxruntime==1.20.1", + "onnx==1.22.0", + "onnxmltools==1.16.0", + "skl2onnx==1.20.0", "mlflow==2.22.5", + "matplotlib==3.10.3", ] [project.optional-dependencies] @@ -28,6 +32,7 @@ dev = [ "pytest==8.4.2", "ruff==0.12.0", "pre-commit==4.6.2", + "httpx==0.28.1", ] # Src layout: package har lives under src/ (Poetry equivalent: diff --git a/serving/Dockerfile b/serving/Dockerfile new file mode 100644 index 0000000..e43bfcb --- /dev/null +++ b/serving/Dockerfile @@ -0,0 +1,21 @@ +FROM python:3.13-slim-bookworm + +RUN apt-get update \ + && apt-get install -y --no-install-recommends libgomp1 \ + && rm -rf /var/lib/apt/lists/* + +WORKDIR /app +COPY pyproject.toml README.md ./ +COPY src ./src +# Inference-only image: skip full `pip install .` so we do not pull MLflow, +# XGBoost, or pyarrow. The API only needs these runtime packages. +RUN pip install --no-cache-dir \ + "numpy==2.2.6" \ + "fastapi==0.115.14" \ + "uvicorn==0.34.3" \ + "onnxruntime==1.20.1" \ + && pip install --no-cache-dir --no-deps . + +EXPOSE 8000 +ENV HAR_MODEL_PATH=/models/model.onnx +CMD ["uvicorn", "har.serve.app:app", "--host", "0.0.0.0", "--port", "8000"] diff --git a/serving/README.md b/serving/README.md new file mode 100644 index 0000000..b373614 --- /dev/null +++ b/serving/README.md @@ -0,0 +1,80 @@ +# HAR API + +CPU service for one 5 s, 20 Hz window (`T=100`, `C=6`). The v1 artifact is ONNX from `python -m har.models.export` (XGBoost trees via `onnxmltools`; statistical features still run in Python). joblib remains a fallback for stubs and non-XGBoost estimators. + +Shipped default to train for serving is watch statistical XGBoost (`configs/protocol_b_watch_stat_xgb.yaml`, Protocol B macro-F1 0.7031). Phone is a different model; do not send phone windows to a watch bundle. + +## Train to a bundle + +From the repo root, after `data/processed/` exists: + +```bash +python -m har.models.export --config configs/protocol_b_watch_stat_xgb.yaml --out models/watch_stat_xgb.onnx +``` + +That fits on all windows (one subject held out only for XGBoost early stopping), then writes gitignored `models/watch_stat_xgb.onnx` plus sidecar `models/watch_stat_xgb.json`. `data.device` must be `phone` or `watch`, not `both`. Export forces `device: cpu` even if the YAML says `cuda`. Use `--out *.joblib` only if you need a pickle. + +Abstain is `max(proba) < threshold`. Default threshold is `0.0` (never abstain) until a calibration pass. + +```bash +python -m har.models.export --config configs/protocol_b_watch_stat_xgb.yaml --out models/watch_stat_xgb.onnx --abstain-threshold 0.0 +``` + +## Run locally + +```bash +export HAR_MODEL_PATH=models/watch_stat_xgb.onnx +# optional override: HAR_ABSTAIN_THRESHOLD=0.0 +uvicorn har.serve.app:app --host 0.0.0.0 --port 8000 +``` + +The sidecar JSON must sit next to the `.onnx` file (same stem). + +```http +GET /health +GET /labels +POST /predict +``` + +`POST /predict` needs `T=100` rows (`window_s * hz` at the default 5 s / 20 Hz). Each row is 6 channels in `ax, ay, az, gx, gy, gz` order. Wrong `T` or `C` returns 422. Wrong `device` or `hz` also returns 422. + +```bash +python -c "import json,urllib.request; body=json.dumps({'device':'watch','hz':20,'channels':['ax','ay','az','gx','gy','gz'],'samples':[[0,0,0,0,0,0]]*100}).encode(); req=urllib.request.Request('http://127.0.0.1:8000/predict', data=body, headers={'Content-Type':'application/json'}); print(json.load(urllib.request.urlopen(req)))" +``` + +Response: + +```json +{ + "activity_code": "A", + "activity_name": "walking", + "group": "locomotion", + "proba": {"A": 0.81}, + "confidence": 0.81, + "abstained": false +} +``` + +(`proba` includes all 18 codes A-S except N.) + +p95 on this CPU was 2.7 ms over 100 `POST /predict` calls through FastAPI TestClient with a 200-tree XGBoost on a statistical 100x6 window. Not Docker/uvicorn. Pytest asserts the stub path stays under 500 ms. + +```bash +python -c "import json,urllib.request; print(json.load(urllib.request.urlopen('http://127.0.0.1:8000/health')))" +``` + +## Docker + +Build from the repo root (not from `serving/`): + +```bash +docker build -f serving/Dockerfile -t har-api . +MSYS_NO_PATHCONV=1 docker run --rm -p 8000:8000 \ + -v "$PWD/models:/models" \ + -e HAR_MODEL_PATH=/models/watch_stat_xgb.onnx \ + har-api +``` + +Git Bash rewrites `/models/...` to a Git path unless `MSYS_NO_PATHCONV=1` is set. If local uvicorn is already on 8000, map `-p 8001:8000` instead. + +The image is CPU inference only. It does not install MLflow, XGBoost, or pyarrow. A full `pip install .` is the train/eval env, not this image. diff --git a/src/har/data/audit.py b/src/har/data/audit.py index 3e182a2..f7a98e3 100644 --- a/src/har/data/audit.py +++ b/src/har/data/audit.py @@ -238,13 +238,14 @@ def write_data_card( lines = [ "# WISDM data card", "", - "Generated by `python scripts/audit.py`. Sampling rate is implied Hz: " - "`1e9 / median_dt_ns` from timestamp diffs inside a session. " - "Absolute Unix epoch is not used.", + "Audit of the raw [WISDM Smartphone and Smartwatch Activity and Biometrics " + "Dataset (UCI 507)](https://archive.ics.uci.edu/dataset/507/" + "wisdm+smartphone+and+smartwatch+activity+and+biometrics+dataset) dump on disk. " + "This card describes raw sessions, not the repaired 20 Hz parquet. " + "Regenerate with `python -m har.data.audit` (or `python scripts/audit.py`).", "", - "Dataset: [WISDM Smartphone and Smartwatch Activity and Biometrics Dataset " - "(UCI 507)](https://archive.ics.uci.edu/dataset/507/" - "wisdm+smartphone+and+smartwatch+activity+and+biometrics+dataset).", + "Sampling rate is implied Hz: `1e9 / median_dt_ns` from timestamp diffs " + "inside a session. Absolute Unix epoch is unused.", "", "## Row counts vs Weiss", "", @@ -368,9 +369,11 @@ def write_data_card( "", "- No demographics (gender, handedness, height, phone model) in this dump, " "so no fairness slices.", - "- Start-of-trial seconds may not match the labeled activity; trim is a later repair flag.", - "- Accel and gyro clocks are not assumed to share sample instants; " - "alignment is a later repair step.", + "- Start-of-trial seconds may not match the labeled activity. " + "Repair can drop them (`trim_start_s`); the default tree is untrimmed.", + "- Accel and gyro clocks do not share sample instants. " + "Repair interpolates both onto a shared 20 Hz grid per session " + "(`python -m har.data.repair`).", "", ] ) diff --git a/src/har/eval/plots.py b/src/har/eval/plots.py index 269d04c..7bce6ff 100644 --- a/src/har/eval/plots.py +++ b/src/har/eval/plots.py @@ -1,13 +1,51 @@ -"""Confusion-matrix helpers for experiment reports.""" +"""Confusion matrices and README / MLflow figures from metrics JSON.""" from __future__ import annotations -from collections.abc import Sequence +import argparse +import json +import logging +from collections.abc import Mapping, Sequence from pathlib import Path +from typing import Any +import matplotlib import numpy as np from sklearn.metrics import confusion_matrix as sklearn_confusion_matrix +from har.constants import CODE_TO_NAME, LABEL_ORDER + +matplotlib.use("Agg", force=True) + +log = logging.getLogger(__name__) + +PHONE = "#0072B2" +WATCH = "#D55E00" +CONCAT = "#009E73" +MUTED = "#7A7A7A" +INK = "#222222" + +HZ_SESSION_COUNTS = ((20, 2838), (25, 543), (50, 322), (100, 14)) + +LADDER_ROWS = ( + ("protocol_b_phone_stat_dummy.json", "Dummy (phone)"), + ("protocol_b_phone_stat_logreg.json", "LogReg (phone)"), + ("protocol_b_phone_stat_rf.json", "Random forest (phone)"), + ("protocol_b_phone_stat_xgb.json", "XGBoost (phone)"), + ("protocol_b_concat_stat_xgb.json", "XGBoost (concat)"), + ("protocol_b_watch_stat_xgb.json", "XGBoost (watch)"), +) + +ABLATION_ROWS = ( + ("protocol_b_phone_stat_xgb.json", "Control 5 s XYZ"), + ("ablations/window_2s.json", "Window 2 s"), + ("ablations/window_10s.json", "Window 10 s"), + ("ablations/trim_15s.json", "Trim 15 s"), + ("ablations/reorient_on.json", "Reorient on"), + ("ablations/magnitude.json", "Magnitude only"), + ("ablations/hierarchical.json", "Hierarchical"), +) + def confusion_counts( y_true: np.ndarray, @@ -17,6 +55,23 @@ def confusion_counts( return np.asarray(sklearn_confusion_matrix(y_true, y_pred, labels=list(labels))) +def class_f1_by_name(per_class_f1: Mapping[str, float]) -> dict[str, float]: + """Map metrics JSON keys (``"0"``..``"17"`` or activity codes) to class names.""" + out: dict[str, float] = {} + for key, value in per_class_f1.items(): + try: + idx = int(key) + except (TypeError, ValueError): + code = str(key) + out[str(CODE_TO_NAME.get(code, code))] = float(value) + continue + if 0 <= idx < len(LABEL_ORDER): + out[CODE_TO_NAME[LABEL_ORDER[idx]]] = float(value) + else: + out[str(key)] = float(value) + return out + + def save_confusion_matrix( path: Path, y_true: np.ndarray, @@ -29,15 +84,312 @@ def save_confusion_matrix( counts = confusion_counts(y_true, y_pred, labels) names = class_names if class_names is not None else [str(x) for x in labels] - fig, ax = plt.subplots() - image = ax.imshow(counts, interpolation="nearest") - ax.set_xlabel("predicted") - ax.set_ylabel("true") - ax.set_xticks(range(len(names)), labels=names, rotation=45, ha="right") + fig, ax = plt.subplots(figsize=(8.2, 7.2)) + image = ax.imshow(counts, interpolation="nearest", cmap="Blues") + ax.set_xlabel("Predicted") + ax.set_ylabel("True") + ax.set_xticks(range(len(names)), labels=names, rotation=55, ha="right") ax.set_yticks(range(len(names)), labels=names) - fig.colorbar(image, ax=ax) + fig.colorbar(image, ax=ax, fraction=0.046, pad=0.04) + return _savefig(fig, path) + + +def save_run_summary_figure(path: Path, payload: Mapping[str, Any]) -> Path: + """Per-class F1 bars for one run (MLflow artifact).""" + import matplotlib.pyplot as plt + + rows = _ordered_class_f1(payload) + names = [name for name, _ in rows] + values = [value for _, value in rows] + fig, ax = plt.subplots(figsize=(7.2, 6.4)) + y = np.arange(len(names)) + ax.barh(y, values, color=PHONE, height=0.72) + ax.set_yticks(y, labels=names) + ax.invert_yaxis() + ax.set_xlim(0, 1) + ax.set_xlabel("F1") + ax.set_title(_run_title(payload)) + ax.axvline( + float(payload["macro_f1"]), color=WATCH, linewidth=1.2, linestyle="--", label="macro-F1" + ) + ax.legend(frameon=False, loc="lower right") + return _savefig(fig, path) + + +def write_readme_figures(reports_dir: Path, out_dir: Path) -> list[Path]: + """Build the README figure set from metrics JSON. Skip charts whose files are missing.""" + reports_dir = Path(reports_dir) + out_dir = Path(out_dir) + out_dir.mkdir(parents=True, exist_ok=True) + written: list[Path] = [] + + a2 = _load(reports_dir / "protocol_a2_phone_raw_flat_xgb.json") + b_flat = _load(reports_dir / "protocol_b_phone_raw_flat_xgb.json") + if a2 and b_flat: + written.append( + _labeled_bars( + out_dir / "leakage_macro_f1.png", + title="Same phone windows: leaky split vs GroupKFold", + xlabel="macro-F1", + labels=( + "A2 leaky\n(flattened 5 s)", + "B GroupKFold\n(flattened 5 s)", + ), + values=(float(a2["macro_f1"]), float(b_flat["macro_f1"])), + colors=(MUTED, PHONE), + ) + ) + + ladder = [(label, _load(reports_dir / name)) for name, label in LADDER_ROWS] + if all(row[1] for row in ladder): + written.append( + _labeled_bars( + out_dir / "protocol_b_ladder.png", + title="Protocol B GroupKFold, statistical features unless noted", + xlabel="macro-F1", + labels=tuple(label for label, _ in ladder), + values=tuple(float(row["macro_f1"]) for _, row in ladder if row), + colors=(MUTED, MUTED, MUTED, PHONE, CONCAT, WATCH), + invert=False, + ) + ) + + phone = _load(reports_dir / "protocol_b_phone_stat_xgb.json") + watch = _load(reports_dir / "protocol_b_watch_stat_xgb.json") + if phone and watch: + written.append(_grouped_class_f1(out_dir / "per_class_f1_phone_watch.png", phone, watch)) + written.append(_grouped_group_f1(out_dir / "per_group_f1_phone_watch.png", phone, watch)) + + ablation_loaded = [(label, _load(reports_dir / name)) for name, label in ABLATION_ROWS] + if all(row[1] for row in ablation_loaded): + written.append( + _labeled_bars( + out_dir / "ablations_macro_f1.png", + title="Phone statistical XGBoost ablations (Protocol B)", + xlabel="macro-F1", + labels=tuple(label for label, _ in ablation_loaded), + values=tuple(float(row["macro_f1"]) for _, row in ablation_loaded if row), + colors=(PHONE,) + (MUTED,) * (len(ablation_loaded) - 1), + ) + ) + + written.append(_hz_modes(out_dir / "sampling_rate_modes.png")) + return written + + +def sync_mlflow_run_names(reports_dir: Path) -> list[str]: + """Set MLflow run names to the metrics JSON stem. Skip missing tracking stores.""" + import mlflow + + updated: list[str] = [] + for path in _metric_json_paths(Path(reports_dir)): + payload = _load(path) + if not payload: + continue + run_id = payload.get("mlflow_run_id") + uri = payload.get("mlflow_tracking_uri") + if not run_id or not uri: + continue + try: + client = mlflow.MlflowClient(tracking_uri=str(uri)) + name = path.stem + if path.parent.name == "ablations": + name = f"ablation_{name}" + client.set_tag(str(run_id), "mlflow.runName", name) + _backfill_run_metrics(client, str(run_id), payload) + except Exception as exc: # noqa: BLE001 - tracking store may be absent + log.warning("skip mlflow rename %s: %s", path.name, exc) + continue + updated.append(name) + return updated + + +def main(argv: list[str] | None = None) -> list[Path]: + parser = argparse.ArgumentParser(description="Write README figures from metrics JSON.") + parser.add_argument("--from-reports", type=Path, default=Path("docs/reports")) + parser.add_argument("--out", type=Path, default=Path("docs/figures")) + parser.add_argument( + "--sync-mlflow", + action="store_true", + help="Rename existing MLflow runs to the report filename stem.", + ) + args = parser.parse_args(argv) + logging.basicConfig(level=logging.INFO, format="%(message)s") + written = write_readme_figures(args.from_reports, args.out) + for path in written: + log.info("wrote %s", path) + print(path) + if args.sync_mlflow: + for name in sync_mlflow_run_names(args.from_reports): + log.info("named mlflow run %s", name) + return written + + +def _load(path: Path) -> dict[str, Any] | None: + if not path.is_file(): + return None + try: + payload = json.loads(path.read_text(encoding="utf-8")) + except json.JSONDecodeError: + return None + return payload if isinstance(payload, dict) else None + + +def _metric_json_paths(reports_dir: Path) -> list[Path]: + paths = [p for p in sorted(reports_dir.glob("*.json")) if p.name != "ladder_summary.json"] + paths.extend(sorted((reports_dir / "ablations").glob("*.json"))) + return paths + + +def _backfill_run_metrics(client: Any, run_id: str, payload: Mapping[str, Any]) -> None: + existing = client.get_run(run_id).data.metrics + if "fold_macro_f1" not in existing: + for i, fold in enumerate(payload.get("folds") or [], start=1): + client.log_metric(run_id, "fold_macro_f1", float(fold["macro_f1"]), step=i) + if "accuracy" in fold: + client.log_metric(run_id, "fold_accuracy", float(fold["accuracy"]), step=i) + groups = payload.get("per_group_f1") or {} + for name, value in groups.items(): + key = f"group_f1_{name}" + if key not in existing: + client.log_metric(run_id, key, float(value)) + + +def _ordered_class_f1(payload: Mapping[str, Any]) -> list[tuple[str, float]]: + raw = payload.get("per_class_f1") or {} + rows: list[tuple[str, float]] = [] + for i, code in enumerate(LABEL_ORDER): + if str(i) in raw: + value = raw[str(i)] + elif i in raw: + value = raw[i] + elif code in raw: + value = raw[code] + else: + value = 0.0 + rows.append((CODE_TO_NAME[code], float(value))) + return rows + + +def _run_title(payload: Mapping[str, Any]) -> str: + protocol = payload.get("protocol_name") or payload.get("protocol") or "run" + device = payload.get("device") or "?" + model = payload.get("model") or "?" + return f"Per-class F1 · {protocol} · {device} {model}" + + +def _style(ax: Any) -> None: + ax.spines["top"].set_visible(False) + ax.spines["right"].set_visible(False) + ax.tick_params(colors=INK) + ax.xaxis.label.set_color(INK) + ax.yaxis.label.set_color(INK) + ax.title.set_color(INK) + ax.grid(axis="x", linestyle=":", alpha=0.45) + ax.set_axisbelow(True) + + +def _savefig(fig: Any, path: Path) -> Path: out = Path(path) out.parent.mkdir(parents=True, exist_ok=True) - fig.savefig(out, bbox_inches="tight") + fig.savefig(out, bbox_inches="tight", dpi=200, facecolor="white") + import matplotlib.pyplot as plt + plt.close(fig) return out + + +def _labeled_bars( + path: Path, + *, + title: str, + xlabel: str, + labels: Sequence[str], + values: Sequence[float], + colors: Sequence[str], + invert: bool = True, +) -> Path: + import matplotlib.pyplot as plt + + fig, ax = plt.subplots(figsize=(7.4, 0.55 * len(labels) + 1.6)) + y = np.arange(len(labels)) + ax.barh(y, values, color=list(colors), height=0.66) + ax.set_yticks(y, labels=list(labels)) + if invert: + ax.invert_yaxis() + ax.set_xlim(0, 1.18) + ax.set_xticks([0.0, 0.2, 0.4, 0.6, 0.8, 1.0]) + ax.set_xlabel(xlabel) + ax.set_title(title) + for yi, value in zip(y, values, strict=True): + ax.text(value + 0.02, float(yi), f"{value:.3f}", va="center", color=INK, fontsize=9) + _style(ax) + return _savefig(fig, path) + + +def _grouped_class_f1(path: Path, phone: Mapping[str, Any], watch: Mapping[str, Any]) -> Path: + import matplotlib.pyplot as plt + + phone_rows = _ordered_class_f1(phone) + watch_map = dict(_ordered_class_f1(watch)) + names = [name for name, _ in phone_rows] + phone_vals = [value for _, value in phone_rows] + watch_vals = [watch_map[name] for name in names] + fig, ax = plt.subplots(figsize=(8.0, 7.2)) + y = np.arange(len(names)) + ax.barh(y + 0.18, phone_vals, 0.36, label="Phone", color=PHONE) + ax.barh(y - 0.18, watch_vals, 0.36, label="Watch", color=WATCH) + ax.set_yticks(y, labels=names) + ax.invert_yaxis() + ax.set_xlim(0, 1) + ax.set_xlabel("F1") + ax.set_title("Per-class F1, Protocol B statistical XGBoost") + ax.legend(frameon=False, loc="lower right") + _style(ax) + return _savefig(fig, path) + + +def _grouped_group_f1(path: Path, phone: Mapping[str, Any], watch: Mapping[str, Any]) -> Path: + import matplotlib.pyplot as plt + + order = ("locomotion", "hand", "eating", "posture") + phone_g = {str(k): float(v) for k, v in (phone.get("per_group_f1") or {}).items()} + watch_g = {str(k): float(v) for k, v in (watch.get("per_group_f1") or {}).items()} + labels = [name.capitalize() for name in order] + fig, ax = plt.subplots(figsize=(7.2, 3.6)) + x = np.arange(len(order)) + ax.bar(x - 0.18, [phone_g[k] for k in order], 0.36, label="Phone", color=PHONE) + ax.bar(x + 0.18, [watch_g[k] for k in order], 0.36, label="Watch", color=WATCH) + ax.set_xticks(x, labels=labels) + ax.set_ylim(0, 1) + ax.set_ylabel("F1") + ax.set_title("Activity-group F1, Protocol B statistical XGBoost") + ax.legend(frameon=False) + ax.spines["top"].set_visible(False) + ax.spines["right"].set_visible(False) + ax.grid(axis="y", linestyle=":", alpha=0.45) + ax.set_axisbelow(True) + return _savefig(fig, path) + + +def _hz_modes(path: Path) -> Path: + import matplotlib.pyplot as plt + + labels = [f"{hz} Hz" for hz, _ in HZ_SESSION_COUNTS] + values = [count for _, count in HZ_SESSION_COUNTS] + fig, ax = plt.subplots(figsize=(6.4, 3.4)) + x = np.arange(len(labels)) + ax.bar(x, values, color=PHONE) + ax.set_xticks(x, labels=labels) + ax.set_ylabel("Sessions") + ax.set_title("Implied sampling-rate modes in raw WISDM") + for xi, value in zip(x, values, strict=True): + ax.text(float(xi), value + 40, f"{value:,}", ha="center", va="bottom", fontsize=9, color=INK) + ax.spines["top"].set_visible(False) + ax.spines["right"].set_visible(False) + ax.set_ylim(0, max(values) * 1.15) + return _savefig(fig, path) + + +if __name__ == "__main__": + main() diff --git a/src/har/evaluate.py b/src/har/evaluate.py index a25b8c3..36cad9f 100644 --- a/src/har/evaluate.py +++ b/src/har/evaluate.py @@ -9,6 +9,7 @@ from pathlib import Path from typing import Any +from har.eval.plots import write_readme_figures from har.train import _repo_root, _tracking_uri, run_experiment log = logging.getLogger(__name__) @@ -50,7 +51,15 @@ def summarize_reports(reports_dir: Path) -> Path: continue runs.append(payload) table.append(_table_row(payload, source=path.name)) - return _write_summary(reports_dir, runs, table) + summary = _write_summary(reports_dir, runs, table) + write_readme_figures(reports_dir, _figure_dir(reports_dir)) + return summary + + +def _figure_dir(reports_dir: Path) -> Path: + if reports_dir.name == "reports": + return reports_dir.parent / "figures" + return reports_dir / "figures" def main(argv: list[str] | None = None) -> Path | None: @@ -81,9 +90,7 @@ def _table_row(payload: Mapping[str, Any], *, source: str) -> dict[str, Any]: return row -def _write_summary( - out_dir: Path, runs: list[dict[str, Any]], table: list[dict[str, Any]] -) -> Path: +def _write_summary(out_dir: Path, runs: list[dict[str, Any]], table: list[dict[str, Any]]) -> Path: out_dir.mkdir(parents=True, exist_ok=True) out = out_dir / LADDER_NAME out.write_text(json.dumps({"runs": runs, "table": table}, indent=2) + "\n", encoding="utf-8") diff --git a/src/har/models/__init__.py b/src/har/models/__init__.py index e2c9d52..53a9f46 100644 --- a/src/har/models/__init__.py +++ b/src/har/models/__init__.py @@ -1 +1 @@ -"""Classical HAR models: dummy, logreg, random forest, XGBoost, hierarchical.""" +"""Classical HAR models: dummy, logreg, random forest, XGBoost, hierarchical, export.""" diff --git a/src/har/models/export.py b/src/har/models/export.py new file mode 100644 index 0000000..1db08ed --- /dev/null +++ b/src/har/models/export.py @@ -0,0 +1,353 @@ +"""Persist a fitted estimator for the API. XGBoost goes to ONNX; joblib is the fallback.""" + +from __future__ import annotations + +import argparse +import json +import os +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +import numpy as np + +from har.constants import CHANNEL_NAMES, CODE_TO_NAME, GROUP_OF, LABEL_ORDER, TARGET_HZ +from har.features.statistical import extract_statistical, flatten_raw, to_magnitude +from har.types import Device + +BUNDLE_FORMAT = "har.bundle.v1" +ONNX_META_FORMAT = "har.onnx.v1" + + +@dataclass +class ModelBundle: + """Serving payload: estimator plus the window contract it was trained on.""" + + estimator: Any + n_timesteps: int + n_channels: int + hz: float + device: Device + features: str + model_id: str + abstain_threshold: float = 0.0 + channel_names: tuple[str, ...] = CHANNEL_NAMES + format: str = BUNDLE_FORMAT + + +class OnnxEstimator: + """onnxruntime wrapper with sklearn-style predict_proba.""" + + def __init__(self, session: Any, *, classes: np.ndarray, n_features: int) -> None: + self._session = session + self.classes_ = np.asarray(classes) + self.n_features_in_ = int(n_features) + inputs = session.get_inputs() + outputs = session.get_outputs() + if not inputs or not outputs: + raise ValueError("ONNX model has no inputs or outputs") + self._input_name = inputs[0].name + names = [out.name.lower() for out in outputs] + if "probabilities" in names: + self._proba_index = names.index("probabilities") + else: + self._proba_index = len(outputs) - 1 + + def predict_proba(self, X: np.ndarray) -> np.ndarray: + arr = np.ascontiguousarray(np.asarray(X, dtype=np.float32)) + outputs = self._session.run(None, {self._input_name: arr}) + return np.asarray(outputs[self._proba_index], dtype=np.float64) + + +def save_bundle(path: Path, bundle: ModelBundle) -> Path: + path = Path(path) + if path.suffix == ".onnx": + return save_onnx_bundle(path, bundle) + path.parent.mkdir(parents=True, exist_ok=True) + _force_cpu(bundle.estimator) + import joblib + + joblib.dump(bundle, path) + return path + + +def save_onnx_bundle(path: Path, bundle: ModelBundle) -> Path: + path = Path(path) + n_features = int(getattr(bundle.estimator, "n_features_in_")) + export_onnx(bundle.estimator, path, n_features) + classes = [int(c) for c in np.asarray(bundle.estimator.classes_).tolist()] + meta = { + "format": ONNX_META_FORMAT, + "n_timesteps": int(bundle.n_timesteps), + "n_channels": int(bundle.n_channels), + "n_features": n_features, + "hz": float(bundle.hz), + "device": bundle.device, + "features": bundle.features, + "model_id": bundle.model_id, + "abstain_threshold": float(bundle.abstain_threshold), + "channel_names": list(bundle.channel_names[: bundle.n_channels]), + "classes": classes, + } + path.with_suffix(".json").write_text(json.dumps(meta, indent=2) + "\n", encoding="utf-8") + return path + + +def load_bundle(path: Path) -> ModelBundle: + path = Path(path) + if path.suffix == ".onnx": + return load_onnx_bundle(path) + import joblib + + loaded = joblib.load(path) + if not isinstance(loaded, ModelBundle): + raise TypeError(f"expected ModelBundle, got {type(loaded).__name__}") + if loaded.format != BUNDLE_FORMAT: + raise ValueError(f"unsupported bundle format {loaded.format!r}") + _force_cpu(loaded.estimator) + return loaded + + +def load_onnx_bundle(path: Path) -> ModelBundle: + import onnxruntime as ort + + path = Path(path) + meta_path = path.with_suffix(".json") + if not meta_path.is_file(): + raise FileNotFoundError(f"missing ONNX sidecar {meta_path}") + meta = json.loads(meta_path.read_text(encoding="utf-8")) + if meta.get("format") != ONNX_META_FORMAT: + raise ValueError(f"unsupported ONNX sidecar format {meta.get('format')!r}") + session = ort.InferenceSession(str(path), providers=["CPUExecutionProvider"]) + estimator = OnnxEstimator( + session, + classes=np.asarray(meta["classes"], dtype=np.int64), + n_features=int(meta["n_features"]), + ) + names = meta.get("channel_names") or CHANNEL_NAMES[: int(meta["n_channels"])] + return ModelBundle( + estimator=estimator, + n_timesteps=int(meta["n_timesteps"]), + n_channels=int(meta["n_channels"]), + hz=float(meta["hz"]), + device=meta["device"], + features=str(meta["features"]), + model_id=str(meta["model_id"]), + abstain_threshold=float(meta.get("abstain_threshold") or 0.0), + channel_names=tuple(names), + format=ONNX_META_FORMAT, + ) + + +def export_onnx(estimator: Any, path: Path, n_features: int) -> Path: + """Convert an XGBoost classifier to ONNX. Feature extraction stays in Python.""" + if "XGB" not in type(estimator).__name__: + raise TypeError(f"ONNX export supports XGBoost, got {type(estimator).__name__}") + from onnxmltools.convert import convert_xgboost + from onnxmltools.convert.common.data_types import FloatTensorType + + _force_cpu(estimator) + onnx_model = convert_xgboost( + estimator, + initial_types=[("input", FloatTensorType([None, int(n_features)]))], + ) + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(onnx_model.SerializeToString()) + return path + + +def predict_window(bundle: ModelBundle, samples: np.ndarray) -> dict[str, Any]: + """Featurize one (T, C) window and return the /predict payload fields.""" + arr = np.asarray(samples, dtype=np.float32) + expected = (int(bundle.n_timesteps), int(bundle.n_channels)) + if arr.ndim != 2 or arr.shape != expected: + raise ValueError(f"expected samples shape {expected}, got {arr.shape}") + feat = _featurize_one(arr, bundle.features) + n_in = getattr(bundle.estimator, "n_features_in_", None) + if n_in is not None and int(feat.shape[1]) != int(n_in): + raise ValueError(f"expected {int(n_in)} features, got {int(feat.shape[1])}") + if not hasattr(bundle.estimator, "predict_proba"): + raise TypeError(f"{type(bundle.estimator).__name__} has no predict_proba") + raw = np.asarray(bundle.estimator.predict_proba(feat)[0], dtype=np.float64) + classes = np.asarray(getattr(bundle.estimator, "classes_", np.arange(raw.size))) + proba = {code: 0.0 for code in LABEL_ORDER} + for p, cls in zip(raw, classes, strict=True): + idx = int(cls) + if 0 <= idx < len(LABEL_ORDER): + proba[LABEL_ORDER[idx]] = float(p) + code = max(proba.items(), key=lambda item: item[1])[0] + confidence = float(proba[code]) + return { + "activity_code": code, + "activity_name": CODE_TO_NAME[code], + "group": GROUP_OF[code], + "proba": proba, + "confidence": confidence, + "abstained": confidence < float(bundle.abstain_threshold), + } + + +def export_from_config( + config_path: Path, + out_path: Path, + *, + model_id: str | None = None, + abstain_threshold: float = 0.0, +) -> Path: + """Fit on all windows from a train YAML (one device) and write ONNX or joblib.""" + from har.data.windows import make_windows, stack_windows + from har.eval.splits import Split + from har.train import ( + _apply_session_repair, + _as_device, + _device_filter, + _featurize, + _fit_model, + _load_config, + _repo_root, + _require_config_path, + _resolve_path, + _section, + _window_seconds, + load_aligned_sessions, + ) + + repo = _repo_root() + config_path = _require_config_path(Path(config_path), repo) + cfg = _load_config(config_path, repo) + model_cfg = _serve_model_cfg(_section(cfg, "model")) + data_cfg = _section(cfg, "data") + device_cfg = data_cfg.get("device") + if device_cfg in (None, "both", "all"): + raise ValueError("export needs data.device of phone or watch, not both") + device = _as_device(device_cfg) + processed_dir = _resolve_path(data_cfg.get("processed_dir") or "data/processed", repo) + sessions = load_aligned_sessions( + processed_dir, + device=_device_filter(device_cfg), + subjects=data_cfg.get("subjects"), + ) + if not sessions: + raise FileNotFoundError(f"no aligned sessions under {processed_dir}") + sessions = _apply_session_repair(sessions, _section(cfg, "repair")) + window_cfg = _section(cfg, "window") + windows = [] + for session in sessions: + length_s, hop_s = _window_seconds(session, window_cfg) + windows.extend( + make_windows( + session, + length_s=length_s, + hop_s=hop_s, + min_coverage=float(window_cfg.get("min_coverage", 0.95)), + ) + ) + X, y, groups = stack_windows(windows) + if X.shape[0] == 0: + raise ValueError("no windows produced") + feature_kind = str(_section(cfg, "features").get("kind") or "statistical") + X_feat = _featurize(X, feature_kind) + seed = int(cfg.get("seed", 42)) + split = Split( + X_train=X_feat, + y_train=y, + X_test=X_feat[:1], + y_test=y[:1], + groups_train=groups, + groups_test=groups[:1], + ) + model = _fit_model(split, model_cfg, protocol="groupkfold", seed=seed) + if not hasattr(model, "predict_proba"): + raise TypeError(f"{type(model).__name__} has no predict_proba; cannot export for serving") + bundle = ModelBundle( + estimator=model, + n_timesteps=int(X.shape[1]), + n_channels=int(X.shape[2]), + hz=float(sessions[0].hz) if sessions[0].hz else TARGET_HZ, + device=device, + features=feature_kind, + model_id=model_id or config_path.stem, + abstain_threshold=float(abstain_threshold), + channel_names=CHANNEL_NAMES[: int(X.shape[2])], + ) + return save_bundle(out_path, bundle) + + +def bundle_from_env() -> ModelBundle: + raw = os.environ.get("HAR_MODEL_PATH") + if not raw: + raise RuntimeError("HAR_MODEL_PATH is not set") + bundle = load_bundle(Path(raw)) + threshold = os.environ.get("HAR_ABSTAIN_THRESHOLD") + if threshold is not None and threshold != "": + bundle.abstain_threshold = float(threshold) + model_id = os.environ.get("HAR_MODEL_ID") + if model_id: + bundle.model_id = model_id + return bundle + + +def main(argv: list[str] | None = None) -> Path: + parser = argparse.ArgumentParser( + description="Fit a one-device config and write an ONNX or joblib bundle." + ) + parser.add_argument("--config", type=Path, required=True) + parser.add_argument( + "--out", + type=Path, + required=True, + help="Ends with .onnx (model + sidecar json) or .joblib (pickle).", + ) + parser.add_argument("--model-id") + parser.add_argument("--abstain-threshold", type=float, default=0.0) + args = parser.parse_args(argv) + out = export_from_config( + args.config, + args.out, + model_id=args.model_id, + abstain_threshold=args.abstain_threshold, + ) + print(out) + return out + + +def _serve_model_cfg(model_cfg: dict[str, Any]) -> dict[str, Any]: + """CPU-only export. Training YAML may say cuda; Docker has no GPU.""" + out = dict(model_cfg) + if str(out.get("name") or "xgboost") == "hierarchical": + raise TypeError("hierarchical has no predict_proba; cannot export for serving") + params = dict(out.get("params") or {}) + params["device"] = "cpu" + out["params"] = params + return out + + +def _featurize_one(x: np.ndarray, kind: str) -> np.ndarray: + if kind == "raw_flat": + return flatten_raw(x).reshape(1, -1) + if kind == "statistical": + return extract_statistical(x).reshape(1, -1) + if kind == "magnitude": + return extract_statistical(to_magnitude(x)).reshape(1, -1) + raise ValueError(f"unknown features.kind {kind!r}") + + +def _force_cpu(estimator: Any) -> None: + setter = getattr(estimator, "set_params", None) + if setter is not None: + try: + setter(device="cpu") + except (TypeError, ValueError): + pass + get_booster = getattr(estimator, "get_booster", None) + if get_booster is None: + return + try: + get_booster().set_param({"device": "cpu"}) + except (TypeError, ValueError, AttributeError): + return + + +if __name__ == "__main__": + main() diff --git a/src/har/models/xgboost.py b/src/har/models/xgboost.py index 7edb7e9..87ee84b 100644 --- a/src/har/models/xgboost.py +++ b/src/har/models/xgboost.py @@ -14,7 +14,7 @@ log = logging.getLogger(__name__) -# From docs/reports/evaluation.txt. Protocol A reproduction only. +# From notebooks/archive/student_evaluation.txt. Protocol A reproduction only. STUDENT_XGB_PARAMS: dict[str, Any] = { "colsample_bytree": 0.9396893641976711, "gamma": 0, diff --git a/src/har/serve/__init__.py b/src/har/serve/__init__.py new file mode 100644 index 0000000..b512493 --- /dev/null +++ b/src/har/serve/__init__.py @@ -0,0 +1 @@ +"""FastAPI surface for window-level HAR predictions.""" diff --git a/src/har/serve/app.py b/src/har/serve/app.py new file mode 100644 index 0000000..ad008ab --- /dev/null +++ b/src/har/serve/app.py @@ -0,0 +1,103 @@ +"""FastAPI app: health, labels, and one-window predict.""" + +from __future__ import annotations + +from collections.abc import AsyncIterator, Awaitable, Callable +from contextlib import asynccontextmanager + +import numpy as np +from fastapi import FastAPI, HTTPException, Request +from fastapi.responses import JSONResponse +from starlette.responses import Response + +from har.constants import ACTIVITY_CODES, CODE_TO_NAME, GROUP_OF +from har.models.export import ModelBundle, bundle_from_env, predict_window +from har.serve.schema import ( + MAX_BODY_BYTES, + HealthResponse, + LabelsResponse, + PredictRequest, + PredictResponse, +) + + +def create_app(bundle: ModelBundle | None = None) -> FastAPI: + """Build an app. Tests pass a bundle; uvicorn loads HAR_MODEL_PATH on startup.""" + holder: dict[str, ModelBundle | None] = {"bundle": bundle} + + @asynccontextmanager + async def lifespan(_application: FastAPI) -> AsyncIterator[None]: + if holder["bundle"] is None: + holder["bundle"] = bundle_from_env() + yield + + application = FastAPI(title="WISDM HAR", version="0.1.0", lifespan=lifespan) + + @application.middleware("http") + async def cap_body( + request: Request, call_next: Callable[[Request], Awaitable[Response]] + ) -> Response: + length = request.headers.get("content-length") + if length is not None: + try: + n = int(length) + except ValueError: + n = MAX_BODY_BYTES + 1 + if n > MAX_BODY_BYTES: + return JSONResponse({"detail": "request too large"}, status_code=413) + return await call_next(request) + + def _bundle() -> ModelBundle: + loaded = holder["bundle"] + if loaded is None: + loaded = bundle_from_env() + holder["bundle"] = loaded + return loaded + + @application.get("/health", response_model=HealthResponse) + def health() -> HealthResponse: + return HealthResponse(status="ok", model_id=_bundle().model_id) + + @application.get("/labels", response_model=LabelsResponse) + def labels() -> LabelsResponse: + return LabelsResponse( + codes=list(ACTIVITY_CODES), + names=dict(CODE_TO_NAME), + groups=dict(GROUP_OF), + ) + + @application.post("/predict", response_model=PredictResponse) + def predict(req: PredictRequest) -> PredictResponse: + loaded = _bundle() + err = _shape_error(req, loaded) + if err is not None: + raise HTTPException(status_code=422, detail=err) + try: + payload = predict_window(loaded, np.asarray(req.samples, dtype=np.float32)) + except ValueError as exc: + raise HTTPException(status_code=422, detail=str(exc)) from exc + return PredictResponse(**payload) + + return application + + +def _shape_error(req: PredictRequest, bundle: ModelBundle) -> str | None: + t = len(req.samples) + if t != bundle.n_timesteps: + return f"expected T={bundle.n_timesteps}, got {t}" + width = len(req.samples[0]) + if width != bundle.n_channels: + return f"expected C={bundle.n_channels}, got {width}" + if len(req.channels) != bundle.n_channels: + return f"expected C={bundle.n_channels} channel names, got {len(req.channels)}" + expected_names = tuple(bundle.channel_names[: bundle.n_channels]) + if tuple(req.channels) != expected_names: + return f"channel names must be {list(expected_names)} in that order" + if abs(float(req.hz) - float(bundle.hz)) > 1e-6: + return f"expected hz={bundle.hz}, got {req.hz}" + if req.device != bundle.device: + return f"expected device={bundle.device}, got {req.device}" + return None + + +app = create_app() diff --git a/src/har/serve/schema.py b/src/har/serve/schema.py new file mode 100644 index 0000000..10ff422 --- /dev/null +++ b/src/har/serve/schema.py @@ -0,0 +1,50 @@ +"""HTTP request and response models for the HAR API.""" + +from __future__ import annotations + +from typing import Literal + +from pydantic import BaseModel, Field, model_validator + +from har.types import Device + +MAX_SAMPLES = 512 +MAX_CHANNELS = 16 +MAX_BODY_BYTES = 1_048_576 + + +class PredictRequest(BaseModel): + device: Device + hz: float + channels: list[str] = Field(min_length=1, max_length=MAX_CHANNELS) + samples: list[list[float]] = Field(min_length=1, max_length=MAX_SAMPLES) + + @model_validator(mode="after") + def samples_are_rectangular(self) -> PredictRequest: + widths = {len(row) for row in self.samples} + if len(widths) != 1: + raise ValueError("samples rows must have equal length") + width = next(iter(widths)) + if width > MAX_CHANNELS: + raise ValueError(f"samples row length must be <= {MAX_CHANNELS}") + return self + + +class PredictResponse(BaseModel): + activity_code: str + activity_name: str + group: str + proba: dict[str, float] + confidence: float + abstained: bool + + +class HealthResponse(BaseModel): + status: Literal["ok"] + model_id: str + + +class LabelsResponse(BaseModel): + codes: list[str] + names: dict[str, str] + groups: dict[str, str] diff --git a/src/har/train.py b/src/har/train.py index 4e90a91..91f5f98 100644 --- a/src/har/train.py +++ b/src/har/train.py @@ -6,6 +6,7 @@ import json import logging import subprocess +import tempfile from collections.abc import Iterator, Mapping from pathlib import Path from typing import Any @@ -15,10 +16,11 @@ import pandas as pd import yaml -from har.constants import CHANNEL_NAMES, LABEL_ORDER, TARGET_HZ +from har.constants import CHANNEL_NAMES, CODE_TO_NAME, LABEL_ORDER, TARGET_HZ from har.data.repair import reorient_phone_accel, trim_start from har.data.windows import make_windows, stack_windows from har.eval.metrics import MetricsDict, compute_metrics +from har.eval.plots import save_confusion_matrix, save_run_summary_figure from har.eval.splits import Split, group_kfold, grouped_holdout, leaky_split, loso from har.features.statistical import extract_statistical, to_magnitude from har.models.baselines import fit_dummy, fit_logreg, fit_rf @@ -87,6 +89,7 @@ def run_experiment(config_path: Path) -> Path: mlflow.set_tracking_uri(tracking_uri) mlflow.set_experiment(str(tracking.get("experiment") or "wisdm-har")) + run_name = str(tracking.get("run_name") or config_path.stem) y_true_parts: list[np.ndarray] = [] y_pred_parts: list[np.ndarray] = [] @@ -96,7 +99,7 @@ def run_experiment(config_path: Path) -> Path: test_subj_union: set[int] = set() labels = list(range(len(LABEL_ORDER))) - with mlflow.start_run() as run: + with mlflow.start_run(run_name=run_name) as run: mlflow.log_param("protocol", protocol) mlflow.log_param("protocol_name", protocol_name) mlflow.log_param("git_sha", _git_sha(repo)) @@ -105,8 +108,9 @@ def run_experiment(config_path: Path) -> Path: mlflow.log_param("device", device_label) mlflow.log_dict(_jsonable(cfg), "config.json") log.info( - "mlflow run_id=%s experiment=%s", + "mlflow run_id=%s run_name=%s experiment=%s", run.info.run_id, + run_name, tracking.get("experiment") or "wisdm-har", ) @@ -130,6 +134,8 @@ def run_experiment(config_path: Path) -> Path: y_pred_parts.append(y_pred) fold_metrics = compute_metrics(split.y_test, y_pred, labels) fold_metric_rows.append(fold_metrics) + mlflow.log_metric("fold_macro_f1", fold_metrics["macro_f1"], step=fold_i) + mlflow.log_metric("fold_accuracy", fold_metrics["accuracy"], step=fold_i) log.info("fold %d/%d macro_f1=%.4f", fold_i, n_folds, fold_metrics["macro_f1"]) fold_rows.append( { @@ -166,6 +172,8 @@ def run_experiment(config_path: Path) -> Path: mlflow.log_metric("balanced_accuracy", metrics["balanced_accuracy"]) mlflow.log_metric("mean_fold_macro_f1", mean_fold_macro_f1) mlflow.log_metric("std_fold_macro_f1", std_fold_macro_f1) + for group, value in metrics["per_group_f1"].items(): + mlflow.log_metric(f"group_f1_{group}", value) payload = { "accuracy": metrics["accuracy"], @@ -196,6 +204,18 @@ def run_experiment(config_path: Path) -> Path: } out.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8") mlflow.log_artifact(str(out)) + class_names = [CODE_TO_NAME[code] for code in LABEL_ORDER] + with tempfile.TemporaryDirectory() as td: + fig_dir = Path(td) + save_run_summary_figure(fig_dir / "per_class_f1.png", payload) + save_confusion_matrix( + fig_dir / "confusion.png", + y_true, + y_pred, + labels=labels, + class_names=class_names, + ) + mlflow.log_artifacts(str(fig_dir)) log.info("wrote %s macro_f1=%.4f protocol=%s", out, metrics["macro_f1"], protocol_name) return out diff --git a/tests/fixtures/tiny_wisdm/raw/phone/accel/data_1600_accel_phone.txt b/tests/fixtures/tiny_wisdm/raw/phone/accel/data_1600_accel_phone.txt index 3f19215..619e0e7 100644 --- a/tests/fixtures/tiny_wisdm/raw/phone/accel/data_1600_accel_phone.txt +++ b/tests/fixtures/tiny_wisdm/raw/phone/accel/data_1600_accel_phone.txt @@ -1 +1,122 @@ -1600,A,252207666810782,-0.36476135,8.793503,1.0550842; +1600,A,252207666810782,0.1,9.8,0.2; +1600,A,252207716810782,0.1,9.8,0.2; +1600,A,252207766810782,0.1,9.8,0.2; +1600,A,252207816810782,0.1,9.8,0.2; +1600,A,252207866810782,0.1,9.8,0.2; +1600,A,252207916810782,0.1,9.8,0.2; +1600,A,252207966810782,0.1,9.8,0.2; +1600,A,252208016810782,0.1,9.8,0.2; +1600,A,252208066810782,0.1,9.8,0.2; +1600,A,252208116810782,0.1,9.8,0.2; +1600,A,252208166810782,0.1,9.8,0.2; +1600,A,252208216810782,0.1,9.8,0.2; +1600,A,252208266810782,0.1,9.8,0.2; +1600,A,252208316810782,0.1,9.8,0.2; +1600,A,252208366810782,0.1,9.8,0.2; +1600,A,252208416810782,0.1,9.8,0.2; +1600,A,252208466810782,0.1,9.8,0.2; +1600,A,252208516810782,0.1,9.8,0.2; +1600,A,252208566810782,0.1,9.8,0.2; +1600,A,252208616810782,0.1,9.8,0.2; +1600,A,252208666810782,0.1,9.8,0.2; +1600,A,252208716810782,0.1,9.8,0.2; +1600,A,252208766810782,0.1,9.8,0.2; +1600,A,252208816810782,0.1,9.8,0.2; +1600,A,252208866810782,0.1,9.8,0.2; +1600,A,252208916810782,0.1,9.8,0.2; +1600,A,252208966810782,0.1,9.8,0.2; +1600,A,252209016810782,0.1,9.8,0.2; +1600,A,252209066810782,0.1,9.8,0.2; +1600,A,252209116810782,0.1,9.8,0.2; +1600,A,252209166810782,0.1,9.8,0.2; +1600,A,252209216810782,0.1,9.8,0.2; +1600,A,252209266810782,0.1,9.8,0.2; +1600,A,252209316810782,0.1,9.8,0.2; +1600,A,252209366810782,0.1,9.8,0.2; +1600,A,252209416810782,0.1,9.8,0.2; +1600,A,252209466810782,0.1,9.8,0.2; +1600,A,252209516810782,0.1,9.8,0.2; +1600,A,252209566810782,0.1,9.8,0.2; +1600,A,252209616810782,0.1,9.8,0.2; +1600,A,252209666810782,0.1,9.8,0.2; +1600,A,252209716810782,0.1,9.8,0.2; +1600,A,252209766810782,0.1,9.8,0.2; +1600,A,252209816810782,0.1,9.8,0.2; +1600,A,252209866810782,0.1,9.8,0.2; +1600,A,252209916810782,0.1,9.8,0.2; +1600,A,252209966810782,0.1,9.8,0.2; +1600,A,252210016810782,0.1,9.8,0.2; +1600,A,252210066810782,0.1,9.8,0.2; +1600,A,252210116810782,0.1,9.8,0.2; +1600,A,252210166810782,0.1,9.8,0.2; +1600,A,252210216810782,0.1,9.8,0.2; +1600,A,252210266810782,0.1,9.8,0.2; +1600,A,252210316810782,0.1,9.8,0.2; +1600,A,252210366810782,0.1,9.8,0.2; +1600,A,252210416810782,0.1,9.8,0.2; +1600,A,252210466810782,0.1,9.8,0.2; +1600,A,252210516810782,0.1,9.8,0.2; +1600,A,252210566810782,0.1,9.8,0.2; +1600,A,252210616810782,0.1,9.8,0.2; +1600,A,252210666810782,0.1,9.8,0.2; +1600,B,252211716810782,0.1,-2,0.3; +1600,B,252211766810782,0.1,-2,0.3; +1600,B,252211816810782,0.1,-2,0.3; +1600,B,252211866810782,0.1,-2,0.3; +1600,B,252211916810782,0.1,-2,0.3; +1600,B,252211966810782,0.1,-2,0.3; +1600,B,252212016810782,0.1,-2,0.3; +1600,B,252212066810782,0.1,-2,0.3; +1600,B,252212116810782,0.1,-2,0.3; +1600,B,252212166810782,0.1,-2,0.3; +1600,B,252212216810782,0.1,-2,0.3; +1600,B,252212266810782,0.1,-2,0.3; +1600,B,252212316810782,0.1,-2,0.3; +1600,B,252212366810782,0.1,-2,0.3; +1600,B,252212416810782,0.1,-2,0.3; +1600,B,252212466810782,0.1,-2,0.3; +1600,B,252212516810782,0.1,-2,0.3; +1600,B,252212566810782,0.1,-2,0.3; +1600,B,252212616810782,0.1,-2,0.3; +1600,B,252212666810782,0.1,-2,0.3; +1600,B,252212716810782,0.1,-2,0.3; +1600,B,252212766810782,0.1,-2,0.3; +1600,B,252212816810782,0.1,-2,0.3; +1600,B,252212866810782,0.1,-2,0.3; +1600,B,252212916810782,0.1,-2,0.3; +1600,B,252212966810782,0.1,-2,0.3; +1600,B,252213016810782,0.1,-2,0.3; +1600,B,252213066810782,0.1,-2,0.3; +1600,B,252213116810782,0.1,-2,0.3; +1600,B,252213166810782,0.1,-2,0.3; +1600,B,252213216810782,0.1,-2,0.3; +1600,B,252213266810782,0.1,-2,0.3; +1600,B,252213316810782,0.1,-2,0.3; +1600,B,252213366810782,0.1,-2,0.3; +1600,B,252213416810782,0.1,-2,0.3; +1600,B,252213466810782,0.1,-2,0.3; +1600,B,252213516810782,0.1,-2,0.3; +1600,B,252213566810782,0.1,-2,0.3; +1600,B,252213616810782,0.1,-2,0.3; +1600,B,252213666810782,0.1,-2,0.3; +1600,B,252213716810782,0.1,-2,0.3; +1600,B,252213766810782,0.1,-2,0.3; +1600,B,252213816810782,0.1,-2,0.3; +1600,B,252213866810782,0.1,-2,0.3; +1600,B,252213916810782,0.1,-2,0.3; +1600,B,252213966810782,0.1,-2,0.3; +1600,B,252214016810782,0.1,-2,0.3; +1600,B,252214066810782,0.1,-2,0.3; +1600,B,252214116810782,0.1,-2,0.3; +1600,B,252214166810782,0.1,-2,0.3; +1600,B,252214216810782,0.1,-2,0.3; +1600,B,252214266810782,0.1,-2,0.3; +1600,B,252214316810782,0.1,-2,0.3; +1600,B,252214366810782,0.1,-2,0.3; +1600,B,252214416810782,0.1,-2,0.3; +1600,B,252214466810782,0.1,-2,0.3; +1600,B,252214516810782,0.1,-2,0.3; +1600,B,252214566810782,0.1,-2,0.3; +1600,B,252214616810782,0.1,-2,0.3; +1600,B,252214666810782,0.1,-2,0.3; +1600,B,252214716810782,0.1,-2,0.3; diff --git a/tests/fixtures/tiny_wisdm/raw/phone/accel/data_1601_accel_phone.txt b/tests/fixtures/tiny_wisdm/raw/phone/accel/data_1601_accel_phone.txt new file mode 100644 index 0000000..e0afc64 --- /dev/null +++ b/tests/fixtures/tiny_wisdm/raw/phone/accel/data_1601_accel_phone.txt @@ -0,0 +1,122 @@ +1601,A,253207666810782,0.11,9.8,0.2; +1601,A,253207716810782,0.11,9.8,0.2; +1601,A,253207766810782,0.11,9.8,0.2; +1601,A,253207816810782,0.11,9.8,0.2; +1601,A,253207866810782,0.11,9.8,0.2; +1601,A,253207916810782,0.11,9.8,0.2; +1601,A,253207966810782,0.11,9.8,0.2; +1601,A,253208016810782,0.11,9.8,0.2; +1601,A,253208066810782,0.11,9.8,0.2; +1601,A,253208116810782,0.11,9.8,0.2; +1601,A,253208166810782,0.11,9.8,0.2; +1601,A,253208216810782,0.11,9.8,0.2; +1601,A,253208266810782,0.11,9.8,0.2; +1601,A,253208316810782,0.11,9.8,0.2; +1601,A,253208366810782,0.11,9.8,0.2; +1601,A,253208416810782,0.11,9.8,0.2; +1601,A,253208466810782,0.11,9.8,0.2; +1601,A,253208516810782,0.11,9.8,0.2; +1601,A,253208566810782,0.11,9.8,0.2; +1601,A,253208616810782,0.11,9.8,0.2; +1601,A,253208666810782,0.11,9.8,0.2; +1601,A,253208716810782,0.11,9.8,0.2; +1601,A,253208766810782,0.11,9.8,0.2; +1601,A,253208816810782,0.11,9.8,0.2; +1601,A,253208866810782,0.11,9.8,0.2; +1601,A,253208916810782,0.11,9.8,0.2; +1601,A,253208966810782,0.11,9.8,0.2; +1601,A,253209016810782,0.11,9.8,0.2; +1601,A,253209066810782,0.11,9.8,0.2; +1601,A,253209116810782,0.11,9.8,0.2; +1601,A,253209166810782,0.11,9.8,0.2; +1601,A,253209216810782,0.11,9.8,0.2; +1601,A,253209266810782,0.11,9.8,0.2; +1601,A,253209316810782,0.11,9.8,0.2; +1601,A,253209366810782,0.11,9.8,0.2; +1601,A,253209416810782,0.11,9.8,0.2; +1601,A,253209466810782,0.11,9.8,0.2; +1601,A,253209516810782,0.11,9.8,0.2; +1601,A,253209566810782,0.11,9.8,0.2; +1601,A,253209616810782,0.11,9.8,0.2; +1601,A,253209666810782,0.11,9.8,0.2; +1601,A,253209716810782,0.11,9.8,0.2; +1601,A,253209766810782,0.11,9.8,0.2; +1601,A,253209816810782,0.11,9.8,0.2; +1601,A,253209866810782,0.11,9.8,0.2; +1601,A,253209916810782,0.11,9.8,0.2; +1601,A,253209966810782,0.11,9.8,0.2; +1601,A,253210016810782,0.11,9.8,0.2; +1601,A,253210066810782,0.11,9.8,0.2; +1601,A,253210116810782,0.11,9.8,0.2; +1601,A,253210166810782,0.11,9.8,0.2; +1601,A,253210216810782,0.11,9.8,0.2; +1601,A,253210266810782,0.11,9.8,0.2; +1601,A,253210316810782,0.11,9.8,0.2; +1601,A,253210366810782,0.11,9.8,0.2; +1601,A,253210416810782,0.11,9.8,0.2; +1601,A,253210466810782,0.11,9.8,0.2; +1601,A,253210516810782,0.11,9.8,0.2; +1601,A,253210566810782,0.11,9.8,0.2; +1601,A,253210616810782,0.11,9.8,0.2; +1601,A,253210666810782,0.11,9.8,0.2; +1601,B,253211716810782,0.11,-2,0.3; +1601,B,253211766810782,0.11,-2,0.3; +1601,B,253211816810782,0.11,-2,0.3; +1601,B,253211866810782,0.11,-2,0.3; +1601,B,253211916810782,0.11,-2,0.3; +1601,B,253211966810782,0.11,-2,0.3; +1601,B,253212016810782,0.11,-2,0.3; +1601,B,253212066810782,0.11,-2,0.3; +1601,B,253212116810782,0.11,-2,0.3; +1601,B,253212166810782,0.11,-2,0.3; +1601,B,253212216810782,0.11,-2,0.3; +1601,B,253212266810782,0.11,-2,0.3; +1601,B,253212316810782,0.11,-2,0.3; +1601,B,253212366810782,0.11,-2,0.3; +1601,B,253212416810782,0.11,-2,0.3; +1601,B,253212466810782,0.11,-2,0.3; +1601,B,253212516810782,0.11,-2,0.3; +1601,B,253212566810782,0.11,-2,0.3; +1601,B,253212616810782,0.11,-2,0.3; +1601,B,253212666810782,0.11,-2,0.3; +1601,B,253212716810782,0.11,-2,0.3; +1601,B,253212766810782,0.11,-2,0.3; +1601,B,253212816810782,0.11,-2,0.3; +1601,B,253212866810782,0.11,-2,0.3; +1601,B,253212916810782,0.11,-2,0.3; +1601,B,253212966810782,0.11,-2,0.3; +1601,B,253213016810782,0.11,-2,0.3; +1601,B,253213066810782,0.11,-2,0.3; +1601,B,253213116810782,0.11,-2,0.3; +1601,B,253213166810782,0.11,-2,0.3; +1601,B,253213216810782,0.11,-2,0.3; +1601,B,253213266810782,0.11,-2,0.3; +1601,B,253213316810782,0.11,-2,0.3; +1601,B,253213366810782,0.11,-2,0.3; +1601,B,253213416810782,0.11,-2,0.3; +1601,B,253213466810782,0.11,-2,0.3; +1601,B,253213516810782,0.11,-2,0.3; +1601,B,253213566810782,0.11,-2,0.3; +1601,B,253213616810782,0.11,-2,0.3; +1601,B,253213666810782,0.11,-2,0.3; +1601,B,253213716810782,0.11,-2,0.3; +1601,B,253213766810782,0.11,-2,0.3; +1601,B,253213816810782,0.11,-2,0.3; +1601,B,253213866810782,0.11,-2,0.3; +1601,B,253213916810782,0.11,-2,0.3; +1601,B,253213966810782,0.11,-2,0.3; +1601,B,253214016810782,0.11,-2,0.3; +1601,B,253214066810782,0.11,-2,0.3; +1601,B,253214116810782,0.11,-2,0.3; +1601,B,253214166810782,0.11,-2,0.3; +1601,B,253214216810782,0.11,-2,0.3; +1601,B,253214266810782,0.11,-2,0.3; +1601,B,253214316810782,0.11,-2,0.3; +1601,B,253214366810782,0.11,-2,0.3; +1601,B,253214416810782,0.11,-2,0.3; +1601,B,253214466810782,0.11,-2,0.3; +1601,B,253214516810782,0.11,-2,0.3; +1601,B,253214566810782,0.11,-2,0.3; +1601,B,253214616810782,0.11,-2,0.3; +1601,B,253214666810782,0.11,-2,0.3; +1601,B,253214716810782,0.11,-2,0.3; diff --git a/tests/fixtures/tiny_wisdm/raw/phone/gyro/data_1600_gyro_phone.txt b/tests/fixtures/tiny_wisdm/raw/phone/gyro/data_1600_gyro_phone.txt new file mode 100644 index 0000000..1986f37 --- /dev/null +++ b/tests/fixtures/tiny_wisdm/raw/phone/gyro/data_1600_gyro_phone.txt @@ -0,0 +1,122 @@ +1600,A,252207676810782,0.01,0.02,0.03; +1600,A,252207726810782,0.01,0.02,0.03; +1600,A,252207776810782,0.01,0.02,0.03; +1600,A,252207826810782,0.01,0.02,0.03; +1600,A,252207876810782,0.01,0.02,0.03; +1600,A,252207926810782,0.01,0.02,0.03; +1600,A,252207976810782,0.01,0.02,0.03; +1600,A,252208026810782,0.01,0.02,0.03; +1600,A,252208076810782,0.01,0.02,0.03; +1600,A,252208126810782,0.01,0.02,0.03; +1600,A,252208176810782,0.01,0.02,0.03; +1600,A,252208226810782,0.01,0.02,0.03; +1600,A,252208276810782,0.01,0.02,0.03; +1600,A,252208326810782,0.01,0.02,0.03; +1600,A,252208376810782,0.01,0.02,0.03; +1600,A,252208426810782,0.01,0.02,0.03; +1600,A,252208476810782,0.01,0.02,0.03; +1600,A,252208526810782,0.01,0.02,0.03; +1600,A,252208576810782,0.01,0.02,0.03; +1600,A,252208626810782,0.01,0.02,0.03; +1600,A,252208676810782,0.01,0.02,0.03; +1600,A,252208726810782,0.01,0.02,0.03; +1600,A,252208776810782,0.01,0.02,0.03; +1600,A,252208826810782,0.01,0.02,0.03; +1600,A,252208876810782,0.01,0.02,0.03; +1600,A,252208926810782,0.01,0.02,0.03; +1600,A,252208976810782,0.01,0.02,0.03; +1600,A,252209026810782,0.01,0.02,0.03; +1600,A,252209076810782,0.01,0.02,0.03; +1600,A,252209126810782,0.01,0.02,0.03; +1600,A,252209176810782,0.01,0.02,0.03; +1600,A,252209226810782,0.01,0.02,0.03; +1600,A,252209276810782,0.01,0.02,0.03; +1600,A,252209326810782,0.01,0.02,0.03; +1600,A,252209376810782,0.01,0.02,0.03; +1600,A,252209426810782,0.01,0.02,0.03; +1600,A,252209476810782,0.01,0.02,0.03; +1600,A,252209526810782,0.01,0.02,0.03; +1600,A,252209576810782,0.01,0.02,0.03; +1600,A,252209626810782,0.01,0.02,0.03; +1600,A,252209676810782,0.01,0.02,0.03; +1600,A,252209726810782,0.01,0.02,0.03; +1600,A,252209776810782,0.01,0.02,0.03; +1600,A,252209826810782,0.01,0.02,0.03; +1600,A,252209876810782,0.01,0.02,0.03; +1600,A,252209926810782,0.01,0.02,0.03; +1600,A,252209976810782,0.01,0.02,0.03; +1600,A,252210026810782,0.01,0.02,0.03; +1600,A,252210076810782,0.01,0.02,0.03; +1600,A,252210126810782,0.01,0.02,0.03; +1600,A,252210176810782,0.01,0.02,0.03; +1600,A,252210226810782,0.01,0.02,0.03; +1600,A,252210276810782,0.01,0.02,0.03; +1600,A,252210326810782,0.01,0.02,0.03; +1600,A,252210376810782,0.01,0.02,0.03; +1600,A,252210426810782,0.01,0.02,0.03; +1600,A,252210476810782,0.01,0.02,0.03; +1600,A,252210526810782,0.01,0.02,0.03; +1600,A,252210576810782,0.01,0.02,0.03; +1600,A,252210626810782,0.01,0.02,0.03; +1600,A,252210676810782,0.01,0.02,0.03; +1600,B,252211726810782,0.01,0.02,0.04; +1600,B,252211776810782,0.01,0.02,0.04; +1600,B,252211826810782,0.01,0.02,0.04; +1600,B,252211876810782,0.01,0.02,0.04; +1600,B,252211926810782,0.01,0.02,0.04; +1600,B,252211976810782,0.01,0.02,0.04; +1600,B,252212026810782,0.01,0.02,0.04; +1600,B,252212076810782,0.01,0.02,0.04; +1600,B,252212126810782,0.01,0.02,0.04; +1600,B,252212176810782,0.01,0.02,0.04; +1600,B,252212226810782,0.01,0.02,0.04; +1600,B,252212276810782,0.01,0.02,0.04; +1600,B,252212326810782,0.01,0.02,0.04; +1600,B,252212376810782,0.01,0.02,0.04; +1600,B,252212426810782,0.01,0.02,0.04; +1600,B,252212476810782,0.01,0.02,0.04; +1600,B,252212526810782,0.01,0.02,0.04; +1600,B,252212576810782,0.01,0.02,0.04; +1600,B,252212626810782,0.01,0.02,0.04; +1600,B,252212676810782,0.01,0.02,0.04; +1600,B,252212726810782,0.01,0.02,0.04; +1600,B,252212776810782,0.01,0.02,0.04; +1600,B,252212826810782,0.01,0.02,0.04; +1600,B,252212876810782,0.01,0.02,0.04; +1600,B,252212926810782,0.01,0.02,0.04; +1600,B,252212976810782,0.01,0.02,0.04; +1600,B,252213026810782,0.01,0.02,0.04; +1600,B,252213076810782,0.01,0.02,0.04; +1600,B,252213126810782,0.01,0.02,0.04; +1600,B,252213176810782,0.01,0.02,0.04; +1600,B,252213226810782,0.01,0.02,0.04; +1600,B,252213276810782,0.01,0.02,0.04; +1600,B,252213326810782,0.01,0.02,0.04; +1600,B,252213376810782,0.01,0.02,0.04; +1600,B,252213426810782,0.01,0.02,0.04; +1600,B,252213476810782,0.01,0.02,0.04; +1600,B,252213526810782,0.01,0.02,0.04; +1600,B,252213576810782,0.01,0.02,0.04; +1600,B,252213626810782,0.01,0.02,0.04; +1600,B,252213676810782,0.01,0.02,0.04; +1600,B,252213726810782,0.01,0.02,0.04; +1600,B,252213776810782,0.01,0.02,0.04; +1600,B,252213826810782,0.01,0.02,0.04; +1600,B,252213876810782,0.01,0.02,0.04; +1600,B,252213926810782,0.01,0.02,0.04; +1600,B,252213976810782,0.01,0.02,0.04; +1600,B,252214026810782,0.01,0.02,0.04; +1600,B,252214076810782,0.01,0.02,0.04; +1600,B,252214126810782,0.01,0.02,0.04; +1600,B,252214176810782,0.01,0.02,0.04; +1600,B,252214226810782,0.01,0.02,0.04; +1600,B,252214276810782,0.01,0.02,0.04; +1600,B,252214326810782,0.01,0.02,0.04; +1600,B,252214376810782,0.01,0.02,0.04; +1600,B,252214426810782,0.01,0.02,0.04; +1600,B,252214476810782,0.01,0.02,0.04; +1600,B,252214526810782,0.01,0.02,0.04; +1600,B,252214576810782,0.01,0.02,0.04; +1600,B,252214626810782,0.01,0.02,0.04; +1600,B,252214676810782,0.01,0.02,0.04; +1600,B,252214726810782,0.01,0.02,0.04; diff --git a/tests/fixtures/tiny_wisdm/raw/phone/gyro/data_1601_gyro_phone.txt b/tests/fixtures/tiny_wisdm/raw/phone/gyro/data_1601_gyro_phone.txt new file mode 100644 index 0000000..ef828c1 --- /dev/null +++ b/tests/fixtures/tiny_wisdm/raw/phone/gyro/data_1601_gyro_phone.txt @@ -0,0 +1,122 @@ +1601,A,253207676810782,0.02,0.02,0.03; +1601,A,253207726810782,0.02,0.02,0.03; +1601,A,253207776810782,0.02,0.02,0.03; +1601,A,253207826810782,0.02,0.02,0.03; +1601,A,253207876810782,0.02,0.02,0.03; +1601,A,253207926810782,0.02,0.02,0.03; +1601,A,253207976810782,0.02,0.02,0.03; +1601,A,253208026810782,0.02,0.02,0.03; +1601,A,253208076810782,0.02,0.02,0.03; +1601,A,253208126810782,0.02,0.02,0.03; +1601,A,253208176810782,0.02,0.02,0.03; +1601,A,253208226810782,0.02,0.02,0.03; +1601,A,253208276810782,0.02,0.02,0.03; +1601,A,253208326810782,0.02,0.02,0.03; +1601,A,253208376810782,0.02,0.02,0.03; +1601,A,253208426810782,0.02,0.02,0.03; +1601,A,253208476810782,0.02,0.02,0.03; +1601,A,253208526810782,0.02,0.02,0.03; +1601,A,253208576810782,0.02,0.02,0.03; +1601,A,253208626810782,0.02,0.02,0.03; +1601,A,253208676810782,0.02,0.02,0.03; +1601,A,253208726810782,0.02,0.02,0.03; +1601,A,253208776810782,0.02,0.02,0.03; +1601,A,253208826810782,0.02,0.02,0.03; +1601,A,253208876810782,0.02,0.02,0.03; +1601,A,253208926810782,0.02,0.02,0.03; +1601,A,253208976810782,0.02,0.02,0.03; +1601,A,253209026810782,0.02,0.02,0.03; +1601,A,253209076810782,0.02,0.02,0.03; +1601,A,253209126810782,0.02,0.02,0.03; +1601,A,253209176810782,0.02,0.02,0.03; +1601,A,253209226810782,0.02,0.02,0.03; +1601,A,253209276810782,0.02,0.02,0.03; +1601,A,253209326810782,0.02,0.02,0.03; +1601,A,253209376810782,0.02,0.02,0.03; +1601,A,253209426810782,0.02,0.02,0.03; +1601,A,253209476810782,0.02,0.02,0.03; +1601,A,253209526810782,0.02,0.02,0.03; +1601,A,253209576810782,0.02,0.02,0.03; +1601,A,253209626810782,0.02,0.02,0.03; +1601,A,253209676810782,0.02,0.02,0.03; +1601,A,253209726810782,0.02,0.02,0.03; +1601,A,253209776810782,0.02,0.02,0.03; +1601,A,253209826810782,0.02,0.02,0.03; +1601,A,253209876810782,0.02,0.02,0.03; +1601,A,253209926810782,0.02,0.02,0.03; +1601,A,253209976810782,0.02,0.02,0.03; +1601,A,253210026810782,0.02,0.02,0.03; +1601,A,253210076810782,0.02,0.02,0.03; +1601,A,253210126810782,0.02,0.02,0.03; +1601,A,253210176810782,0.02,0.02,0.03; +1601,A,253210226810782,0.02,0.02,0.03; +1601,A,253210276810782,0.02,0.02,0.03; +1601,A,253210326810782,0.02,0.02,0.03; +1601,A,253210376810782,0.02,0.02,0.03; +1601,A,253210426810782,0.02,0.02,0.03; +1601,A,253210476810782,0.02,0.02,0.03; +1601,A,253210526810782,0.02,0.02,0.03; +1601,A,253210576810782,0.02,0.02,0.03; +1601,A,253210626810782,0.02,0.02,0.03; +1601,A,253210676810782,0.02,0.02,0.03; +1601,B,253211726810782,0.02,0.02,0.04; +1601,B,253211776810782,0.02,0.02,0.04; +1601,B,253211826810782,0.02,0.02,0.04; +1601,B,253211876810782,0.02,0.02,0.04; +1601,B,253211926810782,0.02,0.02,0.04; +1601,B,253211976810782,0.02,0.02,0.04; +1601,B,253212026810782,0.02,0.02,0.04; +1601,B,253212076810782,0.02,0.02,0.04; +1601,B,253212126810782,0.02,0.02,0.04; +1601,B,253212176810782,0.02,0.02,0.04; +1601,B,253212226810782,0.02,0.02,0.04; +1601,B,253212276810782,0.02,0.02,0.04; +1601,B,253212326810782,0.02,0.02,0.04; +1601,B,253212376810782,0.02,0.02,0.04; +1601,B,253212426810782,0.02,0.02,0.04; +1601,B,253212476810782,0.02,0.02,0.04; +1601,B,253212526810782,0.02,0.02,0.04; +1601,B,253212576810782,0.02,0.02,0.04; +1601,B,253212626810782,0.02,0.02,0.04; +1601,B,253212676810782,0.02,0.02,0.04; +1601,B,253212726810782,0.02,0.02,0.04; +1601,B,253212776810782,0.02,0.02,0.04; +1601,B,253212826810782,0.02,0.02,0.04; +1601,B,253212876810782,0.02,0.02,0.04; +1601,B,253212926810782,0.02,0.02,0.04; +1601,B,253212976810782,0.02,0.02,0.04; +1601,B,253213026810782,0.02,0.02,0.04; +1601,B,253213076810782,0.02,0.02,0.04; +1601,B,253213126810782,0.02,0.02,0.04; +1601,B,253213176810782,0.02,0.02,0.04; +1601,B,253213226810782,0.02,0.02,0.04; +1601,B,253213276810782,0.02,0.02,0.04; +1601,B,253213326810782,0.02,0.02,0.04; +1601,B,253213376810782,0.02,0.02,0.04; +1601,B,253213426810782,0.02,0.02,0.04; +1601,B,253213476810782,0.02,0.02,0.04; +1601,B,253213526810782,0.02,0.02,0.04; +1601,B,253213576810782,0.02,0.02,0.04; +1601,B,253213626810782,0.02,0.02,0.04; +1601,B,253213676810782,0.02,0.02,0.04; +1601,B,253213726810782,0.02,0.02,0.04; +1601,B,253213776810782,0.02,0.02,0.04; +1601,B,253213826810782,0.02,0.02,0.04; +1601,B,253213876810782,0.02,0.02,0.04; +1601,B,253213926810782,0.02,0.02,0.04; +1601,B,253213976810782,0.02,0.02,0.04; +1601,B,253214026810782,0.02,0.02,0.04; +1601,B,253214076810782,0.02,0.02,0.04; +1601,B,253214126810782,0.02,0.02,0.04; +1601,B,253214176810782,0.02,0.02,0.04; +1601,B,253214226810782,0.02,0.02,0.04; +1601,B,253214276810782,0.02,0.02,0.04; +1601,B,253214326810782,0.02,0.02,0.04; +1601,B,253214376810782,0.02,0.02,0.04; +1601,B,253214426810782,0.02,0.02,0.04; +1601,B,253214476810782,0.02,0.02,0.04; +1601,B,253214526810782,0.02,0.02,0.04; +1601,B,253214576810782,0.02,0.02,0.04; +1601,B,253214626810782,0.02,0.02,0.04; +1601,B,253214676810782,0.02,0.02,0.04; +1601,B,253214726810782,0.02,0.02,0.04; diff --git a/tests/test_audit.py b/tests/test_audit.py index bd655ce..620ffc4 100644 --- a/tests/test_audit.py +++ b/tests/test_audit.py @@ -193,6 +193,8 @@ def test_write_data_card_includes_missing_and_hz_tables(tmp_path: Path): assert "| 1609 | B | phone | accel |" in text assert "| 20 |" in text assert "NaN values in xyz" in text + assert "later repair" not in text + assert "python -m har.data.repair" in text for name in ("sessions.csv", "coverage.csv", "missing_cells.csv", "hz_by_session.csv"): assert (audit_dir / name).is_file() diff --git a/tests/test_ci.py b/tests/test_ci.py new file mode 100644 index 0000000..8f785ef --- /dev/null +++ b/tests/test_ci.py @@ -0,0 +1,72 @@ +import re +from pathlib import Path + +import yaml + +REPO = Path(__file__).resolve().parents[1] +MAKEFILE = REPO / "Makefile" +WORKFLOW = REPO / ".github" / "workflows" / "ci.yml" +PYPROJECT = REPO / "pyproject.toml" +SERVING_README = REPO / "serving" / "README.md" +REQUIRED_MAKE_TARGETS = ("install", "test", "audit", "prepare", "train", "eval", "serve") + + +def _dep_pin(name: str) -> str: + text = PYPROJECT.read_text(encoding="utf-8") + match = re.search(rf'"{re.escape(name)}==([^"]+)"', text) + assert match, name + return match.group(1) + + +def test_makefile_exposes_pipeline_targets(): + raw = MAKEFILE.read_bytes() + assert b"\r" not in raw + text = raw.decode("utf-8") + targets = set(re.findall(r"^([a-zA-Z][\w-]*)\s*:", text, flags=re.M)) + assert set(REQUIRED_MAKE_TARGETS) <= targets + assert "pip install" in text + assert "pytest" in text + assert "har.data.audit" in text + assert "har.data.repair" in text + assert "har.train" in text + assert "har.evaluate" in text + assert "uvicorn" in text + + +def test_ci_runs_ruff_and_pytest_without_wisdm(): + text = WORKFLOW.read_text(encoding="utf-8") + payload = yaml.safe_load(text) + jobs = payload.get("jobs") or {} + assert jobs, "ci.yml needs at least one job" + blob = text.lower() + assert "ruff" in blob + assert "pytest" in blob + assert "har.data.download" not in blob + assert "archive.ics.uci.edu" not in blob + assert "data/external" not in blob + assert 'python-version: "3.13"' in text + + +def test_pyarrow_pin_satisfies_mlflow_2_22(): + pyarrow = _dep_pin("pyarrow") + mlflow = _dep_pin("mlflow") + major = int(pyarrow.split(".", 1)[0]) + assert mlflow.startswith("2.22."), mlflow + assert 4 <= major < 20, pyarrow + + +def test_serving_readme_uses_portable_models_mount(): + text = SERVING_README.read_text(encoding="utf-8") + assert "C:/Users/" not in text + assert "$PWD/models:/models" in text + + +def test_gitignore_ignores_artifact_dir_not_package_models(): + lines = [ + line.strip() + for line in (REPO / ".gitignore").read_text(encoding="utf-8").splitlines() + if line.strip() and not line.strip().startswith("#") + ] + assert "/models/" in lines + assert "models/" not in lines + assert (REPO / "src" / "har" / "models" / "export.py").is_file() diff --git a/tests/test_plots.py b/tests/test_plots.py new file mode 100644 index 0000000..0ef60f3 --- /dev/null +++ b/tests/test_plots.py @@ -0,0 +1,136 @@ +import json +from pathlib import Path + +from har.constants import LABEL_ORDER +from har.eval.plots import class_f1_by_name, sync_mlflow_run_names, write_readme_figures +from har.train import run_experiment +from test_train import _write_config, _write_session + + +def _report(**overrides: object) -> dict[str, object]: + per_class = {str(i): 0.1 * ((i % 5) + 1) for i in range(len(LABEL_ORDER))} + row: dict[str, object] = { + "macro_f1": 0.32, + "accuracy": 0.33, + "protocol": "groupkfold", + "protocol_name": "B", + "model": "xgboost", + "device": "phone", + "features": "statistical", + "per_class_f1": per_class, + "per_group_f1": { + "locomotion": 0.88, + "posture": 0.37, + "hand": 0.60, + "eating": 0.49, + }, + } + row.update(overrides) + return row + + +def _write(path: Path, **overrides: object) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(_report(**overrides)) + "\n", encoding="utf-8") + + +def test_class_f1_by_name_maps_index_keys() -> None: + named = class_f1_by_name({"0": 0.7, "1": 0.2, str(len(LABEL_ORDER) - 1): 0.4}) + assert named["walking"] == 0.7 + assert named["jogging"] == 0.2 + assert named["folding clothes"] == 0.4 + + +def test_write_readme_figures_creates_pngs(tmp_path: Path) -> None: + reports = tmp_path / "reports" + _write( + reports / "protocol_a2_phone_raw_flat_xgb.json", + protocol="leaky", + protocol_name="A2", + features="raw_flat", + macro_f1=0.89, + ) + _write( + reports / "protocol_b_phone_raw_flat_xgb.json", + features="raw_flat", + macro_f1=0.29, + ) + for name, device, model, f1 in ( + ("protocol_b_phone_stat_dummy.json", "phone", "dummy", 0.02), + ("protocol_b_phone_stat_logreg.json", "phone", "logreg", 0.28), + ("protocol_b_phone_stat_rf.json", "phone", "rf", 0.31), + ("protocol_b_phone_stat_xgb.json", "phone", "xgboost", 0.33), + ("protocol_b_concat_stat_xgb.json", "both", "xgboost", 0.52), + ("protocol_b_watch_stat_xgb.json", "watch", "xgboost", 0.70), + ): + _write(reports / name, device=device, model=model, macro_f1=f1) + _write(reports / "ablations" / "window_10s.json", macro_f1=0.34) + _write(reports / "ablations" / "window_2s.json", macro_f1=0.30) + _write(reports / "ablations" / "trim_15s.json", macro_f1=0.32) + _write(reports / "ablations" / "reorient_on.json", macro_f1=0.32) + _write(reports / "ablations" / "magnitude.json", macro_f1=0.31) + _write(reports / "ablations" / "hierarchical.json", macro_f1=0.33, model="hierarchical") + + out = tmp_path / "figures" + written = write_readme_figures(reports, out) + names = {path.name for path in written} + assert names == { + "leakage_macro_f1.png", + "protocol_b_ladder.png", + "per_class_f1_phone_watch.png", + "per_group_f1_phone_watch.png", + "ablations_macro_f1.png", + "sampling_rate_modes.png", + } + for path in written: + assert path.read_bytes()[:8] == b"\x89PNG\r\n\x1a\n" + + +def test_write_readme_figures_skips_missing_reports(tmp_path: Path) -> None: + written = write_readme_figures(tmp_path / "reports", tmp_path / "figures") + assert {path.name for path in written} == {"sampling_rate_modes.png"} + + +def test_run_experiment_uses_config_stem_as_mlflow_run_name(tmp_path: Path) -> None: + processed = tmp_path / "processed" + for subject_id in (1600, 1601): + _write_session(processed, subject_id, "A", ax=1.0) + _write_session(processed, subject_id, "B", ax=-1.0) + + metrics_path = run_experiment( + _write_config(tmp_path, processed, "dummy", filename="protocol_b_phone_stat_dummy.yaml") + ) + payload = json.loads(metrics_path.read_text(encoding="utf-8")) + import mlflow + + run = mlflow.MlflowClient(tracking_uri=payload["mlflow_tracking_uri"]).get_run( + payload["mlflow_run_id"] + ) + assert run.info.run_name == "protocol_b_phone_stat_dummy" + assert "fold_macro_f1" in run.data.metrics + assert "group_f1_locomotion" in run.data.metrics + + +def test_sync_mlflow_run_names_renames_existing_run(tmp_path: Path) -> None: + processed = tmp_path / "processed" + for subject_id in (1600, 1601): + _write_session(processed, subject_id, "A", ax=1.0) + _write_session(processed, subject_id, "B", ax=-1.0) + + from har.train import run_experiment + + metrics_path = run_experiment(_write_config(tmp_path, processed, "dummy", filename="exp.yaml")) + payload = json.loads(metrics_path.read_text(encoding="utf-8")) + import mlflow + + client = mlflow.MlflowClient(tracking_uri=payload["mlflow_tracking_uri"]) + client.set_tag(payload["mlflow_run_id"], "mlflow.runName", "amusing-gibbon-7") + reports = metrics_path.parent + reports.joinpath("protocol_b_watch_stat_xgb.json").write_text( + json.dumps(payload) + "\n", encoding="utf-8" + ) + metrics_path.unlink() + updated = sync_mlflow_run_names(reports) + assert updated == ["protocol_b_watch_stat_xgb"] + run = client.get_run(payload["mlflow_run_id"]) + assert run.info.run_name == "protocol_b_watch_stat_xgb" diff --git a/tests/test_serve.py b/tests/test_serve.py new file mode 100644 index 0000000..24c2f0f --- /dev/null +++ b/tests/test_serve.py @@ -0,0 +1,384 @@ +from __future__ import annotations + +import time +from pathlib import Path + +import numpy as np +import pandas as pd +import pytest +import yaml +from fastapi.testclient import TestClient + +from har.constants import ACTIVITY_CODES, CHANNEL_NAMES, CODE_TO_NAME, GROUP_OF, TARGET_HZ +from har.features.statistical import feature_names +from har.models.export import ( + ModelBundle, + export_from_config, + export_onnx, + load_bundle, + predict_window, + save_bundle, + save_onnx_bundle, +) +from har.models.xgboost import fit_xgboost +from har.serve.app import create_app +from har.serve.schema import MAX_BODY_BYTES + +NS_PER_S = 1_000_000_000 +N_T = 100 +N_C = 6 + + +class _StubEstimator: + classes_ = np.arange(len(ACTIVITY_CODES)) + n_features_in_ = len(feature_names(N_C)) + + def predict_proba(self, X: np.ndarray) -> np.ndarray: + n = len(np.asarray(X)) + p = np.zeros((n, len(ACTIVITY_CODES)), dtype=np.float64) + p[:, 0] = 0.81 + p[:, 1:] = 0.19 / (len(ACTIVITY_CODES) - 1) + return p + + def predict(self, X: np.ndarray) -> np.ndarray: + return np.zeros(len(np.asarray(X)), dtype=np.int64) + + +def _stub_bundle(*, abstain_threshold: float = 0.0) -> ModelBundle: + return ModelBundle( + estimator=_StubEstimator(), + n_timesteps=N_T, + n_channels=N_C, + hz=TARGET_HZ, + device="phone", + features="statistical", + model_id="stub", + abstain_threshold=abstain_threshold, + ) + + +def _payload( + *, + t: int = N_T, + c: int = N_C, + device: str = "phone", + hz: float = TARGET_HZ, + channels: list[str] | None = None, +) -> dict: + return { + "device": device, + "hz": hz, + "channels": list(CHANNEL_NAMES[:c] if channels is None else channels), + "samples": [[0.0] * c for _ in range(t)], + } + + +def _client(bundle: ModelBundle | None = None) -> TestClient: + return TestClient(create_app(bundle or _stub_bundle())) + + +def test_health_and_labels_happy_path(): + with _client() as client: + health = client.get("/health") + assert health.status_code == 200 + assert health.json() == {"status": "ok", "model_id": "stub"} + labels = client.get("/labels") + assert labels.status_code == 200 + body = labels.json() + assert body["codes"] == list(ACTIVITY_CODES) + assert body["names"] == dict(CODE_TO_NAME) + assert body["groups"] == dict(GROUP_OF) + + +def test_predict_happy_path_with_stub(): + with _client() as client: + resp = client.post("/predict", json=_payload()) + assert resp.status_code == 200 + body = resp.json() + assert body["activity_code"] == "A" + assert body["activity_name"] == "walking" + assert body["group"] == "locomotion" + assert body["abstained"] is False + assert body["confidence"] == pytest.approx(0.81) + assert set(body["proba"]) == set(ACTIVITY_CODES) + assert body["proba"]["A"] == pytest.approx(0.81) + + +def test_predict_wrong_t_returns_422(): + with _client() as client: + resp = client.post("/predict", json=_payload(t=80)) + assert resp.status_code == 422 + assert resp.json()["detail"] == "expected T=100, got 80" + + +def test_predict_wrong_c_returns_422(): + with _client() as client: + resp = client.post("/predict", json=_payload(c=3)) + assert resp.status_code == 422 + assert resp.json()["detail"] == "expected C=6, got 3" + + +def test_predict_wrong_device_returns_422(): + with _client() as client: + resp = client.post("/predict", json=_payload(device="watch")) + assert resp.status_code == 422 + assert resp.json()["detail"] == "expected device=phone, got watch" + + +def test_predict_wrong_hz_returns_422(): + with _client() as client: + resp = client.post("/predict", json=_payload(hz=50.0)) + assert resp.status_code == 422 + assert resp.json()["detail"] == "expected hz=20.0, got 50.0" + + +def test_predict_wrong_channel_names_returns_422(): + swapped = ["ay", "ax", "az", "gx", "gy", "gz"] + with _client() as client: + resp = client.post("/predict", json=_payload(channels=swapped)) + assert resp.status_code == 422 + assert resp.json()["detail"] == ( + "channel names must be ['ax', 'ay', 'az', 'gx', 'gy', 'gz'] in that order" + ) + + +def test_predict_oversized_body_returns_413(): + with _client() as client: + resp = client.post( + "/predict", + content=b"{}", + headers={"Content-Length": str(MAX_BODY_BYTES + 1), "Content-Type": "application/json"}, + ) + assert resp.status_code == 413 + assert resp.json()["detail"] == "request too large" + + +def test_predict_abstains_below_threshold(): + with _client(_stub_bundle(abstain_threshold=0.9)) as client: + body = client.post("/predict", json=_payload()).json() + assert body["abstained"] is True + assert body["activity_code"] == "A" + + +def test_joblib_roundtrip_matches_in_memory_predict(tmp_path: Path): + rng = np.random.default_rng(0) + y = np.array([0, 1] * 16, dtype=np.int64) + x = rng.normal(size=(y.size, 8)).astype(np.float32) + x[y == 1] += 4.0 + model = fit_xgboost( + x[:24], + y[:24], + x[24:], + y[24:], + {"n_estimators": 2, "max_depth": 2, "n_jobs": 1, "device": "cpu"}, + ) + bundle = ModelBundle( + estimator=model, + n_timesteps=4, + n_channels=2, + hz=TARGET_HZ, + device="watch", + features="raw_flat", + model_id="fixture-xgb", + ) + path = save_bundle(tmp_path / "model.joblib", bundle) + loaded = load_bundle(path) + window = rng.normal(size=(4, 2)).astype(np.float32) + assert predict_window(loaded, window)["activity_code"] == predict_window(bundle, window)[ + "activity_code" + ] + + +@pytest.mark.parametrize("suffix", [".joblib", ".onnx"]) +def test_export_from_config_serves_fixture_windows(tmp_path: Path, suffix: str): + processed = tmp_path / "processed" + for subject_id, ax in ((1600, 1.0), (1601, 8.0)): + for activity in ("A", "B"): + _write_session(processed, subject_id, activity, ax=ax) + cfg = tmp_path / "phone.yaml" + cfg.write_text( + yaml.safe_dump( + { + "seed": 42, + "data": {"processed_dir": str(processed), "device": "phone"}, + "window": {"length_s": 5.0, "hop_s": 1.0, "min_coverage": 0.95}, + "features": {"kind": "statistical"}, + "model": { + "name": "xgboost", + "params": { + "n_estimators": 2, + "max_depth": 2, + "n_jobs": 1, + "device": "cuda", + }, + }, + "split": {"protocol": "groupkfold", "n_splits": 2}, + } + ), + encoding="utf-8", + ) + out = export_from_config(cfg, tmp_path / f"phone{suffix}", model_id="fixture-phone") + bundle = load_bundle(out) + assert bundle.model_id == "fixture-phone" + assert bundle.device == "phone" + assert bundle.n_timesteps == N_T + assert bundle.n_channels == N_C + if suffix == ".joblib": + assert bundle.estimator.get_params()["device"] == "cpu" + else: + assert out.with_suffix(".json").is_file() + with TestClient(create_app(bundle)) as client: + resp = client.post("/predict", json=_payload()) + assert resp.status_code == 200 + body = resp.json() + assert body["activity_code"] in ACTIVITY_CODES + assert body["abstained"] is False + + +def test_export_onnx_rejects_non_xgboost(tmp_path: Path): + with pytest.raises(TypeError, match="XGBoost"): + export_onnx(object(), tmp_path / "model.onnx", n_features=104) + + +def test_onnx_roundtrip_matches_sklearn_proba(tmp_path: Path): + rng = np.random.default_rng(0) + y = np.array([0, 1, 2] * 12, dtype=np.int64) + x = rng.normal(size=(y.size, 8)).astype(np.float32) + for i in range(3): + x[y == i, 0] += float(i) * 3.0 + model = fit_xgboost( + x[:24], + y[:24], + x[24:], + y[24:], + {"n_estimators": 8, "max_depth": 3, "n_jobs": 1, "device": "cpu"}, + ) + bundle = ModelBundle( + estimator=model, + n_timesteps=4, + n_channels=2, + hz=TARGET_HZ, + device="watch", + features="raw_flat", + model_id="onnx-xgb", + ) + path = save_onnx_bundle(tmp_path / "model.onnx", bundle) + loaded = load_bundle(path) + x_te = x[24:28] + np.testing.assert_allclose( + loaded.estimator.predict_proba(x_te), + model.predict_proba(x_te), + rtol=1e-5, + atol=1e-6, + ) + window = rng.normal(size=(4, 2)).astype(np.float32) + assert predict_window(loaded, window)["activity_code"] in ACTIVITY_CODES[:3] + + +def test_create_app_loads_onnx_har_model_path(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): + rng = np.random.default_rng(1) + y = np.array([0, 1] * 16, dtype=np.int64) + x = rng.normal(size=(y.size, 8)).astype(np.float32) + x[y == 1] += 4.0 + model = fit_xgboost( + x[:24], + y[:24], + x[24:], + y[24:], + {"n_estimators": 4, "max_depth": 2, "n_jobs": 1, "device": "cpu"}, + ) + path = save_onnx_bundle( + tmp_path / "env.onnx", + ModelBundle( + estimator=model, + n_timesteps=4, + n_channels=2, + hz=TARGET_HZ, + device="watch", + features="raw_flat", + model_id="onnx-env", + ), + ) + monkeypatch.setenv("HAR_MODEL_PATH", str(path)) + with TestClient(create_app()) as client: + assert client.get("/health").json() == {"status": "ok", "model_id": "onnx-env"} + resp = client.post("/predict", json=_payload(t=4, c=2, device="watch")) + assert resp.status_code == 200 + assert resp.json()["activity_code"] in ("A", "B") + + +def test_export_from_config_rejects_hierarchical(tmp_path: Path): + cfg = tmp_path / "hier.yaml" + cfg.write_text( + yaml.safe_dump({"data": {"device": "phone"}, "model": {"name": "hierarchical"}}), + encoding="utf-8", + ) + with pytest.raises(TypeError, match="predict_proba"): + export_from_config(cfg, tmp_path / "hier.joblib") + + +def test_create_app_loads_har_model_path(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): + path = save_bundle(tmp_path / "env.joblib", _stub_bundle()) + monkeypatch.setenv("HAR_MODEL_PATH", str(path)) + with TestClient(create_app()) as client: + assert client.get("/health").json() == {"status": "ok", "model_id": "stub"} + resp = client.post("/predict", json=_payload()) + assert resp.status_code == 200 + assert resp.json()["activity_code"] == "A" + + +def test_predict_window_uses_argmax_over_padded_proba(): + class SubsetEstimator: + classes_ = np.array([5, 10, 12]) + n_features_in_ = len(feature_names(N_C)) + + def predict_proba(self, X: np.ndarray) -> np.ndarray: + p = np.zeros((len(np.asarray(X)), 3), dtype=np.float64) + p[:, 1] = 1.0 + return p + + def predict(self, X: np.ndarray) -> np.ndarray: + return np.zeros(len(np.asarray(X)), dtype=np.int64) + + bundle = ModelBundle( + estimator=SubsetEstimator(), + n_timesteps=N_T, + n_channels=N_C, + hz=TARGET_HZ, + device="phone", + features="statistical", + model_id="subset", + ) + out = predict_window(bundle, np.zeros((N_T, N_C), dtype=np.float32)) + assert out["activity_code"] == "K" + assert out["activity_name"] == "drinking" + assert out["proba"]["K"] == pytest.approx(1.0) + assert out["proba"]["A"] == pytest.approx(0.0) + + +def test_predict_p95_under_500ms(): + with _client() as client: + payload = _payload() + assert client.post("/predict", json=payload).status_code == 200 + times_ms: list[float] = [] + for _ in range(100): + t0 = time.perf_counter() + resp = client.post("/predict", json=payload) + times_ms.append((time.perf_counter() - t0) * 1000.0) + assert resp.status_code == 200 + p95 = float(np.percentile(times_ms, 95)) + assert p95 < 500.0 + + +def _write_session(processed: Path, subject_id: int, activity: str, *, ax: float) -> None: + n = int(round(6.0 * TARGET_HZ)) + dt_ns = int(round(NS_PER_S / TARGET_HZ)) + data: dict[str, np.ndarray] = {"timestamps_ns": np.arange(n, dtype=np.int64) * dt_ns} + for name in CHANNEL_NAMES: + col = np.zeros(n, dtype=np.float32) + if name == "ax": + col[:] = ax + data[name] = col + path = processed / "phone" / f"{subject_id}_{activity}_0.parquet" + path.parent.mkdir(parents=True, exist_ok=True) + pd.DataFrame(data).to_parquet(path, index=False) diff --git a/tests/test_tiny_wisdm.py b/tests/test_tiny_wisdm.py new file mode 100644 index 0000000..84b0049 --- /dev/null +++ b/tests/test_tiny_wisdm.py @@ -0,0 +1,45 @@ +from pathlib import Path + +import pandas as pd + +from har.data.audit import audit_dataset +from har.data.repair import prepare_dataset + +TINY_ROOT = Path(__file__).resolve().parent / "fixtures" / "tiny_wisdm" + + +def test_tiny_wisdm_has_two_subjects_two_activities_at_20hz(): + sessions = audit_dataset(TINY_ROOT) + subjects = set(sessions["subject_id"].astype(int)) + activities = set(sessions["activity"].astype(str)) + sensors = set(sessions["sensor"].astype(str)) + devices = set(sessions["device"].astype(str)) + + assert subjects == {1600, 1601} + assert activities == {"A", "B"} + assert sensors == {"accel", "gyro"} + assert devices == {"phone"} + assert len(sessions) == 8 + assert sessions["implied_hz"].between(19.0, 21.0).all() + assert (sessions["duration_s"] >= 2.0).all() + assert (sessions["n_samples"] >= 40).all() + + +def test_tiny_wisdm_prepare_writes_four_aligned_sessions(tmp_path: Path): + processed = tmp_path / "processed" + prepare_dataset(TINY_ROOT, processed, {"repair": {"target_hz": 20.0}}) + parquets = sorted(processed.rglob("*.parquet")) + names = {path.stem for path in parquets} + assert names == {"1600_A_0", "1600_B_0", "1601_A_0", "1601_B_0"} + for path in parquets: + table = pd.read_parquet(path) + assert len(table) > 0 + assert list(table.columns) == [ + "timestamps_ns", + "ax", + "ay", + "az", + "gx", + "gy", + "gz", + ]