Transformers
Safetensors
time-series
patchtst
livestock
dairy
synthetic-data
student-project
time-series-classification
Instructions to use YasenDzhenkov/herdsight-patchtst with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use YasenDzhenkov/herdsight-patchtst with Transformers:
# pip install -U transformers accelerate # Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("YasenDzhenkov/herdsight-patchtst", device_map="auto") - Notebooks
- Google Colab
- Kaggle
|
Download README.md from YasenDzhenkov/herdsight-patchtst: direct link, hf CLI and curl.
- Browser
- Download file 9.66 kB
-
https://huggingface.co/YasenDzhenkov/herdsight-patchtst/resolve/main/README.md
- Command line
-
hf download hf://YasenDzhenkov/herdsight-patchtst/README.md
-
curl -L -o README.md https://huggingface.co/YasenDzhenkov/herdsight-patchtst/resolve/main/README.md
9.66 kB
| license: apache-2.0 | |
| base_model: ibm-granite/granite-timeseries-patchtst | |
| library_name: transformers | |
| pipeline_tag: time-series-classification | |
| tags: [time-series, patchtst, livestock, dairy, synthetic-data, student-project] | |
| # HerdSight ear-tag + drone health classifier (PatchTST, fine-tuned on synthetic data) | |
| Student project (Tech with Impact, HerdSight). Classifies each cow-day from the last 14 days | |
| of sensor data into: `normal`, `brd` (respiratory disease), `lame`, `estrus`, `calving_24h` | |
| (calving within 24 h), `stray` (outside the geofence). | |
| **This is not a veterinary diagnosis.** It is a prototype that flags cows for a person to check. | |
| **It was trained and tested only on simulated data.** The numbers below show the pipeline works | |
| end to end; they do not show how it would perform on a real farm. | |
| ## Base model and licence | |
| - Base: [`ibm-granite/granite-timeseries-patchtst`](https://huggingface.co/ibm-granite/granite-timeseries-patchtst) | |
| (PatchTST, 3 transformer layers, d_model 128, pretrained for forecasting on ETTh1), | |
| licence **Apache-2.0** (checked on the model card, 30 Nov 2026). This fine-tune is also Apache-2.0. | |
| - What was kept from pretraining: the 3 transformer encoder layers and the CLS token. | |
| What was re-initialised: the patch embedding and positional table (our series is 14 daily | |
| values, patch length 2 / stride 1, instead of 512 hourly values with patch 12) and the new | |
| 6-class classification head. So this is partial transfer: be careful not to over-claim what | |
| the pretraining contributes. | |
| - Why this model: it loads natively in `transformers` (no extra package), is 0.6 M parameters, | |
| and fine-tunes on an Apple-silicon laptop in about 20 minutes. TinyTimeMixer needs at least | |
| 52 time steps and the `granite-tsfm` package; Chronos-Bolt needs its own package and is a | |
| univariate forecaster. | |
| ## Input | |
| A window of 14 days x 16 channels: | |
| - 8 cow channels. From the **ear tag (motion sensor + GPS, no thermometer)**: steps, | |
| distance_km, feeding_min, rumination_min, lying_min, isolation_m (mean distance to herd), | |
| outside_fence_min. From the **barn drone's thermal camera**: `thermal_drone`, the mean of the | |
| day's hourly body-surface readings taken from a distance (about 28-36 degC, not core | |
| temperature). It is noisier than a contact sensor: 10-30 % of each cow's rounds are missed | |
| (under trees, inside the barn), and whole farms have no readings on storm or heavy-snow days | |
| (about 4 % of cow-days missing in total). Each is her change versus her own median in the first 7 days of the window, | |
| in units of the signal's typical day-to-day spread (log scale for counts and minutes). | |
| - 8 herd channels: the same signals for the farm's median cow that day, same normalisation. | |
| **Heat stress is handled as input context, not as a class.** Heat stress (THI >= 72) is a | |
| herd-level state that shifts every cow at once; it is not an illness of one cow. Giving the model | |
| the herd's own change lets it learn "the whole herd ruminates less today" is not "this cow is sick". | |
| The evaluation reports false alerts on heat-stress days separately. | |
| ## Training data (synthetic) | |
| `simulate.py`: 10,000 cows x 1,000 days (10 million cow-days), 20 farms with different | |
| climates and herd baselines, individual cow baselines, seasonality, AR(1) weather plus summer heat | |
| waves (THI), sensor noise, 3 % missing tag cow-days (random gaps and tag outages) and separate drone gaps | |
| (missed rounds, grounded days). Events with onsets, | |
| ramps and durations: BRD (2-4 day subclinical ramp, then 4-10 days), lameness (3-5 day ramp, then | |
| 10-40 days), estrus (21-day cycles after calving, 20 % silent), calving (label on the day before), | |
| straying (1 day). Effect sizes follow the direction and rough size reported in dairy-sensor | |
| studies where named in the code comments; the rest are labelled ASSUMPTION. Effect sizes vary | |
| per farm (x0.6-1.4) and per event (x0.6-1.4) so the labels are not a fixed signature. | |
| Splits (by farm, by cow and by time): | |
| - Train: 16 farms, 85 % of their cows, window end days 13-699. | |
| Sampled **217,674 windows** class-balanced (normal 120,000; brd 10,081; lame 40,000; | |
| estrus 29,219; calving_24h 13,198; stray 5,176) out of 10 M cow-days. | |
| - Validation: the other 15 % of cows on those farms, days 750-999 (30,000 random windows). | |
| - Test: **4 farms never seen in training** (all their cows), days 750-999, every cow-day. | |
| - Because training was class-balanced, predicted probabilities are re-weighted to the true | |
| class frequencies (prior correction) before alerts, so the alert rate is realistic. | |
| Training: 3 epochs, batch 512, AdamW (lr 5e-4, one-cycle), cross-entropy, Apple M-series GPU | |
| (MPS), about 7 minutes per epoch. Per-epoch log in `model/herdsight_meta.json`. | |
| Gradient-boosting baseline: scikit-learn `HistGradientBoostingClassifier` (300 trees) on the same | |
| 217,674 windows flattened to 224 numbers, same prior correction. | |
| ## Results (unseen farms, SYNTHETIC) | |
| Test set: farms [5, 9, 11, 14] (never seen in training), 1,975 cows, days 750-999, 493,750 cow-days (1,419 on heat-stress days). Every cow-day is scored. | |
| Per class, fine-tuned PatchTST vs gradient boosting (precision / recall / F1): | |
| | class | support | PatchTST P / R / F1 | GBM P / R / F1 | | |
| |---|---|---|---| | |
| | normal | 475,558 | 0.978 / 0.999 / 0.988 | 0.978 / 0.96 / 0.969 | | |
| | brd | 1,095 | 0.958 / 0.58 / 0.722 | 0.202 / 0.534 / 0.293 | | |
| | lame | 12,247 | 0.93 / 0.206 / 0.338 | 0.196 / 0.222 / 0.208 | | |
| | estrus | 2,985 | 0.917 / 0.814 / 0.863 | 0.432 / 0.819 / 0.566 | | |
| | calving_24h | 1,339 | 0.994 / 0.82 / 0.899 | 0.3 / 0.823 / 0.439 | | |
| | stray | 526 | 1.0 / 0.93 / 0.964 | 0.548 / 0.947 / 0.694 | | |
| Macro-F1 over the 5 event classes: PatchTST **0.757**, gradient boosting 0.44. | |
| Any-alert view (alert = anything other than normal; the z-score rule can only do this): | |
| | method | precision | recall | false alerts / 100 cows / day | on heat-stress days | other days | | |
| |---|---|---|---|---|---| | |
| | Fine-tuned PatchTST | 0.964 | 0.404 | 0.05 | 0.07 | 0.05 | | |
| | Gradient boosting | 0.3 | 0.445 | 3.82 | 4.16 | 3.82 | | |
| | z-rule, herd-adjusted, any signal |z|>2 | 0.05 | 0.622 | 43.88 | 43.97 | 43.88 | | |
| | z-rule, herd-adjusted, 2+ signals | 0.094 | 0.386 | 13.67 | 13.32 | 13.67 | | |
| | z-rule, NOT herd-adjusted, any signal | 0.047 | 0.662 | 49.44 | 65.61 | 49.4 | | |
| | z-rule, NOT herd-adjusted, 2+ signals | 0.081 | 0.419 | 17.49 | 35.02 | 17.44 | | |
| Early detection (episode counted as detected if flagged on a labelled day; lead = onset day minus first flag; flags before the label starts are counted as false alerts, not credited). Onset = clinical BRD, scoreable lameness, calving day. Max possible lead: 2-4 days (BRD), 3-5 (lame), 1 (calving). | |
| | method | BRD detected / before onset / median lead d | lame | calving (24 h) | | |
| |---|---|---|---| | |
| | Fine-tuned PatchTST | 94% / 42% / 0.0 | 80% / 27% / 0.0 | 82% / 82% / 1.0 | | |
| | Gradient boosting | 92% / 46% / 0.0 | 94% / 41% / 0.0 | 82% / 82% / 1.0 | | |
| | z-rule, herd-adjusted, 2+ signals | 100% / 89% / 2.0 | 100% / 79% / 2.0 | 92% / 92% / 1.0 | | |
| Reading this honestly: after prior correction the fine-tuned model is very conservative. It | |
| raises almost no false alarms (0.05 per 100 cows per day) but catches only about 40 % of sick or | |
| event cow-days, and it flags BRD and lameness mostly on or after onset, not days before. The | |
| herd-adjusted z-score rule warns earlier but cries wolf 14-44 times per 100 cows per day. Herd | |
| adjustment clearly matters on heat-stress days (z-rule without it: 35 vs 13 false alerts per 100 | |
| cows). Lowering the alert threshold would trade false alarms for recall; that was not tuned. | |
| Confusion matrices: `confusion.png`. Full numbers: `results.json`. **All of this is synthetic: it does not prove real-farm accuracy.** | |
| Earlier run kept for reference: `v1_tag_thermometer/` (same pipeline, but with temperature | |
| from a thermometer in the ear tag, 4 epochs). The tag has no thermometer in the final design, so | |
| that run is superseded; its gradient-boosting baseline also scored oddly low on straying (not | |
| investigated, re-trained cleanly in the final run). | |
| ## How to load | |
| ```python | |
| import json, numpy as np, torch | |
| from transformers import PatchTSTForClassification | |
| model = PatchTSTForClassification.from_pretrained("model").eval() | |
| meta = json.load(open("model/herdsight_meta.json")) # classes, scale, priors | |
| x = torch.zeros(1, 14, 16) # built by train.windows(...) | |
| p = torch.softmax(model(past_values=x).prediction_logits, -1).numpy() | |
| p = p * np.array(meta["true_prior"]) / np.array(meta["train_prior"]); p /= p.sum(1, keepdims=True) | |
| print(meta["classes"][p.argmax()]) | |
| ``` | |
| Reproduce: `hf download ibm-granite/granite-timeseries-patchtst --local-dir base/patchtst`, | |
| then `python simulate.py && python train.py && python train.py --gbm-only && python evaluate.py`. | |
| Self-check: `python test_simulate.py`. | |
| ## Limitations | |
| - Synthetic data only. Real tags differ in sensor quality, gaps, farm routines and disease mix; | |
| real labels (vet records) are noisy and late. Expect much lower accuracy on real farms until | |
| the model is retrained and validated on labelled farm data. | |
| - The simulator encodes our own assumptions, so the model partly learns those assumptions back. | |
| - Daily summaries only: an estrus bout of 12-18 hours and short calving restlessness are blurred | |
| across day boundaries. | |
| - Rare classes (BRD, straying) have few training examples. One window per cow-day; no | |
| multi-label output (overlaps are resolved by a fixed priority). | |
| - Intended use: early-warning list for a farmer or vet to look at. Out of scope: diagnosis, | |
| treatment decisions, welfare audits, any decision without a human check. | |