Anomaly detection | Predictive maintenance¶

Thinking Red — applied analytics

Can unusual machine operating conditions help identify equipment failures? This demonstration fits a diagonal Gaussian density without failure labels, then uses labelled validation data to select a threshold and an independent test set to evaluate it. The AI4I dataset is synthetic; this is a retrospective detection demonstration, not a validated future failure prediction system.

Source: UCI AI4I 2020 Predictive Maintenance.

In [3]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from pathlib import Path
from scipy.stats import multivariate_normal, probplot
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.metrics import (precision_recall_curve, average_precision_score,
                             classification_report, ConfusionMatrixDisplay, f1_score)
from zipfile import ZipFile
from urllib.request import urlopen
from io import BytesIO

SEED = 42
RED, GREY, BG = '#c71e31', '#777b80', '#f5f4f0'

1. Load and inspect the data¶

Use a local CSV if available, otherwise retrieve the public UCI archive. Failure subtype indicators and identifiers are excluded from model features because they can leak the outcome or encode row identity.

In [4]:
path = Path('ai4i2020.csv')
if path.exists():
    data = pd.read_csv(path)
else:
    url = 'https://archive.ics.uci.edu/static/public/601/ai4i+2020+predictive+maintenance+dataset.zip'
    with ZipFile(BytesIO(urlopen(url, timeout=60).read())) as z:
        name = next(s for s in z.namelist() if s.endswith('ai4i2020.csv'))
        data = pd.read_csv(z.open(name))
print(data.shape)
print(data['Machine failure'].value_counts())
display(data.head())
(10000, 14)
Machine failure
0    9661
1     339
Name: count, dtype: int64
UDI Product ID Type Air temperature [K] Process temperature [K] Rotational speed [rpm] Torque [Nm] Tool wear [min] Machine failure TWF HDF PWF OSF RNF
0 1 M14860 M 298.1 308.6 1551 42.8 0 0 0 0 0 0 0
1 2 L47181 L 298.2 308.7 1408 46.3 3 0 0 0 0 0 0
2 3 L47182 L 298.1 308.5 1498 49.4 5 0 0 0 0 0 0
3 4 L47183 L 298.2 308.6 1433 39.5 7 0 0 0 0 0 0
4 5 L47184 L 298.2 308.7 1408 40.0 9 0 0 0 0 0 0
In [5]:
features = ['Air temperature [K]', 'Process temperature [K]',
            'Rotational speed [rpm]', 'Torque [Nm]', 'Tool wear [min]']
X = data[features].copy()
y = data['Machine failure'].astype(int)
assert not X.isna().any().any()
X_train, X_hold, y_train, y_hold = train_test_split(X, y, test_size=.4, stratify=y, random_state=SEED)
X_val, X_test, y_val, y_test = train_test_split(X_hold, y_hold, test_size=.5, stratify=y_hold, random_state=SEED)
print('Train, validation, test:', len(X_train), len(X_val), len(X_test))
Train, validation, test: 6000 2000 2000

2. Explore training feature distributions¶

The Gaussian model assumes approximately normal marginal distributions and independence under diagonal covariance. Inspect these assumptions rather than assuming they hold.

In [6]:
X_train.hist(bins=30, figsize=(12, 7), color=GREY)
plt.tight_layout(); plt.show()
fig, axes = plt.subplots(2, 3, figsize=(13, 7))
for col, ax in zip(features, axes.flat):
    probplot(X_train[col], dist='norm', plot=ax)
    ax.set_title(col)
axes.flat[-1].axis('off')
plt.tight_layout(); plt.show()
display(X_train.corr().round(2))
No description has been provided for this image
No description has been provided for this image
Air temperature [K] Process temperature [K] Rotational speed [rpm] Torque [Nm] Tool wear [min]
Air temperature [K] 1.00 0.88 0.02 -0.01 0.02
Process temperature [K] 0.88 1.00 0.01 -0.01 0.03
Rotational speed [rpm] 0.02 0.01 1.00 -0.87 -0.01
Torque [Nm] -0.01 -0.01 -0.87 1.00 0.00
Tool wear [min] 0.02 0.03 -0.01 0.00 1.00

3. Normalisation and PCA¶

Fit preprocessing on training data only. PCA is used for visualisation, not as input to the detector.

In [7]:
scaler = StandardScaler()
A = scaler.fit_transform(X_train)
B = scaler.transform(X_val)
C = scaler.transform(X_test)
pca = PCA(n_components=2).fit(A)
Z = pca.transform(A)
plt.scatter(Z[:,0], Z[:,1], s=8, alpha=.35, color=GREY)
plt.xlabel('PC1'); plt.ylabel('PC2'); plt.title('Training feature space'); plt.show()
No description has been provided for this image

4. Estimate Gaussian parameters¶

Fit on all training observations without using their labels. The model assumes failures are relatively rare. Use negative log density as an anomaly score to avoid numerical underflow. Larger scores indicate less typical observations; they are not failure probabilities.

In [8]:
#commented code is used for diagaonal covariance assuming independence of variables.  However, in this case we have chosen the full covariance due to likely dependence between variables

'''def estimateGaussian(X):
    return X.mean(axis=0), np.maximum(X.var(axis=0), 1e-12)
mu, sigma2 = estimateGaussian(A)
distribution = multivariate_normal(mean=mu, cov=np.diag(sigma2))

def anomaly_score(X):
    return -distribution.logpdf(X)
s_train = anomaly_score(A)
s_val = anomaly_score(B)
s_test = anomaly_score(C)
plt.hist(s_train, bins=50, color=GREY)
plt.xlabel('Negative log density'); plt.ylabel('Count'); plt.show()'''

def estimateGaussian(X):
    mu = X.mean(axis=0)
    covariance = np.cov(X, rowvar=False, ddof=0)

    return mu, covariance


mu, covariance = estimateGaussian(A)

distribution = multivariate_normal(
    mean=mu,
    cov=covariance
)

def anomaly_score(X):
    return -distribution.logpdf(X)


s_train = anomaly_score(A)
s_val = anomaly_score(B)
s_test = anomaly_score(C)

plt.hist(s_train, bins=50, color=GREY)
plt.xlabel('Negative log density')
plt.ylabel('Count')
plt.show()
No description has been provided for this image

5. Select threshold on validation data¶

Here we maximise F1 using validation labels. The threshold is on negative log density rather than epsilon on density: score >= threshold is equivalent to density <= exp(-threshold). This is unsupervised fitting with supervised threshold calibration.

In [9]:
precision, recall, thresholds = precision_recall_curve(y_val, s_val)
f1 = np.divide(2*precision*recall, precision+recall, out=np.zeros_like(precision), where=(precision+recall)>0)
best = np.argmax(f1[:-1])
threshold = thresholds[best]
print('Threshold:', threshold, 'Validation F1:', f1[best])
plt.plot(thresholds, f1[:-1], color=GREY)
plt.axvline(threshold, color=RED, linestyle='--')
plt.xlabel('Anomaly score threshold'); plt.ylabel('Validation F1'); plt.show()
Threshold: 8.164776295272391 Validation F1: 0.38961038961038963
No description has been provided for this image

6. Independent test evaluation¶

The threshold is now fixed. Compare flags against recorded failures. Average precision summarises ranking performance; compare it with the failure prevalence baseline.

In [10]:
pred = (s_test >= threshold).astype(int)
print(classification_report(y_test, pred, target_names=['No failure','Failure'], zero_division=0))
print('Average precision:', average_precision_score(y_test, s_test))
print('Prevalence baseline:', y_test.mean())
ConfusionMatrixDisplay.from_predictions(y_test, pred, display_labels=['No failure','Failure'])
plt.show()
p_test, r_test, _ = precision_recall_curve(y_test, s_test)
plt.plot(r_test, p_test, color=RED)
plt.axhline(y_test.mean(), color=GREY, linestyle='--')
plt.xlabel('Recall'); plt.ylabel('Precision'); plt.show()
              precision    recall  f1-score   support

  No failure       0.98      0.96      0.97      1932
     Failure       0.25      0.34      0.29        68

    accuracy                           0.94      2000
   macro avg       0.61      0.65      0.63      2000
weighted avg       0.95      0.94      0.95      2000

Average precision: 0.2038728671215532
Prevalence baseline: 0.034
No description has been provided for this image
No description has been provided for this image

7. Visualise flagged observations and export portfolio graphic¶

The PCA projection is only a view of the five-dimensional detector. Red points indicate model flags, not necessarily actual failures. The score plot shows the actual decision boundary.

In [11]:
Z_test = pca.transform(C)
fig, ax = plt.subplots(figsize=(8, 4.5), facecolor=BG)
ax.set_facecolor(BG)
for flag, color, label in [(0,GREY,'Not flagged'),(1,RED,'Flagged')]:
    mask = pred == flag
    ax.scatter(Z_test[mask,0], Z_test[mask,1], s=16, alpha=.65, color=color, label=label)
ax.set(xlabel='Principal component 1', ylabel='Principal component 2', title='Gaussian anomaly detection | Equipment operating conditions')
ax.legend(frameon=False)
ax.spines[['top','right']].set_visible(False)
fig.tight_layout()
fig.savefig('anomaly-detection.png', dpi=200, facecolor=BG, bbox_inches='tight')
plt.show()
plt.hist(s_test[pred==0], bins=40, color=GREY, alpha=.7, label='Not flagged')
plt.hist(s_test[pred==1], bins=30, color=RED, alpha=.7, label='Flagged')
plt.axvline(threshold, color='black', linestyle='--'); plt.legend(); plt.xlabel('Anomaly score'); plt.show()
No description has been provided for this image
No description has been provided for this image
In [12]:
# Retrieve original observations from the test dataset
results = data.loc[X_test.index].copy()

# Add model outputs
results["Anomaly_score"] = s_test
results["Flagged"] = pred

# Add PCA coordinates
results["PC1"] = Z_test[:, 0]
results["PC2"] = Z_test[:, 1]

# Extract flagged observations
anomalies = results[results["Flagged"] == 1].copy()

# Rank from most to least anomalous
anomalies = anomalies.sort_values(
    "Anomaly_score", ascending=False
)

print("Number of anomalies:", len(anomalies))

display(anomalies.head(10))
Number of anomalies: 92
UDI Product ID Type Air temperature [K] Process temperature [K] Rotational speed [rpm] Torque [Nm] Tool wear [min] Machine failure TWF HDF PWF OSF RNF Anomaly_score Flagged PC1 PC2
4302 4303 L51482 L 301.7 310.1 2695 12.6 10 0 0 0 0 0 0 43.005428 1 4.877298 -4.301149
7997 7998 M22857 M 301.0 312.2 2710 9.7 143 1 0 0 1 0 0 42.007303 1 5.648817 -3.904798
5334 5335 M20194 M 303.4 312.6 2706 9.8 65 1 0 0 1 0 0 40.343185 1 6.362330 -3.215472
7011 7012 L54191 L 300.5 310.5 2633 12.2 17 1 0 0 1 0 0 35.981865 1 4.562116 -4.300941
8114 8115 H37528 H 300.4 311.8 2496 13.5 5 0 0 0 0 0 0 29.436440 1 4.550201 -3.448315
3589 3590 L50769 L 301.7 310.5 2465 13.7 149 0 0 0 0 0 0 24.405344 1 4.386385 -3.391322
6987 6988 L54167 L 300.7 311.1 2437 13.8 163 0 0 0 0 0 0 22.861286 1 4.261785 -3.344261
2421 2422 L49601 L 298.9 308.2 2384 15.0 19 0 0 0 0 0 0 21.593612 1 2.547531 -4.593131
9038 9039 L56218 L 297.3 308.3 2358 14.9 49 0 0 0 0 0 0 19.429722 1 2.115971 -4.863504
4956 4957 M19816 M 303.8 312.5 2344 15.2 146 0 0 0 0 0 0 19.143034 1 5.217918 -1.807196
In [13]:
import plotly.express as px

results["Status"] = np.where(
    results["Flagged"] == 1,
    "Flagged",
    "Not flagged"
)

fig = px.scatter(
    results,
    x="PC1",
    y="PC2",
    color="Status",
    color_discrete_map={
        "Flagged": "#c71e31",
        "Not flagged": "#777b80"
    },
    hover_data=[
        "UDI",
        "Product ID",
        "Air temperature [K]",
        "Process temperature [K]",
        "Rotational speed [rpm]",
        "Torque [Nm]",
        "Tool wear [min]",
        "Anomaly_score",
        "Machine failure"
    ],
    labels={
        "PC1": "Principal component 1",
        "PC2": "Principal component 2"
    },
    opacity=0.7,
    template="plotly_white"
)

fig.update_traces(marker=dict(size=6))

fig.update_layout(
    title=dict(
        text="Equipment operating conditions",
        font=dict(size=16)
    ),
    paper_bgcolor="#f5f4f0",
    plot_bgcolor="#f5f4f0",
    font=dict(
        family="Arial",
        color="#555555",
        size=11
    ),
    autosize=True,
    margin=dict(l=45, r=20, t=50, b=60),
    legend=dict(
        orientation="h",
        y=-0.2,
        x=0
    ),
    legend_title_text=""
)

from IPython.display import HTML, display

display(
    HTML(
        fig.to_html(
            full_html=False,
            include_plotlyjs=True,
            config={
                "responsive": True,
                "displaylogo": False
            }
        )
    )
)
In [15]:
fig.write_html(
    "anomaly-detection.html",
    include_plotlyjs=True,
    full_html=True,
    default_width="100%",
    default_height="100%",
    config={
        "responsive": True,
        "displaylogo": False,
        "scrollZoom": False
    }
)

8. Interpretation and limitations¶

  • A flagged observation is a candidate for investigation, not proof of failure.
  • Correlated or non-Gaussian features can weaken a diagonal Gaussian detector. Compare full covariance or Isolation Forest in future work.
  • The random split is suitable for this illustrative retrospective benchmark, but does not demonstrate prospective performance; use time-ordered or asset-grouped splits where appropriate.
  • Threshold choice should reflect the cost of missed failures and unnecessary inspections.
  • Review the actual test metrics before making any commercial performance claim.