In this project you will build a model for a small microfinance office. It must predict which loan applicants are likely to default, which means not paying back. You will explore the data, compare models, pick a decision threshold based on money rather than accuracy, and score new applicants. Along the way you will use skills from many earlier lessons.
In this project you will
- Explore a loan dataset with missing values and text columns
- Add a feature that captures loan burden
- Compare a baseline, logistic regression and gradient boosting in a pipeline
- Choose a threshold that keeps the cost of mistakes lowest
- Read the model’s weights and score new applicants
You should know pipelines and ColumnTransformer, ROC AUC and imbalanced data.
Step 1: Explore the Data
The data is made up, but it behaves like real loan records. Each row is one past loan with the applicant’s age, monthly income, loan amount, term, job, district and number of past late payments. The default column is 1 if the loan was not repaid.
import numpy as np
import pandas as pd
# Made-up loan records for a small microfinance office (6,000 past loans)
rng = np.random.default_rng(11)
n = 6000
age = rng.integers(21, 65, n)
income = np.round(rng.lognormal(3.5, 0.45, n), 1) # thousand taka / month
amount = np.round(income * rng.uniform(2, 12, n), 1) # loan size
term = rng.choice([12, 24, 36], n, p=[0.4, 0.4, 0.2]) # months
job = rng.choice(["salaried", "business", "farmer", "day labour"], n,
p=[0.35, 0.3, 0.2, 0.15])
district = rng.choice(["Dhaka", "Chattogram", "Rajshahi", "Khulna", "Sylhet"], n)
late_before = rng.poisson(0.6, n) # past late payments
# the true risk rule (hidden from the model)
burden = amount / (income * term / 12)
z = (-3.6 + 0.3 * burden + 0.55 * late_before - 0.012 * (age - 40)
+ np.select([job == "day labour", job == "farmer", job == "business"], [0.7, 0.4, 0.2], 0))
default = (rng.random(n) < 1 / (1 + np.exp(-z))).astype(int)
df = pd.DataFrame({"age": age, "income": income, "amount": amount, "term": term,
"job": job, "district": district, "late_before": late_before,
"default": default})
# some forms were filled in badly: income missing for about 5% of rows
df.loc[rng.random(n) < 0.05, "income"] = np.nan
df.to_csv("loans.csv", index=False) # the next steps start from this file
print(df.head(4).to_string(index=False))
print("\nrows:", len(df), " default rate:", round(df["default"].mean(), 3))
print("missing income values:", df["income"].isna().sum())
print("\ndefault rate by job:")
print(df.groupby("job")["default"].mean().round(3).sort_values())
print("\ndefault rate by loan term (months):")
print(df.groupby("term")["default"].mean().round(3))
Output
age income amount term job district late_before default
26 20.8 234.8 12 business Rajshahi 0 0
26 38.6 118.1 12 salaried Rajshahi 0 0
56 24.8 106.1 24 day labour Dhaka 0 0
42 58.5 396.4 24 salaried Chattogram 0 0
rows: 6000 default rate: 0.189
missing income values: 309
default rate by job:
job
salaried 0.156
business 0.180
farmer 0.210
day labour 0.258
Name: default, dtype: float64
default rate by loan term (months):
term
12 0.286
24 0.139
36 0.091
Name: default, dtype: float64
- About 19% of loans defaulted. The classes are imbalanced, so plain accuracy would be misleading: always saying “no default” is already 81% right.
- 309 rows have no income. We will fill them inside the pipeline, not before, to avoid data leakage.
- Day labourers default most and salaried workers least.
- Short loans default more. That seems odd until you notice that a 12-month loan needs bigger monthly payments for the same amount.
Step 2: Build and Compare Models
The term pattern suggests a new feature. Burden is the loan amount divided by the income earned during the loan’s term. A burden of 1 means the loan equals all the income over that period.
import pandas as pd
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import make_pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.dummy import DummyClassifier
df = pd.read_csv("loans.csv")
# A new column built from domain sense: how many months of income the loan costs
df["burden"] = df["amount"] / (df["income"] * df["term"] / 12)
X, y = df.drop(columns="default"), df["default"]
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, stratify=y, random_state=0)
num = ["age", "income", "amount", "term", "late_before", "burden"]
cat = ["job", "district"]
prep = ColumnTransformer([
("num", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()), num),
("cat", OneHotEncoder(handle_unknown="ignore"), cat),
])
models = {
"always 'no default'": DummyClassifier(strategy="prior"),
"logistic regression": make_pipeline(prep, LogisticRegression(max_iter=1000)),
"gradient boosting": make_pipeline(prep, HistGradientBoostingClassifier(
learning_rate=0.05, max_iter=300, random_state=0)),
}
print("5-fold ROC AUC on the training part:")
for name, m in models.items():
auc = cross_val_score(m, X_tr, y_tr, cv=5, scoring="roc_auc").mean()
print(f" {name:<21} {auc:.3f}")
Output
5-fold ROC AUC on the training part:
always 'no default' 0.500
logistic regression 0.740
gradient boosting 0.697
- The
ColumnTransformerfills missing numbers with the median, scales them, and one-hot encodes job and district. All of it happens inside each cross-validation fold. - The dummy model scores an AUC of 0.5, the level of pure guessing. Any useful model must beat it.
- Logistic regression wins with 0.740. Gradient boosting scores lower. When the true pattern is simple and smooth, a simple model can beat a powerful one.
- An AUC near 0.74 is typical for credit data. Repayment depends on many things that are not in the form, like illness or a bad harvest.
Step 3: Choose a Threshold by Cost
The model gives each applicant a risk between 0 and 1. The office must decide above which risk it will refuse or review a loan. The default threshold of 0.5 assumes both mistakes cost the same. They do not:
- A missed default loses about 50,000 taka.
- Refusing a good customer loses about 10,000 taka of interest.
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import make_pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score, confusion_matrix
df = pd.read_csv("loans.csv")
df["burden"] = df["amount"] / (df["income"] * df["term"] / 12)
X, y = df.drop(columns="default"), df["default"]
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, stratify=y, random_state=0)
num = ["age", "income", "amount", "term", "late_before", "burden"]
prep = ColumnTransformer([
("num", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()), num),
("cat", OneHotEncoder(handle_unknown="ignore"), ["job", "district"]),
])
model = make_pipeline(prep, LogisticRegression(max_iter=1000)).fit(X_tr, y_tr)
risk = model.predict_proba(X_te)[:, 1] # chance of default for each test loan
print(f"test ROC AUC: {roc_auc_score(y_te, risk):.3f}")
# A missed default loses about 50,000 taka. Turning away a good customer
# loses about 10,000 taka of interest. So a miss costs 5 times more.
COST_MISS, COST_REJECT = 50, 10 # thousand taka
print("\nthreshold rejected missed defaults good refused cost (k taka)")
for t in (0.5, 0.4, 0.3, 0.2, 0.15, 0.1):
reject = risk >= t
tn, fp, fn, tp = confusion_matrix(y_te, reject).ravel()
cost = fn * COST_MISS + fp * COST_REJECT
print(f" {t:<8} {reject.sum():>8} {fn:>16} {fp:>13} {cost:>14}")
print(f"\napprove everyone: cost {y_te.sum() * COST_MISS} (k taka)")
print(f"theory says best threshold = {COST_REJECT / (COST_MISS + COST_REJECT):.3f}")
Output
test ROC AUC: 0.731
threshold rejected missed defaults good refused cost (k taka)
0.5 81 233 31 11960
0.4 159 204 80 11000
0.3 269 169 155 10000
0.2 489 115 321 8960
0.15 673 81 471 8760
0.1 976 40 733 9330
approve everyone: cost 14150 (k taka)
theory says best threshold = 0.167
- At 0.5, the model refuses few people but misses 233 defaults. It costs almost 12 million taka.
- Lowering the threshold catches more defaults but refuses more good customers. In the table, 0.15 gives the lowest cost. The chart shows a wide, flat valley from about 0.12 to 0.25, so any value in that range works about as well.
- Theory agrees. When a miss costs 50 and a refusal costs 10, the best threshold is 10 / (50 + 10), which is about 0.17.
- Compared with approving everyone (14.15 million), the model saves about 5.4 million taka on these 1,500 test loans.
Step 4: Understand and Use the Model
We refit the chosen model on all 6,000 loans. Then we read its weights and score three new applicants.
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import make_pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.linear_model import LogisticRegression
df = pd.read_csv("loans.csv")
df["burden"] = df["amount"] / (df["income"] * df["term"] / 12)
X, y = df.drop(columns="default"), df["default"]
num = ["age", "income", "amount", "term", "late_before", "burden"]
prep = ColumnTransformer([
("num", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()), num),
("cat", OneHotEncoder(handle_unknown="ignore"), ["job", "district"]),
])
# Final model: train on ALL the past loans now that the choices are made
model = make_pipeline(prep, LogisticRegression(max_iter=1000)).fit(X, y)
# Which inputs push risk up (+) or down (-)? Numbers use scaled units.
names = model[0].get_feature_names_out()
coefs = pd.Series(model[-1].coef_[0], index=names).round(2)
print(coefs.sort_values(ascending=False).to_string())
# Score three new applicants and apply the 0.17 threshold from step 3
new = pd.DataFrame({
"age": [35, 28, 50], "income": [45.0, 18.0, 30.0], "amount": [150.0, 160.0, 90.0],
"term": [24, 12, 36], "job": ["salaried", "day labour", "farmer"],
"district": ["Sylhet", "Dhaka", "Khulna"], "late_before": [0, 2, 1],
})
new["burden"] = new["amount"] / (new["income"] * new["term"] / 12)
new["risk"] = model.predict_proba(new)[:, 1].round(3)
new["decision"] = ["review" if r >= 0.17 else "approve" for r in new["risk"]]
print()
print(new[["age", "income", "amount", "term", "job", "late_before", "risk", "decision"]]
.to_string(index=False))
Output
num__burden 0.56
num__late_before 0.43
num__amount 0.21
cat__job_day labour 0.10
cat__district_Sylhet -0.06
num__age -0.13
num__income -0.14
cat__job_farmer -0.18
num__term -0.19
cat__district_Dhaka -0.22
cat__district_Rajshahi -0.23
cat__district_Khulna -0.29
cat__district_Chattogram -0.30
cat__job_business -0.42
cat__job_salaried -0.60
age income amount term job late_before risk decision
35 45.0 150.0 24 salaried 0 0.052 approve
28 18.0 160.0 12 day labour 2 0.688 review
50 30.0 90.0 36 farmer 1 0.066 approve
- Burden has the biggest positive weight, followed by past late payments. Both raise risk, which matches common sense.
- For job, compare the values with each other: day labour is highest and salaried is lowest. That matches what we saw in step 1.
- The district weights are close together. The small gaps between them are likely noise, so district adds little.
- The second applicant has a low income, a short loan and two past late payments. A risk of 0.69 sends the case for review. The other two are approved.
Fairness check
A loan model affects people’s lives. Before using it, check its error rates for each group, such as each job type and district. Make sure the model does not refuse one group much more often for reasons that are not about repayment. A human should review borderline cases.
Ideas to Go Further
- Tune the gradient boosting model with early stopping and compare again.
- Use a corrected t-test to check whether logistic regression really beats it.
- Check whether the risk scores are well calibrated, since the threshold relies on them.
- Plan how you would watch for drift after launch.
- Save the final pipeline with joblib.
Common Mistakes
- Judging by accuracy on imbalanced data. A model that never predicts default is 81% accurate and useless.
- Keeping the 0.5 threshold. Base the threshold on the real costs of each mistake.
- Imputing before the split. Keep every step that learns from data inside the pipeline.
- Assuming the fanciest model wins. Always compare against simple models.
Practice Exercises
Exercise 1. If a missed default cost 30,000 taka and a refusal cost 10,000, what threshold would theory suggest?
Show answer
10 / (30 + 10) = 0.25. When misses become cheaper, the office can afford to approve more applicants, so the threshold rises.
Exercise 2. Remove the burden column from loan2.py. What do you expect to happen to the logistic regression score, and why?
Show answer
The score drops a little, from 0.740 to about 0.733. Logistic regression can only add up its inputs, so it cannot divide amount by income and term by itself. Burden hands it that ratio directly. Gradient boosting loses less (0.697 to 0.693), because trees can partly learn such combinations on their own.
Frequently Asked Questions
Why use ROC AUC instead of accuracy for loan default?
Defaults are rare, so accuracy rewards a model that always says no default. ROC AUC measures how well the model ranks risky applicants above safe ones, which is what the threshold step needs.
How do I choose the decision threshold?
Estimate the cost of each kind of mistake, then pick the threshold with the lowest total cost on held-out data. If the probabilities are calibrated, the cost of a refusal divided by the sum of both costs is a good starting point.
Summary
- Explore first: the term pattern led to the burden feature.
- Pipelines keep imputing, scaling and encoding inside each fold.
- Logistic regression beat gradient boosting on this simple pattern.
- A cost-based threshold of about 0.17 saved far more money than 0.5.
Back to the start of the series: Introduction to Machine Learning.
