The First Assignment: an End-to-End Classifier
This is the curriculum's "first practical assignment", done in full: twelve steps from a raw table to a saved model that a separate program loads to score new applications, with a write-up at the end. You met a shorter version in the ML Foundations mini project, which used a clean public data set (breast-cancer measurements, all numeric) with a little mess added. This time the table is the kind most first jobs bring: mixed types (numbers, categories, an identifier), values missing for a reason, resubmitted rows, impossible values from data entry, and a label that is not balanced. The level is beginner; the skills are the whole lifecycle once, a ColumnTransformer pipeline, a fair model comparison on validation data, one test, a saved artefact with metadata, and a written account of what the model can and cannot do.
The user. A small lender reviews personal-loan applications by hand. It wants a score that ranks new applications by the risk of default, so that reviewers look at the riskiest ones first. The score supports a person; it does not approve or reject anyone on its own.
The completion criterion of the assignment is that you can explain, without notes: where the data came from, how it was prepared, how the model learned, how performance was measured, and how a new prediction is produced. The write-up at the end is built around those five questions.
Goal and success criteria
Written before any model is trained:
| Criterion | |
|---|---|
| Task | Binary classification: will the applicant default (yes) or not (no) |
| Primary metric | ROC-AUC (ranking quality, since reviewers work through a ranked list), taught here |
| Also reported | average precision (PR-AUC), log loss, precision and recall at the default threshold 0.5 |
| Model choice | on the validation set; the Random Forest replaces the Logistic Regression baseline only if it is at least 0.01 ROC-AUC better |
| Target | test ROC-AUC of at least 0.75, measured once on the 20 % test split |
| Must not | use the test set for any decision; fit any preprocessing on validation or test rows |
The data
The assignment's first step is "download a public tabular dataset". Examples on this site run offline, so the table is generated by a small function with a fixed seed. Its real counterparts are the Statlog (German Credit Data) set and the Adult census-income set in the UCI Machine Learning Repository, both licensed CC BY 4.0, which permits reuse with attribution. Real loan data is personal and financial: in a real project you would need a lawful basis to use it, access controls, a retention period, and a check that no protected attribute (or an obvious proxy for one) drives the decisions; see privacy, consent and licensing. Scores on generated data describe the generator and the method, not real borrowers.
The generator draws 3,000 applications. The default risk rises with the loan-to-income ratio and with late payments (sharply from three of them), and is higher for the unemployed and contract workers. Then it adds the mess on purpose: income left blank more often by the self-employed, a few missing employment types, five incomes typed in euros instead of thousands of euros, three impossible ages and 40 resubmitted applications.
Steps 1 and 2: get the data, inspect it
Write the raw table to a CSV file, read it back as a new user of the file would, and look at it: size, column types, a few rows, the label balance and the distributions. This is dataset inspection and summary statistics applied.
import numpy as np
import pandas as pd
def make_applications(n=3000, seed=0):
rng = np.random.default_rng(seed)
emp = rng.choice(["salaried", "self-employed", "contract", "unemployed"], n, p=[0.6, 0.15, 0.18, 0.07])
df = pd.DataFrame({
"app_id": np.arange(100001, 100001 + n),
"age": rng.integers(19, 70, n).astype(float),
"employment": emp,
"region": rng.choice(["north", "south", "east", "west"], n),
"home": rng.choice(["rent", "own", "mortgage"], n, p=[0.45, 0.2, 0.35]),
"income_k": np.round(rng.lognormal(3.6, 0.45, n) * np.where(emp == "unemployed", 0.4, 1.0), 1),
"loan_k": np.round(rng.uniform(1, 30, n), 1),
"term_months": rng.choice([12, 36, 60], n),
"late_payments": rng.poisson(0.6, n),
})
ratio = df.loan_k / df.income_k
logit = (-3.0 + 2.5 * np.minimum(ratio, 2) + 0.5 * df.late_payments + 1.2 * (df.late_payments >= 3)
+ 0.9 * (emp == "unemployed") + 0.5 * (emp == "contract") - 0.02 * (df.age - 40)
+ 0.006 * (df.term_months - 36))
df["default"] = np.where(rng.random(n) < 1 / (1 + np.exp(-logit)), "yes", "no")
# the mess a real export has
df.loc[rng.random(n) < np.where(emp == "self-employed", 0.2, 0.04), "income_k"] = np.nan
df.loc[rng.random(n) < 0.03, "employment"] = np.nan
df.loc[rng.choice(n, 5, replace=False), "income_k"] *= 1000 # euros typed instead of k euros
df.loc[rng.choice(n, 3, replace=False), "age"] = 999 # a placeholder for "unknown"
return pd.concat([df, df.sample(40, random_state=seed)], ignore_index=True) # resubmitted rows
make_applications().to_csv("applications.csv", index=False)
df = pd.read_csv("applications.csv")
print("shape:", df.shape)
print(df.dtypes.to_string())
print()
print(df.head(3).to_string(index=False))
print("\nlabel:", df["default"].value_counts().to_dict(), f"-> {(df['default'] == 'yes').mean():.1%} default")
print()
print(df[["age", "income_k", "loan_k", "late_payments"]].describe().round(1).to_string())
for col in ["employment", "region", "home", "term_months"]:
print(f"{col}: {df[col].value_counts().to_dict()}")shape: (3040, 10)
app_id int64
age float64
employment object
region object
home object
income_k float64
loan_k float64
term_months int64
late_payments int64
default object
app_id age employment region home income_k loan_k term_months late_payments default
100001 64.0 self-employed north own NaN 24.8 60 1 no
100002 27.0 salaried north mortgage 55.7 6.1 36 0 no
100003 46.0 salaried west rent 51.1 6.0 12 1 no
label: {'no': 2288, 'yes': 752} -> 24.7% default
age income_k loan_k late_payments
count 3040.0 2851.0 3040.0 3040.0
mean 44.7 105.5 15.8 0.6
std 33.5 1720.7 8.3 0.8
min 19.0 4.6 1.0 0.0
25% 31.0 25.3 8.7 0.0
50% 44.0 35.3 15.8 0.0
75% 57.0 48.7 22.9 1.0
max 999.0 59400.0 30.0 5.0
employment: {'salaried': 1799, 'contract': 545, 'self-employed': 415, 'unemployed': 193}
region: {'east': 795, 'west': 772, 'north': 748, 'south': 725}
home: {'rent': 1395, 'mortgage': 1079, 'own': 566}
term_months: {12: 1019, 36: 1017, 60: 1004}
Read it like a reviewer: one identifier (app_id, never a feature), four numeric columns, four categorical ones (term_months is a number but has only three values, so either treatment works), and a minority class of about a quarter (24.7 % default). Two numbers in the summary are already suspicious: the maximum age and the maximum income.
Step 3: missing values, duplicates and outliers
Each problem gets a count and, more importantly, an explanation, because the explanation decides the fix (missing values, duplicates, outliers).
import numpy as np
import pandas as pd
def make_applications(n=3000, seed=0):
rng = np.random.default_rng(seed)
emp = rng.choice(["salaried", "self-employed", "contract", "unemployed"], n, p=[0.6, 0.15, 0.18, 0.07])
df = pd.DataFrame({
"app_id": np.arange(100001, 100001 + n),
"age": rng.integers(19, 70, n).astype(float),
"employment": emp,
"region": rng.choice(["north", "south", "east", "west"], n),
"home": rng.choice(["rent", "own", "mortgage"], n, p=[0.45, 0.2, 0.35]),
"income_k": np.round(rng.lognormal(3.6, 0.45, n) * np.where(emp == "unemployed", 0.4, 1.0), 1),
"loan_k": np.round(rng.uniform(1, 30, n), 1),
"term_months": rng.choice([12, 36, 60], n),
"late_payments": rng.poisson(0.6, n),
})
ratio = df.loan_k / df.income_k
logit = (-3.0 + 2.5 * np.minimum(ratio, 2) + 0.5 * df.late_payments + 1.2 * (df.late_payments >= 3)
+ 0.9 * (emp == "unemployed") + 0.5 * (emp == "contract") - 0.02 * (df.age - 40)
+ 0.006 * (df.term_months - 36))
df["default"] = np.where(rng.random(n) < 1 / (1 + np.exp(-logit)), "yes", "no")
df.loc[rng.random(n) < np.where(emp == "self-employed", 0.2, 0.04), "income_k"] = np.nan
df.loc[rng.random(n) < 0.03, "employment"] = np.nan
df.loc[rng.choice(n, 5, replace=False), "income_k"] *= 1000
df.loc[rng.choice(n, 3, replace=False), "age"] = 999
return pd.concat([df, df.sample(40, random_state=seed)], ignore_index=True)
df = make_applications()
print("missing values per column:")
print(df.isna().sum()[lambda s: s > 0].to_string())
print("\nincome missing, share by employment type:")
print(df.groupby("employment", dropna=False)["income_k"].apply(lambda s: round(s.isna().mean(), 3)).to_string())
print("\nexact duplicate rows:", int(df.duplicated().sum()), "| duplicated app_id:", int(df["app_id"].duplicated().sum()))
# range rules from the domain, not from statistics: adults up to 100, incomes below 1,000 k a year
print("\nage outside 18-100:", df.loc[~df.age.between(18, 100), "age"].tolist())
print("income_k above 1000:", sorted(df.loc[df.income_k > 1000, "income_k"].round(1).tolist()))
q1, q3 = df.loan_k.quantile([0.25, 0.75])
print("loan_k outside the IQR fences:", int((~df.loan_k.between(q1 - 1.5 * (q3 - q1), q3 + 1.5 * (q3 - q1))).sum()))
print("late_payments value counts:", df.late_payments.value_counts().sort_index().to_dict())missing values per column:
employment 88
income_k 189
income missing, share by employment type:
employment
contract 0.050
salaried 0.039
self-employed 0.193
unemployed 0.026
NaN 0.068
exact duplicate rows: 40 | duplicated app_id: 40
age outside 18-100: [999.0, 999.0, 999.0]
income_k above 1000: [12600.0, 32300.0, 37300.0, 48400.0, 59400.0]
loan_k outside the IQR fences: 0
late_payments value counts: {0: 1668, 1: 1004, 2: 303, 3: 57, 4: 7, 5: 1}
What the counts mean, and the decision for each:
- Income is missing far more often for the self-employed. It is not missing at random, so dropping those rows would remove a group. Impute it with the training median and add a missing indicator so that the model can learn from the fact that it was blank (missing indicators). Missing employment gets its own treatment in the pipeline: the most frequent category.
- The 40 duplicates are resubmissions (same
app_id, same values). Drop them before splitting; otherwise copies of the same application can land in training and test and inflate the score (duplicates and leakage). - Age 999 is a placeholder, and incomes above 1,000 k are unit errors. Both are rule violations, not statistical outliers, so they become missing values (and are then imputed like any other gap). You could divide the incomes by 1,000, but you cannot be sure that is the right repair; record the choice in the cleaning log either way (cleaning log).
- Late payments of 4 and 5 are rare but real (8 rows). A rare value is not an error; keep it.
These rules use no statistics of the data, so applying them to the whole table before the split leaks nothing. Anything learned from the data (medians, scales, category lists) is learned inside the pipeline, from training rows only.
Step 4: split into training, validation and test
A stratified random split keeps the default rate equal in all three parts (split strategies). A random split is right here because the applications are independent and come from one period; if they spanned years, a time split would be the honest choice (Project 1 does that).
Before you build the pipeline, see why every fitted step must live inside it. Open the leakage lab on "scaler before split": fitting a scaler on all rows changes the estimate only a little, as the lab says on screen. Then switch to "feature selection before split" and watch the leaky estimate climb to 0.94 against an honest 0.54 on data that is pure noise.
Steps 5 to 8: the pipeline, two models, validation metrics
One ColumnTransformer handles both column kinds (pipelines and ColumnTransformer): numbers get median imputation with missing indicators and standard scaling; categories get most-frequent imputation and one-hot encoding that ignores categories it has never seen. The same preprocessing feeds a Logistic Regression baseline and a Random Forest. Both are wrapped in a Pipeline, so fit learns every statistic from the training rows only. A majority-class "model" shows what a score means when nothing is learned.
import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.dummy import DummyClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import average_precision_score, log_loss, precision_score, recall_score, roc_auc_score
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline, make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
def make_applications(n=3000, seed=0):
rng = np.random.default_rng(seed)
emp = rng.choice(["salaried", "self-employed", "contract", "unemployed"], n, p=[0.6, 0.15, 0.18, 0.07])
df = pd.DataFrame({
"app_id": np.arange(100001, 100001 + n),
"age": rng.integers(19, 70, n).astype(float),
"employment": emp,
"region": rng.choice(["north", "south", "east", "west"], n),
"home": rng.choice(["rent", "own", "mortgage"], n, p=[0.45, 0.2, 0.35]),
"income_k": np.round(rng.lognormal(3.6, 0.45, n) * np.where(emp == "unemployed", 0.4, 1.0), 1),
"loan_k": np.round(rng.uniform(1, 30, n), 1),
"term_months": rng.choice([12, 36, 60], n),
"late_payments": rng.poisson(0.6, n),
})
ratio = df.loan_k / df.income_k
logit = (-3.0 + 2.5 * np.minimum(ratio, 2) + 0.5 * df.late_payments + 1.2 * (df.late_payments >= 3)
+ 0.9 * (emp == "unemployed") + 0.5 * (emp == "contract") - 0.02 * (df.age - 40)
+ 0.006 * (df.term_months - 36))
df["default"] = np.where(rng.random(n) < 1 / (1 + np.exp(-logit)), "yes", "no")
df.loc[rng.random(n) < np.where(emp == "self-employed", 0.2, 0.04), "income_k"] = np.nan
df.loc[rng.random(n) < 0.03, "employment"] = np.nan
df.loc[rng.choice(n, 5, replace=False), "income_k"] *= 1000
df.loc[rng.choice(n, 3, replace=False), "age"] = 999
return pd.concat([df, df.sample(40, random_state=seed)], ignore_index=True)
def clean(df):
"""Rule-based cleaning: no statistics of the data, so it is safe before the split."""
df = df.drop_duplicates().copy()
df.loc[~df.age.between(18, 100), "age"] = np.nan
df.loc[df.income_k > 1000, "income_k"] = np.nan
return df
NUM = ["age", "income_k", "loan_k", "late_payments"]
CAT = ["employment", "region", "home", "term_months"]
def preprocessor():
return ColumnTransformer([
("num", make_pipeline(SimpleImputer(strategy="median", add_indicator=True), StandardScaler()), NUM),
("cat", make_pipeline(SimpleImputer(strategy="most_frequent"), OneHotEncoder(handle_unknown="ignore")), CAT),
])
df = clean(make_applications())
X, y = df[NUM + CAT], (df["default"] == "yes").astype(int)
X_rest, X_test, y_rest, y_test = train_test_split(X, y, test_size=0.2, stratify=y, random_state=0)
X_tr, X_val, y_tr, y_val = train_test_split(X_rest, y_rest, test_size=0.25, stratify=y_rest, random_state=0)
print(f"rows: train {len(X_tr)}, validation {len(X_val)}, test {len(X_test)} (test is not touched below)")
print(f"default rate: train {y_tr.mean():.3f}, validation {y_val.mean():.3f}, test {y_test.mean():.3f}")
models = {
"majority class": DummyClassifier(strategy="most_frequent"),
"logistic regression": LogisticRegression(max_iter=1000),
"random forest": RandomForestClassifier(n_estimators=300, min_samples_leaf=5, random_state=0),
}
print(f"\n{'validation':20} {'ROC-AUC':>8} {'PR-AUC':>7} {'logloss':>8} {'prec@.5':>8} {'rec@.5':>7}")
for name, clf in models.items():
pipe = Pipeline([("prep", preprocessor()), ("clf", clf)]).fit(X_tr, y_tr)
p = pipe.predict_proba(X_val)[:, 1]
pred = (p >= 0.5).astype(int)
print(f"{name:20} {roc_auc_score(y_val, p):8.3f} {average_precision_score(y_val, p):7.3f} "
f"{log_loss(y_val, p):8.3f} {precision_score(y_val, pred, zero_division=0):8.3f} "
f"{recall_score(y_val, pred):7.3f}")rows: train 1800, validation 600, test 600 (test is not touched below)
default rate: train 0.249, validation 0.248, test 0.248
validation ROC-AUC PR-AUC logloss prec@.5 rec@.5
majority class 0.500 0.248 8.951 0.000 0.000
logistic regression 0.733 0.509 0.496 0.557 0.262
random forest 0.739 0.527 0.485 0.717 0.255
Both models learn something: ROC-AUC 0.733 and 0.739 against 0.500 for the majority class, which also shows why accuracy alone would mislead (it never flags anyone, yet would be right on 75 % of the rows). The Random Forest is ahead by 0.006, less than the 0.01 the success criteria demanded, so the rule written before the results keeps the Logistic Regression. That is not timidity: a 0.006 difference on 600 validation rows (about 150 defaults) is well inside the noise of a single split, and the linear model is faster, easier to explain to a reviewer and easier to check. Notice also the low recall at 0.5 (about a quarter of the defaults reach the threshold): the score is meant for ranking, and a threshold for a review budget is an extension.
Steps 9 to 11: test once, save, score in a separate program
The decision is made, so the test set is opened. The chosen pipeline is refitted on training plus validation rows (more data, same recipe; a common choice, stated in the write-up), scored once on the test rows, and saved with joblib next to a JSON file of metadata: the input columns and their kinds, the categories seen in training, the threshold, the test scores, a hash of the data file and the seed.
The scoring program is a separate file, score.py, run with runpy in a fresh namespace: it sees nothing of the training code, only the two files. It checks every new record against the metadata (missing columns are an error; an unknown category is allowed but flagged), then returns a risk score.
import hashlib, json, runpy
import joblib
import numpy as np
import pandas as pd
import sklearn
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import average_precision_score, precision_score, recall_score, roc_auc_score
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline, make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
def make_applications(n=3000, seed=0):
rng = np.random.default_rng(seed)
emp = rng.choice(["salaried", "self-employed", "contract", "unemployed"], n, p=[0.6, 0.15, 0.18, 0.07])
df = pd.DataFrame({
"app_id": np.arange(100001, 100001 + n),
"age": rng.integers(19, 70, n).astype(float),
"employment": emp,
"region": rng.choice(["north", "south", "east", "west"], n),
"home": rng.choice(["rent", "own", "mortgage"], n, p=[0.45, 0.2, 0.35]),
"income_k": np.round(rng.lognormal(3.6, 0.45, n) * np.where(emp == "unemployed", 0.4, 1.0), 1),
"loan_k": np.round(rng.uniform(1, 30, n), 1),
"term_months": rng.choice([12, 36, 60], n),
"late_payments": rng.poisson(0.6, n),
})
ratio = df.loan_k / df.income_k
logit = (-3.0 + 2.5 * np.minimum(ratio, 2) + 0.5 * df.late_payments + 1.2 * (df.late_payments >= 3)
+ 0.9 * (emp == "unemployed") + 0.5 * (emp == "contract") - 0.02 * (df.age - 40)
+ 0.006 * (df.term_months - 36))
df["default"] = np.where(rng.random(n) < 1 / (1 + np.exp(-logit)), "yes", "no")
df.loc[rng.random(n) < np.where(emp == "self-employed", 0.2, 0.04), "income_k"] = np.nan
df.loc[rng.random(n) < 0.03, "employment"] = np.nan
df.loc[rng.choice(n, 5, replace=False), "income_k"] *= 1000
df.loc[rng.choice(n, 3, replace=False), "age"] = 999
return pd.concat([df, df.sample(40, random_state=seed)], ignore_index=True)
def clean(df):
df = df.drop_duplicates().copy()
df.loc[~df.age.between(18, 100), "age"] = np.nan
df.loc[df.income_k > 1000, "income_k"] = np.nan
return df
NUM = ["age", "income_k", "loan_k", "late_payments"]
CAT = ["employment", "region", "home", "term_months"]
prep = ColumnTransformer([
("num", make_pipeline(SimpleImputer(strategy="median", add_indicator=True), StandardScaler()), NUM),
("cat", make_pipeline(SimpleImputer(strategy="most_frequent"), OneHotEncoder(handle_unknown="ignore")), CAT),
])
# ---- train.py: the training program ----
make_applications().to_csv("applications.csv", index=False)
data_hash = hashlib.sha256(open("applications.csv", "rb").read()).hexdigest()[:12]
df = clean(pd.read_csv("applications.csv"))
X, y = df[NUM + CAT], (df["default"] == "yes").astype(int)
X_rest, X_test, y_rest, y_test = train_test_split(X, y, test_size=0.2, stratify=y, random_state=0)
CHOSEN = LogisticRegression(max_iter=1000) # the rule: RF must beat it by 0.01 ROC-AUC on validation
final = Pipeline([("prep", prep), ("clf", CHOSEN)]).fit(X_rest, y_rest) # train + validation rows
p = final.predict_proba(X_test)[:, 1] # the one look at the test set
test = {"roc_auc": round(roc_auc_score(y_test, p), 3), "pr_auc": round(average_precision_score(y_test, p), 3),
"precision_at_0.5": round(precision_score(y_test, p >= 0.5), 3),
"recall_at_0.5": round(recall_score(y_test, p >= 0.5), 3), "n_test": int(len(y_test))}
print("test, once:", test)
joblib.dump(final, "model.joblib")
cats = final.named_steps["prep"].named_transformers_["cat"][-1].categories_
meta = {"model": type(CHOSEN).__name__, "target": "default == 'yes'", "threshold": 0.5,
"numeric": NUM, "categorical": {c: [str(v) for v in cs] for c, cs in zip(CAT, cats)},
"data": {"file": "applications.csv", "sha256_12": data_hash, "rows_after_cleaning": int(len(df))},
"split": "stratified 60/20/20, random_state=0; refit on train+validation",
"test_metrics": test, "sklearn": sklearn.__version__, "seed": 0}
json.dump(meta, open("model.json", "w"), indent=2)
print("saved model.joblib and model.json; categories of employment:", meta["categorical"]["employment"])
# ---- score.py: a separate program that only knows the two files ----
open("score.py", "w").write('''
import json, joblib, pandas as pd
meta = json.load(open("model.json"))
model = joblib.load("model.joblib") # only load model files you trust: joblib can run code
columns = meta["numeric"] + list(meta["categorical"])
def score(records):
df = pd.DataFrame(records)
missing = [c for c in columns if c not in df]
if missing:
raise ValueError(f"missing columns: {missing}")
p = model.predict_proba(df[columns])[:, 1]
for rec, pi in zip(records, p):
notes = [f"unknown {c}={rec[c]!r}" for c, known in meta["categorical"].items()
if rec[c] is not None and str(rec[c]) not in known]
notes += [f"{c} missing" for c in columns if rec[c] is None]
flag = "review first" if pi >= meta["threshold"] else "normal queue"
print(f"{rec['app_id']}: risk {pi:.2f} -> {flag}" + (f" ({'; '.join(notes)})" if notes else ""))
new = [
{"app_id": 200001, "age": 34, "employment": "salaried", "region": "east", "home": "rent",
"income_k": 52.0, "loan_k": 8.0, "term_months": 36, "late_payments": 0},
{"app_id": 200002, "age": 27, "employment": "contract", "region": "west", "home": "rent",
"income_k": 21.0, "loan_k": 25.0, "term_months": 60, "late_payments": 3},
{"app_id": 200003, "age": 45, "employment": "freelance", "region": "north", "home": "own",
"income_k": None, "loan_k": 12.0, "term_months": 36, "late_payments": 1},
]
score(new)
try:
score([{"app_id": 200004, "age": 50, "employment": "salaried"}])
except ValueError as e:
print("rejected 200004:", e)
''')
runpy.run_path("score.py", run_name="__main__")test, once: {'roc_auc': 0.768, 'pr_auc': 0.589, 'precision_at_0.5': 0.667, 'recall_at_0.5': 0.322, 'n_test': 600}
saved model.joblib and model.json; categories of employment: ['contract', 'salaried', 'self-employed', 'unemployed']
200001: risk 0.05 -> normal queue
200002: risk 0.90 -> review first
200003: risk 0.27 -> normal queue (unknown employment='freelance'; income_k missing)
rejected 200004: missing columns: ['income_k', 'loan_k', 'late_payments', 'region', 'home', 'term_months']
The single test measurement is ROC-AUC 0.768 on 600 rows, above the target of 0.75, with average precision 0.589. It is a little higher than on validation (0.733), which is normal variation between two samples of 600 and a reason not to over-read the third decimal. The scorer ranks the high-ratio contract applicant with three late payments (200002, risk 0.90) far above the salaried one with a small loan (200001, 0.05), scores the freelance applicant but says why the score is less trustworthy, and rejects a record that lacks six of the eight inputs instead of guessing them.
Note:
joblib.loadcan execute code stored in the file, likepickle. A scoring service loads only model files it built itself or can verify (a hash in the metadata, a registry); see security of ML systems.
Step 12: document the experiment and its limitations
The write-up answers the five questions of the completion criterion (where the data came from: item 1; how it was prepared: items 2 and 3; how the model learned: item 5; how performance was measured: items 4 and 6; how a new prediction is produced: item 7) and lists what the numbers do not show. Here it is for this run; the template below is the empty version for your own data.
Experiment: loan default ranking, first assignment
1. Data: generated table of 3,040 applications (seed 0), standing in for a public set such as
UCI Statlog German Credit (CC BY 4.0). 8 inputs + app_id + label; 24.7 % default.
2. Problems: income missing 189 (19 % for self-employed vs about 4 % otherwise), employment
missing 88, 40 resubmitted duplicates, 3 placeholder ages (999), 5 incomes in the wrong unit.
Duplicates dropped; impossible values set to missing (rules, before the split).
3. Preparation: in a Pipeline fitted on training rows only: median imputation + missing
indicators + standard scaling for numbers; most-frequent imputation + one-hot
(unknown categories ignored) for categories.
4. Split: stratified 60/20/20 (1,800 / 600 / 600); applications are independent and from one
period, so a random split matches use.
5. Models: majority class 0.500, Logistic Regression 0.733, Random Forest 0.739 ROC-AUC on
validation. Rule fixed in advance (RF must win by 0.01): Logistic Regression kept.
6. Result: refit on train + validation; test ROC-AUC 0.768, PR-AUC 0.589, precision 0.667 and
recall 0.322 at 0.5, on 600 rows, measured once.
7. Prediction: score.py loads model.joblib + model.json, checks columns, flags unknown
categories and missing values, returns a risk and a queue.
8. Limitations: synthetic data; one period, so no drift tested; threshold 0.5 not tuned to a
review budget; scores not checked for calibration; no fairness audit by age or region;
a 0.006 model gap is not resolved by one split.
9. Reproduce: data sha256 prefix in model.json, seed 0, scikit-learn version in model.json.Extensions
- Pick the threshold for a review budget (say, reviewers can check 20 % of applications) instead of 0.5: log loss and choosing a threshold.
- Check whether the risk scores are calibrated before anyone reads them as probabilities: calibration.
- Replace the single validation split by 5-fold cross-validation for the model choice, and compare the spread of the scores with the gap between the models: holdout and k-fold.
- Add the loan-to-income ratio as an engineered feature and see whether the Logistic Regression closes the gap: ratios and interactions.
- Serve
score.pyas an HTTP endpoint with request validation: a prediction service with FastAPI.
Write-up template
Experiment: <name, date, author>
1. Data: source, licence, rows/columns, period, how it was collected, personal data and consent
2. Problems found: missing (how many, why), duplicates, impossible values, and what was done with each
3. Preparation: cleaning rules (before split) / fitted steps (inside the pipeline, training rows only)
4. Split: kind, sizes, stratified?, why this split matches how the model will be used
5. Models: baseline and candidates, hyperparameters, how the choice was made (metric, set, rule)
6. Result: test metrics, measured once, number of test rows
7. Prediction: which files, which program, what it checks, what it returns
8. Limitations: what the data does not cover, who could be harmed, what is not measured
9. Reproduce: data hash, seed, library versions, commandPractice
- Change the generator's seed to 1 and rerun Steps 5 to 8. Does the same model win on validation, and by how much?
Answer
Run it and compare with the table above. The point of the exercise is the size of the change: if the ranking of the two models flips, or the gap moves by more than the 0.01 rule, the comparison on a single validation split of about 600 rows was not decisive, and cross-validation (or more data) is needed before claiming one model is better.
- A colleague imputes the missing incomes with the median of the whole cleaned table before splitting, because "the median barely changes". What is wrong, even if the score does not move?
Answer
The median then contains information from the validation and test rows, so the evaluation no longer simulates new data. With one median the effect is tiny, but the habit is what breaks evaluations: the same pattern with feature selection or target encoding inflates scores a lot (the leakage lab's 0.94 vs 0.54). Keeping the imputer inside the pipeline costs nothing.
- Application 200003 has
employment = "freelance", a value never seen in training. What did the pipeline do with it, and what should a production system do?
Answer
OneHotEncoder(handle_unknown="ignore") encodes it as all zeros, so the model scores the applicant as if no employment category applied. The scorer still returns a score but flags the unknown value. In production, count such values per day: a new category that keeps appearing means the upstream form changed and the model needs retraining with it (data validation).
Test yourself
On validation the Random Forest scored ROC-AUC 0.739 and the Logistic Regression 0.733. Why does the project keep the Logistic Regression?
- Logistic Regression always generalises better
- The rule fixed before the results required a gain of at least 0.01, and 0.006 is within the noise of one 600-row split
- The Random Forest overfitted the test set
- Random Forests cannot handle one-hot features
Why are the 40 resubmitted applications removed before the split rather than inside the pipeline?
- Pipelines cannot drop rows
- A copy in training and its twin in test would let the model be scored on rows it has already seen
- Duplicates change the median income
- The test set must have exactly 600 rows
Income is missing for 19.3 % of the self-employed and about 4 % of the others. What does the pipeline do about it?
- Drops every row with a missing income
- Fills with zero
- Fills with the training median and adds a missing indicator column
- Fills with the median of the whole table
What does score.py need in order to score a new application?
- The training CSV and the training code
- Only model.joblib and model.json
- The validation set, to recompute the scaler
- Nothing; it retrains on each request