Pulse Data Hub

Decision Trees in Python: Depth, Pruning and Rules, Tested

Decision trees in Python are the easiest model to explain and the easiest to over-fit. A tree asks a chain of yes/no questions about the features, and you can print every one of them. This tutorial grows trees on the UCI Adult census data (48,842 people, predicting who earns more than $50,000) and measures what tree depth, pruning and leaf size do to accuracy, reads the rules a small tree learns, and checks how stable the first split is. Everything ran on 23 November 2026 with Python 3.13, scikit-learn 1.9.1 and pandas 3.0.5.

The data and the baseline

The Adult data comes from the 1994 US census (UCI repository); we load it from a public copy. 23.9% of the 48,842 records have income above $50,000, so always answering “no” is right 76.1% of the time. We use eight columns (age, education years, marital status, occupation, sex, capital gain, capital loss and hours per week), turn the text columns into 0/1 columns, and hold out 25% of the rows (12,211) for testing.

import numpy as np, pandas as pd
from sklearn.tree import DecisionTreeClassifier, export_text
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.ensemble import RandomForestClassifier

URL = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/adult-all.csv"
cols = ["age", "workclass", "fnlwgt", "education", "education_num", "marital", "occupation", "relationship",
        "race", "sex", "capital_gain", "capital_loss", "hours", "country", "income"]
df = pd.read_csv(URL, names=cols, skipinitialspace=True)
df["high"] = (df.income == ">50K").astype(int)
X = pd.get_dummies(df[["age", "education_num", "marital", "occupation", "sex", "capital_gain", "capital_loss", "hours"]], drop_first=True).astype(float)
Xtr, Xte, ytr, yte = train_test_split(X, df.high, test_size=0.25, random_state=0, stratify=df.high)
print(len(Xtr), "train", len(Xte), "test", "| majority", round(1 - yte.mean(), 3))
36631 train 12211 test | majority 0.761

Overfitting: grow decision trees in Python to different depths

A tree with no depth limit keeps splitting until every training row is classified correctly. That memorises noise. We compare accuracy on the training and test sets as depth grows.

print("depth  train  test  leaves")
for d in (1, 2, 3, 5, 8, 12, 20, None):
    t = DecisionTreeClassifier(max_depth=d, random_state=0).fit(Xtr, ytr)
    print(f"{str(d):5s}  {t.score(Xtr, ytr):.3f}  {t.score(Xte, yte):.3f}  {t.get_n_leaves()}")
depth  train  test  leaves
1      0.761  0.761  2
2      0.830  0.827  4
3      0.845  0.843  8
5      0.853  0.853  29
8      0.861  0.857  119
12     0.875  0.858  571
20     0.912  0.840  2904
None   0.955  0.825  6317

Training accuracy only rises with depth, ending at 95.5% with 6,317 leaves, but test accuracy peaks at depth 12 (85.8%) and then falls to 82.5% for the unrestricted tree. The gap between 95.5% and 82.5% is the overfitting. A tree of depth 1 is no better than the baseline (76.1%), and depth 3 already reaches 84.3% with only eight leaves.

Bar chart of decision tree test accuracy by depth: depth 1 76.1%, depth 12 85.8%, no limit 82.5%, pruned 86.5%

Read the rules of a small tree

The strength of a tree is that you can read it. export_text prints the depth-3 tree:

small = DecisionTreeClassifier(max_depth=3, random_state=0).fit(Xtr, ytr)
print(export_text(small, feature_names=list(X.columns)))
|--- marital_Married-civ-spouse <= 0.50
|   |--- capital_gain <= 7055.50
|   |   |--- education_num <= 13.50 -> class: 0
|   |   |--- education_num >  13.50 -> class: 0
|   |--- capital_gain >  7055.50 -> class: 1
|--- marital_Married-civ-spouse >  0.50
|   |--- education_num <= 12.50
|   |   |--- capital_gain <= 5095.50 -> class: 0
|   |   |--- capital_gain >  5095.50 -> class: 1
|   |--- education_num >  12.50 -> class: 1

(The printout is shortened here: branches that end in the same class are merged on one line.) In words: people who are not married to a civilian spouse are predicted to earn under $50,000 unless they have capital gains above $7,055; married people with at least 13 years of education are predicted to earn over $50,000, and married people with fewer years of education only when their capital gains exceed $5,095. The importance scores show three features carry the whole tree: marital status 0.521, capital gain 0.247 and education years 0.232. Remember what this is: a pattern in 1994 census data, and it mixes marital status with household income, so it should not be read as a cause.

Prune decision trees in Python: leaf size and cost-complexity

Instead of capping depth, you can require each leaf to hold a minimum number of rows, or prune a full tree back with a penalty on its size (ccp_alpha).

for leaf in (1, 5, 20, 50, 100):
    t = DecisionTreeClassifier(min_samples_leaf=leaf, random_state=0).fit(Xtr, ytr)
    print("min_samples_leaf", leaf, round(t.score(Xte, yte), 3), "leaves", t.get_n_leaves())
path = DecisionTreeClassifier(random_state=0).cost_complexity_pruning_path(Xtr, ytr)
step = max(1, len(path.ccp_alphas) // 25)
best = max(((a, cross_val_score(DecisionTreeClassifier(ccp_alpha=a, random_state=0), Xtr, ytr, cv=3).mean())
            for a in path.ccp_alphas[::step]), key=lambda t: t[1])
pr = DecisionTreeClassifier(ccp_alpha=best[0], random_state=0).fit(Xtr, ytr)
print("pruned: alpha", round(best[0], 6), "test", round(pr.score(Xte, yte), 3), "leaves", pr.get_n_leaves())
rf = RandomForestClassifier(200, min_samples_leaf=3, random_state=0, n_jobs=2).fit(Xtr, ytr)
print("forest test", round(rf.score(Xte, yte), 3))
min_samples_leaf 1 0.825 leaves 6317
min_samples_leaf 5 0.845 leaves 2556
min_samples_leaf 20 0.858 leaves 872
min_samples_leaf 50 0.86 leaves 398
min_samples_leaf 100 0.857 leaves 223
pruned: alpha 8e-05 test 0.865 leaves 144
forest test 0.863

Requiring 50 rows per leaf lifts test accuracy from 82.5% to 86.0% and cuts the leaves from 6,317 to 398. Cost-complexity pruning, choosing alpha by 3-fold cross-validation on the training data only, reaches 86.5% with just 144 leaves. That single pruned tree matches a 200-tree random forest on the same features (86.3%), although it is much easier to read. Do not read too much into 0.2 points: the test set has 12,211 rows, so differences that small are within noise.

How stable is the first split?

Trees are often described as unstable, because small changes in the data can change the first question. We tested that by training depth-3 trees on 10 bootstrap resamples of the training set and recording the root question each time. All 10 chose marital status (Married-civ-spouse) as the root. On this data the top of the tree is stable; the instability people warn about shows more in the deeper splits, which we did not measure here. A forest of many trees, as in our random forests tutorial, averages that variation away.

When decision trees in Python are the right choice

  • You must explain each prediction, or hand the rules to non-technical people.
  • Features are mixed numbers and categories, with no need to scale them, unlike k-nearest neighbors.
  • You want a strong baseline fast. A pruned tree reached 86.5% here in seconds.
  • Not alone for top accuracy. For that, use a forest or boosting; see XGBoost, LightGBM and CatBoost compared.

For the evaluation habits used above (baseline, held-out test set, no peeking), read our scikit-learn model tutorial. The scikit-learn decision tree guide documents every parameter.

FAQ

What is a decision tree in machine learning?

A model that predicts by asking a series of yes/no questions about the features, such as “is the person married?” or “are capital gains above 7,055?”, until it reaches a leaf with a prediction.

How do I stop a decision tree from overfitting?

Limit its depth, require a minimum number of rows per leaf, or prune it with ccp_alpha. In our test, an unrestricted tree scored 82.5% on new data, while 50 rows per leaf gave 86.0% and pruning gave 86.5%.

What max_depth should I use?

Choose it with cross-validation. On the census data the test accuracy peaked around depth 12 (85.8%), but depth 3 already reached 84.3% with only eight leaves.

Are decision trees better than random forests?

A single tree is easier to read, a forest is usually more accurate and stable. On this data a pruned tree (86.5%) matched a 200-tree forest (86.3%), but that is not guaranteed on other data.

Newsletter Signup Form

Latest tutorials

Latest articles

On this page
Verified by MonsterInsights