TExcelTAD
Home › ML Foundations: AI, ML, Deep Learning & the ML Lifecycle › Mini Project: Your First End-to-End Classifier

Mini Project: Your First End-to-End Classifier

This project walks once around the whole ML lifecycle on a small, realistic problem: from a messy table to a saved model that a separate program loads to score new records, with a short write-up at the end. It follows the "first practical assignment" of the curriculum this track is built on, and it uses only ideas from this course. Later courses go deeper into every step.

The problem. A clinic network wants a second opinion for its pathologists: given measurements of cell nuclei from a breast-tumour biopsy image, estimate whether the tumour is malignant. A missed malignant tumour (a false negative) is far worse than a false alarm, which only leads to further review.

The data. The Breast Cancer Wisconsin (Diagnostic) data set, 569 tumours with 30 measurements each, collected at the University of Wisconsin and published in the UCI Machine Learning Repository; it ships with scikit-learn as load_breast_cancer. It is anonymised research data shared for reuse. To make the project realistic, the code keeps 8 of the measurements, adds a clinic column, removes about 4 % of the values at random and duplicates three rows: the kind of mess real tables have. Each step is a complete program, so you can run them in any order.

Step 1: Inspect the data

Look before you model: size, column types, class balance, missing values, duplicates, extreme values.

python · try it yourself
import numpy as np
import pandas as pd
from sklearn.datasets import load_breast_cancer

def load_raw():
    """The project's raw table: a public data set plus the mess real data usually has."""
    data = load_breast_cancer(as_frame=True)
    df = data.frame.iloc[:, [0, 1, 4, 6, 7, 20, 21, 27, 30]].copy()     # 8 features + target
    df.columns = ["radius", "texture", "smoothness", "concavity", "concave_points",
                  "worst_radius", "worst_texture", "worst_concave_points", "target"]
    rng = np.random.default_rng(0)
    df.insert(0, "clinic", rng.choice(["north", "south", "east"], size=len(df)))
    for col in ["texture", "smoothness", "clinic"]:                       # 4 % missing values
        df.loc[rng.random(len(df)) < 0.04, col] = np.nan
    df = pd.concat([df, df.iloc[[3, 50, 120]]], ignore_index=True)        # 3 duplicated rows
    df["diagnosis"] = np.where(df.pop("target") == 0, "malignant", "benign")
    return df

df = load_raw()
print("shape:", df.shape)
print(df.dtypes.value_counts().to_string())
print("\nclass balance:\n" + df["diagnosis"].value_counts().to_string())
print("\nmissing values:\n" + df.isna().sum()[df.isna().sum() > 0].to_string())
print("\nduplicated rows:", df.duplicated().sum())
z = (df.select_dtypes("number") - df.mean(numeric_only=True)) / df.std(numeric_only=True)
print("values more than 4 std from the mean:", int((z.abs() > 4).sum().sum()))
shape: (572, 10)
float64    8
object     2

class balance:
diagnosis
benign       359
malignant    213

missing values:
clinic        30
texture       21
smoothness    28

duplicated rows: 3
values more than 4 std from the mean: 6

Findings to note in the write-up:

  • 572 rows and 10 columns: 8 numeric measurements, the categorical clinic and the label diagnosis.
  • 213 malignant and 359 benign: imbalanced, but not severely. A model that always says "benign" would be right 63 % of the time; that is the baseline to beat.
  • Missing values in clinic (30), texture (21) and smoothness (28). They must be imputed, and the imputer must be fitted on training rows only.
  • 3 exact duplicate rows. Duplicates could land in both the training and the test set and make the test easier, so they are removed before splitting.
  • 6 values lie more than 4 standard deviations from their column mean. In this data set they are real, large tumours, not errors, so they stay. Deciding that requires domain knowledge, not a rule.

Step 2: Split, build the pipeline, compare two models

Split into 60 % training, 20 % validation and 20 % test, each with the same class balance (stratify). All preprocessing lives in a ColumnTransformer inside the pipeline: median imputation and scaling for numbers, most-frequent imputation and one-hot encoding for clinic. Then compare a logistic-regression baseline with a random forest on the validation set.

python · try it yourself
import numpy as np
import pandas as pd
from sklearn.datasets import load_breast_cancer

def load_raw():
    """The project's raw table: a public data set plus the mess real data usually has."""
    data = load_breast_cancer(as_frame=True)
    df = data.frame.iloc[:, [0, 1, 4, 6, 7, 20, 21, 27, 30]].copy()     # 8 features + target
    df.columns = ["radius", "texture", "smoothness", "concavity", "concave_points",
                  "worst_radius", "worst_texture", "worst_concave_points", "target"]
    rng = np.random.default_rng(0)
    df.insert(0, "clinic", rng.choice(["north", "south", "east"], size=len(df)))
    for col in ["texture", "smoothness", "clinic"]:                       # 4 % missing values
        df.loc[rng.random(len(df)) < 0.04, col] = np.nan
    df = pd.concat([df, df.iloc[[3, 50, 120]]], ignore_index=True)        # 3 duplicated rows
    df["diagnosis"] = np.where(df.pop("target") == 0, "malignant", "benign")
    return df

from sklearn.model_selection import train_test_split
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline, make_pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, recall_score

df = load_raw().drop_duplicates()
X, y = df.drop(columns="diagnosis"), (df["diagnosis"] == "malignant").astype(int)   # 1 = malignant

# 60 % train, 20 % validation, 20 % test, all with the same class balance.
X_trval, X_test, y_trval, y_test = train_test_split(X, y, test_size=0.2, random_state=0, stratify=y)
X_train, X_val, y_train, y_val = train_test_split(X_trval, y_trval, test_size=0.25, random_state=0, stratify=y_trval)
print("rows: train", len(X_train), " validation", len(X_val), " test", len(X_test))

numeric = [c for c in X.columns if c != "clinic"]
prep = ColumnTransformer([
    ("num", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()), numeric),
    ("cat", make_pipeline(SimpleImputer(strategy="most_frequent"), OneHotEncoder(handle_unknown="ignore")), ["clinic"]),
])
candidates = {
    "logistic regression": LogisticRegression(max_iter=1000),
    "random forest": RandomForestClassifier(n_estimators=300, random_state=0),
}
for name, clf in candidates.items():
    pipe = Pipeline([("prep", prep), ("model", clf)]).fit(X_train, y_train)
    pred = pipe.predict(X_val)
    print(f"{name:20} validation accuracy {accuracy_score(y_val, pred):.3f}, malignant recall {recall_score(y_val, pred):.3f}")
rows: train 341  validation 114  test 114
logistic regression  validation accuracy 0.982, malignant recall 0.977
random forest        validation accuracy 0.956, malignant recall 0.930

On 114 validation rows, logistic regression is right on 0.982 and finds 0.977 of the malignant tumours (42 of 43); the random forest finds 0.930 (40 of 43). Both clearly beat the 63 % baseline. The simpler model wins here, so we choose it: it is also faster and easier to explain. With only 43 malignant validation cases, a difference of two tumours is suggestive, not proof; cross-validation (taught in Training, Evaluation & Improvement) would give a steadier comparison.

Step 3: Test once, save, load, predict

Refit the chosen pipeline on training plus validation rows, evaluate it once on the test set, save the whole fitted pipeline with joblib, and load it again as the serving program would. Then score two new records, one of them from a clinic the model has never seen and with a missing value.

python · try it yourself
import numpy as np
import pandas as pd
from sklearn.datasets import load_breast_cancer

def load_raw():
    """The project's raw table: a public data set plus the mess real data usually has."""
    data = load_breast_cancer(as_frame=True)
    df = data.frame.iloc[:, [0, 1, 4, 6, 7, 20, 21, 27, 30]].copy()     # 8 features + target
    df.columns = ["radius", "texture", "smoothness", "concavity", "concave_points",
                  "worst_radius", "worst_texture", "worst_concave_points", "target"]
    rng = np.random.default_rng(0)
    df.insert(0, "clinic", rng.choice(["north", "south", "east"], size=len(df)))
    for col in ["texture", "smoothness", "clinic"]:                       # 4 % missing values
        df.loc[rng.random(len(df)) < 0.04, col] = np.nan
    df = pd.concat([df, df.iloc[[3, 50, 120]]], ignore_index=True)        # 3 duplicated rows
    df["diagnosis"] = np.where(df.pop("target") == 0, "malignant", "benign")
    return df

import joblib
from sklearn.model_selection import train_test_split
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline, make_pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, recall_score, confusion_matrix

df = load_raw().drop_duplicates()
X, y = df.drop(columns="diagnosis"), (df["diagnosis"] == "malignant").astype(int)
X_trval, X_test, y_trval, y_test = train_test_split(X, y, test_size=0.2, random_state=0, stratify=y)

numeric = [c for c in X.columns if c != "clinic"]
prep = ColumnTransformer([
    ("num", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()), numeric),
    ("cat", make_pipeline(SimpleImputer(strategy="most_frequent"), OneHotEncoder(handle_unknown="ignore")), ["clinic"]),
])
# The chosen model, refitted on train + validation, then tested exactly once.
final = Pipeline([("prep", prep), ("model", LogisticRegression(max_iter=1000))]).fit(X_trval, y_trval)
pred = final.predict(X_test)
print(f"TEST accuracy {accuracy_score(y_test, pred):.3f}, malignant recall {recall_score(y_test, pred):.3f}")
print("confusion matrix [[TN FP] [FN TP]]:", confusion_matrix(y_test, pred).tolist())

joblib.dump(final, "breast_model.joblib")          # save the whole fitted pipeline
del final

# --- the "separate program": load the file and score new records ---
model = joblib.load("breast_model.joblib")
new = pd.DataFrame([
    {"clinic": "north", "radius": 12.1, "texture": 17.0, "smoothness": 0.09, "concavity": 0.03,
     "concave_points": 0.02, "worst_radius": 13.2, "worst_texture": 22.0, "worst_concave_points": 0.07},
    {"clinic": "west", "radius": 19.8, "texture": np.nan, "smoothness": 0.11, "concavity": 0.21,
     "concave_points": 0.12, "worst_radius": 25.1, "worst_texture": 30.5, "worst_concave_points": 0.22},
])
for i, p in enumerate(model.predict_proba(new)[:, 1]):
    print(f"record {i}: P(malignant) = {p:.3f} ->", "malignant" if p >= 0.5 else "benign")
TEST accuracy 0.956, malignant recall 0.952
confusion matrix [[TN FP] [FN TP]]: [[69, 3], [2, 40]]
record 0: P(malignant) = 0.001 -> benign
record 1: P(malignant) = 1.000 -> malignant

The final test result on 114 untouched rows: accuracy 0.956 and malignant recall 0.952. The confusion matrix shows 2 missed malignant tumours (false negatives) and 3 false alarms. The saved pipeline handles the new clinic west (the one-hot encoder ignores unknown categories) and the missing texture (the imputer fills in the training median), because both steps are part of the saved file.

Note: joblib.load, like pickle, can execute code from the file. Only load model files you created or trust.

Step 4: Write it up

A model without a write-up cannot be reviewed, reproduced or safely used. Copy this template and fill it in (the answers for this project are mostly above):

text
PROJECT:       Breast-tumour malignancy second opinion
DATE / AUTHOR:

1. Problem     Input: 8 nucleus measurements + clinic. Target: malignant (1) / benign (0).
               Decision supported: flag for extra pathologist review. Cost of errors: FN >> FP.
2. Data        Source, licence and consent: UCI Breast Cancer Wisconsin (Diagnostic), via scikit-learn.
               Rows, classes, missing values, duplicates, outliers and what was done about each.
3. Split       60/20/20 stratified, duplicates removed before splitting, random_state=0.
4. Pipeline    Imputation, scaling, encoding (all fitted on training rows only); model and settings.
5. Selection   Candidates and validation metrics; why the chosen model was chosen.
6. Test        Metrics on the test set, used once; confusion matrix.
7. Limits      Small data from one source and era; validation and test sets are small;
               performance on other hospitals, scanners or populations is unknown;
               threshold 0.5 not tuned for the FN/FP cost ratio.
8. Use         How a prediction is produced (file, function, inputs); who reviews flagged cases;
               what must be monitored (input drift, share flagged, recall when labels arrive).
9. Reproduce   Code version, library versions, seeds, data version.

The curriculum's completion criterion is a good final check: you should be able to explain where the data came from, how it was prepared, how the model learned, how performance was measured, and how a new prediction is produced.

Extensions

  1. Tune the threshold. Missed malignancies cost more than false alarms. Use predict_proba on the validation set to find the threshold that reaches a recall of at least 0.99, and report how many false alarms it costs.
  2. Use all 30 features. Does validation performance improve? Is the model still easy to explain?
  3. Cross-validate the comparison. Replace the single validation split with 5-fold cross-validation on the training-plus-validation rows (cross_val_score on the pipeline) and compare the mean and spread of recall for both models.
  4. Monitor drift. Simulate a scanner change by multiplying radius and worst_radius of the test rows by 1.15, and write a check that flags the drift before accuracy is measured.
  5. Learning curve. Train on 10 %, 25 %, 50 % and 100 % of the training rows and plot validation recall. Would collecting more data help?

Test yourself

Why are the duplicate rows removed before the split rather than after?

  1. To save memory
  2. So that a copy of a row cannot be in both the training and the test set, which would make the test easier
  3. Because pandas requires it
  4. Duplicates do not matter

Why was the test set used only once, after the model was chosen on the validation set?

  1. Because testing is slow
  2. So the test score stays an honest estimate of performance on new data
  3. Because scikit-learn allows one call
  4. It does not matter how often it is used

How could the loaded model handle a record from the unknown clinic 'west' with a missing texture value?

  1. It crashed and was retrained
  2. The saved pipeline contains the imputer and the one-hot encoder with handle_unknown="ignore"
  3. The record was dropped
  4. Pickle fixes missing values

In this problem, which kind of error is most costly?

  1. False positives (benign flagged as malignant)
  2. False negatives (malignant classified as benign)
  3. Both are equally costly
  4. Neither matters