Skip to main content

AI and machine learning · Beginner · 20 min

Classify data with logistic regression and decision trees

By Padding · Updated 18 Nov 2026
Python 3.15 (python:3.15-slim) · scikit-learn 1.9.1 · NumPy 2.5.5

You will train a logistic regression and a shallow decision tree to flag loan instalments likely to be late, print the tree's rules, watch a deep tree overfit, and pick a decision threshold from what each kind of mistake costs.

On this page

A lender that collects instalments by mobile money or bank debit wants to know, a few days before each due date, which borrowers are likely to pay late. A reminder call or SMS to those borrowers is cheap; a late instalment is not. That is a classification problem: each row is a borrower, and the answer is one of two classes, late or on time.

In this tutorial you generate 4,000 loan records, then train two classic classifiers on them with scikit-learn. Logistic regression gives each borrower a score between 0 and 1. A decision tree gives you rules a credit officer can read. You check both against a baseline that always says "on time", see what happens when a tree is allowed to grow without limits, and finish by choosing the score at which you make the call, based on what each kind of mistake costs.

The data is synthetic, so the numbers are repeatable and no real borrower's details are involved. Everything runs on a laptop CPU in seconds.

Step 1 · Create the project and install scikit-learn

Make a throwaway folder and a virtual environment, then install pinned versions of scikit-learn and NumPy:

Bash
mkdir -p ~/late-loans-demo
cd ~/late-loans-demo
python3 -m venv .venv
source .venv/bin/activate
pip install --quiet scikit-learn==1.9.1 numpy==2.5.5

The download is something like 60 to 70 MB (scikit-learn, NumPy and SciPy). On prepaid mobile data, run it on Wi-Fi once; everything after this works offline.

Check it worked

Bash
python -c "import sklearn, numpy; print(sklearn.__version__, numpy.__version__)"

The output is 1.9.1 2.5.5.

Step 2 · Generate 4,000 loan records

Each record has five features and one label:

  • income: the borrower's monthly income, in thousands of the local currency
  • instalment: the monthly instalment, in the same units
  • tenure_months: how long they have borrowed from this lender
  • past_late: late instalments in the last 12 months
  • payday_match: 1 if the due date falls within three days of their payday, otherwise 0
  • late: 1 if this instalment was paid late, the thing you want to predict

The script draws the features at random and then decides late from a hidden rule: a bigger instalment relative to income and more past late payments push the chance up; a longer history and a due date near payday pull it down. Randomness on top means the same kind of borrower is sometimes late and sometimes not, as in real life.

Bash
cat > make_data.py <<'PY'
import csv

import numpy as np

rng = np.random.default_rng(11)
N = 4000

income = rng.lognormal(mean=np.log(250), sigma=0.45, size=N).round(0)   # monthly income, thousands
instalment = (income * rng.uniform(0.05, 0.45, size=N)).round(0)         # monthly instalment, thousands
tenure = rng.integers(1, 61, size=N)                                     # months with the lender
past_late = rng.poisson(0.6, size=N)                                     # late instalments in the last year
payday_match = rng.integers(0, 2, size=N)                                # 1 if due within 3 days of payday

ratio = instalment / income
score = -0.8 + 7.5 * (ratio - 0.25) + 0.9 * past_late - 0.03 * tenure - 0.8 * payday_match
p_late = 1 / (1 + np.exp(-score))
late = (rng.random(N) < p_late).astype(int)

with open("loans.csv", "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerow(["income", "instalment", "tenure_months", "past_late", "payday_match", "late"])
    for row in zip(income, instalment, tenure, past_late, payday_match, late):
        writer.writerow([int(v) for v in row])

print(f"wrote {N} loans, {late.mean():.1%} late")
PY
python make_data.py
head -4 loans.csv

The fixed seed in default_rng(11) gives you the same 4,000 rows every time.

Check it worked

The script prints wrote 4000 loans, 22.5% late, and head shows the header and three rows, the first being 254,33,19,0,1,0. About one instalment in five is late. Keep that figure in mind: a model that never predicts "late" is already right about 77% of the time.

Step 3 · Train logistic regression and beat a baseline

Both models need the same train and test split, so put the loading code in a small shared file. stratify=y keeps the share of late rows the same in both parts, and random_state=42 makes the split repeatable:

Bash
cat > common.py <<'PY'
import numpy as np
from sklearn.model_selection import train_test_split

FEATURES = ["income", "instalment", "tenure_months", "past_late", "payday_match"]


def load_split():
    data = np.loadtxt("loans.csv", delimiter=",", skiprows=1)
    X, y = data[:, :-1], data[:, -1].astype(int)
    return train_test_split(X, y, test_size=0.25, stratify=y, random_state=42)
PY

Logistic regression adds up the features, each multiplied by a learned weight, and squeezes the total into a number between 0 and 1. The features sit on very different scales (income in the hundreds, payday_match 0 or 1), so a StandardScaler goes in front of it in a pipeline. That also makes the weights comparable: each one is the effect of a one-standard-deviation change in that feature.

Bash
cat > logreg.py <<'PY'
import numpy as np
from sklearn.dummy import DummyClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

from common import FEATURES, load_split

X_train, X_test, y_train, y_test = load_split()
print(f"train: {len(y_train)}  test: {len(y_test)}  late in test: {y_test.mean():.1%}")

baseline = DummyClassifier(strategy="most_frequent").fit(X_train, y_train)
print(f"baseline (always 'on time') accuracy: {baseline.score(X_test, y_test):.3f}")

model = make_pipeline(StandardScaler(), LogisticRegression())
model.fit(X_train, y_train)
print(f"logistic regression accuracy:         {model.score(X_test, y_test):.3f}")

print("\nweights (per standard deviation of each feature):")
for name, weight in zip(FEATURES, model[-1].coef_[0]):
    print(f"  {name:<14} {weight:+.2f}")

applicants = np.array([
    [300, 30, 48, 0, 1],    # small instalment, long history, due on payday
    [200, 80, 6, 1, 0],     # 40% of income, new customer, one late payment
    [150, 70, 3, 3, 0],     # nearly half of income, three late payments
])
print("\nP(late) for three borrowers:")
for row, p in zip(applicants, model.predict_proba(applicants)[:, 1]):
    print(f"  income={row[0]:.0f} instalment={row[1]:.0f} tenure={row[2]:.0f} past_late={row[3]:.0f} -> {p:.2f}")

proba = model.predict_proba(X_test)[:, 1]
print("\nscore band   borrowers  actually late")
for low, high in [(0, 0.1), (0.1, 0.3), (0.3, 0.5), (0.5, 0.7), (0.7, 1.01)]:
    band = (proba >= low) & (proba < high)
    if band.any():
        print(f"  {low:.1f}-{min(high, 1):.1f}   {band.sum():>9}  {y_test[band].mean():>13.0%}")

assert model.score(X_test, y_test) > baseline.score(X_test, y_test)
PY
python logreg.py

Check it worked

The first lines show train: 3000 test: 1000, a baseline accuracy of 0.775 and a logistic regression accuracy of about 0.816. That gap looks small, and it is the honest way to judge a classifier: against the score you get for free by always guessing the common class.

The weights read the way the hidden rule was built. instalment and past_late are positive (they push towards late); income, tenure_months and payday_match are negative. The model was never told about the instalment-to-income ratio, yet it found that a large instalment and a small income both raise the risk.

Step 4 · Read predict_proba as a score, not a certainty

The three example borrowers get something like 0.02, 0.64 and 0.92. It is tempting to read 0.92 as "this borrower will be late". It means something weaker: among borrowers who look like this one, the model expects about 9 in 10 to pay late. One borrower is still either late or not.

The score-band table in the same output tests whether the scores mean what they say. It groups the 1,000 test borrowers by their score and shows how many in each group were really late:

  • 0.0-0.1: about 290 borrowers, 3% late
  • 0.3-0.5: about 160 borrowers, 45% late
  • 0.7-1.0: about 30 borrowers, 85% late

Higher scores go with more lateness, and each band's real rate sits roughly inside it. That is what makes the score useful for ranking borrowers and for setting a cut-off later. On your own data, check this table before you trust the numbers as probabilities: models trained on unbalanced or shifted data can be well ordered and still badly calibrated.

Check it worked

In your output, the actually late column rises from the first band to the last. If it does not, the score is not ranking borrowers and nothing later in this tutorial would help.

Step 5 · Train a shallow decision tree and print its rules

A decision tree asks a series of yes-or-no questions about the features ("is past_late above 1.5?") and ends in a leaf that holds a prediction. Limit it to three levels of questions and at least 50 training borrowers per leaf, so it stays small enough to read:

Bash
cat > tree.py <<'PY'
import numpy as np
from sklearn.tree import DecisionTreeClassifier, export_text

from common import FEATURES, load_split

X_train, X_test, y_train, y_test = load_split()

tree = DecisionTreeClassifier(max_depth=3, min_samples_leaf=50, random_state=0)
tree.fit(X_train, y_train)

print(export_text(tree, feature_names=FEATURES, show_weights=True))
print(f"tree accuracy on test: {tree.score(X_test, y_test):.3f}")
print(f"leaves: {tree.get_n_leaves()}")
print("distinct P(late) values on the test set:", np.unique(tree.predict_proba(X_test)[:, 1].round(2)))

assert tree.get_depth() == 3
PY
python tree.py

export_text prints the tree as indented rules. With show_weights=True, each leaf shows how many training borrowers landed there, as [on time, late].

Check it worked

The first split is on past_late <= 1.50, followed by splits on instalment, then tenure_months (and past_late again in one branch), and the tree has 8 leaves. One leaf reads like this:

Text
|--- past_late >  1.50
|   |--- instalment >  52.50
|   |   |--- tenure_months <= 13.00
|   |   |   |--- weights: [13.00, 37.00] class: 1

In words: two or more late payments last year, an instalment above 52,500, and 13 months or less with the lender. 37 of the 50 such borrowers in the training data paid late. A threshold usually falls halfway between two values seen in training, which is why most of them end in .50. This one is a whole number because no borrower in that branch has exactly 13 months, so the halfway point between 12 and 14 is 13. A credit officer can check that rule against experience, which is the main reason to choose a small tree.

Two other things to see in the output. The test accuracy, about 0.783, is below logistic regression's and barely above the baseline. And the tree's P(late) takes only eight values, one per leaf, because a tree's probability is the share of late borrowers in the leaf. It can sort borrowers into eight groups, not rank them finely.

Step 6 · Watch a deep tree overfit

A tree with no depth limit keeps splitting until every leaf is pure. On training data that looks perfect. Compare training and test accuracy as the depth grows:

Bash
cat > overfit.py <<'PY'
from sklearn.tree import DecisionTreeClassifier

from common import load_split

X_train, X_test, y_train, y_test = load_split()

print("max_depth  leaves  train_acc  test_acc  gap")
results = {}
for depth in [1, 2, 3, 5, 8, 12, None]:
    tree = DecisionTreeClassifier(max_depth=depth, random_state=0).fit(X_train, y_train)
    train_acc, test_acc = tree.score(X_train, y_train), tree.score(X_test, y_test)
    results[depth] = (train_acc, test_acc)
    print(f"{str(depth):>9}  {tree.get_n_leaves():>6}  {train_acc:>9.3f}  {test_acc:>8.3f}  {train_acc - test_acc:>+.3f}")

assert results[None][0] > 0.99
assert results[None][1] < results[3][1]
PY
python overfit.py

Check it worked

The last row, None, shows a tree with around 700 leaves, a training accuracy of 1.000 and a test accuracy near 0.71: worse than always saying "on time". Up to depth 5 the gap between the two columns stays near zero; from depth 8 it opens quickly.

That gap is overfitting. The deep tree has learned the noise in its 3,000 training rows, down to individual borrowers, and those details do not repeat in new borrowers. Always report the test score, and treat a large train-versus-test gap as a warning. Limits such as max_depth and min_samples_leaf are the fix for a single tree; validate a model honestly with cross-validation shows how to choose them without peeking at the test set.

Step 7 · Pick a threshold from the cost of each mistake

model.predict calls a borrower late when the score is 0.5 or more. That cut-off assumes both mistakes cost the same. Here they do not:

  • Missed late payer: no reminder, the instalment goes late. Say this costs 10 units in collection work and lost fees.
  • Needless call: a reminder to someone who would have paid. Say 2 units of staff time or SMS credit.

Replace those two numbers with your own. In general, if a miss costs M and a needless call costs C, a well-calibrated score should be acted on above about C / (C + M), here 2 / 12, about 0.17. The script below finds the cheapest threshold from the data instead of trusting that formula.

Choose the threshold on training data only, so the test set stays an honest check. cross_val_predict gives every training row a score from a model that never saw that row:

Bash
cat > threshold.py <<'PY'
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_predict
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

from common import load_split

# What each mistake costs, in the same units (say, thousands of naira or shillings).
COST_MISSED_LATE = 10   # no reminder call, the instalment goes late: collection work and lost fees
COST_NEEDLESS_CALL = 2  # a reminder call to a borrower who would have paid anyway

X_train, X_test, y_train, y_test = load_split()
model = make_pipeline(StandardScaler(), LogisticRegression())

# Out-of-fold scores on the training data: each row is scored by a model that never saw it.
oof = cross_val_predict(model, X_train, y_train, cv=5, method="predict_proba")[:, 1]


def cost(y_true, scores, threshold):
    flagged = scores >= threshold
    missed = np.sum(~flagged & (y_true == 1))
    needless = np.sum(flagged & (y_true == 0))
    return missed * COST_MISSED_LATE + needless * COST_NEEDLESS_CALL, missed, needless


print("threshold  flagged  missed_late  needless_calls  cost")
thresholds = np.round(np.arange(0.05, 0.96, 0.05), 2)
costs = []
for t in thresholds:
    total, missed, needless = cost(y_train, oof, t)
    costs.append(total)
    print(f"{t:>9.2f}  {np.mean(oof >= t):>7.1%}  {missed:>11}  {needless:>14}  {total:>5}")

best = float(thresholds[int(np.argmin(costs))])
print(f"\ncheapest threshold on training data: {best:.2f}")

model.fit(X_train, y_train)
scores = model.predict_proba(X_test)[:, 1]
for label, t in [("default 0.50", 0.5), (f"chosen {best:.2f}", best)]:
    total, missed, needless = cost(y_test, scores, t)
    print(f"test set, {label:<12}: missed {missed:>3}, needless calls {needless:>3}, cost {total:>5}")

assert cost(y_test, scores, best)[0] < cost(y_test, scores, 0.5)[0]
PY
python threshold.py

Check it worked

The table shows the trade as the threshold rises: fewer borrowers flagged, fewer needless calls, more missed late payers. The cost column is lowest at 0.15, close to the 0.17 from the formula, and the script prints cheapest threshold on training data: 0.15.

The last two lines apply both thresholds to the 1,000 test borrowers. At the default 0.50, the model misses about 157 late payers and costs about 1,624 units. At 0.15 it misses about 35, makes many more calls, and costs about 1,060 units, roughly a third less. Same model, different cut-off.

Try COST_MISSED_LATE = 3 and run the script again: the cheapest threshold moves up, to around 0.4, because a miss now costs only a little more than a call. If reminders go out by SMS, a cheap channel, a low threshold is often right; if each one takes a person's time, a higher one is. Whichever you choose, have a person review a sample of flagged and unflagged borrowers each month, and do not use a score like this alone to refuse or penalise someone: it is a prompt for a reminder, not a judgement.

Step 8 · Clean up

When you have finished, leave the virtual environment and remove the project folder:

Bash
deactivate
cd ~
rm -rf ~/late-loans-demo
ls ~/late-loans-demo 2>/dev/null || echo "removed"

Check it worked

The last command prints removed.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

AI-Integrated Solutions

Get new tutorials

New tutorials, about twice a month.