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.
Use the packaged Iris teaching dataset, which needs no download. Features are four flower measurements; the target is species. This is classification, not engineering diagnosis.
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score,confusion_matrix
dataset=load_iris(); X,y=dataset.data,dataset.target
X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=.25,stratify=y,random_state=SEED)
print(dataset.feature_names, dataset.target_names, X_train.shape, X_test.shape)
Checkpoint. Training and test observations are distinct. Stratification approximately preserves class proportions.
The scaler estimates means and variances using training rows. A Pipeline applies the same learned transformation to test rows.
model=make_pipeline(StandardScaler(),LogisticRegression(max_iter=300,random_state=SEED))
model.fit(X_train,y_train)
pred=model.predict(X_test)
summary={"test_accuracy":float(accuracy_score(y_test,pred)),"training_rows":len(y_train),"test_rows":len(y_test)}
print(summary)
assert np.allclose(model[0].mean_,X_train.mean(axis=0))
Checkpoint. Explain which values were learned during fit. Do not refit the scaler on test.
Rows of this confusion matrix are true classes and columns are predictions. Inspect any errors and relate them to overlapping feature distributions.
matrix=confusion_matrix(y_test,pred)
plt.imshow(matrix,cmap="Blues"); plt.xticks(range(3),dataset.target_names,rotation=20)
plt.yticks(range(3),dataset.target_names); plt.xlabel("Predicted"); plt.ylabel("True"); plt.colorbar(); plt.show()
print("Wrong sample positions in test:",np.flatnonzero(pred!=y_test))
Checkpoint. A correct result may have few or no errors. State that this small test does not establish broad reliability.
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":2,"seed":SEED,"numpy":np.__version__,"python":platform.python_version(),"result":summary}
(ARTIFACTS/"week-02-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.