Project 2: Student Performance Prediction
A group of six secondary schools has counsellors who can meet only a limited number of students each term. Their question: six weeks into the school year, which students are most likely to fail the final exam, so we can offer help early? Today they use a rule of thumb (low attendance or a poor grade last year). The level is beginner; the main skills are binary classification, choosing a threshold for a fixed budget rather than at 0.5, checking that the predicted probabilities are calibrated, auditing results per school and per group of students, interpreting the model with permutation importance, and thinking about what it means to act on a prediction about a teenager.
No earlier lesson built this project. Each technique has its own lesson, linked where it is used: classification metrics, thresholds, calibration, error analysis and slices, fairness checks.
Goal and success criteria
Agreed with the counsellors before any model is trained:
| Criterion | |
|---|---|
| Use | rank students in week 6; counsellors contact the top 15 % of each cohort |
| Primary metric | recall at the 15 % budget: the share of students who will fail that are among those contacted |
| Also reported | precision at the budget, PR-AUC, Brier score (calibration), the same numbers per school and per group |
| Baseline | the current rule: attendance below 85 % or last year's grade below 50 |
| Target | recall at the budget at least 0.10 higher than the rule's recall at the same number of contacts, on the next cohort |
| Fairness check | no school or group whose failing students are reached at less than 0.8 times the overall recall without an explanation |
| Split | train and validate on the 2023 cohort, test once on the 2024 cohort |
The data
Real data would come from the schools' information systems: attendance registers, grades, homework platforms. It is data about minors, which calls for particular care (in the EU the GDPR gives children's data specific protection, Recital 38; in the US FERPA governs student education records): a clear purpose, a legal basis, the shortest retention possible, access only for staff who need it, and transparency towards students and parents; see privacy, consent and licensing. Public anonymised equivalents exist, for example the UCI Student Performance data set (two Portuguese schools, CC BY 4.0).
Here a generator creates two cohorts of 1,500 students each. The risk of failing rises with low attendance in the first six weeks, a low grade last year, missing homework, weak early quiz results and long hours in a part-time job, and differs a little between schools. A free_meals flag (eligibility for free school meals, a common proxy for low family income) is correlated with the other risk factors. It is not a model input: it is kept only to audit the results. A coursework_final column holds the end-of-year coursework mark, which is not known in week 6.
Step 1: explore, and ask when each column is known
import numpy as np
import pandas as pd
def make_students(n=3000, seed=0):
rng = np.random.default_rng(seed)
school = rng.choice(list("ABCDEF"), n, p=[0.2, 0.2, 0.15, 0.15, 0.15, 0.15])
free_meals = rng.random(n) < np.where(np.isin(school, ["C", "D"]), 0.45, 0.2)
ability = rng.normal(0, 1, n) - 0.35 * free_meals
df = pd.DataFrame({
"cohort": np.repeat([2023, 2024], n // 2), "school": school, "free_meals": free_meals,
"attendance_pct": np.clip(np.round(92 + 4 * ability + rng.normal(0, 5, n) - 3 * free_meals), 50, 100),
"prior_grade": np.clip(np.round(62 + 12 * ability + rng.normal(0, 8, n)), 10, 100),
"homework_pct": np.clip(np.round(75 + 10 * ability + rng.normal(0, 15, n)), 0, 100),
"quiz_week6": np.clip(np.round(60 + 10 * ability + rng.normal(0, 12, n)), 0, 100),
"job_hours": np.where(rng.random(n) < 0.3, rng.integers(4, 21, n), 0),
})
school_effect = pd.Series(school).map({"A": 0, "B": -0.2, "C": 0.4, "D": 0.1, "E": -0.4, "F": 0.2}).to_numpy()
logit = (-1.9 - 0.07 * (df.attendance_pct - 92) - 0.04 * (df.prior_grade - 62) - 0.015 * (df.homework_pct - 75)
- 0.03 * (df.quiz_week6 - 60) + 0.05 * df.job_hours + school_effect)
df["fail"] = (rng.random(n) < 1 / (1 + np.exp(-logit))).astype(int)
df["coursework_final"] = np.clip(np.round(55 + 8 * ability - 18 * df.fail + rng.normal(0, 7, n)), 0, 100)
return df
df = make_students()
print(df.head(3).to_string(index=False))
print("\nfail rate by cohort:", df.groupby("cohort").fail.mean().round(3).to_dict())
print("fail rate by school:", df.groupby("school").fail.mean().round(3).to_dict())
print("fail rate by free_meals:", df.groupby("free_meals").fail.mean().round(3).to_dict())
print("free_meals share by school:", df.groupby("school").free_meals.mean().round(2).to_dict())
print("\ncorrelation with fail:")
print(df.drop(columns=["cohort", "school", "free_meals", "fail"]).corrwith(df.fail).round(2).to_string()) cohort school free_meals attendance_pct prior_grade homework_pct quiz_week6 job_hours fail coursework_final
2023 D True 86.0 50.0 53.0 77.0 0 0 50.0
2023 B False 96.0 67.0 71.0 97.0 0 0 57.0
2023 A True 87.0 45.0 60.0 51.0 18 1 26.0
fail rate by cohort: {2023: 0.246, 2024: 0.245}
fail rate by school: {'A': 0.236, 'B': 0.211, 'C': 0.313, 'D': 0.282, 'E': 0.176, 'F': 0.272}
fail rate by free_meals: {False: 0.215, True: 0.329}
free_meals share by school: {'A': 0.23, 'B': 0.25, 'C': 0.38, 'D': 0.41, 'E': 0.17, 'F': 0.2}
correlation with fail:
attendance_pct -0.33
prior_grade -0.39
homework_pct -0.30
quiz_week6 -0.36
job_hours 0.14
coursework_final -0.73
About a quarter of students fail in both cohorts (24.6 % and 24.5 %). Fail rates differ by school (17.6 % in E to 31.3 % in C) and by group: 32.9 % of students with free meals fail against 21.5 % of the others. Schools C and D have the most students with free meals, so part of their higher fail rate is the same effect seen twice. That is exactly why the audit in Step 5 looks at both cuts.
The correlations look encouraging for all five early-term columns (−0.30 to −0.39 for the school measures, 0.14 for job hours). One column stands out: coursework_final at −0.73. It is the end-of-year coursework mark, and it is strongly related to failing because it is part of the same end-of-year result. Ask of every column: would we have it on the day we predict?
| Column | Known in week 6? | Use |
|---|---|---|
attendance_pct, homework_pct, quiz_week6 |
yes, weeks 1-6 only | input |
prior_grade, job_hours, school |
yes | input |
coursework_final |
no, end of year | dropped: leakage |
free_meals |
yes | audit only, never an input |
fail |
end of year | label |
Step 2: split by cohort, baseline and two models
The model trained on one year's students will be used on the next year's, so the test set is the 2024 cohort, used once. The 2023 cohort is split, stratified, into 75 % training and 25 % validation for all choices. Every candidate is scored by recall at the budget: rank the validation students by predicted risk, take the top 15 %, count how many of the students who failed are among them.
First, what the leaky column would do, so that nobody is tempted later. Then the current rule, a Logistic Regression and a gradient-boosted model (HistGradientBoosting).
import numpy as np
import pandas as pd
from sklearn.compose import make_column_transformer
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import average_precision_score, roc_auc_score
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
def make_students(n=3000, seed=0):
rng = np.random.default_rng(seed)
school = rng.choice(list("ABCDEF"), n, p=[0.2, 0.2, 0.15, 0.15, 0.15, 0.15])
free_meals = rng.random(n) < np.where(np.isin(school, ["C", "D"]), 0.45, 0.2)
ability = rng.normal(0, 1, n) - 0.35 * free_meals
df = pd.DataFrame({
"cohort": np.repeat([2023, 2024], n // 2), "school": school, "free_meals": free_meals,
"attendance_pct": np.clip(np.round(92 + 4 * ability + rng.normal(0, 5, n) - 3 * free_meals), 50, 100),
"prior_grade": np.clip(np.round(62 + 12 * ability + rng.normal(0, 8, n)), 10, 100),
"homework_pct": np.clip(np.round(75 + 10 * ability + rng.normal(0, 15, n)), 0, 100),
"quiz_week6": np.clip(np.round(60 + 10 * ability + rng.normal(0, 12, n)), 0, 100),
"job_hours": np.where(rng.random(n) < 0.3, rng.integers(4, 21, n), 0),
})
school_effect = pd.Series(school).map({"A": 0, "B": -0.2, "C": 0.4, "D": 0.1, "E": -0.4, "F": 0.2}).to_numpy()
logit = (-1.9 - 0.07 * (df.attendance_pct - 92) - 0.04 * (df.prior_grade - 62) - 0.015 * (df.homework_pct - 75)
- 0.03 * (df.quiz_week6 - 60) + 0.05 * df.job_hours + school_effect)
df["fail"] = (rng.random(n) < 1 / (1 + np.exp(-logit))).astype(int)
df["coursework_final"] = np.clip(np.round(55 + 8 * ability - 18 * df.fail + rng.normal(0, 7, n)), 0, 100)
return df
NUM = ["attendance_pct", "prior_grade", "homework_pct", "quiz_week6", "job_hours"]
def recall_at(y, score, budget=0.15):
k = int(round(budget * len(y)))
top = np.argsort(-score, kind="stable")[:k]
return y[top].sum() / y.sum(), y[top].mean()
def model(kind, num):
prep = make_column_transformer((StandardScaler(), num), (OneHotEncoder(), ["school"]))
clf = (LogisticRegression(max_iter=1000) if kind == "logreg"
else HistGradientBoostingClassifier(max_iter=200, learning_rate=0.05, max_leaf_nodes=15, random_state=0))
return make_pipeline(prep, clf)
df = make_students()
d23 = df[df.cohort == 2023]
tr, va = train_test_split(d23, test_size=0.25, stratify=d23.fail, random_state=0)
y_va = va.fail.to_numpy()
print(f"train {len(tr)}, validation {len(va)} (2023); budget = top 15 % = {int(round(0.15 * len(va)))} students")
print(f"{'validation':28} {'recall@15%':>10} {'prec@15%':>9} {'PR-AUC':>7} {'ROC-AUC':>8}")
leaky = model("logreg", NUM + ["coursework_final"]).fit(tr, tr.fail).predict_proba(va)[:, 1]
r, p = recall_at(y_va, leaky)
print(f"{'with coursework_final (leak)':28} {r:10.3f} {p:9.3f} {average_precision_score(y_va, leaky):7.3f} {roc_auc_score(y_va, leaky):8.3f}")
for kind in ["logreg", "boosting"]:
s = model(kind, NUM).fit(tr, tr.fail).predict_proba(va)[:, 1]
r, p = recall_at(y_va, s)
print(f"{kind:28} {r:10.3f} {p:9.3f} {average_precision_score(y_va, s):7.3f} {roc_auc_score(y_va, s):8.3f}")
rule = ((va.attendance_pct < 85) | (va.prior_grade < 50)).to_numpy()
s = model("logreg", NUM).fit(tr, tr.fail).predict_proba(va)[:, 1]
r_m, _ = recall_at(y_va, s, budget=rule.mean())
print(f"\ncurrent rule flags {rule.sum()} students ({rule.mean():.1%}): recall {y_va[rule].sum() / y_va.sum():.3f}, "
f"precision {y_va[rule].mean():.3f}")
print(f"logreg with the same number of contacts: recall {r_m:.3f}")train 1125, validation 375 (2023); budget = top 15 % = 56 students
validation recall@15% prec@15% PR-AUC ROC-AUC
with coursework_final (leak) 0.598 0.982 0.925 0.963
logreg 0.424 0.696 0.635 0.816
boosting 0.391 0.643 0.588 0.767
current rule flags 115 students (30.7%): recall 0.609, precision 0.487
logreg with the same number of contacts: recall 0.641
Read the table with one fact in mind: 25 % of students fail but only 15 % can be contacted, so even a perfect ranking reaches at most 56 of the 92 failing validation students, a recall of 0.609. The leaky model gets 0.598, almost the maximum, with 98 % precision: it looks perfect because it uses the answer. It would collapse in week 6, when the column is empty.
Of the honest models, the Logistic Regression is ahead of gradient boosting on every metric (recall 0.424 against 0.391 at the budget, PR-AUC 0.635 against 0.588). The data is small (1,125 training students) and the generator's risk is close to additive in the inputs, which suits a linear model; boosting has more to estimate and no interaction to find. It is chosen.
The current rule flags 115 students, 30.7 % of the cohort: twice what the counsellors can handle, which is part of why they asked for help. At its own number of contacts it reaches 0.609 of the failing students; the model with the same 115 contacts reaches 0.641. The difference is the model's value at the rule's size; its larger value is that it can be cut at any budget, while the rule cannot.
Step 3: the threshold for the budget, and calibration
The ranking decides who is contacted. A counsellor will also read the number: "this student has a 45 % risk" leads to a different conversation than 15 %. So the probabilities must mean what they say: among students given about 30 %, about 30 % should fail. That is calibration, checked with a reliability table and the Brier score.
Try the trade-off first in the lab. Its scores are generic (positives drawn higher than negatives), but the mechanics are the project's: with 20 % positives, slide the threshold until about 15 % of all students are above it and read the recall and precision; then make the classes more or less separable and see how recall at the same budget changes.
The threshold that fills the budget is the 85th percentile of the validation scores. It is fixed now and reused on the 2024 cohort, where it may flag a slightly different share; that is a real effect of a new cohort, and the counsellors want to know about it.
import numpy as np
import pandas as pd
from sklearn.compose import make_column_transformer
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import brier_score_loss
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
def make_students(n=3000, seed=0):
rng = np.random.default_rng(seed)
school = rng.choice(list("ABCDEF"), n, p=[0.2, 0.2, 0.15, 0.15, 0.15, 0.15])
free_meals = rng.random(n) < np.where(np.isin(school, ["C", "D"]), 0.45, 0.2)
ability = rng.normal(0, 1, n) - 0.35 * free_meals
df = pd.DataFrame({
"cohort": np.repeat([2023, 2024], n // 2), "school": school, "free_meals": free_meals,
"attendance_pct": np.clip(np.round(92 + 4 * ability + rng.normal(0, 5, n) - 3 * free_meals), 50, 100),
"prior_grade": np.clip(np.round(62 + 12 * ability + rng.normal(0, 8, n)), 10, 100),
"homework_pct": np.clip(np.round(75 + 10 * ability + rng.normal(0, 15, n)), 0, 100),
"quiz_week6": np.clip(np.round(60 + 10 * ability + rng.normal(0, 12, n)), 0, 100),
"job_hours": np.where(rng.random(n) < 0.3, rng.integers(4, 21, n), 0),
})
school_effect = pd.Series(school).map({"A": 0, "B": -0.2, "C": 0.4, "D": 0.1, "E": -0.4, "F": 0.2}).to_numpy()
logit = (-1.9 - 0.07 * (df.attendance_pct - 92) - 0.04 * (df.prior_grade - 62) - 0.015 * (df.homework_pct - 75)
- 0.03 * (df.quiz_week6 - 60) + 0.05 * df.job_hours + school_effect)
df["fail"] = (rng.random(n) < 1 / (1 + np.exp(-logit))).astype(int)
df["coursework_final"] = np.clip(np.round(55 + 8 * ability - 18 * df.fail + rng.normal(0, 7, n)), 0, 100)
return df
NUM = ["attendance_pct", "prior_grade", "homework_pct", "quiz_week6", "job_hours"]
def model(kind):
prep = make_column_transformer((StandardScaler(), NUM), (OneHotEncoder(), ["school"]))
clf = (LogisticRegression(max_iter=1000) if kind == "logreg"
else HistGradientBoostingClassifier(max_iter=200, learning_rate=0.05, max_leaf_nodes=15, random_state=0))
return make_pipeline(prep, clf)
df = make_students()
d23 = df[df.cohort == 2023]
tr, va = train_test_split(d23, test_size=0.25, stratify=d23.fail, random_state=0)
for kind in ["logreg", "boosting"]:
p = model(kind).fit(tr, tr.fail).predict_proba(va)[:, 1]
print(f"{kind}: Brier {brier_score_loss(va.fail, p):.4f} (always predicting the base rate: "
f"{brier_score_loss(va.fail, np.full(len(va), tr.fail.mean())):.4f})")
bins = pd.cut(p, [0, 0.05, 0.1, 0.2, 0.35, 0.5, 1.0])
table = pd.DataFrame({"p": p, "y": va.fail.to_numpy()}).groupby(bins, observed=True).agg(
n=("y", "size"), predicted=("p", "mean"), observed=("y", "mean"))
print(table.round(3).to_string(), "\n")
p = model("logreg").fit(tr, tr.fail).predict_proba(va)[:, 1]
threshold = float(np.quantile(p, 0.85))
print(f"threshold for the 15 % budget (logreg, validation): {threshold:.3f}")
print(f"flagged on validation: {(p >= threshold).mean():.1%}, mean predicted risk of the flagged: {p[p >= threshold].mean():.2f}, "
f"observed fail rate among them: {va.fail.to_numpy()[p >= threshold].mean():.2f}")logreg: Brier 0.1357 (always predicting the base rate: 0.1851)
n predicted observed
(0.0, 0.05] 53 0.031 0.019
(0.05, 0.1] 68 0.072 0.088
(0.1, 0.2] 99 0.147 0.141
(0.2, 0.35] 60 0.260 0.333
(0.35, 0.5] 42 0.417 0.310
(0.5, 1.0] 53 0.682 0.717
boosting: Brier 0.1491 (always predicting the base rate: 0.1851)
n predicted observed
(0.0, 0.05] 100 0.022 0.090
(0.05, 0.1] 55 0.074 0.091
(0.1, 0.2] 70 0.144 0.229
(0.2, 0.35] 58 0.266 0.207
(0.35, 0.5] 32 0.420 0.312
(0.5, 1.0] 60 0.723 0.667
threshold for the 15 % budget (logreg, validation): 0.486
flagged on validation: 15.2%, mean predicted risk of the flagged: 0.67, observed fail rate among them: 0.70
The Logistic Regression is reasonably calibrated: in each band the observed fail rate is near the mean predicted risk (for example 0.147 predicted, 0.141 observed in the 10-20 % band). The bands hold 42 to 99 students, so differences of a few points (0.417 predicted against 0.310 observed in the 35-50 % band, 42 students) are within sampling noise and not a reason to recalibrate. Its Brier score is 0.1357, against 0.1851 for predicting the base rate for everyone. The boosting model is worse calibrated at the bottom: among the 100 students it gives about 2 % risk, 9 % fail. If a counsellor said "your risk is 2 %" to those students, the number would be wrong by a factor of four; a reason, besides the ranking, to keep the Logistic Regression (calibration shows how to fix such a model with Platt or isotonic scaling).
The budget threshold is 0.486. Among the 15.2 % of validation students above it, the mean predicted risk is 0.67 and the observed fail rate 0.70: the counsellors can say "about two in three students on this list would fail without help" and be right.
Step 4: what drives the ranking
Counsellors will ask why a student is on the list. Two levels of answer: for the model as a whole, permutation importance on the validation set (shuffle one column, measure how much recall at the budget and PR-AUC drop); for one student, the inputs that are unusual compared with the cohort. Both describe the model, not the causes of failing: a model can rely on a symptom (low quiz marks) as much as on a cause.
import numpy as np
import pandas as pd
from sklearn.compose import make_column_transformer
from sklearn.inspection import permutation_importance
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
def make_students(n=3000, seed=0):
rng = np.random.default_rng(seed)
school = rng.choice(list("ABCDEF"), n, p=[0.2, 0.2, 0.15, 0.15, 0.15, 0.15])
free_meals = rng.random(n) < np.where(np.isin(school, ["C", "D"]), 0.45, 0.2)
ability = rng.normal(0, 1, n) - 0.35 * free_meals
df = pd.DataFrame({
"cohort": np.repeat([2023, 2024], n // 2), "school": school, "free_meals": free_meals,
"attendance_pct": np.clip(np.round(92 + 4 * ability + rng.normal(0, 5, n) - 3 * free_meals), 50, 100),
"prior_grade": np.clip(np.round(62 + 12 * ability + rng.normal(0, 8, n)), 10, 100),
"homework_pct": np.clip(np.round(75 + 10 * ability + rng.normal(0, 15, n)), 0, 100),
"quiz_week6": np.clip(np.round(60 + 10 * ability + rng.normal(0, 12, n)), 0, 100),
"job_hours": np.where(rng.random(n) < 0.3, rng.integers(4, 21, n), 0),
})
school_effect = pd.Series(school).map({"A": 0, "B": -0.2, "C": 0.4, "D": 0.1, "E": -0.4, "F": 0.2}).to_numpy()
logit = (-1.9 - 0.07 * (df.attendance_pct - 92) - 0.04 * (df.prior_grade - 62) - 0.015 * (df.homework_pct - 75)
- 0.03 * (df.quiz_week6 - 60) + 0.05 * df.job_hours + school_effect)
df["fail"] = (rng.random(n) < 1 / (1 + np.exp(-logit))).astype(int)
df["coursework_final"] = np.clip(np.round(55 + 8 * ability - 18 * df.fail + rng.normal(0, 7, n)), 0, 100)
return df
NUM = ["attendance_pct", "prior_grade", "homework_pct", "quiz_week6", "job_hours"]
df = make_students()
d23 = df[df.cohort == 2023]
tr, va = train_test_split(d23, test_size=0.25, stratify=d23.fail, random_state=0)
pipe = make_pipeline(make_column_transformer((StandardScaler(), NUM), (OneHotEncoder(), ["school"])),
LogisticRegression(max_iter=1000)).fit(tr, tr.fail)
def recall_at_budget(est, X, y):
s = est.predict_proba(X)[:, 1]
top = np.argsort(-s, kind="stable")[:int(round(0.15 * len(y)))]
return y.to_numpy()[top].sum() / y.sum()
cols = NUM + ["school"]
imp = permutation_importance(pipe, va[cols], va.fail, scoring={"recall@15%": recall_at_budget, "PR-AUC": "average_precision"},
n_repeats=20, random_state=0)
table = pd.DataFrame({k: v.importances_mean for k, v in imp.items()}, index=cols).sort_values("PR-AUC", ascending=False)
print("drop in the score when a column is shuffled (validation, 20 repeats):")
print(table.round(3).to_string())
coef = pd.Series(pipe[-1].coef_[0][:len(NUM)], index=NUM)
print("\nlogistic coefficients per standard deviation:", coef.round(2).to_dict())
s = pipe.predict_proba(va)[:, 1]
i = int(np.argsort(-s, kind="stable")[5])
student = va.iloc[i]
z = (student[NUM] - tr[NUM].mean()) / tr[NUM].std()
print(f"\nflagged student (risk {s[i]:.2f}): " + ", ".join(f"{c} {student[c]:g} ({z[c]:+.1f} sd)" for c in NUM))drop in the score when a column is shuffled (validation, 20 repeats):
recall@15% PR-AUC
prior_grade 0.093 0.142
quiz_week6 0.037 0.047
job_hours 0.026 0.033
attendance_pct 0.021 0.029
homework_pct 0.010 0.019
school 0.005 0.013
logistic coefficients per standard deviation: {'attendance_pct': -0.28, 'prior_grade': -0.63, 'homework_pct': -0.21, 'quiz_week6': -0.49, 'job_hours': 0.44}
flagged student (risk 0.88): attendance_pct 73 (-2.9 sd), prior_grade 32 (-2.0 sd), homework_pct 43 (-1.8 sd), quiz_week6 30 (-1.8 sd), job_hours 13 (+1.5 sd)
Last year's grade matters most: shuffling it costs 0.093 of recall at the budget and 0.142 of PR-AUC. The week-6 quiz comes next, then job hours and attendance; homework and the school matter least. The coefficients (per standard deviation of each input) tell the same story with signs: a higher grade, quiz mark, attendance and homework lower the risk, and more job hours raise it (+0.44). The importance of school is small because school differences are modest next to the individual measures.
For one student on the list (risk 0.88), the explanation a counsellor can use is the list of inputs far from the cohort: attendance 73 % (2.9 standard deviations below the average), last year's grade 32, homework 43 %, quiz 30, and 13 hours a week in a job. Most of these are things a conversation can address. The importances are about the model on generated data; on real data, check them against what teachers know before trusting either.
Step 5: test once on the next cohort, per school and per group
The model (Logistic Regression, refitted on the whole 2023 cohort) and the threshold (from Step 3) are frozen. The 2024 cohort is scored once. Besides the overall numbers, the table is cut by school and by free_meals: how many students are flagged, and what share of the failing students is reached.
import numpy as np
import pandas as pd
from sklearn.compose import make_column_transformer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import average_precision_score, brier_score_loss
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
def make_students(n=3000, seed=0):
rng = np.random.default_rng(seed)
school = rng.choice(list("ABCDEF"), n, p=[0.2, 0.2, 0.15, 0.15, 0.15, 0.15])
free_meals = rng.random(n) < np.where(np.isin(school, ["C", "D"]), 0.45, 0.2)
ability = rng.normal(0, 1, n) - 0.35 * free_meals
df = pd.DataFrame({
"cohort": np.repeat([2023, 2024], n // 2), "school": school, "free_meals": free_meals,
"attendance_pct": np.clip(np.round(92 + 4 * ability + rng.normal(0, 5, n) - 3 * free_meals), 50, 100),
"prior_grade": np.clip(np.round(62 + 12 * ability + rng.normal(0, 8, n)), 10, 100),
"homework_pct": np.clip(np.round(75 + 10 * ability + rng.normal(0, 15, n)), 0, 100),
"quiz_week6": np.clip(np.round(60 + 10 * ability + rng.normal(0, 12, n)), 0, 100),
"job_hours": np.where(rng.random(n) < 0.3, rng.integers(4, 21, n), 0),
})
school_effect = pd.Series(school).map({"A": 0, "B": -0.2, "C": 0.4, "D": 0.1, "E": -0.4, "F": 0.2}).to_numpy()
logit = (-1.9 - 0.07 * (df.attendance_pct - 92) - 0.04 * (df.prior_grade - 62) - 0.015 * (df.homework_pct - 75)
- 0.03 * (df.quiz_week6 - 60) + 0.05 * df.job_hours + school_effect)
df["fail"] = (rng.random(n) < 1 / (1 + np.exp(-logit))).astype(int)
df["coursework_final"] = np.clip(np.round(55 + 8 * ability - 18 * df.fail + rng.normal(0, 7, n)), 0, 100)
return df
NUM = ["attendance_pct", "prior_grade", "homework_pct", "quiz_week6", "job_hours"]
make = lambda: make_pipeline(make_column_transformer((StandardScaler(), NUM), (OneHotEncoder(), ["school"])),
LogisticRegression(max_iter=1000))
df = make_students()
d23, d24 = df[df.cohort == 2023], df[df.cohort == 2024]
tr, va = train_test_split(d23, test_size=0.25, stratify=d23.fail, random_state=0)
threshold = float(np.quantile(make().fit(tr, tr.fail).predict_proba(va)[:, 1], 0.85)) # Step 3
final = make().fit(d23, d23.fail) # whole 2023 cohort
p = final.predict_proba(d24)[:, 1] # the one look at 2024
t = d24.assign(risk=p, flagged=p >= threshold, rule=(d24.attendance_pct < 85) | (d24.prior_grade < 50))
fails = t.fail.sum()
print(f"2024 cohort: {len(t)} students, {fails} failed ({t.fail.mean():.1%})")
print(f"model: flagged {t.flagged.sum()} ({t.flagged.mean():.1%}), recall {t[t.flagged].fail.sum() / fails:.3f}, "
f"precision {t[t.flagged].fail.mean():.3f}, PR-AUC {average_precision_score(t.fail, p):.3f}, "
f"Brier {brier_score_loss(t.fail, p):.4f}")
same_k = t.nlargest(int(t.rule.sum()), "risk")
print(f"rule: flagged {t.rule.sum()} ({t.rule.mean():.1%}), recall {t[t.rule].fail.sum() / fails:.3f}; "
f"model with the same {t.rule.sum()} contacts: recall {same_k.fail.sum() / fails:.3f}")
def slices(col):
g = t.groupby(col)
out = pd.DataFrame({"students": g.size(), "fail_rate": g.fail.mean(), "flag_rate": g.flagged.mean(),
"recall": g.apply(lambda x: x[x.flagged].fail.sum() / max(x.fail.sum(), 1), include_groups=False),
"precision": g.apply(lambda x: x[x.flagged].fail.mean(), include_groups=False),
"mean_risk": g.risk.mean()})
return out.round(3).to_string()
print("\nby school:\n" + slices("school"))
print("\nby free_meals (audit column, not an input):\n" + slices("free_meals"))2024 cohort: 1500 students, 367 failed (24.5%)
model: flagged 215 (14.3%), recall 0.387, precision 0.660, PR-AUC 0.588, Brier 0.1407
rule: flagged 433 (28.9%), recall 0.540; model with the same 433 contacts: recall 0.608
by school:
students fail_rate flag_rate recall precision mean_risk
school
A 322 0.245 0.115 0.304 0.649 0.225
B 310 0.203 0.106 0.302 0.576 0.215
C 238 0.303 0.248 0.514 0.627 0.328
D 203 0.300 0.177 0.459 0.778 0.265
E 211 0.152 0.071 0.312 0.667 0.163
F 216 0.278 0.162 0.400 0.686 0.258
by free_meals (audit column, not an input):
students fail_rate flag_rate recall precision mean_risk
free_meals
False 1103 0.206 0.101 0.317 0.649 0.210
True 397 0.353 0.262 0.500 0.673 0.325
The 2024 result, against the criteria written at the start:
- Budget and recall. The frozen threshold flags 215 students (14.3 %, a little under the 15 % budget) and reaches 0.387 of the 367 who failed, with precision 0.660 (validation: 0.424). The maximum possible at this size is 215 / 367 = 0.586. Calibration held (Brier 0.1407).
- Against the rule: target missed. With the rule's 433 contacts, the model reaches 0.608 of the failing students against the rule's 0.540: +0.068, short of the +0.10 agreed in advance. The model is better, but not by the margin the counsellors asked for.
- Fairness check: two schools below the line. Overall recall is 0.387; schools A (0.304) and B (0.302) reach about 0.78 of it, below the 0.8 limit, and E sits just above (0.312). These are the schools with the lowest fail rates: with one global threshold, their failing students have less extreme profiles and fall below it, so their flag rate is low (7-12 %). Students with free meals are flagged far more often (26.2 % against 10.1 %), which matches their higher fail rate (35.3 % against 20.6 %), and their recall is higher, not lower. That is consistent with the data, but it means the list will over-represent poorer families, and the schools must be ready to explain it.
The honest conclusion is not "the model works", but: it ranks better than the rule, fits any budget and is calibrated; it misses the agreed margin, and it under-serves the failing students of schools A and B under a single threshold. The next decision belongs to the counsellors: a one-term pilot with per-school budgets (see the extensions), evaluated on the following cohort, rather than a launch. Changing the criteria now, to declare success, is the one option that is ruled out.
Acting on the predictions
A risk score about a teenager is not a neutral number. A few rules the project adopts, and the reasons:
- Support, never sanction. The list leads to an offer of help (a meeting, tutoring, a check on the part-time job). It must never feed into grades, streaming, discipline or admissions, or it changes the behaviour it measures and punishes students for their circumstances.
- No labels in records. The risk score lives in the counsellors' tool for the current term and is deleted afterwards. A "predicted to fail" flag that follows a student is a self-fulfilling prophecy in the making.
- The feedback loop. If counselling works, contacted students fail less often, and next year's training data shows their profile as "safer" than it is. Keep a record of who was contacted, and evaluate (and retrain) with that in mind; ideally compare with a period or a group where the rule of thumb was still used.
- Audit by group, every term, with the free-meals flag and any other attribute the schools are allowed to hold for that purpose, and publish the result to the schools' governance board (governance).
- Explain it to students and parents in plain words: what data is used, for what, who sees it, and how to object.
Extensions
- Replace the single validation split by stratified 5-fold cross-validation on 2023 and report the spread of recall at the budget: stratified and group CV.
- Train on 2023 and test on 2024 with schools held out (group split): does the model transfer to a seventh school that joins the group? external validation.
- Add a calibrated gradient-boosting model and compare it at the same budget: calibration.
- Give each school its own budget (counsellors per school) and choose a threshold per school; compare recall with the global threshold.
- Write the model card: purpose, data, metrics per slice, limits, contact: governance.
Write-up template
Project: early-warning list, <schools>, <term>
Use: who acts on the list, what they offer, budget (<x> % of students)
Data: source systems, legal basis, retention, who can see the scores
Inputs known at prediction time: <list>; excluded columns and why: <list>
Split: train/validate <cohort>, test <cohort> (once)
Baseline rule: <rule>, recall <x> at <n> contacts
Model: <model>, threshold <x> (from validation), test recall <x>, precision <x>, Brier <x>
Calibration: <reliability table summary>
Slices: lowest recall <slice> <x> vs overall <x>; explanation
Risks and safeguards: <support only, deletion, feedback loop, audits>Practice
- A teacher suggests adding the midterm grade (week 14) as an input "because it is the best predictor". When is that a good idea?
Answer
Only for a second model used at week 14. At week 6 the column does not exist, so a model trained with it cannot be used when the list is needed; scoring it in week 6 with the column missing or imputed would give misleading risks. A common design is two models, one per checkpoint, each trained only on the columns known at its date.
- Overall recall at the budget dropped from 0.424 on validation to 0.387 on the 2024 cohort. Is the model getting worse?
Answer
Not necessarily. The validation set has 92 failing students, so one student changes recall by about 0.011; a drop of 0.037 is three or four students. Part of the drop is also mechanical: the frozen threshold flagged 14.3 % of 2024 instead of 15 %. To know whether it is noise, bootstrap the validation recall or use cross-validation (see holdout and k-fold).
- Why is
free_mealsnot an input, if it is correlated with failing?
Answer
Because using family income to decide who gets attention would be judging students by their circumstances, and in many places using such data for this purpose is not allowed. Its effect on failing goes mostly through attendance, grades and homework, which the model already sees. Keeping it out of the model but in the audit lets the schools check what the model does to that group (here: flagged more often, matching a higher fail rate, with no loss of recall).
Test yourself
A model that includes coursework_final reaches recall 0.598 at the budget on validation, almost the maximum of 0.609. What should you conclude?
- Use it: it is the best model
- It leaks: the column is only known at the end of the year, so the model cannot be used in week 6
- Recall cannot be that high, so there is a bug in the metric
- Drop the other inputs
Only 15 % of students can be contacted and 24.5 % fail. What is the highest recall any ranking could reach?
- 1.0
- About 0.61
- 0.15
- 0.245
Why does a counselling tool need calibrated probabilities, not only a good ranking?
- Calibration improves recall
- Counsellors read and repeat the number; a 2 % risk that is really 9 % misleads students and staff
- Calibration is required for the threshold to exist
- Uncalibrated models cannot be ranked
On the 2024 cohort the model beat the rule by 0.068 recall, but the agreed target was 0.10. What is the right next step?
- Lower the target to 0.05 and declare success
- Retune the model on the 2024 cohort until it passes
- Report the miss, and propose a pilot with changes (such as per-school budgets) evaluated on a new cohort
- Abandon machine learning