Roughly one in nine diabetic hospital stays in the dataset below ends with the patient back in hospital within 30 days. Readmissions are expensive, often preventable, and in the US Medicare penalises hospitals with excess readmissions for several common conditions. So the question a hospital actually asks is simple: at discharge, which patients should get extra follow-up?
This tutorial answers that question end to end in Python, on a real public dataset of about 100,000 hospital encounters. You will clean the data, engineer features, avoid a common evaluation mistake, compare two models, and turn the scores into risk tiers a care team could use. Every number in this post comes from running the code shown.
What you'll build
- A model that predicts 30-day readmission from information available at discharge
- An honest evaluation: patient-level train/test split, ROC AUC, precision-recall AUC, calibration
- Risk tiers (Low / Medium / High / Very high) with the actual readmission rate in each
- A check of which features drive predictions and whether the model works equally well across age groups
Requirements: Python 3.10+, pandas and scikit-learn (tested with pandas 3.0 and scikit-learn 1.8). Install with pip install pandas scikit-learn. The full script runs in under two minutes on a laptop.
1. The dataset
We use the Diabetes 130-US Hospitals (1999–2008) dataset from the UCI Machine Learning Repository, originally published by Strack et al. (2014) in BioMed Research International. It has 101,766 inpatient encounters for diabetic patients with 50 columns: demographics, admission and discharge details, lab test counts, up to three diagnosis codes, 23 diabetes medications, and the outcome.
Download the zip, extract diabetic_data.csv next to your script, and load it. Missing values are stored as ?.
import numpy as np
import pandas as pd
from sklearn.model_selection import GroupShuffleSplit
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler, OrdinalEncoder
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.metrics import roc_auc_score, average_precision_score, brier_score_loss
from sklearn.inspection import permutation_importance
SEED = 42
# ---- 1. Load ------------------------------------------------------------
df = pd.read_csv("diabetic_data.csv", na_values="?", low_memory=False)
print("raw", df.shape)
The readmitted column has three values: NO (54,864), >30 days (35,545) and <30 days (11,357). Hospitals care about the 30-day window, so our target is <30 versus everything else.
2. Clean the data
Two cleaning steps matter. First, patients who died in hospital or were discharged to hospice cannot be readmitted, so keeping them teaches the model something meaningless. In this dataset those are discharge disposition codes 11, 19, 20 and 21 (expired) and 13 and 14 (hospice). Second, a handful of rows have an invalid gender value.
# ---- 2. Clean -----------------------------------------------------------
# Patients who died or went to hospice can't be readmitted -> remove them
df = df[~df["discharge_disposition_id"].isin([11, 13, 14, 19, 20, 21])]
df = df[df["gender"] != "Unknown/Invalid"]
df["target"] = (df["readmitted"] == "<30").astype(int)
print("clean", df.shape, "positive rate", round(df.target.mean(), 4))
clean (99340, 51) positive rate 0.1139
That leaves 99,340 encounters with an 11.4% readmission rate. This imbalance shapes how we evaluate the model later: a model that predicts "no readmission" for everyone is 88.6% accurate and completely useless, so accuracy is off the table.
3. Engineer features
The raw columns need some work before a model can use them well:
- Diagnosis codes are ICD-9 codes with around 700 distinct values each. We group them into nine clinical categories (circulatory, respiratory, diabetes and so on), following the grouping in the original paper.
- Age comes as a band like
[70-80); we keep the lower bound as a number. - Prior visits: outpatient, emergency and inpatient visits in the year before admission, plus their total. Past utilisation is usually the strongest readmission signal.
- Medical specialty of the admitting physician has about 70 values and is missing for half the rows; we keep the top 10 and group the rest.
- Medication changes: how many of the common diabetes drugs were adjusted up or down during the stay.
We deliberately drop weight (97% missing) and payer_code (about 40% missing, and insurance type is a fairness concern in a care-allocation model).
# ---- 3. Features --------------------------------------------------------
def icd9_group(code):
if pd.isna(code):
return "missing"
if code.startswith(("V", "E")):
return "other"
c = float(code)
if 390 <= c <= 459 or c == 785: return "circulatory"
if 460 <= c <= 519 or c == 786: return "respiratory"
if 520 <= c <= 579 or c == 787: return "digestive"
if int(c) == 250: return "diabetes"
if 800 <= c <= 999: return "injury"
if 710 <= c <= 739: return "musculoskeletal"
if 580 <= c <= 629 or c == 788: return "genitourinary"
if 140 <= c <= 239: return "neoplasms"
return "other"
for col in ["diag_1", "diag_2", "diag_3"]:
df[col + "_grp"] = df[col].apply(icd9_group)
df["age_num"] = df["age"].str.extract(r"\[(\d+)").astype(int) # "[70-80)" -> 70
df["prior_visits"] = df[["number_outpatient", "number_emergency", "number_inpatient"]].sum(axis=1)
top_spec = df["medical_specialty"].value_counts().index[:10]
df["specialty"] = df["medical_specialty"].where(df["medical_specialty"].isin(top_spec), "Other").fillna("Missing")
med_cols = ["metformin", "glipizide", "glyburide", "pioglitazone", "rosiglitazone", "glimepiride", "insulin"]
df["n_med_changes"] = df[med_cols].isin(["Up", "Down"]).sum(axis=1)
numeric = ["time_in_hospital", "num_lab_procedures", "num_procedures", "num_medications",
"number_outpatient", "number_emergency", "number_inpatient", "number_diagnoses",
"age_num", "prior_visits", "n_med_changes"]
categorical = ["gender", "admission_type_id", "discharge_disposition_id", "admission_source_id",
"specialty", "diag_1_grp", "diag_2_grp", "diag_3_grp",
"max_glu_serum", "A1Cresult", "change", "diabetesMed"] + med_cols
for c in categorical:
df[c] = df[c].astype(str)
X, y, groups = df[numeric + categorical], df["target"], df["patient_nbr"]
4. Split by patient, not by row
This is the step most tutorials on this dataset get wrong. The 101,766 encounters belong to only 71,518 patients, and some patients appear dozens of times. A random row split puts the same patient in both training and test sets, so the model can partly recognise the patient instead of learning general patterns. In production the model will score patients it has never seen, so the test set should contain only unseen patients too.
GroupShuffleSplit keeps every encounter of a given patient on the same side of the split:
# ---- 4. Split by PATIENT, not by row -------------------------------------
gss = GroupShuffleSplit(n_splits=1, test_size=0.2, random_state=SEED)
tr, te = next(gss.split(X, y, groups))
X_tr, X_te, y_tr, y_te = X.iloc[tr], X.iloc[te], y.iloc[tr], y.iloc[te]
print("train", X_tr.shape, "test", X_te.shape,
"patient overlap", len(set(groups.iloc[tr]) & set(groups.iloc[te])))
train (79567, 30) test (19773, 30) patient overlap 0
To be transparent: I also ran an ordinary random split, and on this dataset it gave almost the same ROC AUC (0.678 vs 0.679). That's because 77% of patients have only one encounter, so there isn't much to leak. On datasets with more repeat visits, the gap can be large. Splitting by patient costs nothing and protects you when it does matter, so make it a habit.
5. Train two models
We compare a logistic regression baseline, which is transparent and easy to explain to clinicians, with a histogram gradient boosting classifier, which handles non-linear effects and interactions automatically. Both are wrapped in scikit-learn pipelines so preprocessing is fitted on training data only.
For evaluation we report ROC AUC, precision-recall AUC (more informative when positives are rare; a random model scores about 0.11 here), the Brier score (how well the predicted probabilities match reality; lower is better), and what happens if the care team follows up the top 10% riskiest discharges.
# ---- 5. Models ----------------------------------------------------------
logreg = Pipeline([
("prep", ColumnTransformer([
("num", StandardScaler(), numeric),
("cat", OneHotEncoder(handle_unknown="ignore", min_frequency=50), categorical)])),
("clf", LogisticRegression(max_iter=2000, class_weight="balanced")),
])
hgb = Pipeline([
("prep", ColumnTransformer([
("num", "passthrough", numeric),
("cat", OrdinalEncoder(handle_unknown="use_encoded_value", unknown_value=-1), categorical)])),
("clf", HistGradientBoostingClassifier(
categorical_features=list(range(len(numeric), len(numeric) + len(categorical))),
learning_rate=0.05, max_iter=400, max_leaf_nodes=31, l2_regularization=1.0,
early_stopping=True, validation_fraction=0.1, random_state=SEED)),
])
def evaluate(name, model):
model.fit(X_tr, y_tr)
p = model.predict_proba(X_te)[:, 1]
top = p >= np.quantile(p, 0.9) # flag the riskiest 10% of discharges
res = dict(model=name,
roc_auc=roc_auc_score(y_te, p),
pr_auc=average_precision_score(y_te, p),
brier=brier_score_loss(y_te, p),
top10_precision=y_te[top].mean(),
top10_recall=y_te[top].sum() / y_te.sum())
print({k: (round(float(v), 3) if k != "model" else v) for k, v in res.items()})
return p
p_lr = evaluate("logistic_regression", logreg)
p_hgb = evaluate("hist_gradient_boosting", hgb)
print("base rate (test)", round(y_te.mean(), 4))
{'model': 'logistic_regression', 'roc_auc': 0.672, 'pr_auc': 0.226, 'brier': 0.225, 'top10_precision': 0.262, 'top10_recall': 0.231}
{'model': 'hist_gradient_boosting', 'roc_auc': 0.679, 'pr_auc': 0.242, 'brier': 0.095, 'top10_precision': 0.287, 'top10_recall': 0.253}
base rate (test) 0.1135
| Metric | Logistic regression | Gradient boosting |
|---|---|---|
| ROC AUC | 0.672 | 0.679 |
| PR AUC (random ≈ 0.11) | 0.226 | 0.242 |
| Brier score (lower is better) | 0.225 | 0.095 |
| Readmission rate in top 10% | 26.2% | 28.7% |
| Share of all readmissions caught by top 10% | 23.1% | 25.3% |
How to read these results
The models are useful but modest. An AUC around 0.68 is a realistic result for this data. The dataset has nothing about what happens after discharge (social support, follow-up appointments, whether prescriptions are filled), and those drive a lot of readmissions. If you ever see an AUC near 0.9 on this dataset, look for leakage before celebrating.
Ranking matters more than raw AUC here. Among the 10% of patients the boosting model flags as riskiest, 28.7% are readmitted: 2.5 times the base rate. A follow-up programme aimed at that group catches a quarter of all readmissions while calling only a tenth of patients.
Watch the Brier score of the logistic regression. Its ranking is nearly as good, but class_weight="balanced" inflates its probabilities, so a patient with a true 10% risk might be shown as 40%. If clinicians will see the probability itself, not just a rank, remove the class weighting or calibrate the model (for example with CalibratedClassifierCV). The boosting model, trained without weighting, is already reasonably calibrated.
6. What drives the predictions?
Permutation importance measures how much the test AUC drops when one feature is shuffled. It works for any model and is computed on held-out data, so it reflects what the model actually relies on.
# ---- 6. What drives the prediction? -------------------------------------
imp = permutation_importance(hgb, X_te, y_te, scoring="roc_auc", n_repeats=5, random_state=SEED, n_jobs=-1)
print(pd.Series(imp.importances_mean, index=X_te.columns).sort_values(ascending=False).head(8).round(4))
discharge_disposition_id 0.0557
number_inpatient 0.0547
diag_1_grp 0.0062
prior_visits 0.0045
specialty 0.0040
number_diagnoses 0.0036
diag_3_grp 0.0034
diabetesMed 0.0021
Two features dominate. Prior inpatient admissions is the classic readmission predictor: patients who were in hospital recently tend to come back. Discharge disposition (home, home with nursing, skilled nursing facility, and so on) captures how sick and supported the patient is when they leave. Both are known at discharge, so the model is usable at the moment the decision is made. Interestingly, neither the HbA1c result nor any single diabetes medication makes the top eight once utilisation is known.
7. Turn scores into risk tiers
Care teams don't act on probabilities; they act on lists. Cutting the score into tiers makes the model operational:
# ---- 7. Risk tiers ------------------------------------------------------
tiers = pd.qcut(p_hgb, [0, .5, .8, .9, 1.0], labels=["Low", "Medium", "High", "Very high"])
print(pd.DataFrame({"tier": tiers, "y": y_te.values}).groupby("tier", observed=True)["y"]
.agg(patients="size", readmit_rate="mean").round(3))
| Risk tier | Patients (test set) | Actual 30-day readmission rate |
|---|---|---|
| Low (bottom 50%) | 9,887 | 6.5% |
| Medium (50th–80th percentile) | 5,931 | 11.7% |
| High (80th–90th) | 1,977 | 16.9% |
| Very high (top 10%) | 1,978 | 28.7% |
The Very high tier is readmitted 4.4 times as often as the Low tier. A realistic workflow: Very high patients get a pharmacist medication review and a follow-up call within 48 hours; High patients get a scheduled clinic visit within a week; everyone else gets standard discharge instructions. The tier cut-offs should be set by how many patients the team can actually follow up, not by the model.
8. Check performance across groups
A model that works well on average can still fail a subgroup. Before deployment, check performance for groups the model will be used on:
# ---- 8. Does it work equally well across age groups? --------------------
age_band = pd.cut(X_te["age_num"], [0, 50, 70, 100], right=False, labels=["<50", "50-69", "70+"])
for band in age_band.cat.categories:
m = (age_band == band).values
print("AUC", band, round(roc_auc_score(y_te[m], p_hgb[m]), 3), "n", m.sum())
AUC <50 0.721 n 3198
AUC 50-69 0.699 n 7823
AUC 70+ 0.641 n 8752
The model is noticeably weaker for patients aged 70 and over, who are also the largest group. Older patients' readmissions depend more on frailty, living situation and multiple chronic conditions, which this dataset only partly captures. In practice you would either add features that describe those factors or give clinicians more discretion when scoring older patients. The same check should be repeated for sex, race, and admission source.
From notebook to hospital: what changes in production
- Data pipeline: the features come from the EHR (admissions, diagnoses, medication orders) and the data warehouse (prior-year utilisation). Scoring runs as part of the discharge workflow, so features must be available before the patient leaves, not coded weeks later.
- Monitoring: track the readmission rate per tier every month. Coding practice changes (for example the move from ICD-9 to ICD-10 in 2015, which would break the diagnosis grouping above) can silently degrade the model.
- Evaluation over time: a real validation trains on earlier years and tests on later ones. This dataset doesn't include dates, which is one of its limitations.
- Clinical review: a model like this supports decisions; it does not make them. Clinicians should be able to see the main reasons behind a patient's score.
Summary
With about 120 lines of Python you can build a readmission model that flags a tenth of discharges and finds a quarter of all 30-day readmissions among them. The key lessons carry over to most healthcare prediction work: drop patients who can't have the outcome, split by patient, use PR AUC and calibration instead of accuracy, turn scores into tiers people can act on, and check how the model performs for each group before trusting it.
Full script: the code blocks above, in order, form the complete script. Run them top to bottom with diabetic_data.csv in the same folder.
Dataset reference: Strack B, DeShazo JP, Gennings C, et al. Impact of HbA1c Measurement on Hospital Readmission Rates: Analysis of 70,000 Clinical Database Patient Records. BioMed Research International, 2014.
Comments
Post a Comment