All articles →

100 Exercises / Machine Learning / Practical Machine Learning 100 Exercises

Equipment Anomaly Detection in Python: Statistical Rules, Models, and Alerts

Compare statistical rules, Isolation Forest, LOF, and One-Class SVM on equipment data, then explore alert thresholds, missed anomalies, and false alarms.

Exercises No.071–No.080 use equipment temperature, vibration, current, and pressure to compare statistical rules and multivariate anomaly detectors. The final exercise relates false alarms, missed anomalies, and repeated detections to an alert policy.

[!NOTE] This material is adapted, with permission, from notebooks used in corporate training by Surikobo or its representative, Hiroshi Wayama. All data listed is fictional and has no relation whatsoever to real companies, factories, or figures.

Introduction: Practical Challenges in Manufacturing Covered in This Article

This example generates 720 hourly sensor records over 30 days for one fictional machine. Compare methods for detecting changes in equipment condition, then consider who will investigate detections and how much false alarms and missed anomalies cost.

Common situations on site

  • Even with normal load fluctuations, temperature and current rise, and at fixed thresholds, false positives are common.
  • Momentary spikes, gradual degradation, and multi-sensor combination abnormalities are all mixed together.
  • Only the number of alerts increases, and it’s unclear who will check when.
  • Few correct labels, making it difficult to evaluate accuracy

Why is this issue so difficult to judge?

An unusual measurement is not automatically a dangerous equipment condition. Normal values depend on load, product, startup state, and ambient conditions. Compare false alarms and missed anomalies as well as scores, and define who investigates each alert.

Exercises in this article

No.ThemeKey Points to Use for Judgment
071Types of OutliersDistinguishing point, contextual, and collective anomalies
072–074Statistical DetectionUse univariate, robust statistics, and time variation appropriately
075–077Machine LearningLearning boundaries in situations with few correct labels
078–079Multivariate and visualizationSupporting inter-sensor relationships and on-site verification
080Alert DesignAdjusting for false positives and missed detections at cost

Preparing the Python environment

Run each article from top to bottom in a fresh Jupyter kernel, including collapsed setup cells. [IN: n] and [OUT: n] identify matching input and output. The displayed results were rerun; library versions can affect numbers or formatting even with the same random seed. The examples import japanize-matplotlib for font support.

Handle data with numpy and pandas, and visualize it with matplotlib. scikit-learn is used for anomaly detection models. For reproducibility, random number seeds are fixed and do not depend on external data.

Show setup code (run this cell)
[IN: 1]
from IPython.display import display

import sys
import warnings
import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
import japanize_matplotlib

from sklearn.ensemble import IsolationForest
from sklearn.neighbors import LocalOutlierFactor
from sklearn.svm import OneClassSVM
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import confusion_matrix, precision_score, recall_score, f1_score

warnings.filterwarnings("ignore", category=UserWarning)
SEED = 42
rng = np.random.default_rng(SEED)
pd.set_option("display.max_columns", 20)
pd.set_option("display.float_format", "{:.2f}".format)

print("Python      :", sys.version.split()[0])
print("numpy       :", np.__version__)
print("pandas      :", pd.__version__)
print("matplotlib  :", matplotlib.__version__)
[OUT: 1]
Python      : 3.14.4
numpy       : 2.5.1
pandas      : 3.0.3
matplotlib  : 3.11.0

Creating the synthetic data

Generate hourly observations for machine M-01. Bearing temperature, vibration, spindle current, and hydraulic pressure vary with the load load_pct. Add the following synthetic anomalies for evaluation.

  • Point anomaly: Temporary temperature and vibration spikes
  • contextual anomaly: Only the current is excessive relative to the load
  • Collective anomaly: Temperature and vibration worsen across a sequence of observations.
  • multivariate anomaly: Individual values are not extreme, but the combination of temperature, vibration, and pressure is unnatural

The true is_anomaly label is unknown in operation. This is a retrospective demonstration on one 30-day batch. Z-scores, IQR, Isolation Forest, and LOF use the whole batch; One-Class SVM uses labels to select normal rows. These different training conditions do not support a fair ranking of future performance. For online monitoring, separate earlier training, threshold-validation, and later evaluation periods.

Show setup code (run this cell)
[IN: 2]
n = 24 * 30
ts = pd.date_range("2025-04-01", periods=n, freq="h")
hour = np.arange(n)
load = np.clip(68 + 15 * np.sin(2 * np.pi * hour / 24) + rng.normal(0, 6, n), 25, 100)

df = pd.DataFrame(
    {
        "timestamp": ts,
        "load_pct": load,
        "temperature_c": 41 + 0.20 * load + rng.normal(0, 1.1, n),
        "vibration_mm_s": 0.9 + 0.018 * load + rng.normal(0, 0.14, n),
        "current_a": 8 + 0.34 * load + rng.normal(0, 1.2, n),
        "pressure_mpa": 5.5 - 0.006 * load + rng.normal(0, 0.08, n),
        "anomaly_type": "normal",
    }
)


def mark(idx, kind):
    df.loc[idx, "anomaly_type"] = kind


point_idx = np.array([95, 188, 422, 611])
df.loc[point_idx, "temperature_c"] += [9, 12, 10, 11]
df.loc[point_idx, "vibration_mm_s"] += [1.1, 1.5, 1.2, 1.4]
mark(point_idx, "point")

context_idx = np.arange(270, 278)
df.loc[context_idx, "current_a"] += 9
mark(context_idx, "contextual")

collective_idx = np.arange(500, 536)
ramp = np.linspace(0.5, 7.5, len(collective_idx))
df.loc[collective_idx, "temperature_c"] += ramp
df.loc[collective_idx, "vibration_mm_s"] += ramp * 0.11
mark(collective_idx, "collective")

multi_idx = np.arange(650, 660)
df.loc[multi_idx, "temperature_c"] += 4.0
df.loc[multi_idx, "vibration_mm_s"] += 0.55
df.loc[multi_idx, "pressure_mpa"] -= 0.28
mark(multi_idx, "multivariate")

df["is_anomaly"] = (df["anomaly_type"] != "normal").astype(int)
print("Data Shape:", df.shape)
display(df.head())
display(df.groupby("anomaly_type").size().rename("hours").to_frame())
[OUT: 2]
Data Shape: (720, 8)
timestamp load_pct temperature_c vibration_mm_s current_a pressure_mpa anomaly_type is_anomaly
0 2025-04-01 00:00:00 69.83 54.86 2.06 31.12 5.11 normal 0
1 2025-04-01 01:00:00 65.64 55.37 2.13 29.19 5.18 normal 0
2 2025-04-01 02:00:00 80.00 54.49 2.15 36.76 5.08 normal 0
3 2025-04-01 03:00:00 84.25 56.20 2.62 37.41 5.09 normal 0
4 2025-04-01 04:00:00 69.28 53.84 2.13 32.28 5.08 normal 0
hours
anomaly_type
collective 36
contextual 8
multivariate 10
normal 662
point 4

No.071: Organizing Types of Outliers

Practical purpose

Different anomaly types need different checks. A rule for isolated spikes may miss gradual deterioration. Point anomalies are isolated deviations; contextual anomalies depend on conditions such as load; collective anomalies involve an unusual sequence.

Method

Summarize total observed hours and maximum sensor values by anomaly type. With one row per hour, hours is a count of observations, not necessarily the duration of a single continuous event.

Check with Python

[IN: 3]
type_summary = (
    df.groupby("anomaly_type")
    .agg(
        hours=("timestamp", "size"),
        max_temperature_c=("temperature_c", "max"),
        max_vibration_mm_s=("vibration_mm_s", "max"),
        mean_current_a=("current_a", "mean"),
    )
    .sort_values("hours", ascending=False)
)
display(type_summary.round(2))
[OUT: 3]
hours max_temperature_c max_vibration_mm_s mean_current_a
anomaly_type
normal 662 62.85 2.94 30.96
collective 36 65.47 3.45 31.51
multivariate 10 63.64 3.11 35.36
contextual 8 60.68 2.53 42.62
point 4 65.48 3.45 28.00

Interpreting the results

The synthetic point anomalies occupy isolated hours, while the gradual-deterioration interval spans 36 hours. Use the type and severity of an event to define investigation deadlines; the total count alone does not describe a continuous event.

No.072: Detecting Anomalies with Z-Score

Practical purpose

A Z-score measures how many standard deviations a reading lies from the reference mean. Here the reference is the full recorded batch, rather than a prior training period.

Method

For temperature xx, mean μ\mu, and standard deviation σ\sigma, use z=(x−μ)/σz=(x-\mu)/\sigma and flag ∣z∣>3|z|>3. The mean and standard deviation themselves are sensitive to extreme observations, and this cutoff is not a general equipment safety limit.

Check with Python

[IN: 4]
mu = df["temperature_c"].mean()
sigma = df["temperature_c"].std(ddof=0)
df["z_score"] = (df["temperature_c"] - mu) / sigma
df["pred_z"] = (df["z_score"].abs() > 3).astype(int)

z_result = df.loc[
    df["pred_z"] == 1, ["timestamp", "temperature_c", "z_score", "anomaly_type"]
]
print(
    f"average={mu:.2f}℃, standard deviation={sigma:.2f}℃, Detection={len(z_result)}records"
)
display(z_result.head(10).round(2))
[OUT: 4]
average=54.86℃, standard deviation=2.99℃, Detection=4records
timestamp temperature_c z_score anomaly_type
531 2025-04-23 03:00:00 63.96 3.05 collective
533 2025-04-23 05:00:00 65.47 3.55 collective
535 2025-04-23 07:00:00 65.07 3.42 collective
611 2025-04-26 11:00:00 65.48 3.56 point

Interpreting the results

Large temperature spikes can be picked up with fewer rules. On the other hand, normal high temperatures linked to loads or contextual anomalies caused by current alone cannot be evaluated. The Z-score serves as a baseline for monitoring clear deviations from a single sensor.

No.073: Detecting Anomalies with IQR

Practical purpose

IQR-based boundaries use quartiles and are less sensitive to a few extreme observations than a mean-and-standard-deviation rule.

Method

Let Q1Q_1 and Q3Q_3 be the first and third quartiles and IQR=Q3−Q1IQR=Q_3-Q_1. Flag observations outside [Q1−1.5IQR, Q3+1.5IQR][Q_1-1.5IQR,\ Q_3+1.5IQR].

Check with Python

[IN: 5]
q1, q3 = df["vibration_mm_s"].quantile([0.25, 0.75])
iqr = q3 - q1
lower, upper = q1 - 1.5 * iqr, q3 + 1.5 * iqr
df["pred_iqr"] = (
    (df["vibration_mm_s"] < lower) | (df["vibration_mm_s"] > upper)
).astype(int)

print(
    f"IQR={iqr:.3f}, lower limit={lower:.3f}, upper limit={upper:.3f}, Detection={df['pred_iqr'].sum()}records"
)
display(
    df.loc[df["pred_iqr"] == 1, ["timestamp", "vibration_mm_s", "anomaly_type"]]
    .head(10)
    .round(3)
)
[OUT: 5]
IQR=0.375, lower limit=1.368, upper limit=2.869, Detection=19records
timestamp vibration_mm_s anomaly_type
176 2025-04-08 08:00:00 2.94 normal
188 2025-04-08 20:00:00 3.29 point
422 2025-04-18 14:00:00 3.32 point
509 2025-04-22 05:00:00 2.97 collective
529 2025-04-23 01:00:00 3.17 collective
530 2025-04-23 02:00:00 2.90 collective
531 2025-04-23 03:00:00 2.91 collective
532 2025-04-23 04:00:00 3.08 collective
533 2025-04-23 05:00:00 3.45 collective
535 2025-04-23 07:00:00 3.39 collective

Interpreting the results

The IQR rule is less sensitive than a mean-and-standard-deviation rule to a few extreme values. It is still affected by distribution shape: skewed normal operation can produce many high-side flags. Use operating-mode or machine-specific references where appropriate.

No.074: Detecting Anomalies by Deviations from Moving Averages

Practical purpose

A rolling reference compares a machine with its recent history. It can detect abrupt local departures, but a baseline that follows a gradual change may fail to flag it.

Method

Calculate the moving average and moving standard deviation over the past 24 hours without including the current value. By excluding the current value in the baseline calculation, the impact of anomalies simultaneously pushing up the threshold is minimized.

Check with Python

[IN: 6]
past_temp = df["temperature_c"].shift(1)
df["temp_ma24"] = past_temp.rolling(24, min_periods=12).mean()
df["temp_sd24"] = past_temp.rolling(24, min_periods=12).std()
df["rolling_score"] = (df["temperature_c"] - df["temp_ma24"]) / df["temp_sd24"].clip(
    lower=0.3
)
df["pred_rolling"] = (df["rolling_score"] > 3).astype(int)

fig, ax = plt.subplots(figsize=(12, 4))
window = df.iloc[470:550]
ax.plot(
    window["timestamp"], window["temperature_c"], label="temperature", linewidth=1.5
)
ax.plot(
    window["timestamp"], window["temp_ma24"], label="Previous 24-hour mean", linewidth=2
)
flag = window[window["pred_rolling"] == 1]
ax.scatter(
    flag["timestamp"],
    flag["temperature_c"],
    color="crimson",
    label="Detection",
    zorder=3,
)
ax.set_title("Temperature during gradual deterioration")
ax.set_xlabel("Date and Time")
ax.set_ylabel("Bearing temperature (°C)")
ax.grid(True, alpha=0.3)
ax.legend()
fig.tight_layout()
plt.show()
print("Number of Detected Cases:", int(df["pred_rolling"].sum()))
[OUT: 6]

No.074: Detecting Anomalies by Deviations from Moving Averages

Number of Detected Cases: 2

Interpreting the results

This rule flags two observations across the full dataset, but none within the illustrated gradual-deterioration interval. A rolling baseline can follow a slow increase and fail to flag its onset; additional long-term trend monitoring may be needed.

No.075: Using Isolation Forest

Practical purpose

Monitoring can be performed without manually breaking down multiple sensor combinations into numerous thresholds. It can also be used during the startup phase when there are few abnormal labels.

Method

Isolation Forest uses random segmentation to separate small or isolated observations along short paths. Here, we use four sensors and load rates, and set the anomaly rate assumption as contamination=0.08. This value is adjusted based on the number of inspectable cases, not the “true abnormality rate.”

Check with Python

[IN: 7]
features = ["load_pct", "temperature_c", "vibration_mm_s", "current_a", "pressure_mpa"]
X = df[features]
iso = IsolationForest(n_estimators=300, contamination=0.08, random_state=SEED)
iso.fit(X)
df["score_iso"] = -iso.score_samples(X)
df["pred_iso"] = (iso.predict(X) == -1).astype(int)

iso_metrics = {
    "Number of Detected Cases": int(df["pred_iso"].sum()),
    "Precision": precision_score(df["is_anomaly"], df["pred_iso"]),
    "Recall": recall_score(df["is_anomaly"], df["pred_iso"]),
    "F1": f1_score(df["is_anomaly"], df["pred_iso"]),
}
display(pd.Series(iso_metrics, name="Isolation Forest").to_frame().T.round(3))
[OUT: 7]
Number of Detected Cases Precision Recall F1
Isolation Forest 58.00 0.52 0.52 0.52

Interpreting the results

The model can flag combinations that univariate rules miss. Review precision, recall, and detection count to understand the inspection workload. The reported scores describe the fitted batch; evaluate a separate later period before claiming future detection performance.

No.076: Using Local Outlier Factor

Practical purpose

Local Outlier Factor (LOF) compares each observation’s density with that of its neighbors. It can help when normal operation contains several distinct local groups.

Method

LOF treats observations with lower local density compared to nearby points as anomalies. Standardization is essential because distance is used. If the n_neighbors is too small, it is sensitive to noise; if too large, it loses sight of local structure.

Check with Python

[IN: 8]
Xs = StandardScaler().fit_transform(X)
lof = LocalOutlierFactor(n_neighbors=30, contamination=0.08)
df["pred_lof"] = (lof.fit_predict(Xs) == -1).astype(int)
df["score_lof"] = -lof.negative_outlier_factor_

display(
    pd.DataFrame(
        {
            "technique": ["LOF"],
            "Number of Detected Cases": [int(df["pred_lof"].sum())],
            "Precision": [precision_score(df["is_anomaly"], df["pred_lof"])],
            "Recall": [recall_score(df["is_anomaly"], df["pred_lof"])],
            "F1": [f1_score(df["is_anomaly"], df["pred_lof"])],
        }
    ).round(3)
)
[OUT: 8]
technique Number of Detected Cases Precision Recall F1
0 LOF 58 0.71 0.71 0.71

Interpreting the results

LOF can detect locally sparse observations, but a dense group of anomalies may appear normal. To score new observations, fit a separate training set with novelty=True; do not use its novelty predictions to reevaluate the same training rows.

No.077: Using One-Class SVM

Practical purpose

Flexible boundaries are created from normally functioning samples to detect states that deviate from “normality.” It is suitable for equipment that can clearly secure normal data.

Method

The RBF kernel represents a nonlinear normal region. nu controls an upper bound on the fraction of training errors and a lower bound on the fraction of support vectors; it is not the future anomaly rate. gamma controls kernel scale. Selecting known-normal rows with the synthetic labels gives this example information that may not be available in operation.

Check with Python

[IN: 9]
scaler_oc = StandardScaler()
X_normal = scaler_oc.fit_transform(df.loc[df["is_anomaly"] == 0, features])
X_all = scaler_oc.transform(X)
ocsvm = OneClassSVM(kernel="rbf", nu=0.05, gamma="scale")
ocsvm.fit(X_normal)
df["pred_ocsvm"] = (ocsvm.predict(X_all) == -1).astype(int)
df["score_ocsvm"] = -ocsvm.decision_function(X_all)

display(
    pd.DataFrame(
        {
            "technique": ["One-Class SVM"],
            "Number of Detected Cases": [int(df["pred_ocsvm"].sum())],
            "Precision": [precision_score(df["is_anomaly"], df["pred_ocsvm"])],
            "Recall": [recall_score(df["is_anomaly"], df["pred_ocsvm"])],
            "F1": [f1_score(df["is_anomaly"], df["pred_ocsvm"])],
        }
    ).round(3)
)
[OUT: 9]
technique Number of Detected Cases Precision Recall F1
0 One-Class SVM 77 0.57 0.76 0.65

Interpreting the results

The fitted boundary depends on scaling, nu, gamma, and the training sample. A change in operating mode can also shift normal behavior, so define when the reference model should be reviewed or retrained.

No.078: Detecting Anomalies in Multivariate Data

Practical purpose

Even if temperature, vibration, current, and pressure are within the control limits, the combination may still be unnatural. Multivariate detection captures this phenomenon of “normal alone, abnormal in relationships.”

Method

Compare the top anomaly scores in Isolation Forest by anomaly type. Scores are not absolute probabilities but are used as priorities within the same model and population.

Check with Python

[IN: 10]
score_by_type = (
    df.groupby("anomaly_type")["score_iso"]
    .agg(["count", "mean", "median", "max"])
    .sort_values("mean", ascending=False)
)
display(score_by_type.round(3))

top_multivariate = df.nlargest(12, "score_iso")[
    ["timestamp", "anomaly_type", *features, "score_iso"]
]
display(top_multivariate.round(3))
[OUT: 10]
count mean median max
anomaly_type
point 4 0.65 0.64 0.70
multivariate 10 0.60 0.59 0.65
contextual 8 0.53 0.52 0.62
collective 36 0.51 0.52 0.64
normal 662 0.44 0.42 0.65
timestamp anomaly_type load_pct temperature_c vibration_mm_s current_a pressure_mpa score_iso
188 2025-04-08 20:00:00 point 46.80 62.44 3.29 25.71 5.38 0.70
652 2025-04-28 04:00:00 multivariate 91.00 63.65 3.11 38.44 4.78 0.65
377 2025-04-16 17:00:00 normal 41.49 49.84 1.78 20.16 5.38 0.65
535 2025-04-23 07:00:00 collective 86.31 65.07 3.39 38.49 4.99 0.64
611 2025-04-26 11:00:00 point 73.29 65.48 3.45 33.61 4.98 0.64
498 2025-04-21 18:00:00 normal 41.05 47.90 1.54 21.74 5.18 0.64
533 2025-04-23 05:00:00 collective 85.20 65.47 3.45 36.53 4.96 0.64
655 2025-04-28 07:00:00 multivariate 84.41 62.28 3.08 36.05 4.61 0.64
631 2025-04-27 07:00:00 normal 97.78 61.17 2.46 41.12 4.80 0.63
422 2025-04-18 14:00:00 point 56.93 60.19 3.32 27.25 5.23 0.63
126 2025-04-06 06:00:00 normal 91.78 62.85 2.39 40.04 4.79 0.63
654 2025-04-28 06:00:00 multivariate 86.52 62.28 3.02 37.43 4.74 0.63

Interpreting the results

By comparing scores by anomaly type, you can see which anomalies the model prioritizes. If the score for multivariate anomalies is high, relationships can be utilized. If the value is low, options include adding features, modeling by operating mode, or reviewing the training period.

No.079: Visualizing Anomaly Detection Results

Practical purpose

Plot sensor readings and anomaly scores over time to help operators investigate detections and compare them with maintenance records.

Method

The upper section displays the temperature, the lower section the model score, and overlays the detection time with the true abnormal interval. The threshold is the score quantile corresponding to the top 8%.

Check with Python

[IN: 11]
threshold_iso = df["score_iso"].quantile(0.92)
fig, axes = plt.subplots(2, 1, figsize=(13, 7), sharex=True)

axes[0].plot(df["timestamp"], df["temperature_c"], color="tab:blue", linewidth=1)
actual = df[df["is_anomaly"] == 1]
axes[0].scatter(
    actual["timestamp"],
    actual["temperature_c"],
    s=14,
    color="orange",
    label="Confirmed Abnormality",
    zorder=3,
)
axes[0].set_title("Equipment temperature and confirmed abnormalities")
axes[0].set_xlabel("Date and Time")
axes[0].set_ylabel("Bearing temperature (°C)")
axes[0].grid(True, alpha=0.3)
axes[0].legend()

axes[1].plot(df["timestamp"], df["score_iso"], color="tab:purple", linewidth=1)
detected = df[df["pred_iso"] == 1]
axes[1].scatter(
    detected["timestamp"],
    detected["score_iso"],
    s=15,
    color="crimson",
    label="Model Detection",
    zorder=3,
)
axes[1].axhline(threshold_iso, color="black", linestyle="--", label="Alert threshold")
axes[1].set_title("Isolation Forest Abnormal score")
axes[1].set_xlabel("Date and Time")
axes[1].set_ylabel("Abnormal Score")
axes[1].grid(True, alpha=0.3)
axes[1].legend()

fig.tight_layout()
plt.show()
[OUT: 11]

No.079: Visualizing Anomaly Detection Results

Interpreting the results

Sections with consecutive detection points have higher priority than single-shot noise and should be matched against maintenance records and production conditions. Contextual anomalies that are not visible by temperature also appear on the score side, so displaying multiple levels helps with decision-making.

No.080: Designing Alerts for False Alarms and Missed Anomalies

Practical purpose

Even with high model accuracy, too many alerts can be ignored. Clearly indicate the man-hours per inspection item, the downtime loss if overlooked, and the number of cases that can be handled, setting thresholds for each task.

Method

Compare Cost=CFPFP+CFNFNCost=C_{FP}FP+C_{FN}FN, assuming ¥5,000 per false-positive hour and ¥200,000 per missed anomalous hour. These are classification-error costs, not total inspection costs. Separately, mark a single detection as caution and at least two hits in the last three hours as warning. The table does not recalculate costs or notification counts after this grouping.

Check with Python

[IN: 12]
rows = []
for q in np.arange(0.80, 0.991, 0.01):
    threshold = df["score_iso"].quantile(q)
    pred = (df["score_iso"] >= threshold).astype(int)
    tn, fp, fn, tp = confusion_matrix(df["is_anomaly"], pred).ravel()
    rows.append(
        {
            "quantile": q,
            "threshold": threshold,
            "TP": tp,
            "FP": fp,
            "FN": fn,
            "Precision": precision_score(
                df["is_anomaly"], pred, zero_division=0
            ),
            "Recall": recall_score(df["is_anomaly"], pred),
            "estimated_cost_ten_thousand_yen": (fp * 5_000 + fn * 200_000) / 10_000,
        }
    )
cost_table = pd.DataFrame(rows)
best = cost_table.loc[cost_table["estimated_cost_ten_thousand_yen"].idxmin()]
display(cost_table.nsmallest(5, "estimated_cost_ten_thousand_yen").round(3))

best_pred = (df["score_iso"] >= best["threshold"]).astype(int)
recent_hits = best_pred.rolling(3, min_periods=1).sum()
df["alert_level"] = np.select(
    [recent_hits >= 2, best_pred == 1], ["warning", "Note"], default="normal"
)
print(
    f"Candidate threshold: quantile={best['quantile']:.2f}, estimated_cost={best['estimated_cost_ten_thousand_yen']:.1f}ten_thousand_yen"
)
display(df["alert_level"].value_counts().rename("hours").to_frame())

fig, ax = plt.subplots(figsize=(9, 4))
ax.plot(
    cost_table["quantile"],
    cost_table["estimated_cost_ten_thousand_yen"],
    marker="o",
    markersize=3,
)
ax.scatter(
    best["quantile"],
    best["estimated_cost_ten_thousand_yen"],
    color="crimson",
    s=70,
    label="Minimum Cost Candidates",
)
ax.set_title("Alert thresholds and estimated operational costs")
ax.set_xlabel("Abnormal score quantiles (higher thresholds)")
ax.set_ylabel("Estimated cost (ten thousand yen)")
ax.grid(True, alpha=0.3)
ax.legend()
fig.tight_layout()
plt.show()
[OUT: 12]
quantile threshold TP FP FN Precision Recall estimated_cost_ten_thousand_yen
1 0.81 0.47 45 92 13 0.33 0.78 306.00
0 0.80 0.47 45 99 13 0.31 0.78 309.50
2 0.82 0.47 44 86 14 0.34 0.76 323.00
5 0.85 0.49 43 65 15 0.40 0.74 332.50
4 0.84 0.48 43 73 15 0.37 0.74 336.50
Candidate threshold: quantile=0.81, estimated_cost=306.0ten_thousand_yen
hours
alert_level
normal 565
warning 85
Note 70

No.080: Designing alerts that consider false positives and missed spots

Interpreting the results

A high missed-anomaly cost favors a lower detection threshold and more inspections. The minimum is selected and measured on the same batch, so it is not a future expected cost. Validate the threshold and grouped-alert policy on a later period, including detection delay, workload, and any cooldown rules.

What the results mean in practice

  1. Define the anomaly before choosing a method: Point, contextual, collective, and multivariate anomalies may require different checks.
  2. Don’t abandon simple statistical methods: Z-scores and IQRs are highly explainable and serve as benchmarks for model monitoring.
  3. Include operating conditions in the feature: If load and product type are not considered, normal high-load operation may be falsely detected.
  4. Don’t mistake scores for probabilities: Treat as rankings within the same model, and set thresholds based on the number of inspections and costs.
  5. Visualization and response flows determine outcomes: Not only detects, but also leads to cause identification, recording, and retraining.

Requirements for deployment

  • Data quality management including sensor calibration, missing measurements, communication outages, and post-maintenance value changes
  • A data platform linking equipment ID, variety, load, schedule, and maintenance history
  • Defining false positive/missed costs by equipment criticality and failure mode
  • Clearly state alert notification destinations, initial confirmation, escalation, and response deadlines
  • A system to accumulate on-site feedback as a correct answer label
  • Operational KPIs that regularly review data distribution, number of alerts, and post-detection results

Begin with shadow operation on one machine and one failure mode. Compare detections with actual inspection findings before enabling notifications.

Conclusion

From No.071 to No.080, we covered everything from organizing anomaly types to statistical detection, unsupervised learning, multivariate evaluation, visualization, and cost-based alert design. Rather than choosing the best algorithm, it is important to combine easy-to-explain rules and multivariate models and operate them according to the on-site response capabilities.

Consulting for businesses

At Surikobo, we support you according to your challenges and data maturity, from organizing manufacturing data, PoC for equipment anomaly detection, integrating into existing maintenance workflows, to on-site training.

📩 Contact Us: www.surikobo.co.jp/contact
Please feel free to consult us first.