Goal
Build a small machine-learning model like an engineer: a clean train/test split, a pipeline (scaling + model) so no test data leaks into training, cross-validation to pick settings, the right metrics for an unbalanced problem (precision, recall, F1, not only accuracy), and a saved model file that a service can load. The task: predict if a breast tumour sample is malignant (the classic scikit-learn data set).
Before you start
python3 -m venv .venv && . .venv/bin/activate && pip install scikit-learn pandas joblib.- Make the folder
~/ml-lab.
Tasks
Tick a task when it is done. Only your browser remembers it.
- Load
load_breast_cancer(as_frame=True). How many samples, features and samples per class? - Split into train and test (25 %), stratified, with
random_state=42. - Build two pipelines:
StandardScaler + LogisticRegressionandRandomForestClassifier. Compare them with 5-fold cross-validation (F1) on the training data only. - Tune the better one with
GridSearchCV(for exampleCof the logistic regression). - Evaluate once on the test set: confusion matrix, precision, recall, F1 and ROC AUC. In this problem, which error is worse — a false negative or a false positive?
- Save the final pipeline with
jobliband load it in a second script that predicts one sample.
Check your work
python3 train.py
python3 predict.py
ls -lh model.joblib- The data has 569 samples, 30 features (212 malignant, 357 benign).
- Cross-validation F1 of both models is above 0.95.
- The test report shows recall for the malignant class; the confusion matrix has very few false negatives.
predict.pyloadsmodel.jobliband prints a class and a probability.
Hints
Show the hints
- In this data set, class
0= malignant,1= benign. Usepos_label=0or the classification report to read the malignant numbers. cross_val_score(pipe, X_train, y_train, cv=5, scoring="f1").- In a pipeline, grid parameters are named
step__param, for exampleclf__C. - Fit the scaler inside the pipeline; scaling the whole data set before the split leaks information from the test set.
Solution
Show the solution
import joblib
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report, confusion_matrix, roc_auc_score
from sklearn.model_selection import GridSearchCV, cross_val_score, train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_breast_cancer(return_X_y=True, as_frame=True)
print("samples, features:", X.shape, "| per class:", y.value_counts().to_dict())
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, stratify=y, random_state=42)
candidates = {
"logreg": Pipeline([("scale", StandardScaler()), ("clf", LogisticRegression(max_iter=5000))]),
"forest": Pipeline([("clf", RandomForestClassifier(n_estimators=300, random_state=42))]),
}
for name, pipe in candidates.items():
scores = cross_val_score(pipe, X_train, y_train, cv=5, scoring="f1")
print(f"{name}: CV F1 {scores.mean():.3f} +/- {scores.std():.3f}")
grid = GridSearchCV(candidates["logreg"], {"clf__C": [0.01, 0.1, 1, 10]}, cv=5, scoring="f1")
grid.fit(X_train, y_train)
print("best:", grid.best_params_)
model = grid.best_estimator_
pred = model.predict(X_test)
print(confusion_matrix(y_test, pred))
print(classification_report(y_test, pred, target_names=["malignant", "benign"]))
print("ROC AUC:", round(roc_auc_score(y_test, model.predict_proba(X_test)[:, 1]), 3))
joblib.dump(model, "model.joblib")import joblib
from sklearn.datasets import load_breast_cancer
model = joblib.load("model.joblib")
X, _ = load_breast_cancer(return_X_y=True, as_frame=True)
sample = X.iloc[[0]]
proba = model.predict_proba(sample)[0]
print("class:", ["malignant", "benign"][model.predict(sample)[0]], "| p(malignant) =", round(proba[0], 3))python3 train.py
python3 predict.pyA false negative (a malignant sample called benign) is the worse error here, so you watch the recall of the malignant class, and you could lower the decision threshold to catch more of them at the price of more false alarms.
My notes
No notes yet.