100 Exercises / Machine Learning / Practical Machine Learning 100 Exercises
Evaluating Manufacturing Models in Python: Cross-Validation, Overfitting, and Costs
Evaluate quality models with cross-validation and time splits, tune parameters, and select a risk threshold using costs and inspection capacity.
Exercises No.041–No.050 evaluate models that rank manufacturing lots for additional inspection. They compare data splits, parameter searches, overfitting, learning curves, and feature importance, then choose a threshold using missed-defect costs and inspection capacity.
All data, factory names, equipment names, and costs used in this article are fictional. No external data is used.
[!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
At a synthetic precision-parts factory, giving every lot the same inspection effort creates a bottleneck. The example uses temperature, pressure, vibration, and machine load to rank lots for additional inspection.
Evaluate whether performance holds on future lots, how many defects are missed, and whether the inspection team can handle the flagged lots.
Common situations on site
- Although the accuracy during development was high, performance declined in the following month’s batch
- Repeatedly selecting models with the same data, effectively fitting them into test data
- Because there are few defects, even if everything is judged as good, the correct rate appears high.
- Although the losses from missed and over-testing differ, the evaluation metric is only the accuracy.
Why is this issue so difficult to judge?
Evaluation values vary depending on how data is cut, chronology, class ratio, and search scope. Also, statistically good models may not match those that should be adopted in the field. Since manufacturing conditions change with equipment wear and seasons, relying solely on random division may lead to optimistic future performance.
Exercises in this article
| No. | Theme | Practical Questions |
|---|---|---|
| 041 | Holdout verification | Is performance being measured using unused data? |
| 042 | cross-validation | How much does the result depend on the split? |
| 043 | TimeSeriesSplit | Verification that predicts the future from the past |
| 044 | GridSearchCV | Can you compare all candidates without missing anything? |
| 045 | RandomizedSearchCV | Can exploration budgets be allocated efficiently? |
| 046 | overfitting | Is it only suitable for training data? |
| 047 | learning curve | Does adding data work? |
| 048 | Feature Importance | What are the conditions that drive predictions? |
| 049 | Comparison of multiple models | Comparing accuracy, stability, and explainability |
| 050 | Practical Indicators | How do missed defects and inspection workload compare in 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.
Fix the random number seed so you can reproduce the same result. Preprocessing should be included in Pipeline, and the verification data information should not be mixed into the training side. Graphs use only matplotlib.
Show setup code (run this cell)
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 sklearn
from sklearn.base import clone
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
from sklearn.model_selection import (
train_test_split,
StratifiedKFold,
TimeSeriesSplit,
cross_validate,
GridSearchCV,
RandomizedSearchCV,
learning_curve,
)
from sklearn.metrics import (
accuracy_score,
recall_score,
precision_score,
f1_score,
roc_auc_score,
confusion_matrix,
make_scorer,
)
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
warnings.filterwarnings("ignore", message="Glyph .* missing from font")
SEED = 42
np.random.seed(SEED)
plt.rcParams["figure.figsize"] = (8, 4.5)
print("Python :", sys.version.split()[0])
print("numpy :", np.__version__)
print("pandas :", pd.__version__)
print("matplotlib :", matplotlib.__version__)
print("scikit-learn:", sklearn.__version__)
Python : 3.14.4
numpy : 2.5.1
pandas : 3.0.3
matplotlib : 3.11.0
scikit-learn: 1.9.0
Creating the synthetic data
Generate 900 daily lot records. Equipment wear increases in the second half, and temperature follows an annual cycle. Defect probability depends on temperature, vibration, pressure deviation, load, material hardness, and wear. The label is_defect=1 identifies defective lots.
Show setup code (run this cell)
rng = np.random.default_rng(SEED)
n = 900
date = pd.date_range("2023-01-01", periods=n, freq="D")
t = np.arange(n)
temperature = 68 + 7 * np.sin(2 * np.pi * t / 365) + 0.006 * t + rng.normal(0, 2.2, n)
pressure = 100 + rng.normal(0, 4.5, n) + 0.8 * np.sin(2 * np.pi * t / 30)
vibration = np.clip(1.6 + 0.0012 * t + rng.gamma(1.8, 0.28, n), 0, None)
machine_load = np.clip(rng.normal(72, 11, n) + 5 * np.sin(2 * np.pi * t / 7), 35, 100)
material_hardness = rng.normal(61, 3.2, n)
maintenance_days = np.mod(t, 120)
logit = (
-4.8
+ 0.10 * (temperature - 70)
+ 0.60 * (vibration - 2)
+ 0.035 * np.abs(pressure - 100)
+ 0.028 * (machine_load - 70)
- 0.055 * (material_hardness - 60)
+ 0.010 * maintenance_days
+ 0.8 * ((temperature > 75) & (machine_load > 80))
)
probability = 1 / (1 + np.exp(-logit))
is_defect = rng.binomial(1, probability)
df = pd.DataFrame(
{
"date": date,
"temperature": temperature,
"pressure": pressure,
"vibration": vibration,
"machine_load": machine_load,
"material_hardness": material_hardness,
"maintenance_days": maintenance_days,
"is_defect": is_defect,
}
)
features = [
"temperature",
"pressure",
"vibration",
"machine_load",
"material_hardness",
"maintenance_days",
]
X, y = df[features], df["is_defect"]
display(df.head().round({col: 2 for col in df.select_dtypes(include="number")}))
print(f"lot size: {len(df):,}")
print(f"Number of defective lots: {y.sum():,}(Defect rate {y.mean():.1%})")
| date | temperature | pressure | vibration | machine_load | material_hardness | maintenance_days | is_defect | |
|---|---|---|---|---|---|---|---|---|
| 0 | 2023-01-01 | 68.67 | 101.75 | 2.00 | 61.81 | 61.60 | 0 | 0 |
| 1 | 2023-01-02 | 65.84 | 100.63 | 1.92 | 89.41 | 58.75 | 1 | 0 |
| 2 | 2023-01-03 | 69.90 | 99.66 | 2.05 | 83.81 | 65.58 | 2 | 0 |
| 3 | 2023-01-04 | 70.45 | 107.62 | 2.20 | 82.17 | 63.91 | 3 | 0 |
| 4 | 2023-01-05 | 64.21 | 97.79 | 2.03 | 82.93 | 61.93 | 4 | 0 |
lot size: 900
Number of defective lots: 38(Defect rate 4.2%)
Inspect changes over time and the proportion of defective lots. Monthly defect rates fluctuate partly because each month contains only about 30 lots; the synthetic conditions also become less favorable in the second half.
monthly = df.set_index("date")["is_defect"].resample("MS").agg(["mean", "count"])
fig, ax = plt.subplots()
ax.plot(monthly.index, monthly["mean"], marker="o", linewidth=1.5)
ax.set_title("Monthly defect rate (synthetic data)")
ax.set_xlabel("Month")
ax.set_ylabel("Defect rate")
ax.grid(True, alpha=0.3)
fig.tight_layout()
plt.show()

No.041: Conducting Holdout Verification
Practical purpose
Set aside observations that are not used to fit the model. Stratification approximately preserves the proportion of defective lots in each subset.
Method
Reserve 25% of the observations to demonstrate a stratified holdout. No.042–No.043 separately illustrate full-dataset validation methods; their results are not used to choose later parameters or thresholds. For future deployment, reserve the latest period instead. Do not repeatedly tune a model to the holdout results.
Check with Python
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=SEED
)
rf_base = RandomForestClassifier(
n_estimators=200,
max_depth=5,
min_samples_leaf=8,
class_weight="balanced",
random_state=SEED,
n_jobs=-1,
)
rf_base.fit(X_train, y_train)
holdout_prob = rf_base.predict_proba(X_test)[:, 1]
holdout_pred = (holdout_prob >= 0.5).astype(int)
holdout_result = pd.Series(
{
"train_rows": len(X_train),
"test_rows": len(X_test),
"accuracy": accuracy_score(y_test, holdout_pred),
"recall": recall_score(y_test, holdout_pred),
"precision": precision_score(y_test, holdout_pred),
"roc_auc": roc_auc_score(y_test, holdout_prob),
}
)
display(holdout_result.to_frame("value").round(3))
display(
pd.DataFrame(
confusion_matrix(y_test, holdout_pred),
index=["actual_good", "actual_defect"],
columns=["pred_good", "pred_defect"],
)
)
| value | |
|---|---|
| train_rows | 675.000 |
| test_rows | 225.000 |
| accuracy | 0.849 |
| recall | 0.333 |
| precision | 0.097 |
| roc_auc | 0.748 |
| pred_good | pred_defect | |
|---|---|---|
| actual_good | 188 | 28 |
| actual_defect | 6 | 3 |
Interpreting the results
Report recall and ROC-AUC alongside accuracy. In this confusion matrix, rows are actual classes and columns predicted classes, so the lower-left entry counts missed defects. Compare that count with the quality team’s tolerance.
No.042: Performing Cross-Validation
Practical purpose
A single split can produce an unusually high or low score. Cross-validation measures performance across several held-out subsets and reveals how much the score varies.
Method
Use StratifiedKFold to approximately preserve class proportions in five folds. For scores , report and their standard deviation. These folds are subsets of records, not consecutive time intervals.
Check with Python
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=SEED)
cv_scores = cross_validate(
rf_base,
X,
y,
cv=cv,
scoring={"roc_auc": "roc_auc", "recall": "recall", "f1": "f1"},
n_jobs=-1,
)
cv_table = pd.DataFrame(
{
name.replace("test_", ""): values
for name, values in cv_scores.items()
if name.startswith("test_")
}
)
display(cv_table.round(3))
display(cv_table.agg(["mean", "std"]).round(3))
| roc_auc | recall | f1 | |
|---|---|---|---|
| 0 | 0.602 | 0.286 | 0.133 |
| 1 | 0.784 | 0.571 | 0.267 |
| 2 | 0.649 | 0.125 | 0.077 |
| 3 | 0.659 | 0.375 | 0.194 |
| 4 | 0.727 | 0.500 | 0.229 |
| roc_auc | recall | f1 | |
|---|---|---|---|
| mean | 0.684 | 0.371 | 0.180 |
| std | 0.071 | 0.177 | 0.076 |
Interpreting the results
Models with good averages but large standard deviations are unstable depending on the composition of target lots. If the recall rate fluctuates significantly between segments, consider adding defective samples, reviewing process-specific models, and evaluating the period.
No.043: Using TimeSeriesSplit
Practical purpose
At the factory, future lots are predicted using historical data. Random cross-validation mixes future conditions with past learning, so performance can be optimistic when equipment wear or seasonal fluctuations occur.
Method
TimeSeriesSplit trains on earlier rows and validates on later rows. Sort observations by time first. This example has one record per day, so successive folds represent comparable durations. Stratification and chronological validation answer different questions.
Check with Python
tscv = TimeSeriesSplit(n_splits=5)
ts_rows = []
for fold, (train_idx, valid_idx) in enumerate(tscv.split(X), start=1):
model = clone(rf_base).fit(X.iloc[train_idx], y.iloc[train_idx])
p = model.predict_proba(X.iloc[valid_idx])[:, 1]
ts_rows.append(
{
"fold": fold,
"train_end": df.loc[train_idx[-1], "date"].date(),
"valid_start": df.loc[valid_idx[0], "date"].date(),
"valid_end": df.loc[valid_idx[-1], "date"].date(),
"valid_defect_rate": y.iloc[valid_idx].mean(),
"roc_auc": roc_auc_score(y.iloc[valid_idx], p),
}
)
ts_result = pd.DataFrame(ts_rows)
display(ts_result.round(3))
fig, ax = plt.subplots()
ax.plot(ts_result["fold"], ts_result["roc_auc"], marker="o", label="TimeSeriesSplit")
ax.axhline(
cv_table["roc_auc"].mean(),
color="tab:orange",
linestyle="--",
label="Stratified CV mean",
)
ax.set_title("Random CV vs. time-aware validation")
ax.set_xlabel("Fold")
ax.set_ylabel("ROC-AUC")
ax.set_xticks(ts_result["fold"])
ax.grid(True, alpha=0.3)
ax.legend()
fig.tight_layout()
plt.show()
| fold | train_end | valid_start | valid_end | valid_defect_rate | roc_auc | |
|---|---|---|---|---|---|---|
| 0 | 1 | 2023-05-30 | 2023-05-31 | 2023-10-27 | 0.027 | 0.529 |
| 1 | 2 | 2023-10-27 | 2023-10-28 | 2024-03-25 | 0.047 | 0.399 |
| 2 | 3 | 2024-03-25 | 2024-03-26 | 2024-08-22 | 0.060 | 0.649 |
| 3 | 4 | 2024-08-22 | 2024-08-23 | 2025-01-19 | 0.027 | 0.509 |
| 4 | 5 | 2025-01-19 | 2025-01-20 | 2025-06-18 | 0.087 | 0.860 |

Interpreting the results
If the performance of time-series segmentation is lower than random partitioning or drops in the latter half, we suspect changes in process conditions. This difference is not just a matter of model accuracy, but also the material used to design retraining frequency and monitoring metrics.
No.044: Searching for Parameters in GridSearchCV
Practical purpose
The depth of the tree and the minimum number of leaf samples affect the degree to which on-site noise is followed. Grid exploration is suitable when there are few candidates and you want to compare important combinations without omission.
Method
Exploration is performed only through cross-validation within the training data; test data is not touched. This time, we prioritize defect ranking performance and use ROC-AUC as the selection criterion.
Check with Python
param_grid = {
"max_depth": [3, 5, 8],
"min_samples_leaf": [4, 10, 20],
"max_features": ["sqrt", 0.8],
}
grid = GridSearchCV(
RandomForestClassifier(
n_estimators=160, class_weight="balanced", random_state=SEED, n_jobs=-1
),
param_grid=param_grid,
scoring="roc_auc",
cv=cv,
n_jobs=-1,
return_train_score=True,
)
grid.fit(X_train, y_train)
grid_top = (
pd.DataFrame(grid.cv_results_)
.sort_values("rank_test_score")[
[
"rank_test_score",
"mean_test_score",
"std_test_score",
"mean_train_score",
"params",
]
]
.head(5)
)
print("Number of candidate combinations:", len(grid.cv_results_["params"]))
print("Best parameters:", grid.best_params_)
display(grid_top.round(3))
Number of candidate combinations: 18
Best parameters: {'max_depth': 3, 'max_features': 'sqrt', 'min_samples_leaf': 10}
| rank_test_score | mean_test_score | std_test_score | mean_train_score | params | |
|---|---|---|---|---|---|
| 1 | 1 | 0.694 | 0.103 | 0.960 | {'max_depth': 3, 'max_features': 'sqrt', 'min_... |
| 0 | 2 | 0.688 | 0.100 | 0.970 | {'max_depth': 3, 'max_features': 'sqrt', 'min_... |
| 13 | 3 | 0.687 | 0.124 | 0.993 | {'max_depth': 8, 'max_features': 'sqrt', 'min_... |
| 7 | 4 | 0.686 | 0.119 | 0.989 | {'max_depth': 5, 'max_features': 'sqrt', 'min_... |
| 5 | 5 | 0.680 | 0.116 | 0.936 | {'max_depth': 3, 'max_features': 0.8, 'min_sam... |
Interpreting the results
We look not only at the best values but also at the differences and standard deviations among top contenders. If the difference is very small, there is room to adopt simple, stable settings such as shallow trees or large leaves. It is important not to reselect search results based on test data.
No.045: Searching with RandomizedSearchCV
Practical purpose
If there are many search candidates, calculating all combinations may not fit the equipment and time budget. Random search fixes the number of trials and broadly explores promising areas.
Method
Sample a fixed number of parameter combinations from the specified candidates or distributions. Fix random_state and use the same folds and metric as the grid search.
Check with Python
param_dist = {
"n_estimators": [100, 160, 240, 320],
"max_depth": [3, 4, 5, 7, 9, None],
"min_samples_split": [2, 5, 10, 20],
"min_samples_leaf": [2, 4, 8, 12, 20],
"max_features": ["sqrt", "log2", 0.6, 0.9],
}
random_search = RandomizedSearchCV(
RandomForestClassifier(class_weight="balanced", random_state=SEED, n_jobs=-1),
param_distributions=param_dist,
n_iter=16,
scoring="roc_auc",
cv=cv,
random_state=SEED,
n_jobs=-1,
)
random_search.fit(X_train, y_train)
search_compare = pd.DataFrame(
{
"method": ["GridSearchCV", "RandomizedSearchCV"],
"trials": [
len(grid.cv_results_["params"]),
len(random_search.cv_results_["params"]),
],
"best_cv_roc_auc": [grid.best_score_, random_search.best_score_],
}
)
display(search_compare.round(3))
print("Best parameters for random search:", random_search.best_params_)
| method | trials | best_cv_roc_auc | |
|---|---|---|---|
| 0 | GridSearchCV | 18 | 0.694 |
| 1 | RandomizedSearchCV | 16 | 0.694 |
Best parameters for random search: {'n_estimators': 160, 'min_samples_split': 10, 'min_samples_leaf': 8, 'max_features': 'log2', 'max_depth': 3}
Interpreting the results
If you can achieve the same rating with fewer attempts, random search is a computationally efficient choice. However, due to the nature of chance, we record the range of candidates, number of trials, and seeds to ensure reproducibility of the exploration itself.
No.046: Checking for Overfitting
Practical purpose
A model can classify its training lots almost perfectly and still fail on new lots. Compare training and validation performance as model complexity increases.
Method
Increase the depth of decision trees and compare the learning ROC-AUC with cross-validation ROC-AUC. A sign of overfitting is a region where only the learning value rises while the validation value plateaus or falls.
Check with Python
overfit_rows = []
for depth in [2, 3, 4, 5, 7, 10, None]:
tree = DecisionTreeClassifier(
max_depth=depth, class_weight="balanced", random_state=SEED
)
result = cross_validate(
tree, X_train, y_train, cv=cv, scoring="roc_auc", return_train_score=True
)
overfit_rows.append(
{
"max_depth": "None" if depth is None else str(depth),
"train_auc": result["train_score"].mean(),
"valid_auc": result["test_score"].mean(),
}
)
overfit = pd.DataFrame(overfit_rows)
display(overfit.round(3))
fig, ax = plt.subplots()
ax.plot(overfit.index, overfit["train_auc"], marker="o", label="Train")
ax.plot(overfit.index, overfit["valid_auc"], marker="o", label="Validation")
ax.set_title("Overfitting check by tree depth")
ax.set_xlabel("Maximum tree depth")
ax.set_ylabel("ROC-AUC")
ax.set_xticks(overfit.index, overfit["max_depth"])
ax.grid(True, alpha=0.3)
ax.legend()
fig.tight_layout()
plt.show()
| max_depth | train_auc | valid_auc | |
|---|---|---|---|
| 0 | 2 | 0.802 | 0.587 |
| 1 | 3 | 0.877 | 0.628 |
| 2 | 4 | 0.926 | 0.624 |
| 3 | 5 | 0.957 | 0.605 |
| 4 | 7 | 0.981 | 0.644 |
| 5 | 10 | 0.995 | 0.630 |
| 6 | None | 1.000 | 0.570 |

Interpreting the results
A widening training–validation gap suggests overfitting. Consider shallower trees, a larger minimum number of samples per leaf, better features, or additional representative data. Include ease of explanation and maintenance in the selection decision.
No.047: Check the learning curve
Practical purpose
Additional data collection incurs testing and labeling costs. The learning curve is a key factor in determining whether investing in increased data is likely to lead to improved performance.
Method
Increase the number of training observations and plot training and validation ROC-AUC. A rising validation curve suggests that additional representative data may help. If both curves remain low, review features and model assumptions.
Check with Python
train_sizes, train_scores, valid_scores = learning_curve(
grid.best_estimator_,
X_train,
y_train,
cv=cv,
scoring="roc_auc",
train_sizes=np.linspace(0.2, 1.0, 5),
n_jobs=-1,
)
learning = pd.DataFrame(
{
"train_size": train_sizes,
"train_auc": train_scores.mean(axis=1),
"valid_auc": valid_scores.mean(axis=1),
"valid_std": valid_scores.std(axis=1),
}
)
display(learning.round(3))
fig, ax = plt.subplots()
ax.plot(train_sizes, learning["train_auc"], marker="o", label="Train")
ax.plot(train_sizes, learning["valid_auc"], marker="o", label="Validation")
ax.fill_between(
train_sizes,
learning["valid_auc"] - learning["valid_std"],
learning["valid_auc"] + learning["valid_std"],
alpha=0.2,
)
ax.set_title("Learning curve")
ax.set_xlabel("Number of training lots")
ax.set_ylabel("ROC-AUC")
ax.grid(True, alpha=0.3)
ax.legend()
fig.tight_layout()
plt.show()
| train_size | train_auc | valid_auc | valid_std | |
|---|---|---|---|---|
| 0 | 108 | 0.995 | 0.654 | 0.140 |
| 1 | 216 | 0.985 | 0.672 | 0.087 |
| 2 | 324 | 0.979 | 0.637 | 0.122 |
| 3 | 432 | 0.959 | 0.664 | 0.104 |
| 4 | 540 | 0.960 | 0.694 | 0.103 |

Interpreting the results
If the validation curve is rising even at the end, it is worth collecting additional lots. If the gap between training and validation remains large, variance is high, requiring additional data and model constraints covering all conditions. Curves do not guarantee causality, and the representativeness of the collected items is checked separately.
No.048: Checking the Importance of Features
Practical purpose
Quality engineers need to compare what is effective for predictions against process knowledge. Importance can be used to prioritize sensor improvements, maintenance items, and additional investigations.
Method
Inspect impurity-based feature importance from the fitted forest. It measures accumulated reductions in the split criterion, not the direction of an effect or causation. Correlated features can share importance, and many possible split points can bias it.
Check with Python
best_model = grid.best_estimator_.fit(X_train, y_train)
importance = pd.DataFrame(
{"feature": features, "importance": best_model.feature_importances_}
).sort_values("importance", ascending=True)
display(importance.sort_values("importance", ascending=False).round(3))
fig, ax = plt.subplots()
ax.barh(importance["feature"], importance["importance"])
ax.set_title("Random forest feature importance")
ax.set_xlabel("Importance")
ax.set_ylabel("Feature")
ax.grid(True, axis="x", alpha=0.3)
fig.tight_layout()
plt.show()
| feature | importance | |
|---|---|---|
| 0 | temperature | 0.253 |
| 2 | vibration | 0.236 |
| 3 | machine_load | 0.215 |
| 5 | maintenance_days | 0.146 |
| 4 | material_hardness | 0.098 |
| 1 | pressure | 0.052 |

Interpreting the results
Highly ranked features suggest conditions to investigate, not interventions proven to reduce defects. Check them against process tests and equipment history. A prominent date or lot identifier may indicate a proxy relationship or leakage.
No.049: Comparing Multiple Models
Practical purpose
For similar accuracy, models with high inference speed, maintainability, and explainability may be easier to implement. Instead of determining the top of a single indicator, multiple perspectives are considered.
Method
For logistic regression, we use a pipeline that includes standardization, comparing decision trees, random forests, and gradient boosting using the same splits and metrics.
Check with Python
models = {
"Logistic regression": Pipeline(
[
("scale", StandardScaler()),
(
"model",
LogisticRegression(
class_weight="balanced", max_iter=1000, random_state=SEED
),
),
]
),
"Decision tree": DecisionTreeClassifier(
max_depth=4, class_weight="balanced", random_state=SEED
),
"Random forest": grid.best_estimator_,
"Gradient boosting": GradientBoostingClassifier(random_state=SEED),
}
comparison_rows = []
for name, model in models.items():
scores = cross_validate(
model,
X_train,
y_train,
cv=cv,
scoring={"auc": "roc_auc", "recall": "recall", "f1": "f1"},
n_jobs=-1,
)
comparison_rows.append(
{
"model": name,
"roc_auc_mean": scores["test_auc"].mean(),
"roc_auc_std": scores["test_auc"].std(),
"recall_mean": scores["test_recall"].mean(),
"f1_mean": scores["test_f1"].mean(),
}
)
model_comparison = pd.DataFrame(comparison_rows).sort_values(
"roc_auc_mean", ascending=False
)
display(model_comparison.round(3))
fig, ax = plt.subplots()
ax.barh(
model_comparison["model"],
model_comparison["roc_auc_mean"],
xerr=model_comparison["roc_auc_std"],
capsize=4,
)
ax.set_title("Model comparison with cross-validation")
ax.set_xlabel("Mean ROC-AUC")
ax.set_ylabel("Model")
ax.grid(True, axis="x", alpha=0.3)
fig.tight_layout()
plt.show()
| model | roc_auc_mean | roc_auc_std | recall_mean | f1_mean | |
|---|---|---|---|---|---|
| 0 | Logistic regression | 0.775 | 0.097 | 0.593 | 0.147 |
| 2 | Random forest | 0.694 | 0.103 | 0.413 | 0.171 |
| 3 | Gradient boosting | 0.652 | 0.134 | 0.000 | 0.000 |
| 1 | Decision tree | 0.624 | 0.091 | 0.380 | 0.153 |

Interpreting the results
Compare mean ROC-AUC, variability, recall, and F1. The forest parameters were selected using these same folds, so its score can contain selection bias. Treat this as a model-selection table; use an independent test set or nested cross-validation for a final performance estimate.
No.050: Designing Evaluation Indicators Fit for Practical Work
Practical purpose
Missed defects can lead to customer claims and rework; additional inspections consume labor. Since these costs differ, the operating probability threshold need not be 0.5.
Method
Assume a missed defect costs ¥300,000 and each inspected lot costs ¥8,000. Thus . Generate out-of-fold predictions on training data and select the lowest-cost threshold among those with an inspection rate at most 35%. Then freeze the threshold and evaluate the test set.
Check with Python
# Select the threshold using predictions made without training on each row.
from sklearn.model_selection import cross_val_predict
policy_prob = cross_val_predict(
clone(grid.best_estimator_),
X_train,
y_train,
cv=cv,
method="predict_proba",
n_jobs=-1,
)[:, 1]
threshold_rows = []
for threshold in np.linspace(0.05, 0.80, 31):
pred = (policy_prob >= threshold).astype(int)
tn, fp, fn, tp = confusion_matrix(y_train, pred, labels=[0, 1]).ravel()
inspection_rate = pred.mean()
total_cost = 300_000 * fn + 8_000 * (tp + fp)
threshold_rows.append(
{
"threshold": threshold,
"inspection_rate": inspection_rate,
"recall": recall_score(y_train, pred, zero_division=0),
"false_negative": fn,
"total_cost_yen": total_cost,
}
)
threshold_result = pd.DataFrame(threshold_rows)
feasible = threshold_result[threshold_result["inspection_rate"] <= 0.35]
best_policy = feasible.loc[feasible["total_cost_yen"].idxmin()]
display(best_policy.to_frame("selected_policy").round(3))
fig, ax1 = plt.subplots()
ax1.plot(
threshold_result["threshold"],
threshold_result["total_cost_yen"] / 1_000_000,
color="tab:blue",
label="Total cost",
)
ax1.set_title("Threshold selection under inspection capacity")
ax1.set_xlabel("Risk threshold")
ax1.set_ylabel("Estimated cost (million JPY)", color="tab:blue")
ax1.grid(True, alpha=0.3)
ax2 = ax1.twinx()
ax2.plot(
threshold_result["threshold"],
threshold_result["inspection_rate"],
color="tab:orange",
label="Inspection rate",
)
ax2.axhline(0.35, color="tab:red", linestyle="--", label="Capacity limit")
ax2.set_ylabel("Inspection rate", color="tab:orange")
lines = ax1.get_lines() + ax2.get_lines()
ax1.legend(lines, [line.get_label() for line in lines], loc="best")
fig.tight_layout()
plt.show()
# Freeze the threshold before evaluating the test data.
final_model = clone(grid.best_estimator_).fit(X_train, y_train)
test_prob = final_model.predict_proba(X_test)[:, 1]
final_pred = (test_prob >= best_policy["threshold"]).astype(int)
tn, fp, fn, tp = confusion_matrix(y_test, final_pred, labels=[0, 1]).ravel()
display(
pd.Series(
{
"threshold": best_policy["threshold"],
"test_inspection_rate": final_pred.mean(),
"test_false_negative": fn,
"test_recall": recall_score(y_test, final_pred, zero_division=0),
"test_total_cost_yen": 300_000 * fn + 8_000 * (tp + fp),
}
)
.to_frame("test_result")
.round(3)
)
| selected_policy | |
|---|---|
| threshold | 0.400 |
| inspection_rate | 0.335 |
| recall | 0.621 |
| false_negative | 11.000 |
| total_cost_yen | 5108000.000 |

| test_result | |
|---|---|
| threshold | 0.400 |
| test_inspection_rate | 0.356 |
| test_false_negative | 4.000 |
| test_recall | 0.556 |
| test_total_cost_yen | 1840000.000 |
Interpreting the results
The selected threshold uses training-side predictions, not test labels. Its validation cost is a selection criterion rather than an unbiased performance estimate. A 35% inspection limit on the training data may be exceeded on new data; check the test inspection rate as well as missed defects and cost. Serious defects may also need constraints that cannot be reduced to money.
What the results mean in practice
- Evaluation design takes precedence over model design: If you are forecasting the future, follow chronological order and separate exploration data from final tests.
- Average performance alone is not enough.: Variation in cross-validation, performance by period, and learning curve are used to determine reproducibility.
- Include operational constraints: Select models and thresholds using inspection capacity, missed-defect costs, explainability, and predictive performance.
- Feature importance is used for hypothesis generation: Confirm without definitive causality, using process knowledge, experiments, and maintenance records.
Requirements for deployment
- Data definition: Standardize defective labels, measurement timing, equipment, varieties, and lot granularity
- Leakage checks: Exclude inspection results and other information unavailable when the prediction is made.
- Evaluation period: Secure future periods including seasons, equipment maintenance, and material lot changes.
- Agreement on business metrics: Set the allowable limits for missed losses, inspection work, and major defects across departments
- trial operation: First, present judgments as reference information and record the differences from others’ judgments.
- Monitoring and Relearning: Regularly monitor defect rates, input distributions, recall rates, inspection rates, and losses.
Conclusion
No.041–No.050 compared holdout and cross-validation methods, parameter searches, overfitting, and cost-based thresholds. Agree on the evaluation period, acceptable missed defects, and inspection workload before selecting a model.
Consulting for businesses
At Surikobo, we support everything from organizing manufacturing data, quality prediction and anomaly detection, evaluation design, PoC, to model monitoring for production operations, tailored to on-site constraints. You can consult from the stage where “we have data but can’t decide on an evaluation method” or “accuracy is achieved but it doesn’t lead to operational decisions.”
📩 Contact Us: www.surikobo.co.jp/contact
Please feel free to consult us first.