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.
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.
The model receives only X. Generating labels are retained solely for optional teaching comparisons and never passed into fitting.
from sklearn.datasets import make_blobs
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
X,hidden_labels=make_blobs(n_samples=360,n_features=5,centers=3,cluster_std=1.4,random_state=SEED)
Xtr,Xte=train_test_split(X,test_size=.25,random_state=SEED)
scaler=StandardScaler().fit(Xtr)
Ztr,Zte=scaler.transform(Xtr),scaler.transform(Xte)
Checkpoint. No target is available to the clustering algorithm. Preprocessing still learns statistics and must fit training only.
PCA chooses orthogonal directions of maximum training variance. Two components simplify plotting but may discard useful information.
pca=PCA(n_components=2).fit(Ztr)
P=pca.transform(Zte)
print("Explained variance ratios:",pca.explained_variance_ratio_)
plt.scatter(P[:,0],P[:,1]); plt.xlabel("PC1"); plt.ylabel("PC2"); plt.show()
Checkpoint. Explained variance is not prediction accuracy or a guarantee of physically meaningful factors.
K-means finds geometric groups under a chosen distance and k. Labels are arbitrary IDs; cluster 0 is not an engineering diagnosis.
kmeans=KMeans(n_clusters=3,n_init=10,random_state=SEED).fit(Ztr)
groups=kmeans.predict(Zte)
plt.scatter(P[:,0],P[:,1],c=groups,cmap="viridis"); plt.xlabel("PC1"); plt.ylabel("PC2"); plt.show()
summary={"test_silhouette":float(silhouette_score(Zte,groups)),
"retained_training_variance":float(pca.explained_variance_ratio_.sum())}
print(summary)
Checkpoint. A high silhouette supports separation in this representation, not a causal or semantic interpretation of clusters.
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":6,"seed":SEED,"numpy":np.__version__,"python":platform.python_version(),"result":summary}
(ARTIFACTS/"week-06-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.
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.