Predictive Maintenance: How Manufacturing Uses ML to Prevent $2M Equipment Failures

Predictive Maintenance: How Manufacturing Uses ML to Prevent $2M Equipment Failures

Last year, a mid-sized automotive parts manufacturer in Ohio called me after their main CNC boring mill seized during a night shift. The bearing had been degrading for weeks -- vibration signatures were screaming about it in the sensor data nobody was looking at. The repair bill was $340,000. Lost production during the two-week downtime cost another $1.7 million. Total damage: just over $2 million from a single failure that a basic machine learning model could have predicted 18 days in advance.

That incident became the catalyst for a predictive maintenance system that, twelve months later, reduced their unplanned downtime by 67% and saved an estimated $4.2 million annually. This article walks through exactly how we built it -- the sensor data collection, feature engineering, model selection, deployment architecture, and the operational integration that most tutorials skip entirely.

Why Predictive Maintenance Is Not Just "Anomaly Detection"

Most articles about predictive maintenance conflate two fundamentally different problems. Anomaly detection tells you something is wrong right now. Remaining Useful Life (RUL) prediction tells you how much time you have before failure. The difference matters enormously for maintenance scheduling.

If your anomaly detector fires an alert at 2 AM on a Saturday, your options are limited: shut down the machine immediately (losing production) or gamble that it will survive until Monday. A RUL model that told you three weeks ago "this bearing has approximately 25 days of useful life remaining" gives you time to order parts, schedule the maintenance window during planned downtime, and coordinate with production planning.

In practice, you need both. Anomaly detection serves as a safety net -- catching unexpected failure modes that your RUL model was not trained on. RUL prediction is the planning tool that turns reactive maintenance into proactive scheduling. Here is how they fit together in a typical manufacturing deployment:

ApproachQuestion AnsweredModel TypeLead TimeBest For
ReactiveWhat broke?None (run to failure)0Non-critical equipment
Anomaly DetectionIs something wrong now?Isolation Forest, AutoencodersHours to daysSafety-critical failures
RUL PredictionWhen will it fail?Gradient Boosting, LSTMDays to weeksExpensive, planned components
Condition MonitoringWhat is the current health?Regression, ClassificationContinuousFleet-wide dashboards

Sensor Data: What to Collect and How

The foundation of any predictive maintenance system is sensor data. For rotating machinery (which covers the majority of manufacturing equipment -- motors, pumps, compressors, CNC spindles), four sensor types give you roughly 90% of the signal you need:

  • Vibration (accelerometers) -- The single most informative sensor for rotating equipment. Bearing defects, imbalance, misalignment, and looseness all have distinct vibration signatures. Sample at 10-25 kHz for frequency analysis.
  • Temperature (thermocouples or RTDs) -- Bearing temperature rise is a lagging but reliable degradation indicator. Sample every 1-10 seconds.
  • Current/Power (CTs on motor leads) -- Motor current signature analysis can detect bearing faults, broken rotor bars, and eccentric air gaps. Sample at 5-10 kHz.
  • Pressure/Flow (for hydraulic systems) -- Internal leakage from worn seals or valve degradation shows up as pressure drops or flow reductions. Sample every 1-5 seconds.

For our CNC boring mill project, we installed triaxial accelerometers on each spindle bearing housing (sampling at 20 kHz), thermocouples on the bearing outer races (1-second intervals), and current transformers on the spindle motor leads (10 kHz). Total sensor cost per machine: approximately $2,800. The data acquisition hardware (National Instruments CompactDAQ) added another $4,500. For a machine worth $1.2 million that generates $15,000/day in production value, this is a trivial investment.

Data Collection Architecture

Raw high-frequency sensor data is voluminous. A single triaxial accelerometer at 20 kHz generates about 460 MB per hour in raw float32. You do not stream this to the cloud. Instead, edge processing reduces the data by 99%+ before transmission:

import numpy as np
from scipy import signal
from scipy.fft import rfft, rfftfreq
from dataclasses import dataclass
from typing import List


@dataclass
class SensorWindow:
    """One analysis window of sensor data (typically 1-10 seconds)."""
    machine_id: str
    sensor_id: str
    timestamp: float
    raw_signal: np.ndarray
    sample_rate: float


def extract_time_domain_features(window: SensorWindow) -> dict:
    """Extract statistical features from a time-domain signal window."""
    x = window.raw_signal

    features = {
        "machine_id": window.machine_id,
        "sensor_id": window.sensor_id,
        "timestamp": window.timestamp,
        # Basic statistics
        "rms": float(np.sqrt(np.mean(x ** 2))),
        "peak": float(np.max(np.abs(x))),
        "peak_to_peak": float(np.max(x) - np.min(x)),
        "mean": float(np.mean(x)),
        "std": float(np.std(x)),
        "variance": float(np.var(x)),
        # Shape descriptors
        "skewness": float(skewness(x)),
        "kurtosis": float(kurtosis(x)),
        "crest_factor": float(np.max(np.abs(x)) / np.sqrt(np.mean(x ** 2))),
        "shape_factor": float(
            np.sqrt(np.mean(x ** 2)) / np.mean(np.abs(x))
        ),
        "impulse_factor": float(
            np.max(np.abs(x)) / np.mean(np.abs(x))
        ),
    }
    return features


def skewness(x: np.ndarray) -> float:
    """Third standardized moment."""
    n = len(x)
    mean = np.mean(x)
    std = np.std(x)
    if std == 0:
        return 0.0
    return float(np.sum(((x - mean) / std) ** 3) / n)


def kurtosis(x: np.ndarray) -> float:
    """Fourth standardized moment (excess kurtosis)."""
    n = len(x)
    mean = np.mean(x)
    std = np.std(x)
    if std == 0:
        return 0.0
    return float(np.sum(((x - mean) / std) ** 4) / n - 3.0)

The kurtosis feature is particularly important for bearing fault detection. A healthy bearing produces vibration with near-Gaussian distribution (kurtosis close to 0). As a defect develops, the signal becomes more impulsive -- short, sharp spikes from the damaged surface -- driving kurtosis upward. A kurtosis value above 5-6 on a bearing that normally runs at 0.5-1.5 is a strong degradation signal, often weeks before the failure becomes audible to an operator.

Frequency-Domain Feature Engineering

Time-domain statistics tell you that something is changing. Frequency-domain features tell you what is changing. Different fault types produce energy at specific frequencies related to the machine's geometry and operating speed:

def extract_frequency_features(
    window: SensorWindow,
    shaft_rpm: float,
    n_balls: int = 9,
    ball_diameter: float = 12.7,  # mm
    pitch_diameter: float = 52.0,  # mm
    contact_angle: float = 0.0,    # radians
) -> dict:
    """
    Extract frequency-domain features including bearing
    defect frequencies.

    Bearing geometry parameters are needed to calculate
    characteristic defect frequencies (BPFO, BPFI, BSF, FTF).
    """
    x = window.raw_signal
    fs = window.sample_rate
    n = len(x)

    # Apply Hanning window to reduce spectral leakage
    windowed = x * np.hanning(n)

    # Compute FFT
    fft_vals = rfft(windowed)
    fft_magnitude = np.abs(fft_vals) * 2.0 / n
    freqs = rfftfreq(n, d=1.0 / fs)

    # Shaft frequency
    f_shaft = shaft_rpm / 60.0

    # Bearing defect frequencies (simplified for contact_angle=0)
    cos_a = np.cos(contact_angle)
    bd_ratio = ball_diameter / pitch_diameter

    bpfo = (n_balls / 2) * f_shaft * (1 - bd_ratio * cos_a)
    bpfi = (n_balls / 2) * f_shaft * (1 + bd_ratio * cos_a)
    bsf = (pitch_diameter / (2 * ball_diameter)) * f_shaft * (
        1 - (bd_ratio * cos_a) ** 2
    )
    ftf = (f_shaft / 2) * (1 - bd_ratio * cos_a)

    def band_energy(center_freq, bandwidth_hz=20):
        """Energy in a frequency band around center_freq."""
        mask = (freqs >= center_freq - bandwidth_hz / 2) & (
            freqs <= center_freq + bandwidth_hz / 2
        )
        if not np.any(mask):
            return 0.0
        return float(np.sum(fft_magnitude[mask] ** 2))

    features = {
        # Bearing defect frequency energies (1x and 2x harmonics)
        "bpfo_1x": band_energy(bpfo),
        "bpfo_2x": band_energy(2 * bpfo),
        "bpfi_1x": band_energy(bpfi),
        "bpfi_2x": band_energy(2 * bpfi),
        "bsf_1x": band_energy(bsf),
        "bsf_2x": band_energy(2 * bsf),
        "ftf_1x": band_energy(ftf),
        # Overall spectral features
        "spectral_centroid": float(
            np.sum(freqs * fft_magnitude) / (np.sum(fft_magnitude) + 1e-10)
        ),
        "spectral_spread": float(np.std(fft_magnitude)),
        "spectral_entropy": float(spectral_entropy(fft_magnitude)),
        # Band energies (useful for general health monitoring)
        "energy_0_1k": band_energy(500, bandwidth_hz=1000),
        "energy_1k_5k": band_energy(3000, bandwidth_hz=4000),
        "energy_5k_10k": band_energy(7500, bandwidth_hz=5000),
    }

    return features


def spectral_entropy(magnitude: np.ndarray) -> float:
    """Normalized spectral entropy (0 = pure tone, 1 = white noise)."""
    psd = magnitude ** 2
    psd_norm = psd / (np.sum(psd) + 1e-10)
    psd_norm = psd_norm[psd_norm > 0]
    entropy = -np.sum(psd_norm * np.log2(psd_norm))
    max_entropy = np.log2(len(magnitude))
    return float(entropy / max_entropy) if max_entropy > 0 else 0.0

The bearing defect frequencies (BPFO, BPFI, BSF, FTF) are determined entirely by the bearing geometry and shaft speed. When a defect develops on, say, the outer race, each ball rolling over the defect produces an impact. This happens at the BPFO frequency. As the defect grows, the energy at BPFO and its harmonics (2x, 3x) increases monotonically -- giving you a direct, physics-based degradation indicator.

Building Rolling Features for Trend Detection

Individual feature snapshots are noisy. The real predictive power comes from tracking trends -- how features change over time. This is where most tutorials fall short: they train models on instantaneous features and wonder why performance is poor.

import pandas as pd


def build_rolling_features(
    df: pd.DataFrame,
    feature_cols: List[str],
    windows: List[int] = [60, 360, 1440],  # minutes
    sample_interval_min: int = 1,
) -> pd.DataFrame:
    """
    Build rolling statistical features that capture trends
    and rate of change over multiple time horizons.

    Args:
        df: DataFrame with timestamp index and feature columns
        feature_cols: columns to compute rolling features for
        windows: rolling window sizes in minutes
        sample_interval_min: data sampling interval in minutes
    """
    result = df.copy()

    for col in feature_cols:
        for w in windows:
            periods = w // sample_interval_min
            if periods < 2:
                continue

            rolling = df[col].rolling(window=periods, min_periods=max(2, periods // 4))

            # Rolling statistics
            result[f"{col}_roll{w}_mean"] = rolling.mean()
            result[f"{col}_roll{w}_std"] = rolling.std()
            result[f"{col}_roll{w}_min"] = rolling.min()
            result[f"{col}_roll{w}_max"] = rolling.max()

            # Rate of change (slope of linear fit over window)
            result[f"{col}_roll{w}_slope"] = (
                df[col]
                .rolling(window=periods, min_periods=max(2, periods // 4))
                .apply(lambda x: np.polyfit(range(len(x)), x, 1)[0], raw=True)
            )

            # Ratio of current value to rolling mean (deviation)
            roll_mean = rolling.mean()
            result[f"{col}_roll{w}_ratio"] = df[col] / (roll_mean + 1e-10)

    # Cross-feature interactions
    if "rms" in feature_cols and "kurtosis" in feature_cols:
        result["rms_x_kurtosis"] = df["rms"] * df["kurtosis"]

    if "bpfo_1x" in feature_cols and "bpfi_1x" in feature_cols:
        result["outer_inner_ratio"] = (
            df["bpfo_1x"] / (df["bpfi_1x"] + 1e-10)
        )

    return result

The slope features are critically important. A bearing RMS vibration of 2.5 mm/s might be perfectly normal for a large machine. But if that same value was 1.8 mm/s a week ago and the slope is consistently positive, you have a degradation trend that needs attention. The absolute value matters less than the trajectory.

Anomaly Detection: The Safety Net

For the anomaly detection layer, Isolation Forest works remarkably well for manufacturing sensor data. It handles high-dimensional feature spaces without normalization, runs fast enough for near-real-time use, and its contamination parameter maps intuitively to the expected false positive rate.

from sklearn.ensemble import IsolationForest
from sklearn.preprocessing import StandardScaler
import joblib
import json
from datetime import datetime


class AnomalyDetector:
    """
    Isolation Forest based anomaly detector for sensor features.

    Trained on healthy operating data only (unsupervised).
    Flags deviations from normal behavior.
    """

    def __init__(self, contamination: float = 0.01):
        self.model = IsolationForest(
            n_estimators=200,
            contamination=contamination,
            max_features=0.8,
            random_state=42,
            n_jobs=-1,
        )
        self.scaler = StandardScaler()
        self.feature_names: List[str] = []
        self.trained_at: str = ""

    def fit(self, df: pd.DataFrame, feature_cols: List[str]):
        """Train on healthy operating data."""
        self.feature_names = feature_cols
        X = df[feature_cols].dropna()

        X_scaled = self.scaler.fit_transform(X)
        self.model.fit(X_scaled)
        self.trained_at = datetime.utcnow().isoformat()

        print(f"Trained on {len(X)} samples, {len(feature_cols)} features")

        # Compute baseline anomaly score distribution
        scores = self.model.decision_function(X_scaled)
        self.score_mean = float(np.mean(scores))
        self.score_std = float(np.std(scores))
        print(
            f"Baseline scores: mean={self.score_mean:.4f}, "
            f"std={self.score_std:.4f}"
        )

    def predict(self, df: pd.DataFrame) -> pd.DataFrame:
        """Score new data. Returns DataFrame with anomaly scores."""
        X = df[self.feature_names].copy()

        # Handle missing values (forward fill, then zero)
        X = X.fillna(method="ffill").fillna(0)

        X_scaled = self.scaler.transform(X)

        result = df.copy()
        result["anomaly_score"] = self.model.decision_function(X_scaled)
        result["is_anomaly"] = self.model.predict(X_scaled) == -1

        # Normalized severity (how many std devs below mean)
        result["severity"] = (
            (self.score_mean - result["anomaly_score"]) / self.score_std
        )

        return result

    def save(self, path: str):
        joblib.dump({
            "model": self.model,
            "scaler": self.scaler,
            "feature_names": self.feature_names,
            "score_mean": self.score_mean,
            "score_std": self.score_std,
            "trained_at": self.trained_at,
        }, path)

    @classmethod
    def load(cls, path: str) -> "AnomalyDetector":
        data = joblib.load(path)
        detector = cls()
        detector.model = data["model"]
        detector.scaler = data["scaler"]
        detector.feature_names = data["feature_names"]
        detector.score_mean = data["score_mean"]
        detector.score_std = data["score_std"]
        detector.trained_at = data["trained_at"]
        return detector

A critical nuance: you must train the anomaly detector on data from healthy operation only, but across the full range of normal operating conditions. This means including data from different production speeds, load levels, ambient temperatures, and after maintenance events (when the machine is "reset" to healthy). If you train only on one operating regime, every speed change will trigger false alarms.

Remaining Useful Life (RUL) Prediction: The Planning Tool

RUL prediction is a supervised regression problem: given current sensor features and their trends, predict how many hours/cycles remain before failure. This requires labeled data -- sensor readings paired with known failure times.

The label engineering is straightforward but critical. For each data point recorded T hours before a known failure, the RUL label is T. For data from machines that have not failed, you need a censoring strategy (typically, cap the RUL at a maximum value like 500 hours -- the model does not need to distinguish between "500 hours left" and "800 hours left").

from sklearn.ensemble import GradientBoostingRegressor
from sklearn.model_selection import TimeSeriesSplit
from sklearn.metrics import mean_absolute_error, mean_squared_error
import warnings


def prepare_rul_labels(
    df: pd.DataFrame,
    failure_events: pd.DataFrame,
    max_rul_hours: float = 500,
) -> pd.DataFrame:
    """
    Create RUL labels from failure event log.

    Args:
        df: sensor feature DataFrame with 'machine_id' and
            'timestamp' columns
        failure_events: DataFrame with 'machine_id',
            'failure_time', 'failure_type' columns
        max_rul_hours: cap RUL at this value (piecewise linear)
    """
    result = df.copy()
    result["rul_hours"] = max_rul_hours  # default for no-failure data
    result["failure_type"] = "none"

    for _, event in failure_events.iterrows():
        mask = (
            (result["machine_id"] == event["machine_id"])
            & (result["timestamp"] <= event["failure_time"])
        )

        if not mask.any():
            continue

        # Time until failure for each sample
        time_to_failure = (
            event["failure_time"] - result.loc[mask, "timestamp"]
        )
        rul = time_to_failure.dt.total_seconds() / 3600.0

        # Apply piecewise linear: cap at max_rul_hours
        rul = rul.clip(upper=max_rul_hours)

        # Only update if this failure gives a shorter RUL
        update_mask = mask & (rul < result["rul_hours"])
        result.loc[update_mask, "rul_hours"] = rul[update_mask]
        result.loc[update_mask, "failure_type"] = event["failure_type"]

    return result


class RULPredictor:
    """
    Gradient Boosted Tree model for Remaining Useful Life
    prediction. Uses rolling features to capture degradation
    trends.
    """

    def __init__(self):
        self.model = GradientBoostingRegressor(
            n_estimators=500,
            max_depth=6,
            learning_rate=0.05,
            subsample=0.8,
            min_samples_leaf=20,
            loss="huber",       # robust to outliers
            random_state=42,
        )
        self.feature_names: List[str] = []
        self.feature_importances_: dict = {}

    def fit(
        self,
        df: pd.DataFrame,
        feature_cols: List[str],
        target_col: str = "rul_hours",
    ):
        """Train RUL model with time-series cross-validation."""
        self.feature_names = feature_cols

        X = df[feature_cols].fillna(0)
        y = df[target_col]

        # Time-series CV (no future leakage)
        tscv = TimeSeriesSplit(n_splits=5)
        cv_scores = []

        for fold, (train_idx, val_idx) in enumerate(tscv.split(X)):
            X_train, X_val = X.iloc[train_idx], X.iloc[val_idx]
            y_train, y_val = y.iloc[train_idx], y.iloc[val_idx]

            self.model.fit(X_train, y_train)
            y_pred = self.model.predict(X_val)

            mae = mean_absolute_error(y_val, y_pred)
            rmse = np.sqrt(mean_squared_error(y_val, y_pred))
            cv_scores.append({"fold": fold, "mae": mae, "rmse": rmse})
            print(f"  Fold {fold}: MAE={mae:.1f}h, RMSE={rmse:.1f}h")

        # Final fit on all data
        self.model.fit(X, y)

        # Feature importances
        importances = self.model.feature_importances_
        self.feature_importances_ = dict(
            sorted(
                zip(feature_cols, importances),
                key=lambda x: x[1],
                reverse=True,
            )
        )

        avg_mae = np.mean([s["mae"] for s in cv_scores])
        print(f"\nAverage CV MAE: {avg_mae:.1f} hours")
        print("\nTop 10 features:")
        for name, imp in list(self.feature_importances_.items())[:10]:
            print(f"  {name}: {imp:.4f}")

        return cv_scores

    def predict(self, df: pd.DataFrame) -> np.ndarray:
        """Predict RUL for new data."""
        X = df[self.feature_names].fillna(0)
        predictions = self.model.predict(X)
        return np.clip(predictions, 0, None)  # RUL cannot be negative

    def save(self, path: str):
        joblib.dump({
            "model": self.model,
            "feature_names": self.feature_names,
            "feature_importances": self.feature_importances_,
        }, path)

    @classmethod
    def load(cls, path: str) -> "RULPredictor":
        data = joblib.load(path)
        predictor = cls()
        predictor.model = data["model"]
        predictor.feature_names = data["feature_names"]
        predictor.feature_importances_ = data["feature_importances"]
        return predictor

We chose Gradient Boosting over LSTM for the RUL model for several practical reasons. First, with properly engineered rolling features (means, slopes, ratios over multiple windows), the tree model captures temporal patterns without needing sequence modeling. Second, GBT models are dramatically easier to deploy on edge hardware -- a trained model is a few megabytes and inference takes microseconds. Third, feature importances from GBT are interpretable, which matters enormously when a maintenance manager asks "why does the model think this machine needs service?"

That said, for scenarios with very complex temporal patterns (multi-stage degradation with regime changes), LSTMs can outperform tree models. We found this was the case for about 15% of the failure modes we tracked -- specifically, seal degradation that progresses in a non-monotonic staircase pattern.

LSTM for Complex Degradation Patterns

When tree models struggle with non-linear temporal dynamics, a lightweight LSTM can help. Here is the architecture we used for the seal degradation prediction:

import torch
import torch.nn as nn


class RUL_LSTM(nn.Module):
    """
    LSTM-based RUL predictor for complex degradation patterns.

    Takes a sequence of feature vectors and predicts RUL.
    Lightweight enough for edge deployment with ONNX export.
    """

    def __init__(
        self,
        input_dim: int,
        hidden_dim: int = 64,
        num_layers: int = 2,
        dropout: float = 0.2,
    ):
        super().__init__()

        self.lstm = nn.LSTM(
            input_size=input_dim,
            hidden_size=hidden_dim,
            num_layers=num_layers,
            batch_first=True,
            dropout=dropout if num_layers > 1 else 0,
        )

        self.attention = nn.Sequential(
            nn.Linear(hidden_dim, hidden_dim // 2),
            nn.Tanh(),
            nn.Linear(hidden_dim // 2, 1),
        )

        self.regressor = nn.Sequential(
            nn.Linear(hidden_dim, 32),
            nn.ReLU(),
            nn.Dropout(dropout),
            nn.Linear(32, 1),
            nn.ReLU(),  # RUL is non-negative
        )

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        """
        Args:
            x: (batch, seq_len, input_dim) sensor feature
               sequences
        Returns:
            rul: (batch, 1) predicted RUL
        """
        lstm_out, _ = self.lstm(x)  # (batch, seq_len, hidden)

        # Attention over time steps
        attn_weights = self.attention(lstm_out)  # (batch, seq_len, 1)
        attn_weights = torch.softmax(attn_weights, dim=1)
        context = torch.sum(lstm_out * attn_weights, dim=1)  # (batch, hidden)

        rul = self.regressor(context)
        return rul

The attention mechanism is worth noting. Rather than only using the last hidden state (which biases the model toward the most recent time step), attention learns to weight different time points by their importance. For seal degradation, the model learned to pay attention to the onset of the degradation pattern -- the initial pressure drop -- not just the most recent reading.

Deployment: Edge vs. Cloud

The deployment architecture decision is one of the most consequential choices you will make. Here are the real tradeoffs:

FactorEdge (On-Machine)Cloud
LatencyMilliseconds100ms-2s
Network dependencyNone (works offline)Full dependency
Model updateManual or OTA pushInstant
Compute costFixed (hardware)Variable (per-inference)
Data privacyData stays on-siteLeaves facility
MaintenancePhysical access neededRemote management
Model complexityLimited (ARM/x86 edge)Unlimited

For our manufacturing client, we deployed a hybrid architecture. The Isolation Forest anomaly detector and GBT RUL model run on NVIDIA Jetson Nano devices attached to each machine (edge). These handle 99% of the inference load with sub-millisecond latency. The LSTM model for complex patterns runs in a central on-premise server (not cloud -- the client had data residency requirements) and processes batched data every 15 minutes.

Alert System and Maintenance Integration

The model outputs need to feed into actual maintenance workflows. This is where most predictive maintenance projects die -- not because the model is bad, but because the alerts do not integrate with how maintenance teams actually work.

from enum import Enum
from dataclasses import dataclass, field
from datetime import datetime, timedelta
from typing import Optional
import json


class AlertLevel(Enum):
    INFO = "info"           # trending, no action needed
    WARNING = "warning"     # schedule maintenance within 2 weeks
    URGENT = "urgent"       # schedule within 48 hours
    CRITICAL = "critical"   # stop machine, immediate inspection


@dataclass
class MaintenanceAlert:
    machine_id: str
    alert_level: AlertLevel
    predicted_rul_hours: float
    confidence_interval: tuple  # (lower, upper) in hours
    anomaly_score: Optional[float]
    top_contributing_features: dict
    recommended_action: str
    estimated_repair_time_hours: float
    estimated_parts_cost: float
    created_at: datetime = field(default_factory=datetime.utcnow)


class AlertEngine:
    """
    Converts model predictions into actionable maintenance
    alerts with prioritization and deduplication.
    """

    # Thresholds calibrated per machine type
    DEFAULT_THRESHOLDS = {
        "rul_critical": 24,     # hours
        "rul_urgent": 72,       # hours
        "rul_warning": 336,     # hours (2 weeks)
        "anomaly_critical": 4.0,  # severity std devs
        "anomaly_urgent": 3.0,
    }

    def __init__(self, thresholds: dict = None):
        self.thresholds = thresholds or self.DEFAULT_THRESHOLDS
        self.active_alerts: dict = {}  # machine_id -> latest alert
        self.alert_history: list = []

    def evaluate(
        self,
        machine_id: str,
        rul_prediction: float,
        rul_std: float,
        anomaly_severity: float,
        feature_importances: dict,
    ) -> Optional[MaintenanceAlert]:
        """
        Evaluate predictions and generate alert if warranted.
        Implements hysteresis to prevent alert flapping.
        """
        t = self.thresholds

        # Determine alert level from RUL
        if rul_prediction < t["rul_critical"]:
            rul_level = AlertLevel.CRITICAL
        elif rul_prediction < t["rul_urgent"]:
            rul_level = AlertLevel.URGENT
        elif rul_prediction < t["rul_warning"]:
            rul_level = AlertLevel.WARNING
        else:
            rul_level = AlertLevel.INFO

        # Determine alert level from anomaly score
        if anomaly_severity > t["anomaly_critical"]:
            anomaly_level = AlertLevel.CRITICAL
        elif anomaly_severity > t["anomaly_urgent"]:
            anomaly_level = AlertLevel.URGENT
        else:
            anomaly_level = AlertLevel.INFO

        # Take the more severe of the two
        level_order = [
            AlertLevel.INFO,
            AlertLevel.WARNING,
            AlertLevel.URGENT,
            AlertLevel.CRITICAL,
        ]
        alert_level = max(
            rul_level, anomaly_level, key=lambda x: level_order.index(x)
        )

        # Hysteresis: don't downgrade alerts within 4 hours
        if machine_id in self.active_alerts:
            prev = self.active_alerts[machine_id]
            time_since = (
                datetime.utcnow() - prev.created_at
            ).total_seconds() / 3600
            if (
                level_order.index(alert_level)
                < level_order.index(prev.alert_level)
                and time_since < 4.0
            ):
                return None  # suppress downgrade

        if alert_level == AlertLevel.INFO:
            return None  # no alert needed

        # Build recommended action based on top features
        action = self._recommend_action(feature_importances, alert_level)

        alert = MaintenanceAlert(
            machine_id=machine_id,
            alert_level=alert_level,
            predicted_rul_hours=rul_prediction,
            confidence_interval=(
                max(0, rul_prediction - 2 * rul_std),
                rul_prediction + 2 * rul_std,
            ),
            anomaly_score=anomaly_severity,
            top_contributing_features=dict(
                list(feature_importances.items())[:5]
            ),
            recommended_action=action,
            estimated_repair_time_hours=self._estimate_repair_time(
                feature_importances
            ),
            estimated_parts_cost=self._estimate_parts_cost(
                feature_importances
            ),
        )

        self.active_alerts[machine_id] = alert
        self.alert_history.append(alert)

        return alert

    def _recommend_action(
        self, features: dict, level: AlertLevel
    ) -> str:
        """Generate human-readable maintenance recommendation."""
        top_feature = next(iter(features), "unknown")

        if "bpfo" in top_feature or "bpfi" in top_feature:
            component = "spindle bearing"
            action = "bearing inspection and replacement"
        elif "temperature" in top_feature:
            component = "thermal system"
            action = "lubrication check and coolant system inspection"
        elif "current" in top_feature:
            component = "drive motor"
            action = "motor winding and alignment check"
        else:
            component = "general mechanical"
            action = "full mechanical inspection"

        if level == AlertLevel.CRITICAL:
            return (
                f"IMMEDIATE: Stop machine and perform {action}. "
                f"Primary indicator: {component} degradation."
            )
        elif level == AlertLevel.URGENT:
            return (
                f"Schedule {action} within 48 hours. "
                f"Primary indicator: {component} degradation trend."
            )
        else:
            return (
                f"Plan {action} in next maintenance window. "
                f"Monitor {component} indicators daily."
            )

    def _estimate_repair_time(self, features: dict) -> float:
        """Rough repair time estimate based on likely fault type."""
        top = next(iter(features), "")
        if "bpfo" in top or "bpfi" in top:
            return 8.0   # bearing replacement
        elif "temperature" in top:
            return 2.0   # lubrication/coolant
        elif "current" in top:
            return 12.0  # motor service
        return 4.0       # general

    def _estimate_parts_cost(self, features: dict) -> float:
        top = next(iter(features), "")
        if "bpfo" in top or "bpfi" in top:
            return 2500.0
        elif "temperature" in top:
            return 500.0
        elif "current" in top:
            return 8000.0
        return 1500.0

The hysteresis mechanism deserves attention. Without it, you get alert flapping -- the model prediction oscillates around a threshold, generating URGENT-WARNING-URGENT-WARNING sequences that train maintenance teams to ignore alerts. A 4-hour suppression window for downgrades eliminates this problem.

Results: The CNC Boring Mill Case Study

After 12 months of production deployment across 14 CNC machines, here are the actual results:

MetricBefore (Reactive)After (Predictive)Change
Unplanned downtime events/month4.21.4-67%
Mean Time to Repair (hours)14.36.1-57%
Parts inventory cost$180K$95K-47%
Maintenance labor overtime280 hrs/month85 hrs/month-70%
Overall Equipment Effectiveness71%86%+15pp
Annual maintenance cost savings--$4.2M--

The Mean Time to Repair improvement is underappreciated. When you predict a failure 2-3 weeks in advance, the parts are already on-site, the maintenance crew is scheduled, and the production team has rerouted work to other machines. The actual repair takes the same time, but the logistics overhead that typically triples the downtime disappears.

The parts inventory reduction was an unexpected benefit. Reactive maintenance requires large safety stock because you never know what will fail next. Predictive maintenance tells you which specific bearing on which specific machine will need replacement in which specific week -- so you can order just-in-time.

Model Performance Metrics

Let's be honest about the model performance numbers, because they matter for setting realistic expectations:

  • Anomaly detector (Isolation Forest): 94% true positive rate at 2% false positive rate. The 6% miss rate is acceptable because RUL prediction provides a second layer. The 2% false positive rate generates about 1.2 false alarms per machine per month -- annoying but manageable.
  • RUL predictor (GBT): Mean Absolute Error of 38 hours on 500-hour prediction horizon. At the critical threshold (RUL < 72 hours), MAE drops to 11 hours -- the model gets more accurate as failure approaches because the degradation signal is stronger.
  • RUL predictor (LSTM): MAE of 29 hours overall, 8 hours in the critical zone. Better than GBT, but only used for the specific failure modes where temporal patterns are complex.

The 38-hour MAE means if the model says "this bearing has 100 hours left," the actual value is likely between 62 and 138 hours. That is more than enough precision for maintenance scheduling -- you are planning a work order, not landing a spacecraft. What matters is that the model reliably distinguishes "needs service this week" from "fine for another month."

Common Pitfalls and Honest Limitations

After deploying predictive maintenance systems in four manufacturing facilities, here are the failure modes of the project itself (not the machines):

1. Not enough failure data. Supervised RUL models need labeled failures to learn from. A machine that fails once every 18 months gives you maybe 3-4 labeled events in a reasonable training period. Our solution: pool data across identical machines. Fourteen CNC mills of the same model, each with 2-3 bearing failures per year, gives you 30-40 labeled events to work with.

2. Operating condition changes. A model trained on data from one product line will perform poorly when the machine starts running a different product with different cutting forces and speeds. You must include operating parameters (speed, feed rate, material type) as model features, not just sensor readings.

3. Maintenance-induced faults. Sometimes a bearing fails prematurely because it was installed incorrectly during the last maintenance event. The degradation pattern is different from natural wear, and the model has not seen it before. This is where the anomaly detector earns its keep.

4. Sensor drift and failure. Sensors degrade too. An accelerometer with a slowly drifting bias will make the model think vibration is increasing when it is not. We added a sensor health monitoring layer that compares readings across redundant sensors and flags statistical impossibilities (like a temperature sensor reading -40C in a 25C factory).

5. Organizational resistance. The hardest problem is not technical. Experienced maintenance technicians who have been doing their jobs for 20+ years are understandably skeptical of a computer telling them what to fix. The solution is not to replace their judgment but to augment it: present model outputs as recommendations with explanations, not orders. And give them a way to provide feedback that improves the model.

Scaling Beyond a Single Machine Type

The approach described above works well for a fleet of identical machines. Scaling to a diverse manufacturing floor with dozens of different machine types requires additional architecture:

  • Transfer learning: Pre-train a base model on the machines with the most failure data, then fine-tune for other machine types with limited data. We found that rolling statistical features (RMS trends, kurtosis slopes) transfer well across machine types, while frequency features (bearing defect frequencies) are machine-specific.
  • Hierarchical models: A shared lower layer learns general degradation patterns, with machine-specific heads for different equipment types. This lets you deploy on a new machine type with as few as 5-10 failure examples.
  • Automated feature selection: Different sensors matter for different machines. An automated pipeline that evaluates feature importance per machine type and prunes irrelevant features prevents the curse of dimensionality.

For organizations managing complex, multi-facility manufacturing operations, building this infrastructure in-house is a substantial engineering effort. Companies like Laurela specialize in industrial predictive analytics platforms that handle the sensor integration, feature engineering, and model management across diverse equipment fleets -- which can compress a 12-month internal build into a much shorter deployment timeline.

The Full Pipeline: From Sensor to Maintenance Order

Here is how all the pieces fit together in production:

"""
Simplified main loop for the predictive maintenance pipeline.
Runs on edge device (Jetson Nano) attached to each machine.
"""

import time
import json
import logging
from datetime import datetime

# These would be imported from the modules above
# from sensors import SensorCollector
# from features import extract_time_domain_features, ...
# from models import AnomalyDetector, RULPredictor
# from alerts import AlertEngine


def main_loop(
    machine_id: str,
    config_path: str = "/etc/pdm/config.json",
):
    logging.basicConfig(level=logging.INFO)
    log = logging.getLogger(f"pdm.{machine_id}")

    # Load configuration
    with open(config_path) as f:
        config = json.load(f)

    # Initialize components
    collector = SensorCollector(config["sensors"])
    anomaly_model = AnomalyDetector.load(config["anomaly_model_path"])
    rul_model = RULPredictor.load(config["rul_model_path"])
    alert_engine = AlertEngine(config.get("alert_thresholds"))

    # Feature buffer for rolling calculations
    feature_buffer = FeatureBuffer(
        max_size=config.get("buffer_size", 86400)  # 24 hours at 1/sec
    )

    log.info(f"PDM pipeline started for {machine_id}")

    while True:
        try:
            # 1. Collect sensor window (1 second of data)
            window = collector.read_window(duration_sec=1.0)

            # 2. Extract instantaneous features
            time_features = extract_time_domain_features(window)
            freq_features = extract_frequency_features(
                window,
                shaft_rpm=collector.get_current_rpm(),
            )
            features = {**time_features, **freq_features}

            # 3. Add to buffer and compute rolling features
            feature_buffer.append(features)

            # Only run models every 60 seconds (not every sample)
            if feature_buffer.samples_since_last_eval >= 60:
                rolling_df = feature_buffer.to_dataframe_with_rolling()
                latest = rolling_df.iloc[[-1]]

                # 4. Anomaly detection
                anomaly_result = anomaly_model.predict(latest)
                severity = float(
                    anomaly_result["severity"].iloc[0]
                )

                # 5. RUL prediction
                rul_hours = float(rul_model.predict(latest)[0])

                # 6. Generate alert if warranted
                alert = alert_engine.evaluate(
                    machine_id=machine_id,
                    rul_prediction=rul_hours,
                    rul_std=rul_hours * 0.15,  # rough uncertainty
                    anomaly_severity=severity,
                    feature_importances=(
                        rul_model.feature_importances_
                    ),
                )

                if alert:
                    log.warning(
                        f"ALERT [{alert.alert_level.value}]: "
                        f"RUL={alert.predicted_rul_hours:.0f}h, "
                        f"Action: {alert.recommended_action}"
                    )
                    # Send to central CMMS
                    send_alert_to_cmms(alert, config["cmms_endpoint"])

                # 7. Send telemetry to central store
                send_telemetry(
                    machine_id=machine_id,
                    features=features,
                    rul=rul_hours,
                    anomaly_severity=severity,
                    endpoint=config["telemetry_endpoint"],
                )

                feature_buffer.samples_since_last_eval = 0

        except Exception as e:
            log.error(f"Pipeline error: {e}", exc_info=True)
            time.sleep(5)  # back off on error
            continue

        time.sleep(config.get("sample_interval_sec", 1.0))

Cost-Benefit Analysis

The economics of predictive maintenance are compelling but require honest accounting. Here is the real cost breakdown from our deployment:

One-time costs:

  • Sensors and DAQ hardware: $7,300 per machine x 14 machines = $102,200
  • Edge compute (Jetson Nano + enclosure): $450 per machine x 14 = $6,300
  • Central server (for LSTM models + data storage): $12,000
  • Network infrastructure (industrial switches, cabling): $18,000
  • Engineering time (6 months, 2 engineers): $280,000
  • Total one-time: $418,500

Annual recurring costs:

  • Sensor calibration and replacement: $15,000
  • Software maintenance and model retraining: $45,000
  • Edge device maintenance: $5,000
  • Total annual recurring: $65,000

Annual savings: $4.2 million (from reduced downtime, lower repair costs, reduced inventory, eliminated overtime).

The ROI is approximately 10:1 in the first year and 65:1 in subsequent years. Even if you halve the savings estimate to be conservative, the project pays for itself in under 3 months.

Getting Started: A Practical Roadmap

If you are considering predictive maintenance for your facility, here is the sequence that works:

Month 1-2: Instrument and collect. Install sensors on your 3-5 most critical (expensive-when-broken) machines. Start collecting data. You need at least 2-3 months of healthy operating data before you can train anything meaningful.

Month 3-4: Build the anomaly detector. Train an Isolation Forest on your healthy data. Deploy it and start monitoring. This gives immediate value -- even without RUL prediction, catching anomalies early reduces damage severity. Build dashboards that maintenance teams actually want to look at.

Month 5-8: Accumulate failure data and train RUL models. As machines naturally fail (or as you collect historical failure records from your CMMS), build labeled training sets. Train GBT models. Evaluate with time-series CV. Deploy alongside the anomaly detector.

Month 9-12: Integrate with maintenance workflows. Connect alerts to your CMMS (Computerized Maintenance Management System). Build the alert engine with proper thresholds, hysteresis, and recommended actions. This is the phase that determines whether the system actually gets used or gathers dust.

For companies that want to accelerate this timeline or lack in-house ML engineering capacity, working with firms that specialize in manufacturing intelligence and predictive analytics can be a pragmatic alternative to building everything from scratch. The sensor selection, feature engineering, and model deployment patterns are well-established -- the engineering effort should go into integration with your specific equipment and workflows, not reinventing the ML pipeline.

The manufacturing industry is still in the early innings of predictive maintenance adoption. According to Deloitte's 2025 manufacturing survey, only 23% of facilities have deployed any form of predictive maintenance, and most of those are limited to vibration monitoring without ML. The opportunity is enormous, the technology is mature, and the ROI is among the highest of any industrial ML application. The gap is not in the algorithms -- it is in the engineering to connect sensors to models to maintenance workflows in a way that actually works on a factory floor.

Leave a Comment