WOE, Information Value, gains tables, KS and Gini
The credit-risk toolkit banks and analytics firms in India expect: screen variables with Weight of Evidence and Information Value, then judge a default model with a decile gains table, lift, KS and Gini.
Best read after Statistics & Machine Learning 14: Classification Metrics: Confusion Matrix, Precision, Recall, ROC, PR and Business Value in the Data Science & AI handbook.
1. Why it matters
- Credit, collections and marketing teams decide on deciles ("reject the riskiest 30%"), not on accuracy.
- IV is a fast, explainable way to screen dozens of variables before modelling.
- KS and Gini are standard model-validation numbers that regulators and risk teams ask for.
2. Key ideas
3. Step by step
- Bin each numeric variable (quantiles) and keep categories as bins.
- Compute WOE per bin and IV per variable; drop IV under 0.02 and investigate IV above 0.5.
- Check WOE is monotonic for the variables you keep.
- Train the model (logistic regression) on the screened variables.
- Build the decile gains table on the test set.
- Report KS (and its decile), AUC, Gini and the business reading ("the riskiest 30% contains 59% of defaulters").
4. Code you can run
Install once: pip install numpy pandas scipy scikit-learn statsmodels, then run python c6_iv_woe_ks.py. The data is generated inside the script, so it runs anywhere.
"""Credit-risk toolkit used in Indian banking and analytics interviews:
WOE and Information Value to screen variables, then a decile gains table with lift, KS and Gini
to judge a loan-default model. Synthetic bank-loans data shaped like the class case.
Run: python c6_iv_woe_ks.py"""
import numpy as np
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
rng = np.random.default_rng(8)
n = 3000
df = pd.DataFrame({
"age": rng.integers(21, 60, n),
"employ_years": rng.integers(0, 25, n),
"address_years": rng.integers(0, 20, n),
"income_k": rng.lognormal(3.6, .5, n).round(1),
"debt_income_pct": rng.gamma(2.2, 4.5, n).round(1),
"credit_card_debt_k": rng.gamma(1.4, 1.2, n).round(2),
"education": rng.choice(["School", "Graduate", "Postgraduate"], n, p=[.45, .4, .15]),
"phone_brand": rng.choice(["A", "B", "C"], n), # should be useless
})
logit = (-1.4 + .11 * df.debt_income_pct + .25 * df.credit_card_debt_k - .09 * df.employ_years
- .03 * df.address_years - .01 * (df.age - 35) + np.where(df.education == "School", .25, 0))
df["default"] = (rng.random(n) < 1 / (1 + np.exp(-logit))).astype(int)
print(f"{n} loans, default rate {df.default.mean():.1%}\n")
def woe_iv(x, y, bins=5):
"""Bin x (quantiles for numbers, categories as they are), then WOE = ln(%good / %bad) per bin
and IV = sum((%good - %bad) * WOE). A small constant avoids log(0)."""
groups = pd.qcut(x, bins, duplicates="drop") if pd.api.types.is_numeric_dtype(x) else x
t = pd.crosstab(groups, y)
good, bad = (t[0] + .5) / (t[0].sum() + .5), (t[1] + .5) / (t[1].sum() + .5)
woe = np.log(good / bad)
return float(((good - bad) * woe).sum()), pd.DataFrame({"loans": t.sum(axis=1), "default_rate": (t[1] / t.sum(axis=1)).round(3), "WOE": woe.round(3)})
def strength(iv):
return "useless" if iv < .02 else "weak" if iv < .1 else "medium" if iv < .3 else "strong" if iv < .5 else "suspicious (check for leakage)"
ivs = {c: woe_iv(df[c], df.default)[0] for c in df.columns if c != "default"}
print("Information Value (screen variables before modelling)")
for c, iv in sorted(ivs.items(), key=lambda kv: -kv[1]):
print(f" {c:<20} IV = {iv:.3f} {strength(iv)}")
print("\nWOE table for debt_income_pct (WOE falls as risk rises: a monotonic pattern is what you want):")
print(woe_iv(df.debt_income_pct, df.default)[1].to_string())
keep = [c for c, iv in ivs.items() if iv >= .02] # drop "useless" variables
cats = [c for c in keep if not pd.api.types.is_numeric_dtype(df[c])]
X = pd.get_dummies(df[keep], columns=cats, drop_first=True, dtype=float)
X_tr, X_te, y_tr, y_te = train_test_split(X, df.default, test_size=.3, random_state=8, stratify=df.default)
sc = StandardScaler().fit(X_tr)
model = LogisticRegression(max_iter=1000).fit(sc.transform(X_tr), y_tr)
p = model.predict_proba(sc.transform(X_te))[:, 1]
print(f"\nLogistic regression on the {len(keep)} variables with IV >= 0.02: {keep}")
# Gains table: sort by predicted risk, cut into 10 deciles, count defaulters in each
g = pd.DataFrame({"p": p, "y": y_te.values}).sort_values("p", ascending=False)
g["decile"] = np.arange(len(g)) * 10 // len(g) + 1
tab = g.groupby("decile").agg(loans=("y", "size"), defaults=("y", "sum"))
tab["non_defaults"] = tab.loans - tab.defaults
tab["default_rate"] = (tab.defaults / tab.loans).round(3)
tab["cum_%_defaults"] = (tab.defaults.cumsum() / tab.defaults.sum() * 100).round(1)
tab["cum_%_good"] = (tab.non_defaults.cumsum() / tab.non_defaults.sum() * 100).round(1)
tab["KS"] = (tab["cum_%_defaults"] - tab["cum_%_good"]).round(1)
tab["lift"] = (tab.default_rate / g.y.mean()).round(2)
print("\nGains table on the test set (decile 1 = riskiest 10%)")
print(tab.to_string())
auc = roc_auc_score(y_te, p)
print(f"\nKS = {tab.KS.max():.1f} at decile {tab.KS.idxmax()} | AUC = {auc:.3f} | Gini = 2*AUC - 1 = {2 * auc - 1:.3f}")
print(f"Reading: rejecting the riskiest 30% of applicants catches {tab['cum_%_defaults'].iloc[2]:.0f}% of the defaulters.")
3000 loans, default rate 26.3%
Information Value (screen variables before modelling)
debt_income_pct IV = 0.442 strong
employ_years IV = 0.259 medium
credit_card_debt_k IV = 0.114 medium
address_years IV = 0.034 weak
education IV = 0.016 useless
income_k IV = 0.007 useless
age IV = 0.004 useless
phone_brand IV = 0.001 useless
WOE table for debt_income_pct (WOE falls as risk rises: a monotonic pattern is what you want):
loans default_rate WOE
debt_income_pct
(0.099, 4.5] 616 0.141 0.770
(4.5, 7.1] 591 0.171 0.545
(7.1, 10.2] 601 0.208 0.304
(10.2, 14.8] 596 0.289 -0.130
(14.8, 56.4] 596 0.510 -1.070
Logistic regression on the 4 variables with IV >= 0.02: ['employ_years', 'address_years', 'debt_income_pct', 'credit_card_debt_k']
Gains table on the test set (decile 1 = riskiest 10%)
loans defaults non_defaults default_rate cum_%_defaults cum_%_good KS lift
decile
1 90 61 29 0.678 25.7 4.4 21.3 2.57
2 90 50 40 0.556 46.8 10.4 36.4 2.11
3 90 29 61 0.322 59.1 19.6 39.5 1.22
4 90 24 66 0.267 69.2 29.6 39.6 1.01
5 90 11 79 0.122 73.8 41.5 32.3 0.46
6 90 18 72 0.200 81.4 52.3 29.1 0.76
7 90 21 69 0.233 90.3 62.7 27.6 0.88
8 90 12 78 0.133 95.4 74.5 20.9 0.51
9 90 6 84 0.067 97.9 87.2 10.7 0.25
10 90 5 85 0.056 100.0 100.0 0.0 0.21
KS = 39.6 at decile 4 | AUC = 0.758 | Gini = 2*AUC - 1 = 0.516
Reading: rejecting the riskiest 30% of applicants catches 59% of the defaulters.
5. Reading the output
- woe_iv() bins numeric variables into quintiles and adds 0.5 to counts so an empty bin does not give log(0).
- phone_brand, age, income and education score as useless (IV < 0.02) and are dropped before modelling.
- The WOE table for debt-to-income falls steadily from +0.77 to -1.07 as the default rate rises from 14% to 51%: a clean monotonic pattern.
- The gains table shows the top decile has about 2.6 times the average default rate; KS peaks at about 40 in decile 4.
6. Common mistakes
| Mistake | Do this instead |
|---|---|
| Trusting a very high IV | IV above 0.5 often means the variable is recorded after the outcome (leakage). |
| Building the gains table on training data | Always use the test or an out-of-time sample. |
| Too many tiny bins | Bins need enough bads to be stable; 5 to 10 bins with at least 5% of rows each is a common rule. |
| Reporting KS without the decile | Say where the maximum separation happens; that drives the cut-off decision. |
7. Assignment
8. Interview questions
What is Information Value?
A measure of how well a variable separates goods from bads, computed from WOE across bins; used to screen variables.
What does a KS of 40 mean?
At the best cut-off, the model captures 40 percentage points more of the bads than of the goods.
How are Gini and AUC related?
Gini = 2 x AUC - 1.
Why use a gains table instead of accuracy?
Decisions are made on ranked groups (approve the safest 70%); the gains table shows the outcome of each cut-off directly.