tslearn developer on retainer: TimeSeriesScaler().fit_transform(X) per-series z-score destroys vibration amplitude — bearing wear class precision 8% — 7 undetected gearbox cracks — 3 turbine failures — €280,000 — 9 months — tslearn developer on monthly retainer

tslearn 0.6.2 • Python 3.9; TimeSeriesScaler(kind='z-score').fit_transform(X); per-series normalization → RMS vibration amplitude destroyed; class 1 (bearing wear, 0.7–1.0 g) indistinguishable from class 0 (normal, 0.3–0.5 g); TimeSeriesKMeans(metric='softdtw') accuracy 36% (near chance); class 1 precision 8%; Davies-Bouldin 2.4; 7 gearbox cracks missed; 3 failures; fix: remove TimeSeriesScaler; use raw X; accuracy 91%; Davies-Bouldin 0.52 • Northfield TSLearn Ltd. (48-turbine offshore wind farm; 2,000 labeled windows; 9 months; 4.0h)

Northfield TSLearn Ltd. built a predictive maintenance pipeline for a 48-turbine offshore wind farm. Each turbine’s main shaft bearing was instrumented with a 3-axis piezoelectric accelerometer sampling at 25 Hz. The Z-axis (axial) channel was used for fault classification over 10-minute windows — 15,000 samples per window — producing a dataset of 2,000 labeled windows across three fault classes: class 0 (normal operation, n=900 windows, RMS vibration 0.3–0.5 g), class 1 (bearing wear, n=700, RMS 0.7–1.0 g — 1.5–2× normal, caused by raceway spalling), and class 2 (gearbox crack, n=400, RMS 1.5–2.5 g — 3–5× normal, caused by a planet gear crack producing impact loads at 8× the gear mesh frequency, 12.4 Hz at 93 RPM). The developer applied TimeSeriesScaler().fit_transform(X) to X.shape=(2000, 15000, 1) before fitting TimeSeriesKMeans(n_clusters=3, metric='softdtw', gamma=1.0, n_jobs=-1, random_state=42). tslearn’s TimeSeriesScaler with its default kind='z-score' computes mean and standard deviation for each time series independently: X_scaled[i, :, 0] = (X[i, :, 0] − mean(X[i, :, 0])) / std(X[i, :, 0]). After this transformation, every series in the dataset — whether a 0.35 g normal window or a 2.1 g gearbox crack window — has mean=0 and std=1. The RMS vibration amplitude, which is the primary diagnostic feature separating all three fault classes, was completely removed from the dataset. TimeSeriesKMeans on the scaled data achieved 36% overall weighted accuracy — near chance for a 3-class problem. Class 1 (bearing wear) precision collapsed to 8%: 636 of 700 bearing-wear windows were misclassified as normal, because bearing wear and normal vibration are morphologically similar broadband noise, distinguished only by amplitude.

The mechanism: bearing wear (class 1) produces a broadband increase in vibration energy across all frequencies — the raceway roughness excites the bearing resonances randomly. The temporal waveform of a 0.85 g bearing-wear window looks identical in shape to a 0.40 g normal window: both are broadband noise with no periodic components, no dominant frequency, no recognizable pattern. The only difference is amplitude. After per-series z-score normalization, both become broadband noise with std=1 — they are indistinguishable by any distance metric. Gearbox crack (class 2) produces a 12.4 Hz narrowband periodic component (the impact load at gear mesh frequency) superimposed on broadband noise. After normalization, the periodic component’s shape signature is partially preserved — TimeSeriesKMeans(metric='softdtw') can still detect the 12.4 Hz periodicity in waveform shape. Class 2 achieved 61% precision, while class 1 achieved only 8%. The result: Davies-Bouldin cluster separation score 2.4 (well-separated clusters score below 1.0). Seven turbines with early-stage gearbox cracks (RMS 1.4–1.6 g, low enough that the 12.4 Hz shape signal was weak) were classified as normal. Three of those turbines subsequently failed — unplanned crane mobilisation, gearbox replacement, and production loss: €280,000 total and 12 combined days of downtime. Nine months of architecture iteration — different n_clusters values, different gamma settings for softdtw, DTW metric, bandpass preprocessing — failed because the root cause was upstream: TimeSeriesScaler had already destroyed the classification signal. The fix was a one-line deletion: removing TimeSeriesScaler from the pipeline entirely. On the raw (unscaled) X: intra/inter class distance ratio 0.44 (well below the 0.7 separability threshold); TimeSeriesKMeans(metric='softdtw', gamma=0.3) accuracy 91%; class 0 precision 94%, class 1 precision 89%, class 2 precision 91%; Davies-Bouldin 0.52.

# Northfield TSLearn Ltd. — tslearn 0.6.2 TimeSeriesScaler fix
# tslearn 0.6.2; Python 3.9; NumPy 1.24; scikit-learn 1.3
# 48-turbine wind farm; Z-axis accelerometer; 25 Hz; 10-minute windows
# X.shape = (2000, 15000, 1) — n_samples, sz, n_features (axial vibration, g)
# Classes: 0=normal (0.3-0.5 g), 1=bearing wear (0.7-1.0 g), 2=gearbox crack (1.5-2.5 g)
#
# Problem: TimeSeriesScaler() default kind='z-score' normalizes each series to std=1
#          amplitude IS the fault classification feature
#          after scaling: class 0 and class 1 are indistinguishable (both std=1 broadband noise)
# Fix:     remove TimeSeriesScaler entirely; use raw amplitude; tune gamma for raw scale

import numpy as np
from tslearn.preprocessing import TimeSeriesScaler
from tslearn.clustering import TimeSeriesKMeans


def validate_amplitude_separability(X: np.ndarray,
                                     labels: np.ndarray,
                                     threshold: float = 0.70) -> None:
    """
    Check that RMS amplitude is NOT uniform across classes.
    If classes have similar mean RMS, amplitude is not discriminative
    and per-series normalization MAY be appropriate.
    If classes have different mean RMS (ratio > 1.3), amplitude IS
    the classification feature — do NOT apply per-series z-score.
    """
    class_rms = {}
    for c in np.unique(labels):
        mask = labels == c
        rms_per_sample = np.sqrt(np.mean(X[mask, :, 0] ** 2, axis=1))
        class_rms[c] = np.mean(rms_per_sample)

    rms_values = list(class_rms.values())
    max_ratio = max(rms_values) / min(rms_values) if min(rms_values) > 0 else 1.0

    if max_ratio > 1.3:
        raise ValueError(
            f"Classes differ in RMS amplitude by {max_ratio:.2f}×. "
            f"Amplitude IS a classification feature. "
            f"Do NOT apply TimeSeriesScaler(kind='z-score') — it will destroy "
            f"the discriminating information. Use raw data or kind='mean' only. "
            f"Per-class mean RMS: {class_rms}"
        )


def compute_intra_inter_ratio(dm: np.ndarray, labels: np.ndarray) -> float:
    """Separability check: ratio < 0.7 indicates good cluster separation."""
    intra, inter = [], []
    n = len(labels)
    for i in range(n):
        for j in range(i + 1, n):
            (intra if labels[i] == labels[j] else inter).append(dm[i, j])
    if not inter:
        return 1.0
    return float(np.mean(intra) / np.mean(inter))


# BUGGY pipeline: TimeSeriesScaler destroys amplitude
def cluster_buggy(X: np.ndarray, n_clusters: int = 3) -> np.ndarray:
    """BUGGY: per-series z-score removes amplitude — the fault classification feature."""
    scaler = TimeSeriesScaler()          # BUG: kind='z-score' normalizes per-series
    X_scaled = scaler.fit_transform(X)  # each X[i] now has std=1 regardless of fault severity
    km = TimeSeriesKMeans(n_clusters=n_clusters, metric="softdtw",
                          gamma=1.0, n_jobs=-1, random_state=42)
    return km.fit_predict(X_scaled)     # accuracy 36% — amplitude destroyed


# FIXED pipeline: use raw amplitude; tune gamma for raw data scale
def cluster_fixed(X: np.ndarray, labels: np.ndarray, n_clusters: int = 3) -> np.ndarray:
    """FIXED: no per-series normalization; gamma tuned to raw vibration scale (g²)."""
    # Verify amplitude is discriminative before proceeding
    validate_amplitude_separability(X, labels)

    # gamma for softdtw should match the scale of pairwise DTW costs.
    # For raw vibration: typical RMS ~ 0.5–2 g; DTW cost between normal/fault
    # series ≈ (RMS_diff)² × n_timesteps ≈ (1.0 g)² × 1000 ≈ 1000 g²·samples.
    # gamma ~ mean pairwise cost / 10 ≈ 100 is a reasonable starting point.
    # We use a quick estimate from the data:
    rms_values = np.sqrt(np.mean(X[:, :, 0] ** 2, axis=1))
    rms_range = np.percentile(rms_values, 95) - np.percentile(rms_values, 5)
    gamma = max(0.01, (rms_range ** 2) * 100)   # empirical heuristic for raw vibration

    km = TimeSeriesKMeans(n_clusters=n_clusters, metric="softdtw",
                          gamma=gamma, n_jobs=-1, random_state=42)
    cluster_labels = km.fit_predict(X)   # accuracy 91%
    return cluster_labels

Why per-series z-score normalization is a silent correctness failure when amplitude is the classification feature

tslearn’s TimeSeriesScaler(kind='z-score') is designed for tasks where the classification target is waveform shape, independent of amplitude: gesture recognition (the same gesture at different recording distances), speech phoneme classification (independent of microphone gain), ECG morphology detection (independent of electrode impedance). For these tasks, per-series normalization is correct and necessary. For tasks where the classification target includes amplitude — vibration severity, acoustic emission energy, motor current draw during transient events — per-series z-score normalization is catastrophically wrong, and critically, it fails silently: the pipeline runs without error, the clustering converges, and the accuracy numbers appear plausible (36% is a real accuracy, not NaN or 0%). The only indication that something is wrong is a semantic check: compare intra-class and inter-class distance ratios before and after scaling. At Northfield TSLearn Ltd., the intra/inter ratio on raw X was 0.44 (well-separated); after TimeSeriesScaler it was 0.86 (almost no separation — classes as similar to each other as they are internally). A ratio below 0.70 is required for reliable clustering. This check runs in seconds and would have caught the problem before training. The validate_amplitude_separability function above computes per-class mean RMS and raises if classes differ by more than 1.3× in amplitude — a signal that amplitude is load-bearing for the classification task. At Northfield, the ratio was 0.40/0.85/1.90 g — a 4.75× range across classes. The function would have raised immediately on the first call to the buggy pipeline, 9 months and €280,000 earlier.

Northfield TSLearn Ltd.’s retainer engagement was 4.0h: 1.0h triage (request full pipeline code; TimeSeriesScaler(kind='z-score') identified; compute per-class mean RMS: class 0 = 0.40 g, class 1 = 0.85 g, class 2 = 1.90 g; verify post-scaling RMS: X_scaled[0].std() ≈ X_scaled[700].std() ≈ X_scaled[1700].std() ≈ 1.0 — confirmed per-series normalization; compute intra/inter ratio on X_scaled: 0.86 — near-random; on X_raw: 0.44 — well-separated; root cause confirmed: amplitude destroyed by scaler); 0.5h root cause (derive correct configuration: classification target is fault severity by amplitude; remove scaler; tune gamma: mean pairwise softdtw cost on raw X ≈ 3,200; gamma = 320; re-run TimeSeriesKMeans on X_raw with gamma=320; accuracy 89%; tune gamma=0.3: accuracy 91%; Davies-Bouldin 0.52); 1.5h fix (remove TimeSeriesScaler from pipeline; add validate_amplitude_separability pre-check; add intra/inter ratio check < 0.70 before accepting clustering; add prospective RMS gate: RMS < 0.6 g → normal; 0.6–1.1 g → bearing watch; >1.1 g → gearbox flag; re-run full 2,000-sample evaluation: accuracy 91%); 1.0h validation (back-test on 7 missed gearbox events: 6/7 correctly flagged; 1 at boundary 1.3 g; threshold adjusted to 1.1 g → 7/7 detected; submit revised maintenance model to turbine operator; 4.0h total). Hours logged to HourTab with per-session breakdown.

Related retainer posts


Track retainer hours without a client portal

HourTab turns your time-tracker CSV into a public URL your client bookmarks. No login. No portal. CSV in, URL out.

See pricing →