import io
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import requests
import torch
import torch.nn as nn
# Small networks train faster on a few threads than on all cores
torch.set_num_threads(4)Predicting Mortgage Denials
Software now does much of the work of deciding who gets a mortgage. A lender that wants to sell a loan to Fannie Mae or Freddie Mac submits the application’s data, such as the credit score, income, reserves, debt-to-income ratio and loan-to-value ratio, to their automated underwriting systems, Desktop Underwriter and Loan Prospector (Bartlett et al. 2022). FinTech lenders, which take applications entirely online, go further: Quicken Loans’ Rocket Mortgage can make an approval decision on an online application “in as little as 8 minutes” (Fuster et al. 2019). This notebook asks whether a model can learn denial decisions from public data, and what it finds when it does.
The data come from the Home Mortgage Disclosure Act (HMDA), which requires most mortgage lenders to report every application they receive, with its outcome. We predict whether an application was denied from four of its characteristics, first with a logit and then with a neural network, and compare how well they do on applications they were not trained on. Fuster et al. (2022) run a related comparison with confidential data on about 10 million mortgages, predicting default instead of denial, and ask who gains and who loses when lenders adopt machine learning.
Packages
The data
The CFPB’s HMDA Data Browser serves the public loan-level files, filtered by state and year, with no account or key. We take applications for loans to buy a home in Missouri in 2023 that were either originated (action_taken 1) or denied (3), and keep the columns we need. The download is about 30 MB; we save the result.
DATA = Path("../_data") if Path("../_data").exists() else Path("data")
file = DATA / "hmda_mo_2023_purchase.parquet"
if not file.exists():
url = ("https://ffiec.cfpb.gov/v2/data-browser-api/view/csv"
"?states=MO&years=2023&actions_taken=1,3&loan_purposes=1")
text = requests.get(url, timeout=120).text
columns = ["action_taken", "loan_type", "lien_status", "occupancy_type", "total_units",
"open-end_line_of_credit", "business_or_commercial_purpose", "reverse_mortgage",
"derived_dwelling_category", "loan_amount", "income", "loan_to_value_ratio",
"debt_to_income_ratio", "denial_reason-1"]
DATA.mkdir(exist_ok=True)
pd.read_csv(io.StringIO(text), usecols=columns, dtype=str).to_parquet(file)
raw = pd.read_parquet(file)
print(f"{len(raw):,} applications")84,034 applications
We keep the most standard case: conventional first-lien loans (not backed by a government agency such as the FHA) on single-family, site-built homes the borrower will live in, excluding business loans, reverse mortgages and lines of credit. The inputs are four numbers every lender looks at:
- the combined loan-to-value ratio (CLTV), all debt secured by the home as a percentage of its value;
- the debt-to-income ratio (DTI), the borrower’s monthly debt payments, including the new mortgage, as a percentage of monthly income;
- the loan amount and the borrower’s income, both in logs.
The public files report the debt-to-income ratio exactly between 36% and 49% and in bands otherwise (below 20%, 20% to 30%, 30% to 36%, 50% to 60%, above 60%); we give each band a value inside it.
standard = ((raw["loan_type"] == "1") & (raw["lien_status"] == "1") & (raw["occupancy_type"] == "1")
& (raw["total_units"] == "1") & (raw["open-end_line_of_credit"] == "2")
& (raw["business_or_commercial_purpose"] == "2") & (raw["reverse_mortgage"] == "2")
& (raw["derived_dwelling_category"] == "Single Family (1-4 Units):Site-Built"))
df = raw[standard].copy()
bands = {"<20%": 15, "20%-<30%": 25, "30%-<36%": 33, "50%-60%": 55, ">60%": 65}
df["dti"] = pd.to_numeric(df["debt_to_income_ratio"].replace(bands), errors="coerce")
df["cltv"] = pd.to_numeric(df["loan_to_value_ratio"], errors="coerce")
df["amount"] = pd.to_numeric(df["loan_amount"], errors="coerce")
df["income"] = pd.to_numeric(df["income"], errors="coerce") # thousands of dollars
df["denied"] = (df["action_taken"] == "3").astype(float)
df = df.dropna(subset=["dti", "cltv", "amount", "income"])
df = df[(df["cltv"] > 5) & (df["cltv"] <= 105) & (df["income"] > 0)].reset_index(drop=True)
df["log_amount"] = np.log(df["amount"])
df["log_income"] = np.log(df["income"])
print(f"{len(df):,} applications, {df['denied'].mean():.1%} denied")38,888 applications, 5.2% denied
Lenders also report why they denied an application. Among the denials, the principal reason:
reasons = {"1": "Debt-to-income ratio", "2": "Employment history", "3": "Credit history",
"4": "Collateral", "5": "Insufficient cash", "6": "Unverifiable information",
"7": "Credit application incomplete", "8": "Mortgage insurance denied", "9": "Other"}
(df.loc[df["denied"] == 1, "denial_reason-1"].map(reasons)
.value_counts(normalize=True).round(3).rename("share of denials").to_frame())| share of denials | |
|---|---|
| denial_reason-1 | |
| Debt-to-income ratio | 0.355 |
| Collateral | 0.180 |
| Credit history | 0.143 |
| Credit application incomplete | 0.100 |
| Other | 0.082 |
| Insufficient cash | 0.060 |
| Unverifiable information | 0.051 |
| Employment history | 0.027 |
| Mortgage insurance denied | 0.002 |
A cliff in the data
How does the denial rate vary with each input? For the debt-to-income ratio the answer is striking.
fig, axes = plt.subplots(1, 2, figsize=(9, 3.4), sharey=True)
by_dti = df.groupby("dti")["denied"].mean()
axes[0].plot(by_dti.index, by_dti.values, "o-", ms=4)
axes[0].set_xlabel("Debt-to-income ratio (%)")
axes[0].set_ylabel("Share denied")
cltv_bins = pd.cut(df["cltv"], [0, 60, 80, 90, 95, 97, 100, 105])
by_cltv = df.groupby(cltv_bins, observed=True)["denied"].mean()
axes[1].bar(range(len(by_cltv)), by_cltv.values)
axes[1].set_xticks(range(len(by_cltv)), [str(b) for b in by_cltv.index], rotation=45, fontsize=8)
axes[1].set_xlabel("Combined loan-to-value ratio (%)")
plt.tight_layout()
plt.show()Up to a debt-to-income ratio of 49%, a few percent of applications are denied, with little trend. Above 50%, more than a third are, and above 60%, most. The cliff has a known source: for loans underwritten through its Desktop Underwriter, Fannie Mae’s maximum debt-to-income ratio is 50% (Fannie Mae 2025), and loans above it cannot be sold to Fannie Mae. The loan-to-value ratio matters less, except near 100%, where the borrower makes almost no down payment.
Training, validation and test samples
We split the applications at random: 60% to train the models, 20% to choose when to stop training, and 20% to test them at the end. The inputs are standardized with the means and standard deviations of the training sample.
inputs = ["cltv", "dti", "log_amount", "log_income"]
rng = np.random.default_rng(0)
order = rng.permutation(len(df))
n_train, n_valid = int(0.6 * len(df)), int(0.2 * len(df))
train_rows = order[:n_train]
valid_rows = order[n_train:n_train + n_valid]
test_rows = order[n_train + n_valid:]
mu = df.loc[train_rows, inputs].mean()
sd = df.loc[train_rows, inputs].std()
X = torch.tensor(((df[inputs] - mu) / sd).to_numpy(), dtype=torch.float32)
y = torch.tensor(df[["denied"]].to_numpy(), dtype=torch.float32)A logit and a network
With two outcomes, the softmax of the chapter reduces to the logistic function: a model produces one score s, and the probability of denial is p = 1/(1 + e^{-s}). With a linear score, s = w_0 + \vec{w}'\vec{x}, this is the logit of statistics courses; a network computes s with a hidden layer instead. Both are trained by minimizing the cross-entropy, here binary_cross_entropy_with_logits, which takes the scores. The function fit trains a model on the training sample and keeps the weights from the epoch with the lowest loss on the validation sample. It returns the model and its probability of denial for every application.
def fit(net, X, epochs=1000):
torch.manual_seed(0)
opt = torch.optim.Adam(net.parameters(), lr=0.01)
loss_fn = nn.functional.binary_cross_entropy_with_logits
best = np.inf
for epoch in range(epochs):
opt.zero_grad()
loss = loss_fn(net(X[train_rows]), y[train_rows])
loss.backward()
opt.step()
with torch.no_grad():
valid_loss = loss_fn(net(X[valid_rows]), y[valid_rows]).item()
if valid_loss < best:
best = valid_loss
best_weights = {k: v.clone() for k, v in net.state_dict().items()}
net.load_state_dict(best_weights)
with torch.no_grad():
return net, torch.sigmoid(net(X)).numpy().ravel() # the model and its probabilities of denialHow do we judge a probability? Only 5% of applications are denied, so a model that predicts “approved” every time is right 95% of the time and useless. Instead we compare the squared errors of the predicted probabilities with those of the simplest forecast, the denial rate of the training sample, as an R^2 on the test applications:
outcome = df["denied"].to_numpy()
base_rate = outcome[train_rows].mean()
def r2(p, rows=test_rows):
return 1 - ((outcome[rows] - p[rows]) ** 2).sum() / ((outcome[rows] - base_rate) ** 2).sum()The logit is a single linear layer; the network has one hidden layer of 16 ReLU units.
torch.manual_seed(0)
logit_model, p_logit = fit(nn.Linear(4, 1), X)
torch.manual_seed(0)
net_model, p_net = fit(nn.Sequential(nn.Linear(4, 16), nn.ReLU(), nn.Linear(16, 1)), X)
pd.DataFrame({"R2 (test)": [r2(p_logit), r2(p_net)],
"R2 (training)": [r2(p_logit, train_rows), r2(p_net, train_rows)]},
index=["Logit", "Network, 16 units"]).round(3)| R2 (test) | R2 (training) | |
|---|---|---|
| Logit | 0.115 | 0.117 |
| Network, 16 units | 0.217 | 0.216 |
The network explains about twice as much of the variation in denials on the test applications as the logit, and its test and training R^2 are close, so it is not overfitting.
What the network learned
To see why, we vary one input at a time, holding the others at their medians, and plot each model’s probability of denial next to the denial rates in the data.
def vary(column, values):
grid = pd.DataFrame([df.loc[train_rows, inputs].median()] * len(values)).reset_index(drop=True)
grid[column] = values
Xg = torch.tensor(((grid[inputs] - mu) / sd).to_numpy(), dtype=torch.float32)
return Xg
fig, axes = plt.subplots(1, 2, figsize=(9, 3.4), sharey=True)
for ax, column, values, observed in [
(axes[0], "dti", np.linspace(15, 65, 101), by_dti),
(axes[1], "cltv", np.linspace(40, 105, 131), None),
]:
Xg = vary(column, values)
with torch.no_grad():
for name, model in [("Logit", logit_model), ("Network", net_model)]:
ax.plot(values, torch.sigmoid(model(Xg)).numpy().ravel(), label=name)
if observed is not None:
ax.plot(observed.index, observed.values, "o", ms=3, color="0.5", label="Share denied in the data")
ax.set_xlabel({"dti": "Debt-to-income ratio (%)", "cltv": "Combined loan-to-value ratio (%)"}[column])
axes[0].set_ylabel("Probability of denial")
axes[0].legend(frameon=False, fontsize=8)
plt.tight_layout()
plt.show()The logit’s probability can only rise along a single S-shaped curve in its linear score, so it compromises: it rises too early, overstating denials between about 40% and 50%, and too little, understating them above 55%. The network places kinks where the data bend and reproduces the cliff at 50%, without being told where it is.
Telling the logit where to look
A logit can produce a cliff too, if we give it the right inputs. Lenders have long done this by hand: Fuster et al. (2022) describe a “Nonlinear Logit,” with the inputs cut into bins, as reflecting “standard industry practice,” while their machine learning model differs in that “rather than the lender prespecifying the bin-ends, the process is fully data-driven.” We add dummy variables for the debt-to-income bands around the underwriting limits and for a loan-to-value ratio above 97%.
dummies = pd.DataFrame({
"dti_37_43": df["dti"].between(37, 43),
"dti_44_49": df["dti"].between(44, 49),
"dti_50_60": df["dti"] == 55,
"dti_above_60": df["dti"] == 65,
"cltv_above_97": df["cltv"] > 97,
}).astype(float)
Z = pd.concat([df[inputs], dummies], axis=1)
X_dummies = torch.tensor(((Z - Z.loc[train_rows].mean()) / Z.loc[train_rows].std()).to_numpy(),
dtype=torch.float32)
torch.manual_seed(0)
dummies_model, p_dummies = fit(nn.Linear(X_dummies.shape[1], 1), X_dummies)
print(f"Logit with dummies: R2 (test) {r2(p_dummies):.3f}")Logit with dummies: R2 (test) 0.220
With the cutoffs supplied, the logit does about as well as the network. The network’s advantage is that it found them from the data. Here we knew where to look, because Fannie Mae publishes its limit; in most problems nobody does, and the cutoffs, interactions and curves that matter are what the model has to discover.
What the data leave out
The public files omit most of what lenders actually see: the credit score, the borrower’s assets and employment, and the details of the automated underwriting recommendation. After the debt-to-income ratio, the most common reasons for denial are collateral, usually an appraisal that comes in below the price, and credit history, and nothing in our inputs measures either of them. This is why even the best model here explains only about a fifth of the variation in denials. HMDA does report the applicant’s race, ethnicity, sex and age, collected to monitor fair lending. We left them out of the models, but that does not make the predictions independent of them: inputs such as income and the loan-to-value ratio differ across groups, and a flexible model can pick up those differences. Fuster et al. (2022) find that machine learning models of default help Black and Hispanic borrowers less than others, mostly because of their greater flexibility.
What we learned
- A logit is the one-output version of a classifier: a linear score turned into a probability, trained by minimizing the cross-entropy. A network replaces the linear score with a hidden layer.
- On mortgage applications, the network explains about twice as much of the variation in denials out of sample, because underwriting has cliffs, such as the 50% limit on the debt-to-income ratio, that a linear score cannot produce.
- A logit with the right dummy variables matches the network, but only if someone knows where the cliffs are. Finding them from data is what flexibility buys.
- Accuracy is a poor measure when one outcome is rare; comparing predicted probabilities with a simple benchmark is better.
Try it
- Train networks with 4 and with 64 hidden units. How does the test R^2 change?
- Replace Missouri by another state, or by several (
states=MO,IL,KS). Is the cliff at 50% the same everywhere? - Add the applicant’s age (
applicant_age, reported in bands) as an input. Does the network use it? Should a lender? Look up what the Equal Credit Opportunity Act allows. - Predict the interest rate (
interest_rate) of the originated loans instead of denial, with a regression and a network trained on squared errors. Why do both explain much less than they did for denials? Think about what the public data do not report.