Skip to content
ModelListedExternal
Download

Timesformer Dairy Cows

Fine-tuned TimeSformer for seven-class behaviour recognition in dairy cattle, developed as part of the MooAnalytica digital twin framework at Dalhousie University.

KindOtherVersionLastCgrade

Model source

Kind
Other
File size
1.36 GB
Version
vLast
Updated
Oct 10, 2026
Source
Hugging Face

Source description

TimeSformer — Dairy Cow Behaviour Recognition

Fine-tuned TimeSformer for seven-class behaviour recognition in dairy cattle, developed as part of the MooAnalytica digital twin framework at Dalhousie University.

This model forms the behavioural perception layer of an AI-driven dairy cattle digital twin, converting continuous barn surveillance video into structured per-cow behavioural state streams used for nutrition modelling and welfare monitoring.


Model Description

  • Base model: facebook/timesformer-base-finetuned-k400 (Kinetics-400 pretrained)
  • Architecture: TimeSformer with divided space-time attention
  • Input: 12-frame clips at 1.6 fps (10-second windows), 224×224 px crops
  • Output: 7-class behaviour label per clip

Behaviour Classes

IDLabel
0Standing
1Lying
2Drinking
3Feeding & Standing
4Feeding & Lying
5Ruminating & Standing
6Ruminating & Lying

Training Data

  • Source: Dalhousie University Ruminant Animal Centre (RAC), Truro, Nova Scotia — March 2025
  • Setup: 3 overhead CCTV cameras, 17 Holstein dairy cows
  • Annotated clips: 4,964 manually annotated video clips
  • Augmented training set: 9,600 clips (oversampling of minority classes)
  • Validation set: 689 clips (held-out, no augmentation)
  • Split: Clip-level random train/val split (80/20)

Performance

Evaluated on the held-out validation set (n = 689 clips):

MetricValue
Overall accuracy85.8%
Macro-F10.836
Daytime accuracy (n=670)88.2%
Nighttime accuracy (n=449)81.5%
mAP (macro)87.5%

Per-class performance highlights: Feeding & Standing (F1=0.944), Lying (F1=0.912), Drinking (F1=0.905). Lowest: Standing (F1=0.720) and Ruminating & Standing (F1=0.782) due to postural similarity.


Usage

import torch
import numpy as np
from transformers import TimesformerForVideoClassification, AutoConfig
from huggingface_hub import hf_hub_download

# Load model
model_id = "shreyayayay/timesformer-dairy-cows"
config = AutoConfig.from_pretrained(model_id)
model = TimesformerForVideoClassification.from_pretrained(
    model_id,
    config=config,
    ignore_mismatched_sizes=True
)
model.eval()

ID2LABEL = {
    0: "Standing",
    1: "Lying",
    2: "Drinking",
    3: "Feeding & Standing",
    4: "Feeding & Lying",
    5: "Ruminating & Standing",
    6: "Ruminating & Lying",
}

IMNET_MEAN = np.array([0.485, 0.456, 0.406], dtype=np.float32)
IMNET_STD  = np.array([0.229, 0.224, 0.225], dtype=np.float32)

def preprocess_clip(frames):
    arr = np.stack(frames).astype(np.float32) / 255.0
    arr = (arr - IMNET_MEAN) / IMNET_STD
    arr = arr.transpose(0, 3, 1, 2)
    return torch.from_numpy(arr).unsqueeze(0)

with torch.no_grad():
    pixel_values = preprocess_clip(frames).to(next(model.parameters()).device)
    logits = model(pixel_values=pixel_values).logits
    pred = int(torch.argmax(logits, dim=-1))
    print(f"Predicted behaviour: {ID2LABEL[pred]}")

Loading weights directly

import torch
from huggingface_hub import hf_hub_download

weights_path = hf_hub_download(
    repo_id="shreyayayay/timesformer-dairy-cows",
    filename="last.pt"
)
checkpoint = torch.load(weights_path, map_location="cpu")

Integration with MooAnalytica Pipeline

Video → YOLOv11 detection → ByteTrack tracking → TimeSformer classification → Nutrition model (M-M DMI estimation)

Full pipeline code: github.com/raoshreya17/dairycow-digitaltwin


Training Details

ParameterValue
Base modelfacebook/timesformer-base-finetuned-k400
Epochs6 (early stopping, patience=3)
OptimizerAdamW (lr=2e-5, weight decay=1e-4)
LossFocal loss (γ=2, class-weighted)
Batch size8 (gradient accumulation ×4)
Mixed precisionfp16
HardwareNVIDIA A100 40GB
FrameworkPyTorch 2.0, transformers==4.41.2
Clip length12 frames @ 1.6 fps
Resolution224×224 px
AugmentationHorizontal flip, brightness/contrast jitter, temporal jitter

Limitations

  • Trained on a single barn environment (RAC, Truro NS); cross-farm generalisation not yet validated
  • Nighttime performance is 6.7 percentage points lower than daytime due to infrared noise
  • Identity persistence across camera cuts relies on ByteTrack; brief identity switches (~8% of interrupted tracks) may introduce short temporal labelling noise
  • Lying and Ruminating & Lying are occasionally confused due to near-identical posture

Citation

@article{rao2026mooanalytica,
  title     = {An AI-Driven Behavioural Perception and Nutrition Modelling Framework
               as the Behavioural State Layer of a Dairy Cattle Digital Twin},
  author    = {Rao, Shreya and Garcia, Eduardo and Neethirajan, Suresh},
  journal   = {npj Veterinary Sciences},
  volume    = {1},
  number    = {3},
  year      = {2026},
  publisher = {Nature Publishing Group},
  doi       = {10.1038/s44433-026-00004-x}
}

License

MIT — see LICENSE

Contact

Shreya Rao — MCS candidate, Dalhousie University
Supervisor: Dr. Suresh Neethirajan
GitHub: raoshreya17

Sources

1 source
Hugging FacePrimaryVersion 365b904dcc1ec7c158db60e6dcb62f465f6b8790
huggingface.co/shreyayayay/timesformer-dairy-cows/tree/365b904dcc1ec7c158db60e6dcb62f465f6b8790

Verified Oct 10

Model artifacts

1 artifact

last.pt

pt · 1.36 GB · SHA-256 153a460040b1…872c · Hugging Face

Download file

Source excerpts

2 excerpts

--- language: en license: mit tags: - video-classification - timesformer - dairy-cattle - behaviour-recognition - digital-twin - precision-livestock-farming metrics: - accuracy - f1 model-index: - name: timesformer-dairy-cows results: - task: type: video-classification dataset: name: Dairy Cow Behaviour Dataset (RAC 2025) type: custom metrics: - type: accuracy value: 0.858 - type: f1 value: 0.836 --- # TimeSformer — Dairy Cow Behaviour Recognition Fine-tuned [TimeSformer](https://huggingface.co/facebook/timesformer-base-finetuned-k400) for seven-class behaviour recognition in dairy cattle, developed as part of the **MooAnalytica** digital twin framework at Dalhousie University. This model forms the behavioural perception layer of an AI-driven dairy cattle digital twin, converting continuous barn surveillance video into structured per-cow behavioural state streams used for nutrition modelling and welfare monitoring. --- ## Model Description - **Base model:** `facebook/timesformer-base-finetuned-k400` (Kinetics-400 pretrained) - **Architecture:** TimeSformer with divided space-time attention - **Input:** 12-frame clips at 1.6 fps (10-second windows), 224×224 px crops - **Output:** 7-class behaviour label per clip ### Behaviour Classes | ID | Label | |----|-------| | 0 | Standing | | 1 | Lying | | 2 | Drinking | | 3 | Feeding & Standing | | 4 | Feeding & Lying | | 5 | Ruminating & Standing | | 6 | Ruminating & Lying | --- ## Training Data - **Source:** Dalhousie University Ruminant Animal Centre (RAC), Truro, Nova Scotia — March 2025 - **Setup:** 3 overhead CCTV cameras, 17 Holstein dairy cows - **Annotated clips:** 4,964 manually annotated video clips - **Augmented training set:** 9,600 clips (oversampling of minority classes) - **Validation set:** 689 clips (held-out, no augmentation) - **Split:** Clip-level random train/val split (80/20) --- ## Performance Evaluated on the held-out validation set (n = 689 clips): | Metric | Value | |--------|-------| | Overall accuracy | **85.8%** | | Macro-F1 | **0.836** | | Daytime accuracy (n=670) | 88.2% | | Nighttime accuracy (n=449) | 81.5% | | mAP (macro) | 87.5% | Per-class performance highlights: Feeding & Standing (F1=0.944), Lying (F1=0.912), Drinking (F1=0.905). Lowest: Standing (F1=0.720) and Ruminating & Standing (F1=0.782) due to postural similarity. --- ## Usage ```py...

Source context: 0 downloads · 0 likes · Pipeline video-classification · Repo shreyayayay/timesformer-dairy-cows