Chapter 8 — Assignment Project: Predicting Diabetes Progression
Overview¶
A hospital wants to know, one year in advance, which diabetes patients will get worse, so it can follow them more closely. You will build that prediction from start to finish, the way a data scientist would, and write a short report a doctor could read.
Data. The scikit-learn diabetes dataset: 442 patients, 10 measurements each (age, sex, body-mass index, blood pressure and six blood serum values, already standardised), and a number measuring disease progression one year later (25 to 346: higher is worse).
| Part | Task | Points |
|---|---|---|
| A | Explore the data and set up an honest evaluation | 15 |
| B | Regression: predict the progression score | 30 |
| C | Classification: flag the patients at high risk | 35 |
| D | A model card: report for the hospital | 20 |
Rules
Use
random_state=42wherever randomness appears, so your results can be reproduced.The test set is used once, in the final cell of Parts B and C. Never to choose anything.
Cells marked checked have an automatic check under them; the other parts are graded with the rubric at the end.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.datasets import load_diabetes
from sklearn.model_selection import train_test_split, cross_val_score, cross_val_predict, GridSearchCV, KFold, StratifiedKFold
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.dummy import DummyRegressor, DummyClassifier
from sklearn.linear_model import LinearRegression, Ridge, LogisticRegression
from sklearn.ensemble import RandomForestRegressor, RandomForestClassifier
from sklearn.metrics import mean_absolute_error, r2_score, precision_score, recall_score, f1_score, precision_recall_curve, confusion_matrix
def check(name, test):
try:
ok = test()
except NotImplementedError:
print(f'❌ {name}: not implemented yet'); return
except Exception as e:
print(f'❌ {name}: {type(e).__name__}: {e}'); return
print(f'✅ {name}' if ok else f'❌ {name}: wrong result')
data = load_diabetes(as_frame=True)
df = data.frame
df.head()Part A — Explore and Split (15 points)¶
A1 (checked). Split the data into 80% training and 20% test with random_state=42. Return X_train, X_test, y_train, y_test (features as DataFrames, targets as Series).
def split_data(df):
X, y = df.drop(columns='target'), df['target']
# TODO
raise NotImplementedErrorcheck('A1: 353 training and 89 test patients', lambda: [len(p) for p in split_data(df)] == [353, 89, 353, 89])
X_train, X_test, y_train, y_test = split_data(df)A2. Using the training set only, plot the distribution of the target and the correlation of each feature with it. Which three features look most useful? Write two or three sentences.
# TODO: a histogram of y_train, and a bar chart of each feature's correlation with y_trainYour observations:
Part B — Regression (30 points)¶
B1 (checked). A model is only useful if it beats a trivial one. Complete baseline_mae : the mean absolute error, on the given validation data, of always predicting the training mean.
def baseline_mae(y_train, y_valid):
# TODO
raise NotImplementedErrorcheck('B1: the baseline of a toy example', lambda: abs(baseline_mae([1, 2, 3], [2, 4]) - 1.0) < 1e-9)B2. Compare, with 5-fold cross-validation on the training set (scoring: mean absolute error), at least: the baseline (DummyRegressor), linear regression, ridge regression with (alpha) chosen by GridSearchCV, and a random forest. Show a table of the results.
# TODO: cross-validate the candidate models and show a tableB3. Fit your best model on the whole training set and report its MAE and on the test set (once). Explain in one sentence what the MAE means for a doctor.
# TODOInterpretation:
Part C — Flag the High-Risk Patients (35 points)¶
The hospital mostly needs a yes/no answer: will this patient be in the worst quarter?
C1 (checked). Complete make_labels: 1 when the target is above the 75th percentile of the training targets, else 0. (Use the training percentile for both sets: the test set must not influence the threshold.)
def make_labels(y_train, y):
# TODO
raise NotImplementedErrorcheck('C1: a quarter of the training patients are high risk', lambda: abs(make_labels(y_train, y_train).mean() - 0.25) < 0.01)
check('C1: the threshold comes from the training set', lambda: list(make_labels([1, 2, 3, 4, 5, 6, 7, 8], [5, 7, 100])) == [0, 1, 1])C2. Train at least two classifiers (for example logistic regression and a random forest) and compare their cross-validated precision, recall and F1 on the training set.
# TODOC3. Missing a high-risk patient is worse than an extra check-up: the hospital asks for a recall of at least 0.80. Using cross-validated probabilities on the training set, choose the decision threshold that reaches that recall with the best precision. Plot precision and recall against the threshold, then report the confusion matrix on the test set with your threshold.
# TODOPart D — A Model Card (20 points)¶
Write a short report (300–400 words) for the hospital, as a model card:
Purpose: what the model predicts, and for whom.
Data: where it comes from, how many patients, what it lacks.
Performance: your test results in plain words (MAE; precision and recall at your threshold).
Limitations and risks: what could go wrong (small dataset, one population, false alarms, missed patients), and what a doctor must not use it for.
Recommendation: should the hospital use it, and how?
Your model card:
Grading Rubric¶
| Part | Full marks if… |
|---|---|
| A (15) | correct split (checked); a clear exploration with sensible observations |
| B (30) | baseline (checked); at least four models compared fairly by cross-validation; test set used once; a correct interpretation |
| C (35) | labels from the training percentile (checked); two classifiers compared; a threshold chosen on training data that meets the recall target; test confusion matrix |
| D (20) | all five sections, honest about limitations, understandable by a non-specialist |