Home▸Articles▸Anomaly Detection and Predictive Maintenance

Predictive Maintenance

Building predictive maintenance systems - sensor data analysis, survival analysis, remaining useful life prediction, and industrial deployment.

mysimulator teamUpdated 2026-01≈ 6 min read▶ Open the simulation

Predictive maintenance (PdM) uses sensor data and ML to predict when equipment will fail, enabling maintenance before failure occurs. Unlike reactive maintenance (fix after break) or preventive maintenance (fix on schedule), predictive maintenance optimizes the trade-off between maintenance costs and downtime costs.

Where It Is Used

Predictive maintenance powers industrial operations across sectors:

Business impact: Reduce unplanned downtime by 30-50%, maintenance costs by 10-40%.

Problem Types in Predictive Maintenance

Problem Question Output
Failure prediction Will it fail in next N days? Binary classification
Time-to-failure When will it fail? Regression or survival
Remaining Useful Life (RUL) How much life left? Regression
Anomaly detection Is it behaving abnormally? Anomaly score
Failure mode classification What type of failure? Multi-class
Root cause analysis Why did it fail? Feature importance

Typical Data You Will See

Aspect Typical Values
Sensors per machine 10 to 100+
Sampling frequency 1 Hz to 100 kHz
Machines monitored 10 to 10,000+
Failure rate 0.1% to 5% per year
History 1 to 10+ years

Data types: - Sensor readings: Temperature, vibration, pressure, current, speed - Operational data: Load, cycles, runtime hours - Maintenance logs: Repair history, part replacements - Environmental: Ambient temperature, humidity - Metadata: Machine age, model, location

Data challenges: - Class imbalance (failures are rare) - Censored data (machines still running) - Varying operating conditions - Sensor noise and drift - Missing data and gaps - Multiple failure modes

What You Do in Practice

  1. Understand the asset - Failure modes, criticality, maintenance history
  2. Collect and integrate data - Sensors, logs, work orders
  3. Define the target - Failure within window, RUL, anomaly
  4. Engineer features - Rolling statistics, frequency features, degradation
  5. Handle imbalance - Sampling, weighting, or survival approach
  6. Train models - Classification, regression, or survival models
  7. Set alert thresholds - Balance false alarms vs missed failures
  8. Validate with SMEs - Domain experts review predictions
  9. Deploy with integration - Connect to maintenance systems
  10. Monitor and iterate - Track predictions vs outcomes

Baseline First

Start with rolling statistics and random forest:

import pandas as pd
from sklearn.ensemble import RandomForestClassifier

# Feature engineering: rolling statistics
def create_features(sensor_df, window='7D'):
    features = pd.DataFrame()
    for col in sensor_columns:
        rolling = sensor_df[col].rolling(window)
        features[f'{col}_mean'] = rolling.mean()
        features[f'{col}_std'] = rolling.std()
        features[f'{col}_max'] = rolling.max()
        features[f'{col}_min'] = rolling.min()
        features[f'{col}_trend'] = rolling.apply(
            lambda x: np.polyfit(range(len(x)), x, 1)[0]
        )
    return features

# Create labels: failure within 30 days
def create_labels(df, failure_dates, horizon_days=30):
    labels = []
    for date in df['timestamp']:
        next_failure = failure_dates[failure_dates > date].min()
        days_to_failure = (next_failure - date).days
        labels.append(1 if days_to_failure <= horizon_days else 0)
    return labels

# Train model
X = create_features(sensor_df)
y = create_labels(sensor_df, failure_dates)

model = RandomForestClassifier(class_weight='balanced')
model.fit(X, y)

Why this baseline: - Rolling statistics capture degradation trends - Random forest handles non-linear patterns - Class weighting addresses imbalance - Feature importance aids interpretation

Approaches by Problem Type

Binary classification (failure in N days):

from sklearn.ensemble import GradientBoostingClassifier

# Predict failure within 30-day horizon
model = GradientBoostingClassifier()
model.fit(X_train, y_train_binary)
prob_failure = model.predict_proba(X_test)[:, 1]

Remaining Useful Life (regression):

from sklearn.ensemble import GradientBoostingRegressor

# Predict days until failure
model = GradientBoostingRegressor()
model.fit(X_train, y_train_rul)
predicted_rul = model.predict(X_test)

Survival analysis (time-to-event with censoring):

from lifelines import CoxPHFitter

# Handle censored data (machines still running)
cph = CoxPHFitter()
cph.fit(df, duration_col='time_to_event', event_col='failed')

# Predict survival probability
survival_prob = cph.predict_survival_function(X_test)

Deep learning for sequences (LSTM):

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense

# Sequence of sensor readings → RUL
model = Sequential([
    LSTM(64, input_shape=(sequence_length, n_features)),
    Dense(32, activation='relu'),
    Dense(1)  # RUL output
])
model.compile(loss='mse', optimizer='adam')

Feature Engineering Patterns

Time-domain features: - Rolling mean, std, max, min - Rate of change, trend slope - Cumulative sum, integral - Peak counts, threshold crossings

Frequency-domain features (for vibration):

from scipy.fft import fft

def frequency_features(signal, sampling_rate):
    freqs = fft(signal)
    # Peak frequency, spectral centroid, band energy
    return features

Degradation indicators: - Deviation from baseline - Health index (composite metric) - Anomaly scores over time

Operational context: - Operating mode, load level - Time since last maintenance - Cumulative cycles, runtime

Evaluation and Metrics

Metric Description Use Case
Precision Correct failure predictions Cost of false alarms
Recall Failures caught Cost of missed failures
F1-score Balance of precision/recall Overall performance
AUC-PR Precision-recall curve area Imbalanced data
Lead time How early failures predicted Maintenance planning
MAE/RMSE RUL prediction error Regression tasks
C-index Survival ranking accuracy Survival models

Cost-sensitive evaluation:

# Cost matrix
cost_false_alarm = 100  # Unnecessary inspection
cost_missed_failure = 10000  # Unplanned downtime

# Find optimal threshold
for threshold in np.arange(0.1, 0.9, 0.01):
    predictions = (probabilities > threshold).astype(int)
    fp = ((predictions == 1) & (y_true == 0)).sum()
    fn = ((predictions == 0) & (y_true == 1)).sum()
    total_cost = fp * cost_false_alarm + fn * cost_missed_failure

Failure Modes and Debugging Checklist

Production Checklist

Before deployment: - [ ] Model validated on time-based holdout - [ ] Alert thresholds set based on cost analysis - [ ] Integration with maintenance system designed - [ ] Domain expert validation of predictions - [ ] Latency requirements met - [ ] Fallback behavior defined

After deployment: - [ ] Prediction accuracy tracked - [ ] False alarm rate monitored - [ ] Lead time distribution analyzed - [ ] Model drift detection - [ ] Feedback loop from actual failures - [ ] Periodic retraining scheduled

Operational: - [ ] Alerts routed to right team - [ ] Work order integration - [ ] Dashboard for monitoring - [ ] Escalation process defined

Tools and Stack

Category Tools
Data collection IoT platforms, historians, SCADA
Feature engineering tsfresh, Featuretools, pandas
ML models scikit-learn, XGBoost, LightGBM
Survival analysis lifelines, scikit-survival
Deep learning TensorFlow, PyTorch
Streaming Apache Kafka, Spark Streaming
Deployment Edge devices, cloud, hybrid

Example Mini-Case

Scenario: Wind farm operator needs to predict gearbox failures across 100 turbines.

Data: - 50 sensors per turbine (vibration, temperature, power) - 5 years of history - 45 historical gearbox failures

Approach: 1. Feature engineering: Rolling stats (7-day, 30-day windows) + frequency features from vibration 2. Label: Failure within 30 days (binary classification) 3. Model: XGBoost with class weighting 4. Threshold: Optimized for cost (false alarm vs missed failure)

Results:

Metric Value
Precision 0.72
Recall 0.85
Average lead time 18 days
False alarm rate 3 per turbine/year

Business impact: - Prevented 8 of 10 failures (80% catch rate) - Reduced unplanned downtime by 65% - Maintenance cost savings: $2.1M/year - ROI: 4.2x in first year

Architecture:

Turbines → IoT Hub → Data Lake → Feature Pipeline →
ML Model → Alert Service → Maintenance System

Related Pages

Further Reading

Try it live

Everything above runs in your browser — open Predictive Maintenance Lab — A Single-Sensor Anomaly Case Study and change the parameters while it is running. Nothing is installed, nothing is uploaded, the whole model lives in one tab.

▶ Open Predictive Maintenance Lab — A Single-Sensor Anomaly Case Study simulation

What did you find?

Add reproduction steps (optional)