Advanced
Searching inLabs
How to search
  • Search a task or a tool (lvm, selinux, @podman); filter by level and by book or course.
  • With an empty search box, a filter alone lists the labs — for example all hard labs of one course.
  • "two words" finds the exact phrase.
  • Plain words find names, texts and examples.
  • ↑ ↓ to move · Enter to open · Esc to close · / to search
Try:

Lab 1.1IBM AI Engineering, Chapter 1

Train, evaluate and save a classifier the right way (scikit-learn pipeline)

Level
Medium
45 min
Machines
any computer with Python 3.10+ (scikit-learn, pandas, joblib)
Status
Not started

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

  1. Load load_breast_cancer(as_frame=True). How many samples, features and samples per class?
  2. Split into train and test (25 %), stratified, with random_state=42.
  3. Build two pipelines: StandardScaler + LogisticRegression and RandomForestClassifier. Compare them with 5-fold cross-validation (F1) on the training data only.
  4. Tune the better one with GridSearchCV (for example C of the logistic regression).
  5. 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?
  6. Save the final pipeline with joblib and 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.py loads model.joblib and prints a class and a probability.

Hints

Show the hints
  • In this data set, class 0 = malignant, 1 = benign. Use pos_label=0 or 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 example clf__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
train.py
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")
predict.py
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.py

A 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.

Lessons for this lab

Commands in this lab