AI System for Livestock Monitoring

We design and deploy artificial intelligence systems: from prototype to production-ready solutions. Our team combines expertise in machine learning, data engineering and MLOps to make AI work not in the lab, but in real business.
Showing 1 of 1All 1564 services
AI System for Livestock Monitoring
Medium
~1-2 weeks
Frequently Asked Questions

AI Development Areas

AI Solution Development Stages

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1347
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1247
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    948
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1183
  • image_logo-advance_0.webp
    B2B Advance company logo design
    642
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    921

On large dairy farms with 1000+ head, the veterinarian cannot inspect every cow daily. Losing one day with mastitis means a 10-15% drop in milk yield, while missed insemination results in empty days and significant losses. We develop turnkey AI systems: we fuse data from ear sensors, rumen boluses, milk meters, and video, issuing alerts 24-48 hours before clinical signs. Our experience — 10+ projects in Russia and CIS, average mortality reduction of 15-20%. Automatic heat detection is 2 times more efficient than visual observation: accuracy reaches 95% vs 60%. We use machine learning for behavioral analysis of cattle and IoT devices for data collection.

What problems does AI monitoring solve?

Three key tasks the system addresses:

  1. Missed heat — each heat lasts 12-18 hours, visually detected only 60% of the time. The system analyzes activity and rumination at 2-minute intervals and issues an alert 4-6 hours before the insemination window closes.

  2. Subclinical mastitis — milk conductivity increases 24-48 hours before clots appear. Sensitivity 85% at specificity 90%.

  3. SARA (subacute ruminal acidosis) — rumen pH drops below 5.8 for 3+ hours, reducing productivity by 15%. Time series analysis from rumen bolus detects risk 1-2 days in advance.

How to detect heat with 95% accuracy?

Algorithm based on activity and rumination:

import pandas as pd
import numpy as np
from scipy.signal import find_peaks

def detect_estrus(animal_id: str, sensor_data: pd.DataFrame,
                  baseline_days: int = 21) -> dict:
    """
    Heat in cattle: sharp increase in activity + decrease in rumination
    Cycle ~21 days — periodic pattern
    """
    recent = sensor_data[sensor_data['animal_id'] == animal_id].tail(baseline_days * 24)

    activity_baseline = recent['activity_count'].quantile(0.5)
    rumination_baseline = recent['rumination_time'].quantile(0.5)

    current_24h = sensor_data[
        sensor_data['animal_id'] == animal_id
    ].tail(12)

    activity_ratio = current_24h['activity_count'].mean() / (activity_baseline + 1e-9)
    rumination_ratio = current_24h['rumination_time'].mean() / (rumination_baseline + 1e-9)

    estrus_score = activity_ratio * (2 - rumination_ratio)

    prev_cycle_score = check_previous_cycle(animal_id, sensor_data, days_back=21)

    return {
        'animal_id': animal_id,
        'estrus_score': float(estrus_score),
        'estrus_detected': estrus_score > 2.5,
        'confidence': 'high' if prev_cycle_score > 2.0 else 'medium',
        'recommended_action': 'insemination_window_12-18h' if estrus_score > 2.5 else None
    }

Why is rumination a key health indicator?

Early mastitis detection:

def mastitis_risk_score(milking_data: pd.DataFrame, animal_id: str) -> float:
    """
    Mastitis → inflammation → increase in Na+, Cl- ions → increase in conductivity
    """
    today_milking = milking_data[
        (milking_data['animal_id'] == animal_id) &
        (milking_data['date'] == milking_data['date'].max())
    ]

    if today_milking.empty:
        return 0.0

    quarters = ['LF', 'RF', 'LR', 'RR']
    conductivities = {q: today_milking[f'conductivity_{q}'].mean()
                      for q in quarters if f'conductivity_{q}' in today_milking.columns}

    if len(conductivities) < 2:
        return 0.0

    mean_cond = np.mean(list(conductivities.values()))
    max_deviation = max(abs(v - mean_cond) for v in conductivities.values())

    relative_deviation = max_deviation / (mean_cond + 1e-9)

    yield_deviation = check_yield_drop(animal_id, milking_data, today_milking)

    risk_score = 0.6 * (relative_deviation / 0.1) + 0.4 * yield_deviation
    return min(1.0, risk_score)

Additional mastitis signs: increased milk temperature in the quarter (+0.5°C), flocculation, reduced yield, behavioral changes.

How to set up mastitis detection step by step?

  1. Collect baseline data: at least 500 milkings without pathology for each cow.
  2. Compute baseline conductivity for each quarter considering lactation stage.
  3. Set thresholds: sensitivity 85% at specificity 90%.
  4. Validate on historical data: at least 50 confirmed mastitis cases.
  5. A/B test on 10% of herd before full deployment.

What does SARA monitoring provide?

Subacute ruminal acidosis (SARA) — pH < 5.8 for more than 3 hours:

def detect_sara_risk(rumen_bolus_data: pd.DataFrame, animal_id: str) -> dict:
    """
    Data from rumen bolus SmaXtec updates every 10 minutes
    """
    today_data = rumen_bolus_data[
        (rumen_bolus_data['animal_id'] == animal_id) &
        (rumen_bolus_data['date'] == pd.Timestamp.today().date())
    ]

    low_ph_minutes = len(today_data[today_data['rumen_pH'] < 5.8]) * 10

    avg_ph = today_data['rumen_pH'].mean() if not today_data.empty else 6.5
    rumination_today = today_data['rumen_motility'].mean() if not today_data.empty else 1.0

    sara_risk = 'high' if low_ph_minutes > 180 else (
        'medium' if low_ph_minutes > 60 else 'low'
    )

    return {
        'animal_id': animal_id,
        'low_ph_hours': round(low_ph_minutes / 60, 1),
        'avg_ph': round(avg_ph, 2),
        'sara_risk': sara_risk,
        'action': 'adjust_roughage_ratio' if sara_risk == 'high' else None
    }

SARA monitoring enables precision feeding: when risk is detected, the system recommends adjusting the roughage ratio. Implementation reduces veterinary costs and increases herd productivity.

How to integrate the system with existing software?

We support REST API for sending events to DairyComp 305, Lely T4C, DeLaval ALPRO, and herd monitoring software. Integration takes 1-2 days. Real-time data transmission: heat events, disease risks, weight indicators.

How we implement the system: a case study

On a farm with 2000 heads of cattle, we installed SCR ear accelerometers and SmaXtec rumen boluses. In the first week, we collected ~1.5 million activity records and 200,000 pH measurements. After 3 weeks, models reached 92% sensitivity for heat and 90% for SARA. Compare: visual method gives 60% heat detection, manual pH analysis — single measurements. Automation reduced veterinary service costs by 1.5 times.

How we solved the sensor drift problem?During calibration, we encountered sensor drift: after 3 months of operation, some accelerometers started overestimating activity. Solution — automatic recalibration every 2 weeks based on group averages. This improved mastitis detection stability from 82% to 90%.
Method Heat detection accuracy Time spent
Visual observation 60-70% 2-3 hours/day
Accelerometer + AI 95% 5 minutes/day
Sensor combination 98% 2-3 minutes/day

Project stages and timelines

Stage Duration What is included
Analysis and design 5–7 days Farm audit, sensor selection, ML pipeline architecture
Sensor integration 1–2 weeks Gateway setup, baseline data collection, calibration
Model development 2–4 weeks Heat, mastitis, SARA detection — baseline + fine-tuning
Dashboard and alerts 1–2 weeks Web interface, Telegram bot, export to DairyComp
Testing and deployment 1 week A/B test on 10% of herd, latency optimization

What is included in the work

  • Architecture documentation and API description
  • Personnel training (2 days on-site or online)
  • 30 days of post-release technical support
  • Model warranty — 6 months (free updates when herd changes)
  • Adaptation to existing infrastructure (DairyComp 305, Lely T4C, DeLaval ALPRO)

Leave a request — we will assess your farm in 2 days and propose an architecture. Contact us to discuss the project. Get a consultation on your herd and learn how AI monitoring can reduce mortality and increase milk yields.

Anomaly Detection: Autoencoders, Isolation Forest, PyOD

Server monitoring shows CPU 85%, memory 91% — is this the start of an attack or normal peak load? A classifier won’t help: anomalies are by definition rare, diverse, and not pre-labeled. Supervised learning requires examples of anomalies in the training set — so it fails on what you haven’t seen yet. Without an unsupervised approach, detection turns into guesswork.

Why Does Anomaly Detection Require an Unsupervised Approach?

The main problem: no labels and extreme class imbalance. Fraud transactions account for 0.01–0.1% of total volume, production defects 0.5–3%. With such ratios, a naive “all normal” classifier gives 99.9% accuracy but recall for the anomalous class near zero. Supervised models are powerless.

Second: “normality” is always contextual. A login at 3 AM may be normal for a night‑shift user but suspicious for a day‑worker. Bearing vibration at 2.3 mm/s depends on operating mode and machine age. So we embed context via feature engineering and time windows.

Third: quality assessment without ground truth. No standard test set — AUC‑ROC is possible only if a few labeled examples exist. For fully unlabeled data, only domain expert validation and indirect metrics work.

How to Distinguish an Anomaly from Noise in Real Time?

With adaptive thresholds and continuous monitoring of model statistics. In the case section we show how.

Method Data Type Training Speed Typical Application
Isolation Forest Tabular, categorical High Baseline for initial hypotheses
Autoencoder Images, time series, logs Medium Unstructured data
LSTM-AE Multivariate time series Low Industrial telemetry
PyOD (ensemble) Tabular High Quick comparison of 40+ methods

Isolation Forest is the standard baseline for tabular data. Idea: anomalies are isolated faster by random partitioning of the feature space. Works well at contamination=0.01–0.1, robust to feature scale, no normalization required. Implementation in sklearn.ensemble.IsolationForest.

Typical mistake: setting contamination='auto' without understanding the data. Auto mode assumes a threshold of -0.5, which may not match the actual anomaly proportion. Better: estimate expected anomaly percentage through domain knowledge and set it explicitly. We guarantee contamination tuning for your case.

PyOD (Python Outlier Detection) is a library with 40+ algorithms under a unified API — OCSVM, LOF, COPOD, ECOD, DeepSVDD, AutoEncoder. Useful for quickly comparing methods on the same data.

Autoencoders are the main method for unstructured data (time series, images, logs). Train the network to reconstruct normal data; anomalies yield high reconstruction error. Anomaly threshold is the 95th or 99th percentile of error on a validation set of normal data.

Practical problem with autoencoders: overfitting on “normal” patterns that are still rare. If the training set contains even a few anomalies, the model may learn to reconstruct them well. Solution: thorough cleaning of training data or using a Variational Autoencoder (VAE), which generalizes better.

LSTM‑AE for time series captures temporal dependencies better than a regular AE. Especially effective for multivariate time series (10+ sensors simultaneously). Implementation via PyTorch, training with MSELoss on sliding windows.

In Detail: Anomaly Detection in Industrial Time Series

Problem: vibration sensors on 12 pumps at a chemical plant, 6 sensors per pump, frequency 100 Hz. Need to warn of impending failure 4–24 hours in advance.

Solution architecture: raw data → feature extraction (RMS, kurtosis, peak factor, FFT amplitudes at resonant frequencies) → normalization by 24‑hour sliding window → LSTM‑AE → reconstruction error → threshold logic + alerting.

LSTM window size: 60 seconds (6000 points at 100 Hz). Too small a window misses slow patterns, too large loses sensitivity to rapid changes.

Anomaly threshold: not fixed, but adaptive. threshold = mean(errors_last_7d) + 3 * std(errors_last_7d). As normal state drifts (planned wear), the threshold adapts, avoiding false positives.

Result over a 6‑month pilot: detected 4 out of 5 real pre‑failure conditions (recall 0.8), with 2 false alarms over 6 months (precision 0.67). Before implementation: 3 unplanned shutdowns. After implementation: cost savings verified in the pilot report.

What Specifics Does Fraud Detection Face?

Financial transactions have several features that complicate detection:

  • Concept drift: fraud patterns change faster than normal behavior. A model trained six months ago becomes obsolete.
  • Adversarial adaptation: advanced fraudsters adapt — making transactions resemble normal ones.
  • Temporal dependency: a series of normal transactions followed by one unusual transfer is a sequence anomaly, not a single point.

Practical stack for fraud detection: LightGBM with SMOTE oversampling for the supervised part (known fraud cases) + Isolation Forest for unsupervised (new patterns). Both signals combined in an ensemble; final decision via thresholds tuned for acceptable FPR (0.1–1% of transactions sent to manual review).

How to Evaluate Quality Without Labels?

When ground truth is absent, we evaluate using:

  • Synthetic anomaly injection: add artificial anomalies (spike, level shift, point outlier) and check if the model detects them.
  • Expert validation: random sample of top‑K anomalies → expert review → precision.
  • Business metric: did the number of missed incidents / false alarms decrease after deployment?

Technical detail: the adaptive threshold is computed as mean(errors) + k * std(errors) on a 7‑day sliding window. Coefficient k is tuned on a validation set with synthetic anomalies to achieve FPR < 0.1%. When features drift, the window automatically shifts.

Process

  1. Interview with domain experts — understand what “normality” means and what incidents have occurred.
  2. EDA and data preparation — cleaning, feature creation, time windows.
  3. Baseline (Isolation Forest) — fast validation on known incidents.
  4. Model selection and customization — Autoencoder / LSTM‑AE / ensemble.
  5. Training, validation with synthetic anomalies.
  6. Deployment to production — pipeline on Kafka + Flink / Airflow, alerting to Telegram/Slack, drift monitoring.
  7. Post‑deployment support — monitor model metrics, update thresholds.

What's Included

  • Audit of current data and processes
  • Development and training of models (Isolation Forest / Autoencoder / LSTM‑AE / ensemble)
  • Configuration of adaptive thresholds and alerting
  • Anomaly monitoring dashboard (Grafana / Streamlit)
  • Model card and pipeline documentation
  • Training for your team (2–3 sessions)
  • 3‑month warranty support

Timeline: baseline system with one method — 2–4 weeks. Production system with adaptive thresholds, alerting, and monitoring — 2–5 months. Pricing is calculated individually for your case.

Our team has 8+ years of experience in industrial analytics and 15+ successful projects in anomaly detection for telemetry, finance, and IT monitoring. Get a consultation — we’ll tell you how to solve your problem. Contact us to discuss your data and receive a preliminary architecture proposal.