Week 05: Validation, thresholds, precision, and recall

Machine Learning in Engineering Science | NCKU + LAiMM | Fall 2026

Purpose: a fully worked, self-paced in-class practice with an optional extension. Weeks 11 and 18 are optional examination-readiness materials. These notebooks do not create weekly graded assignments.

Before running: choose a Python 3 kernel in Jupyter or a CPU runtime in Colab. Run every cell from top to bottom with Shift+Enter. Setup installs missing free packages. No API key or external dataset download is required.

Learning target: complete the calculation, inspect intermediate values, and explain why the protocol supports a limited claim.

Time: about 25-45 minutes including reading, prediction, execution, and explain-back.

1. Set up and record the environment

Keep the seed fixed for the first run. Record actual outputs and package versions rather than copying a claimed performance number.

import sys, subprocess, importlib.util, platform, json, random, hashlib
from pathlib import Path
required = {"numpy": "numpy", "matplotlib": "matplotlib", "sklearn": "scikit-learn"}
missing = [package for module, package in required.items() if importlib.util.find_spec(module) is None]
if missing:
    subprocess.check_call([sys.executable, "-m", "pip", "install", *missing])
import numpy as np
import matplotlib.pyplot as plt
SEED = 2026
random.seed(SEED)
np.random.seed(SEED)
rng = np.random.default_rng(SEED)
ARTIFACTS = Path("artifacts")
ARTIFACTS.mkdir(exist_ok=True)
print("Python:", platform.python_version(), "NumPy:", np.__version__, "Seed:", SEED)

Checkpoint. The environment cell must finish before any analysis cell. Restart and run all if a variable is missing.

2. Reserve validation and test separately

Class 1 denotes the less frequent synthetic event. Select a decision threshold using validation only; preserve test for one final comparison.

from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import precision_score,recall_score,f1_score,confusion_matrix
X,y=make_classification(n_samples=800,n_features=8,n_informative=4,weights=[.85,.15],random_state=SEED)
Xtr,Xrest,ytr,yrest=train_test_split(X,y,test_size=.4,stratify=y,random_state=SEED)
Xva,Xte,yva,yte=train_test_split(Xrest,yrest,test_size=.5,stratify=yrest,random_state=SEED)
model=LogisticRegression(max_iter=300).fit(Xtr,ytr)
pv=model.predict_proba(Xva)[:,1]

Checkpoint. There are 480 training, 160 validation, and 160 test rows. No threshold has been selected using test outcomes.

3. Select a threshold on validation

For illustration choose the validation threshold with highest F1 among a fixed grid. A real safety specification may instead demand a minimum recall and account for uncertainty.

thresholds=np.linspace(.05,.95,19)
scores=np.array([f1_score(yva,pv>=t,zero_division=0) for t in thresholds])
threshold=float(thresholds[scores.argmax()])
plt.plot(thresholds,scores,"o-"); plt.xlabel("Decision threshold"); plt.ylabel("Validation F1"); plt.show()
print("Selected threshold:",threshold)

Checkpoint. The chosen number is specific to this dataset and protocol. It is not a universal optimal threshold.

4. Explain every confusion-matrix cell

Recall is TP/(TP+FN), also called sensitivity. Specificity is TN/(TN+FP), and precision is TP/(TP+FP). If the denominator is zero, the metric is undefined; software zero_division=0 is a reporting convention.

pt=model.predict_proba(Xte)[:,1]; predicted=(pt>=threshold)
tn,fp,fn,tp=confusion_matrix(yte,predicted,labels=[0,1]).ravel()
summary={"threshold":threshold,"TP":int(tp),"FP":int(fp),"FN":int(fn),"TN":int(tn),
         "precision":float(precision_score(yte,predicted,zero_division=0)),
         "recall_sensitivity":float(recall_score(yte,predicted,zero_division=0)),
         "specificity":float(tn/(tn+fp)),"F1":float(f1_score(yte,predicted,zero_division=0))}
print(summary)

Checkpoint. Identify a false negative and a false positive in words. State which cost your application should care about and why.

6. Preserve your evidence

Export a JSON record with a seed, package version, and measured result. Download the artifacts directory before leaving Colab; runtime storage is temporary.

record={"week":5,"seed":SEED,"numpy":np.__version__,"python":platform.python_version(),"result":summary}
(ARTIFACTS/"week-05-evidence.json").write_text(json.dumps(record,indent=2))
print(json.dumps(record,indent=2))

Checkpoint. The evidence file must match the result you actually obtained. A saved screenshot alone does not permit rerunning the calculation.

7. Try one change and explain it

1. Predict the effect of one change before editing code. Change one parameter, input, or boundary condition only.

2. Rerun all cells in a fresh kernel. Keep the original evidence record and compare the observed difference.

3. Explain the result using the mechanism, not just the final number.

4. Name one assumption that limits the claim, and a new test that could challenge it.

Troubleshooting: if installation fails, restore network access; if a variable is undefined, run earlier cells; if your output differs, compare package versions, seed, and data construction. Do not repeatedly edit code until a preferred score appears.

Completion criterion: one executed notebook, one evidence JSON, and a brief claim/evidence/limitation statement.

Reference documentation

- NumPy user guide

- scikit-learn user guide

- Course repository