100 Exercises / anomaly detection / Abnormality detection: 100 Exercises
Anomaly Detection Evaluation in Python | Metrics, Thresholds and Alert Design
Evaluate anomaly scores with precision, recall, F1, ROC-AUC and AP, then set cost-based thresholds, daily workloads, priorities and notification rules.
Turning Equipment Anomalies into Actionable Alerts: Evaluation and Alert Design
Anomaly detection models do not create value on site simply by producing anomaly scores. This article uses equipment monitoring at a fictional processing plant as a subject, treating Indicators for measuring model quality and Which alerts should the limited maintenance man-hours be assigned to? as a single decision-making issue. The target is No.081 to No.090.
About this material This article adapts notebooks used in corporate training by Surikobo or its representative, Hiroshi Wayama, and is published with permission from the client companies.
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
Imagine a factory where anomaly scores are sent every 5 minutes from processing equipment. There are few true signs of failure, and there is an upper limit to inspection capacity. What is needed in this situation is not only a “highly accurate model,” but also operational design that simultaneously considers downtime due to missed detections, inspection man-hours due to false positives, the importance of the equipment, and response deadlines.
The goal of this article is not to report technical indicators. It’s about creating a state where Which threshold is used, how many alerts result, and who checks them in what order? can be explained.
Common situations on site
- Anomalies make up only a few percent of observations, so a detector that always predicts normal can still have high accuracy.
- As false positives increase, inspectors lose trust in alerts.
- Missed anomalies can lead to sudden stoppages, work-in-progress disposal, and delivery delays, but losses vary by equipment
- Even with the same abnormal score, the order of response differs between critical and auxiliary equipment.
- Model evaluation and on-site alert management tables are separated.
Why is this issue so difficult to judge?
Raising the threshold shrinks the alert set, so false-positive counts and recall cannot increase. Precision depends on the ordering of normal and anomalous scores and need not increase monotonically. F1, ROC-AUC and PR summaries do not directly specify staffing or cost, so also examine counts and operational costs.
Exercises covered in this article
| No. | Theme | Connecting to decision-making |
|---|---|---|
| 081 | Evaluation Indicators | Creating a Comprehensive Picture of Judgment from Confusion Matrices |
| 082 | Precision/Recall | Balancing false positives and missed spots |
| 083 | F1 Score | Comparing the two using a single metric |
| 084 | ROC-AUC | Check the identification order by full threshold |
| 085 | PR-AUC | See effective performance against rare anomalies |
| 086 | False positives and missed costs | Translate technical errors into amounts |
| 087 | Threshold optimization | Choose operating thresholds with lower expected costs |
| 088 | Number of alerts | Understand daily and line loads |
| 089 | priority | Decide the order of response based on importance and urgency |
| 090 | On-site Operation Design | Setting SLAs, Notification Suppression, and Escalation |
Preparing the Python environment
No external data is used; only NumPy, pandas, Matplotlib, and scikit-learn are used. Fix the random number seed so you can reproduce the same result. To avoid environment-dependent garbled text, the graphs are displayed in English, and the accompanying text explains how to read them.
Run the cells from top to bottom in Jupyter Notebook. [IN: n] identifies an input and [OUT: n] its output. Setup code and output are collapsed below.
Show environment setup code and output
import sys
import numpy as np
import pandas as pd
from IPython.display import display
import matplotlib
import matplotlib.pyplot as plt
from sklearn.metrics import (
confusion_matrix,
precision_score,
recall_score,
f1_score,
roc_curve,
roc_auc_score,
precision_recall_curve,
average_precision_score,
)
SEED = 202509
rng = np.random.default_rng(SEED)
pd.set_option("display.max_columns", 20)
pd.set_option("display.float_format", lambda x: f"{x:,.3f}")
print("Python :", sys.version.split()[0])
print("NumPy :", np.__version__)
print("pandas :", pd.__version__)
print("Matplotlib :", matplotlib.__version__)
Python : 3.14.4
NumPy : 2.5.1
pandas : 3.0.3
Matplotlib : 3.11.0
Creation of Fictional Data
Although the operational scenario scores every five minutes, the teaching dataset contains 1,200 decision records spaced 36 minutes apart over 30 days to keep the example manageable. Each record is assigned to one of six machines on three lines. actual_anomaly is the reviewed label, while anomaly_score is an anomaly score between 0 and 1, not a failure probability.
Show synthetic data generation code and output
n = 1200
timestamps = pd.date_range("2025-01-01", periods=n, freq="36min")
lines = rng.choice(["Line-A", "Line-B", "Line-C"], n, p=[0.40, 0.35, 0.25])
machines = np.array([f"{line}-M{rng.integers(1, 3)}" for line in lines])
actual = rng.binomial(1, 0.06, n)
# Partial overlap of normal and abnormal distributions creates situations where complete distinction cannot be made
score = np.where(actual == 1, rng.beta(5.0, 2.2, n), rng.beta(1.5, 6.0, n))
score = np.clip(score + np.where(lines == "Line-C", 0.025, 0), 0, 1)
criticality = np.where(lines == "Line-A", 3, np.where(lines == "Line-B", 2, 1))
impact_k_yen = criticality * rng.integers(
350, 701, n
) # Suspension impact (thousand yen)
elapsed_min = rng.integers(5, 181, n)
df = pd.DataFrame(
{
"timestamp": timestamps,
"line": lines,
"machine": machines,
"actual_anomaly": actual,
"anomaly_score": score,
"criticality": criticality,
"impact_k_yen": impact_k_yen,
"elapsed_min": elapsed_min,
}
)
df["date"] = df["timestamp"].dt.date
print(
f"Number of observations: {len(df):,}records / True anomaly: {df['actual_anomaly'].sum():,}records "
f"({df['actual_anomaly'].mean():.1%})"
)
display(df.head())
Number of observations: 1,200records / True anomaly: 64records (5.3%)
| timestamp | line | machine | actual_anomaly | anomaly_score | criticality | impact_k_yen | elapsed_min | date | |
|---|---|---|---|---|---|---|---|---|---|
| 0 | 2025-01-01 00:00:00 | Line-B | Line-B-M2 | 0 | 0.253 | 2 | 962 | 10 | 2025-01-01 |
| 1 | 2025-01-01 00:36:00 | Line-C | Line-C-M2 | 0 | 0.367 | 1 | 622 | 98 | 2025-01-01 |
| 2 | 2025-01-01 01:12:00 | Line-A | Line-A-M2 | 1 | 0.610 | 3 | 1761 | 177 | 2025-01-01 |
| 3 | 2025-01-01 01:48:00 | Line-A | Line-A-M1 | 0 | 0.264 | 3 | 1059 | 25 | 2025-01-01 |
| 4 | 2025-01-01 02:24:00 | Line-A | Line-A-M2 | 0 | 0.113 | 3 | 1098 | 20 | 2025-01-01 |
fig, ax = plt.subplots(figsize=(9, 4.5))
ax.hist(
df.loc[df["actual_anomaly"] == 0, "anomaly_score"],
bins=25,
alpha=0.65,
label="Normal",
color="#4C78A8",
)
ax.hist(
df.loc[df["actual_anomaly"] == 1, "anomaly_score"],
bins=25,
alpha=0.65,
label="Anomaly",
color="#E45756",
)
ax.set_title("Anomaly score distribution by actual class")
ax.set_xlabel("Anomaly score")
ax.set_ylabel("Number of observations")
ax.grid(True, alpha=0.3)
ax.legend()
fig.tight_layout()
plt.show()

No.081: Organizing Evaluation Indicators for Anomaly Detection
Practical purpose
Compare predictions with reviewed outcomes using TP (true positive), FP (false positive), FN (false negative) and TN (true negative). False positives create unnecessary inspections, while false negatives can leave failure precursors unaddressed. Share these counts alongside accuracy.
Analysis and modeling
Set the threshold to and the score as an alert. The representative indicators are as follows.
First, set the provisional threshold of 0.50 to create an evaluation table.
Check with Python
def metrics_at_threshold(data, threshold):
y_true = data["actual_anomaly"].to_numpy()
y_pred = (data["anomaly_score"].to_numpy() >= threshold).astype(int)
tn, fp, fn, tp = confusion_matrix(y_true, y_pred, labels=[0, 1]).ravel()
return {
"threshold": threshold,
"TP": tp,
"FP": fp,
"FN": fn,
"TN": tn,
"precision": precision_score(y_true, y_pred, zero_division=0),
"recall": recall_score(y_true, y_pred, zero_division=0),
"f1": f1_score(y_true, y_pred, zero_division=0),
"accuracy": (tp + tn) / len(y_true),
}
base = metrics_at_threshold(df, 0.50)
display(pd.DataFrame([base]))
display(
pd.DataFrame(
[[base["TN"], base["FP"]], [base["FN"], base["TP"]]],
index=["Actual normal", "Actual anomaly"],
columns=["Predicted normal", "Predicted alert"],
)
)
| threshold | TP | FP | FN | TN | precision | recall | f1 | accuracy | |
|---|---|---|---|---|---|---|---|---|---|
| 0 | 0.500 | 53 | 41 | 11 | 1095 | 0.564 | 0.828 | 0.671 | 0.957 |
| Predicted normal | Predicted alert | |
|---|---|---|
| Actual normal | 1095 | 41 |
| Actual anomaly | 11 | 53 |
Reading the results
At threshold 0.50, there are 53 true positives, 41 false positives and 11 false negatives. The 94 alerts create inspection work, while the 11 missed anomalies require attention even though accuracy is 0.957. The confusion matrix makes these trade-offs visible.
No.082: Confirm Precision Recall
Practical purpose
Precision is about “how much is truly abnormal when an alert is activated,” which relates to on-site trust and inspection efficiency. Recall refers to “how much actual anomaly has been detected,” and relates to the strength of the maintenance safety net.
Analysis and modeling
Lowering the threshold can increase recall and alert counts or leave them unchanged. Precision often falls, but it is not guaranteed to change monotonically. Compare both metrics and actual counts at each candidate threshold.
Check with Python
thresholds = np.arange(0.20, 0.86, 0.05)
tradeoff = pd.DataFrame([metrics_at_threshold(df, t) for t in thresholds])
tradeoff["alerts"] = tradeoff["TP"] + tradeoff["FP"]
display(tradeoff[["threshold", "precision", "recall", "alerts"]].round(3))
fig, ax = plt.subplots(figsize=(8, 4.5))
ax.plot(tradeoff["threshold"], tradeoff["precision"], marker="o", label="Precision")
ax.plot(tradeoff["threshold"], tradeoff["recall"], marker="s", label="Recall")
ax.set_title("Precision and recall by threshold")
ax.set_xlabel("Threshold")
ax.set_ylabel("Metric value")
ax.set_ylim(0, 1.05)
ax.grid(True, alpha=0.3)
ax.legend()
fig.tight_layout()
plt.show()
| threshold | precision | recall | alerts | |
|---|---|---|---|---|
| 0 | 0.200 | 0.114 | 1.000 | 561 |
| 1 | 0.250 | 0.149 | 0.984 | 422 |
| 2 | 0.300 | 0.194 | 0.984 | 325 |
| 3 | 0.350 | 0.255 | 0.938 | 235 |
| 4 | 0.400 | 0.355 | 0.938 | 169 |
| 5 | 0.450 | 0.483 | 0.906 | 120 |
| 6 | 0.500 | 0.564 | 0.828 | 94 |
| 7 | 0.550 | 0.681 | 0.766 | 72 |
| 8 | 0.600 | 0.833 | 0.703 | 54 |
| 9 | 0.650 | 0.891 | 0.641 | 46 |
| 10 | 0.700 | 0.900 | 0.562 | 40 |
| 11 | 0.750 | 0.963 | 0.406 | 27 |
| 12 | 0.800 | 1.000 | 0.328 | 21 |
| 13 | 0.850 | 1.000 | 0.156 | 10 |

Reading the results
A low threshold reduces missed cases but also generates numerous false positives. A higher threshold reduces the number of inspections but can miss more anomalies; precision must be checked at each threshold. In factories, specifying safety-side constraints such as “Recall 90% or higher” with processing capacity constraints like “no more than 10 cases per day” can make the discussion more concrete.
No.083: Check F1 Score
Practical purpose
F1 is the harmonic mean of precision and recall and treats those two metrics symmetrically. It is useful for comparing models or thresholds, but it neither assigns equal monetary losses to individual false positives and false negatives nor directly models those costs.
Analysis and modeling
If either is lower, F1 will also be low. Check the most important points among the candidates.
Check with Python
f1_best = tradeoff.loc[tradeoff["f1"].idxmax()]
display(tradeoff[["threshold", "precision", "recall", "f1"]].round(3))
print(
f"under candidateF1largest: threshold={f1_best['threshold']:.2f}, "
f"F1={f1_best['f1']:.3f}"
)
fig, ax = plt.subplots(figsize=(8, 4.5))
ax.plot(tradeoff["threshold"], tradeoff["f1"], marker="o", color="#59A14F")
ax.axvline(f1_best["threshold"], linestyle="--", color="#E15759", label="Best F1")
ax.set_title("F1 score by threshold")
ax.set_xlabel("Threshold")
ax.set_ylabel("F1 score")
ax.set_ylim(0, 1.05)
ax.grid(True, alpha=0.3)
ax.legend()
fig.tight_layout()
plt.show()
| threshold | precision | recall | f1 | |
|---|---|---|---|---|
| 0 | 0.200 | 0.114 | 1.000 | 0.205 |
| 1 | 0.250 | 0.149 | 0.984 | 0.259 |
| 2 | 0.300 | 0.194 | 0.984 | 0.324 |
| 3 | 0.350 | 0.255 | 0.938 | 0.401 |
| 4 | 0.400 | 0.355 | 0.938 | 0.515 |
| 5 | 0.450 | 0.483 | 0.906 | 0.630 |
| 6 | 0.500 | 0.564 | 0.828 | 0.671 |
| 7 | 0.550 | 0.681 | 0.766 | 0.721 |
| 8 | 0.600 | 0.833 | 0.703 | 0.763 |
| 9 | 0.650 | 0.891 | 0.641 | 0.745 |
| 10 | 0.700 | 0.900 | 0.562 | 0.692 |
| 11 | 0.750 | 0.963 | 0.406 | 0.571 |
| 12 | 0.800 | 1.000 | 0.328 | 0.494 |
| 13 | 0.850 | 1.000 | 0.156 | 0.270 |
under candidateF1largest: threshold=0.60, F1=0.763

Reading the results
The F1 maximum point is useful as a statistical baseline. However, in factories where the stop loss is orders of magnitude greater than inspection costs, a threshold lower than the F1 maximum point may be reasonable. F1 serves as a “narrowing indicator” for narrowing down candidates, while cost evaluation is a “metric for determining operating thresholds.”
No.084: Checking ROC-AUC
Practical purpose
ROC-AUC can be interpreted as the probability that a randomly chosen anomaly scores above a randomly chosen normal observation, plus half the probability of a tie. It measures ranking ability before a particular decision threshold is selected.
Analysis and modeling
The ROC curve plots the false positive rate and the true positive rate (Recall) at full thresholds. The closer the AUC is to 1, the better the ranking, and 0.5 is equivalent to a random result. However, when abnormalities are rare, note that the FPR appears small due to a large number of TNs.
Check with Python
y_true = df["actual_anomaly"].to_numpy()
y_score = df["anomaly_score"].to_numpy()
fpr, tpr, roc_thresholds = roc_curve(y_true, y_score)
roc_auc = roc_auc_score(y_true, y_score)
print(f"ROC-AUC: {roc_auc:.3f}")
fig, ax = plt.subplots(figsize=(6, 5))
ax.plot(fpr, tpr, label=f"ROC-AUC = {roc_auc:.3f}", color="#4C78A8")
ax.plot([0, 1], [0, 1], linestyle="--", color="gray", label="Random")
ax.set_title("ROC curve")
ax.set_xlabel("False positive rate")
ax.set_ylabel("True positive rate")
ax.grid(True, alpha=0.3)
ax.legend()
fig.tight_layout()
plt.show()
ROC-AUC: 0.976

Reading the results
A higher ROC-AUC means that prioritization based on scores is worth considering. However, AUC does not know how many false positives are generated per day. For anomaly detection with strong class imbalance, the following PR-AUC and actual case counts are always used together.
No.085: Check PR-AUC
Practical purpose
The PR curve directly represents the exchange between alert accuracy and anomaly recall. In manufacturing data where anomalies are rare, the evaluation makes it easier to imagine on-site loads than the ROC curve.
Analysis and modeling
We summarize the PR curve with Average Precision (AP), which weights precision by increments in recall. AP differs from the area calculated by trapezoidal integration of a PR curve. We show prevalence as a reference line and distinguish the metric name from its integration method.
Check with Python
precision_curve, recall_curve, pr_thresholds = precision_recall_curve(y_true, y_score)
average_precision = average_precision_score(y_true, y_score)
baseline = y_true.mean()
print(f"Average Precision (AP): {average_precision:.3f}")
print(f"Random Criteria (Anomaly Rate) : {baseline:.3f}")
fig, ax = plt.subplots(figsize=(6, 5))
ax.plot(
recall_curve,
precision_curve,
label=f"AP = {average_precision:.3f}",
color="#F28E2B",
)
ax.axhline(baseline, linestyle="--", color="gray", label=f"Baseline = {baseline:.3f}")
ax.set_title("Precision-recall curve")
ax.set_xlabel("Recall")
ax.set_ylabel("Precision")
ax.set_xlim(0, 1.02)
ax.set_ylim(0, 1.02)
ax.grid(True, alpha=0.3)
ax.legend()
fig.tight_layout()
plt.show()
Average Precision (AP): 0.835
Random Criteria (Anomaly Rate) : 0.053

Reading the results
AP is 0.835 and prevalence is 0.053. Anomalies are concentrated near the top of this ranking, but AP does not determine an inspection workload. If only the top 50 observations can be reviewed, calculate their precision and anomaly count separately.
No.086: Organizing the Costs of False Positives and Missed Anomalies
Practical purpose
Even with the same case, FP causes inspection time, while FN causes stoppages, disposal, and delivery delays. When the margin of error is converted into amounts, manufacturing, maintenance, and management can discuss thresholds on the same scale.
Analysis and modeling
Let’s define a simple expected cost as follows.
is the cost of unnecessary inspections, is the missed loss, and is the preventive inspection fee when the item is correctly detected. Here, we assume 20,000 yen, 800,000 yen, and 50,000 yen per case. In practice, it is further subdivided by the amount of downtime impact and safety impact by equipment type.
Check with Python
COST_FP = 20_000
COST_FN = 800_000
COST_TP = 50_000
cost_table = tradeoff.copy()
cost_table["false_alarm_cost_yen"] = cost_table["FP"] * COST_FP
cost_table["miss_cost_yen"] = cost_table["FN"] * COST_FN
cost_table["planned_check_cost_yen"] = cost_table["TP"] * COST_TP
cost_table["total_cost_yen"] = cost_table[
["false_alarm_cost_yen", "miss_cost_yen", "planned_check_cost_yen"]
].sum(axis=1)
display(
cost_table[["threshold", "FP", "FN", "TP", "total_cost_yen"]].assign(
total_cost_yen=lambda x: x["total_cost_yen"].map("¥{:,.0f}".format)
)
)
| threshold | FP | FN | TP | total_cost_yen | |
|---|---|---|---|---|---|
| 0 | 0.200 | 497 | 0 | 64 | ¥13,140,000 |
| 1 | 0.250 | 359 | 1 | 63 | ¥11,130,000 |
| 2 | 0.300 | 262 | 1 | 63 | ¥9,190,000 |
| 3 | 0.350 | 175 | 4 | 60 | ¥9,700,000 |
| 4 | 0.400 | 109 | 4 | 60 | ¥8,380,000 |
| 5 | 0.450 | 62 | 6 | 58 | ¥8,940,000 |
| 6 | 0.500 | 41 | 11 | 53 | ¥12,270,000 |
| 7 | 0.550 | 23 | 15 | 49 | ¥14,910,000 |
| 8 | 0.600 | 9 | 19 | 45 | ¥17,630,000 |
| 9 | 0.650 | 5 | 23 | 41 | ¥20,550,000 |
| 10 | 0.700 | 4 | 28 | 36 | ¥24,280,000 |
| 11 | 0.750 | 1 | 38 | 26 | ¥31,720,000 |
| 12 | 0.800 | 0 | 43 | 21 | ¥35,450,000 |
| 13 | 0.850 | 0 | 54 | 10 | ¥43,700,000 |
Reading the results
Because the missed unit price is set high, even a small number of FNs have a significant impact on total costs. Even if the unit price is not a precise accounting value, you can confirm the robustness of decision-making by setting three scenarios: pessimism, standard, and optimism. Abnormalities related to safety or legal regulations are treated not only as monetary conversion but also as restrictions on the “Recall Lower Limit.”
No.087: Setting the threshold based on operational costs
Practical purpose
Thresholds are not parameters set solely by model developers. These are operational rules that reflect maintenance processing capacity, downtime losses, and safety requirements. It simultaneously indicates the minimum cost points and operational constraints, creating an approvable basis.
Analysis and modeling
Candidate thresholds are thoroughly scanned to minimize expected costs. We also check examples where a Recall rate of 85% or higher is mandatory. By optimizing with constraints, the design does not offset safety requirements at the cost of protection.
Check with Python
fine_thresholds = np.linspace(0.10, 0.90, 161)
optimization = pd.DataFrame([metrics_at_threshold(df, t) for t in fine_thresholds])
optimization["alerts"] = optimization["TP"] + optimization["FP"]
optimization["total_cost_yen"] = (
optimization["FP"] * COST_FP
+ optimization["FN"] * COST_FN
+ optimization["TP"] * COST_TP
)
best_cost = optimization.loc[optimization["total_cost_yen"].idxmin()]
feasible = optimization[optimization["recall"] >= 0.85]
best_constrained = feasible.loc[feasible["total_cost_yen"].idxmin()]
display(
pd.DataFrame(
[best_cost, best_constrained],
index=["Minimum cost", "Minimum cost with Recall >= 0.85"],
)[["threshold", "precision", "recall", "f1", "alerts", "total_cost_yen"]].round(3)
)
fig, ax = plt.subplots(figsize=(8, 4.5))
ax.plot(
optimization["threshold"],
optimization["total_cost_yen"] / 1_000_000,
color="#B279A2",
)
ax.axvline(
best_constrained["threshold"],
linestyle="--",
color="#E15759",
label="Selected threshold",
)
ax.set_title("Expected business cost by threshold")
ax.set_xlabel("Threshold")
ax.set_ylabel("Total cost (million JPY)")
ax.grid(True, alpha=0.3)
ax.legend()
fig.tight_layout()
plt.show()
SELECTED_THRESHOLD = float(best_constrained["threshold"])
df["alert"] = (df["anomaly_score"] >= SELECTED_THRESHOLD).astype(int)
print(f"Adoption threshold: {SELECTED_THRESHOLD:.3f}")
| threshold | precision | recall | f1 | alerts | total_cost_yen | |
|---|---|---|---|---|---|---|
| Minimum cost | 0.440 | 0.451 | 0.938 | 0.609 | 133.000 | 7,660,000.000 |
| Minimum cost with Recall >= 0.85 | 0.440 | 0.451 | 0.938 | 0.609 | 133.000 | 7,660,000.000 |

Adoption threshold: 0.440
Reading the results
In this example, both the unconstrained search and the recall-at-least-85% search select 0.440, with recall 0.938. The constraint does not change the optimum. Because selection and reporting use the same data, this is a threshold-search demonstration. Evaluate cost and recall on a separate period before adoption.
No.088: Aggregating the Number of Alerts
Practical purpose
Even if the total number of cases is within an acceptable range, concentrating on a specific day or line will make it impossible to respond. Visualizes daily and line-by-line loads and connects them to shift personnel and patrol plans.
Analysis and modeling
Alerts are aggregated by date and line to detect days exceeding daily processing capacity. Here, we assume the standard processing capacity of 8 cases per day for the entire factory. The aggregation granularity is aligned with the assigned units assigned to actual operations.
Check with Python
daily_line = df[df["alert"] == 1].pivot_table(
index="date", columns="line", values="alert", aggfunc="sum", fill_value=0
)
daily_line = daily_line.reindex(sorted(df["date"].unique()), fill_value=0)
daily_line["Total"] = daily_line.sum(axis=1)
DAILY_CAPACITY = 8
daily_line["Over capacity"] = daily_line["Total"] > DAILY_CAPACITY
display(daily_line.head(10))
print(
f"Processing capacity exceeded date: {daily_line['Over capacity'].sum()}days / {len(daily_line)}days"
)
fig, ax = plt.subplots(figsize=(10, 4.8))
plot_cols = [c for c in ["Line-A", "Line-B", "Line-C"] if c in daily_line.columns]
daily_line[plot_cols].plot(
kind="bar",
stacked=True,
ax=ax,
color=["#4C78A8", "#F28E2B", "#59A14F"][: len(plot_cols)],
)
ax.axhline(DAILY_CAPACITY, linestyle="--", color="#E15759", label="Daily capacity")
ax.set_title("Daily alerts by production line")
ax.set_xlabel("Date")
ax.set_ylabel("Number of alerts")
ax.grid(True, axis="y", alpha=0.3)
ax.legend()
ax.tick_params(axis="x", labelrotation=75)
fig.tight_layout()
plt.show()
| line | Line-A | Line-B | Line-C | Total | Over capacity |
|---|---|---|---|---|---|
| date | |||||
| 2025-01-01 | 3 | 4 | 2 | 9 | True |
| 2025-01-02 | 1 | 1 | 0 | 2 | False |
| 2025-01-03 | 0 | 2 | 0 | 2 | False |
| 2025-01-04 | 3 | 0 | 1 | 4 | False |
| 2025-01-05 | 2 | 0 | 2 | 4 | False |
| 2025-01-06 | 3 | 5 | 3 | 11 | True |
| 2025-01-07 | 4 | 2 | 1 | 7 | False |
| 2025-01-08 | 0 | 4 | 0 | 4 | False |
| 2025-01-09 | 4 | 1 | 1 | 6 | False |
| 2025-01-10 | 2 | 0 | 1 | 3 | False |
Processing capacity exceeded date: 3days / 30days

Reading the results
If there are days when processing capacity exceeds limits, before simply raising the threshold, consider reducing overlap within the same equipment, redistributing by shift, and queue splitting based on importance. Count KPIs monitor not only averages but also maximum, 95% points, and days overrun.
No.089: Designing Alert Priorities
Practical purpose
When all alerts are treated side by side, signs of critical equipment are buried behind minor alerts. Integrate anomalies, downtime impacts, and urgency to create rankings that a limited number of personnel can handle from above.
Analysis and modeling
As an example, align each element from 0 to 1 and define the following priority scores.
is the anomaly score, is the equipment importance, and is the urgency based on elapsed time. Weights are assumptions and will be updated based on past response results and on-site reviews.
Check with Python
alerts = df[df["alert"] == 1].copy()
alerts["importance_norm"] = alerts["criticality"] / 3
alerts["urgency_norm"] = np.clip(alerts["elapsed_min"] / 120, 0, 1)
alerts["priority_score"] = (
0.50 * alerts["anomaly_score"]
+ 0.30 * alerts["importance_norm"]
+ 0.20 * alerts["urgency_norm"]
)
alerts["priority"] = pd.cut(
alerts["priority_score"],
bins=[-np.inf, 0.65, 0.80, np.inf],
labels=["P3", "P2", "P1"],
)
priority_counts = (
alerts["priority"].value_counts().reindex(["P1", "P2", "P3"], fill_value=0)
)
display(priority_counts.rename("alerts").to_frame())
display(
alerts.sort_values("priority_score", ascending=False)[
[
"timestamp",
"line",
"machine",
"anomaly_score",
"criticality",
"impact_k_yen",
"elapsed_min",
"priority_score",
"priority",
]
].head(10)
)
fig, ax = plt.subplots(figsize=(6.5, 4.2))
priority_counts.plot(kind="bar", ax=ax, color=["#E15759", "#F28E2B", "#4C78A8"])
ax.set_title("Alert count by priority")
ax.set_xlabel("Priority")
ax.set_ylabel("Number of alerts")
ax.grid(True, axis="y", alpha=0.3)
ax.tick_params(axis="x", labelrotation=0)
fig.tight_layout()
plt.show()
| alerts | |
|---|---|
| priority | |
| P1 | 19 |
| P2 | 55 |
| P3 | 59 |
| timestamp | line | machine | anomaly_score | criticality | impact_k_yen | elapsed_min | priority_score | priority | |
|---|---|---|---|---|---|---|---|---|---|
| 786 | 2025-01-20 15:36:00 | Line-A | Line-A-M2 | 0.928 | 3 | 1587 | 121 | 0.964 | P1 |
| 716 | 2025-01-18 21:36:00 | Line-A | Line-A-M1 | 0.896 | 3 | 1473 | 150 | 0.948 | P1 |
| 237 | 2025-01-06 22:12:00 | Line-A | Line-A-M2 | 0.843 | 3 | 1296 | 166 | 0.922 | P1 |
| 735 | 2025-01-19 09:00:00 | Line-A | Line-A-M2 | 0.803 | 3 | 1341 | 132 | 0.901 | P1 |
| 574 | 2025-01-15 08:24:00 | Line-A | Line-A-M1 | 0.898 | 3 | 1587 | 88 | 0.896 | P1 |
| 1083 | 2025-01-28 01:48:00 | Line-A | Line-A-M1 | 0.855 | 3 | 1911 | 92 | 0.881 | P1 |
| 266 | 2025-01-07 15:36:00 | Line-A | Line-A-M2 | 0.776 | 3 | 1755 | 112 | 0.874 | P1 |
| 751 | 2025-01-19 18:36:00 | Line-A | Line-A-M2 | 0.727 | 3 | 1899 | 143 | 0.864 | P1 |
| 249 | 2025-01-07 05:24:00 | Line-A | Line-A-M1 | 0.722 | 3 | 1845 | 137 | 0.861 | P1 |
| 1162 | 2025-01-30 01:12:00 | Line-A | Line-A-M1 | 0.827 | 3 | 1899 | 88 | 0.860 | P1 |

Reading the results
The priority is not a “model score reformulation,” but rather a response order that includes business impact. If there are always too many P1s, the segmentation is not working. Keep P1 to an immediate number of cases and leave each element and weight available for auditing.
No.090: Designing alerts usable on the field
Practical purpose
Finally, the responsibility and deadline from judgment to completion are determined. Even if the model is good, without notification recipients, duplication reduction, verification procedures, and result records, the improvement cycle will not continue.
Analysis and modeling
Assign an SLA and owner to each priority. This simplified example suppresses a notification when the previous alert from the same machine was within 120 minutes. It measures from the previous alert, not the last notification, so a continuing sequence may remain suppressed. Production rules should add periodic reminders and escalation when severity increases.
Check with Python
alerts = alerts.sort_values(["machine", "timestamp"]).copy()
alerts["minutes_since_previous"] = (
alerts.groupby("machine")["timestamp"].diff().dt.total_seconds().div(60)
)
COOLDOWN_MIN = 120
alerts["notify"] = alerts["minutes_since_previous"].isna() | (
alerts["minutes_since_previous"] > COOLDOWN_MIN
)
sla_map = {"P1": 15, "P2": 60, "P3": 240}
owner_map = {
"P1": "Person responsible for maintenance+Manufacturing Manager",
"P2": "On-duty maintenance technician",
"P3": "Daily Patrols",
}
alerts["sla_min"] = alerts["priority"].astype(str).map(sla_map)
alerts["owner"] = alerts["priority"].astype(str).map(owner_map)
alerts["due_at"] = alerts["timestamp"] + pd.to_timedelta(alerts["sla_min"], unit="m")
queue = alerts[alerts["notify"]].sort_values(
["priority_score", "timestamp"], ascending=[False, True]
)
print(
f"pre-suppression: {len(alerts)}records / After notification: {len(queue)}records / "
f"suppression rate: {1 - len(queue) / len(alerts):.1%}"
)
# Show complete text for inspection instructions and owners.
with pd.option_context("display.max_colwidth", None):
display(
queue[
[
"timestamp",
"machine",
"priority",
"owner",
"sla_min",
"due_at",
"anomaly_score",
"priority_score",
]
].head(12)
)
pre-suppression: 133records / After notification: 125records / suppression rate: 6.0%
| timestamp | machine | priority | owner | sla_min | due_at | anomaly_score | priority_score | |
|---|---|---|---|---|---|---|---|---|
| 786 | 2025-01-20 15:36:00 | Line-A-M2 | P1 | Person responsible for maintenance+Manufacturing Manager | 15 | 2025-01-20 15:51:00 | 0.928 | 0.964 |
| 716 | 2025-01-18 21:36:00 | Line-A-M1 | P1 | Person responsible for maintenance+Manufacturing Manager | 15 | 2025-01-18 21:51:00 | 0.896 | 0.948 |
| 237 | 2025-01-06 22:12:00 | Line-A-M2 | P1 | Person responsible for maintenance+Manufacturing Manager | 15 | 2025-01-06 22:27:00 | 0.843 | 0.922 |
| 574 | 2025-01-15 08:24:00 | Line-A-M1 | P1 | Person responsible for maintenance+Manufacturing Manager | 15 | 2025-01-15 08:39:00 | 0.898 | 0.896 |
| 1083 | 2025-01-28 01:48:00 | Line-A-M1 | P1 | Person responsible for maintenance+Manufacturing Manager | 15 | 2025-01-28 02:03:00 | 0.855 | 0.881 |
| 266 | 2025-01-07 15:36:00 | Line-A-M2 | P1 | Person responsible for maintenance+Manufacturing Manager | 15 | 2025-01-07 15:51:00 | 0.776 | 0.874 |
| 751 | 2025-01-19 18:36:00 | Line-A-M2 | P1 | Person responsible for maintenance+Manufacturing Manager | 15 | 2025-01-19 18:51:00 | 0.727 | 0.864 |
| 249 | 2025-01-07 05:24:00 | Line-A-M1 | P1 | Person responsible for maintenance+Manufacturing Manager | 15 | 2025-01-07 05:39:00 | 0.722 | 0.861 |
| 1162 | 2025-01-30 01:12:00 | Line-A-M1 | P1 | Person responsible for maintenance+Manufacturing Manager | 15 | 2025-01-30 01:27:00 | 0.827 | 0.860 |
| 1012 | 2025-01-26 07:12:00 | Line-A-M1 | P1 | Person responsible for maintenance+Manufacturing Manager | 15 | 2025-01-26 07:27:00 | 0.862 | 0.856 |
| 975 | 2025-01-25 09:00:00 | Line-A-M1 | P1 | Person responsible for maintenance+Manufacturing Manager | 15 | 2025-01-25 09:15:00 | 0.724 | 0.844 |
| 1175 | 2025-01-30 09:00:00 | Line-B-M2 | P1 | Person responsible for maintenance+Manufacturing Manager | 15 | 2025-01-30 09:15:00 | 0.864 | 0.832 |
Reading the results
By suppressing notifications, we were able to create queues to process from P1 while reducing the number of cases the person in charge viewed. In actual operations, it is necessary to record transitions between states such as “Confirmed,” “Observation Required,” “Work Instructions,” “No Abnormalities,” and “Closed,” escalation when no action is taken, and reasons for judgment. Suppressed notifications are not deleted for audit purposes, and correspondences with previous events are preserved.
Practical points to check
- Model performance and operational quality are two different things.: Even if AUC is high, if the site cannot handle it due to concentrated notifications or duplicate notifications, it will not generate value.
- Thresholds vary depending on business conditions: Missed losses, inspection costs, safety restrictions, and changes in personnel count will also affect adoption values.
- For rare events, the actual number of cases is listed together: Shows not only the percentage, but also TP, FP, FN, daily alert count, and days exceeding capacity.
- Prioritize business impacts: Integrates not only anomaly scores but also critical equipment, downtime impacts, and elapsed times.
- The response results become the next training data.: By structuring and preserving on-site judgments and actions, reassessment and improvement become possible.
Requirements for deployment
- Definition of correct labels: criteria and deadlines for determining faults, quality anomalies, signs, and false positives
- Cost agreement: Evaluation of false positive man-hours, downtime, disposal, delivery schedules, and safety impacts
- Operational capability: Number of personnel by shift, priority SLAs, communication network for nights and holidays
- System integration: sensor infrastructure, maintenance management system, notifications, and audit log connections
- KPIs: Recall, Precision, Number of FNs, Response Time, Days Beyond Capacity, Containment Rate, Recurrence Rate
- Governance: Threshold change approval, model data version management, regular reviews
In the early stages of implementation, use shadow operation to verify alert counts and usefulness before automatically creating work orders. Each equipment group is trialed for 4 to 8 weeks, followed by on-site reviews and then gradually expanded to the target area.
Conclusion
From No.081 to No.090, we progressed from confusion matrices to Precision, Recall, F1, ROC-AUC, and PR-AUC, translating false positives and overlooks into operational costs. Furthermore, we selected thresholds based on cost and Recall constraints, and designed daily loads, priority, SLAs, and duplication reduction.
The anomaly detection deliverables are not limited to model files. Document the evaluation criteria, threshold rationale, alert queue, response rules and review history together so that operators can act on results and improve the system.
Consulting for businesses
At Surikobo, we support manufacturing site constraints, including anomaly detection PoC, evaluation design, equipment-specific loss assessment, threshold optimization, and alert operation design. You can consult from stages such as frequent false positives in existing models, wanting to link evaluation indicators to management decisions, or wanting to integrate with maintenance systems.
📩 Contact Us: www.surikobo.co.jp/contact
Contact us to discuss your project.