A Decision Tree predicts by asking a series of yes/no questions about the features (“Is BMI above 0.01?”), like a flowchart. For regression, each final leaf predicts the average target of the training rows that reach it.
What You Will Learn
- How a tree chooses its splits
- Why a fully grown tree overfits
- Controlling depth with max_depth and min_samples_leaf
- Reading the tree as rules
Prerequisites
How the Tree Is Built
At each step the algorithm tries every feature and many thresholds, and picks the split that makes the two groups most “pure”, meaning the targets in each group are as similar as possible. For regression it minimises the mean squared error inside the groups. It repeats this on each group until a stopping rule is met.
Step 1: Data and Helper
from sklearn.datasets import load_diabetes
from sklearn.model_selection import train_test_split
import numpy as np
import pandas as pd
from sklearn.metrics import r2_score, mean_squared_error, mean_absolute_error
X, y = load_diabetes(return_X_y=True, as_frame=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
def evaluate(name, model):
model.fit(X_train, y_train)
p = model.predict(X_test)
print(f'{name:22s} R2={r2_score(y_test, p):.3f} RMSE={np.sqrt(mean_squared_error(y_test, p)):.1f} MAE={mean_absolute_error(y_test, p):.1f}')
return model
Explanation: We use scikit-learn’s built-in diabetes dataset: 442 patients, 10 features (age, sex, BMI, blood pressure and six blood measurements, already scaled), and a target measuring disease progression one year later. It is a genuinely hard problem, so do not expect R² close to 1. The helper function trains a model and prints its test scores.
Step 2: A Fully Grown Tree
from sklearn.tree import DecisionTreeRegressor
t = evaluate('Tree full', DecisionTreeRegressor(random_state=42))
print('depth', t.get_depth(), 'leaves', t.get_n_leaves(), 'train R2', round(t.score(X_train, y_train), 3))
Explanation: The tree grew 19 levels deep with 346 leaves, almost one leaf per training row. It scores a perfect 1.0 on training data but only 0.06 on test data. This is overfitting: it memorised the training data instead of learning general patterns. (Linear regression scored R²=0.453 on the same split.)
Tree full R2=0.061 RMSE=70.5 MAE=54.5 depth 19 leaves 346 train R2 1.0
Step 3: Limit the Tree
evaluate('Tree depth3', DecisionTreeRegressor(max_depth=3, random_state=42))
evaluate('Tree depth4 minleaf10', DecisionTreeRegressor(max_depth=4, min_samples_leaf=10, random_state=42))
Explanation: Restricting the tree makes it simpler and much better on new data.
| Parameter | Effect |
|---|---|
| max_depth | Maximum number of questions in a row |
| min_samples_leaf | Each leaf must contain at least this many rows |
| min_samples_split | A node needs this many rows to be split |
| max_leaf_nodes | Cap on total leaves |
| ccp_alpha | Cost-complexity pruning strength |
Tree depth3 R2=0.329 RMSE=59.6 MAE=48.1 Tree depth4 minleaf10 R2=0.405 RMSE=56.1 MAE=45.3
Step 4: Read the Tree as Rules
from sklearn.tree import export_text
t3 = DecisionTreeRegressor(max_depth=3, random_state=42).fit(X_train, y_train)
print(export_text(t3, feature_names=list(X.columns)))
Explanation: The first split is on BMI, the most informative feature. Low BMI and low s5 lead to the lowest predicted progression (about 81); high BMI leads to the highest (about 291). This readability is the main strength of decision trees.
|--- bmi <= 0.01 | |--- s5 <= 0.01 | | |--- s5 <= -0.04 | | | |--- value: [80.88] | | |--- s5 > -0.04 | | | |--- value: [109.92] | |--- s5 > 0.01 | | |--- s4 <= 0.09 | | | |--- value: [159.57] | | |--- s4 > 0.09 | | | |--- value: [256.33] |--- bmi > 0.01 | |--- bmi <= 0.07 | | |--- s6 <= 0.03 | | | |--- value: [175.80] | | |--- s6 > 0.03 | | | |--- value: [230.52] | |--- bmi > 0.07 | | |--- s2 <= 0.02 | | | |--- value: [291.22] | | |--- s2 > 0.02 | | | |--- value: [225.75]
Step 5: Plot the Tree
import matplotlib.pyplot as plt
from sklearn.tree import plot_tree
plt.figure(figsize=(16, 6))
plot_tree(t3, feature_names=X.columns, filled=True, rounded=True)
plt.show()
Pros and Cons
Combining many trees fixes most of these weaknesses: see Random Forest and XGBoost.
| Advantages | Disadvantages |
|---|---|
| Easy to explain as rules | Overfits easily if not limited |
| No scaling needed | Unstable: small data changes can change the tree |
| Handles non-linear patterns and interactions | Predictions are step-shaped, not smooth |
| Fast | Usually less accurate than ensembles |
Common Errors
| Problem | Cause and fix |
|---|---|
| Train score 1.0, test score low | Overfitting; set max_depth or min_samples_leaf and tune with cross-validation. |
Practice Exercises
- Loop max_depth from 1 to 10 and plot train vs test R².
- Use GridSearchCV to tune max_depth and min_samples_leaf together.
Interview Questions
Q: How does a regression tree choose splits?
By the split that most reduces mean squared error in the child nodes.
Q: Why do deep trees overfit?
They create tiny leaves that memorise individual training rows.
Q: Does a tree need feature scaling?
No, splits depend only on the order of values.
Summary
A regression tree splits data into rule-based groups and predicts each group’s mean. Limit its depth and leaf size to avoid overfitting.
Next: Random Forest Regression
Machine Learning Tutorials, Courses and Certifications