Decision Tree Regression is a supervised machine learning algorithm that predicts a numerical value by splitting data into smaller groups.
Instead of fitting one equation to all the data, a decision tree learns a sequence of questions. Each question sends an observation down a branch until it reaches a leaf, where the model makes its prediction.
In this tutorial, we’ll learn the intuition behind decision trees, understand how they choose splits, and build a Decision Tree Regression model using Python and scikit-learn.
Quick recap
A decision tree regressor predicts a number by asking a series of yes/no questions about the features, landing in a leaf, and returning the average of the training y values in that leaf.
It does not need feature scaling. Its predictions form a staircase rather than a smooth curve. If the tree grows too deep, it can memorize the training data.
1. Where This Fits
So far, we’ve explored several regression algorithms:
Algorithm
Main idea
Simple Linear Regression
Fit a straight line
Multiple Linear Regression
Fit a plane/line using several features
Polynomial Regression
Fit a curve using powers of the feature
Support Vector Regression (SVR)
Fit a function within an error margin
Decision Tree Regression
Split the data into groups, predict each group's average
The key difference is that many earlier models learn an equation. A decision tree instead learns a sequence of rules.
2. Classification Trees vs. Regression Trees
Decision trees belong to a family of algorithms called CART, which stands for Classification and Regression Trees.
Type
Predicts
Example
scikit-learn class
Classification tree
A category
Is this email spam?
DecisionTreeClassifier
Regression tree
A number
What salary?
DecisionTreeRegressor
This tutorial focuses on regression trees, which predict numerical values. Don’t mix up the two class names.
3. The Intuition Behind a Decision Tree
3.1 A simple example with one feature
Imagine we want to predict a person’s salary from their position level. A tree might ask:
Is the position level less than or equal to 8.5?
If yes, is it less than or equal to 6.5?
If yes, is it less than or equal to 3.5?
Each question divides the data into smaller groups. The final groups are called terminal leaves, or simply leaves.
A simplified tree might look like this:
Level <= 8.5? / \ Yes No / \ Level <= 6.5? Predict / \ average Yes No salary / \ Level <= 3.5? Predict / \ average Yes No salary | | Predict Predict average average salary salary
Each leaf stores a prediction based on the training samples that reached it.
3.2 What if we have two features?
Imagine two input features, x1 and x2, and a target y. We can plot x1 and x2 on a 2D scatterplot. The target y is a third axis sticking out of the screen, so we can’t see it on the plot, but it’s there.
The tree cuts the scatterplot into rectangular regions using threshold questions:
For example:
Is x1 < 20?
If yes, ask: is x2 < 200?
If no, ask: is x2 < 170?
If that answer is yes, ask: is x1 < 40?
These thresholds are only for illustration. The algorithm learns the real ones from the training data.
Each leaf predicts the average y of the training samples inside it.
Example: a new observation arrives with x1 = 30 and x2 = 50.
x1 < 20? No.
x2 < 170? Yes.
x1 < 40? Yes.
We land in a leaf. If the training samples in that leaf have an average y of 64.1, the prediction is 64.1
3.3 Why split the data at all?
Without a model, the default prediction for every new observation would be the average of all y values.
A decision tree tries to do better by dividing the data into groups and using the local average of each group. If a group contains samples with similar y values, its average is a more useful prediction than the global average.
4. How Does the Tree Choose Its Splits?
The algorithm tries many possible split points and keeps the one that makes the resulting groups as uniform as possible in y.
For regression, scikit-learn's default criterion is squared error. The error within a group is measured as the mean squared error (MSE) around the group's average:
MSE=n1i=1∑n(yi−yˉ)2
Where:
n = number of samples in the group
yi = actual target value of a sample
yˉ = average target value of the group
A good split produces groups with small MSE, meaning the points in each group are similar.
A note about entropy: Lectures often mention information entropy. That idea belongs to classification trees. Regression trees in scikit-learn use squared error. The intuition (“does this split add useful information?”) is the same.
Where do the split values come from?
For a numeric feature, candidate thresholds are the midpoints between neighboring values. For example, if the dataset contains position levels 6 and 7, a candidate threshold is:
26+7=6.5
This threshold separates values into:
values less than or equal to6.5 (left branch)
values greater than6.5 (right branch)
When does the tree stop splitting?
When a stopping condition is reached. Examples:
every leaf is "pure" (here: contains one point),
max_depth is reached,
a split would make a leaf with too few samples (min_samples_leaf).
By default, scikit-learn sets none of these limits, so the tree grows until the leaves are pure.
5. How Does a Leaf Make a Prediction?
The rule is simple:
A leaf predicts the average target value of the training samples inside it.
Suppose a leaf contains these salaries:
salaries = [100000, 120000, 140000]
The prediction is:
y^=3100000+120000+140000=120000
Any new observation landing in that leaf is predicted as 120,000. If a leaf contains only one training sample, its average is simply that sample’s target value.
6. Decision Tree Regression vs. Linear Regression
Linear Regression
Decision Tree Regression
Learns an equation
Learns a sequence of rules
Prediction changes smoothly
Prediction is constant inside each leaf
Can extrapolate a linear trend
Prediction is always an average of training targets (so it can't produce values outside that set)
Sometimes benefits from feature scaling
No feature scaling needed
Why don’t decision trees need feature scaling?
A tree only asks: “Is this feature less than or equal to a threshold?” It never computes distances or coefficients, so it doesn’t matter if one feature ranges from 1 to 10 and another from 0 to 1,000,000.
The same applies to Random Forests, which combine many decision trees.
7. Hands-On: Decision Tree Regression in Python
We’ll use the Position Salaries example dataset.
7.1 Understanding the dataset
The dataset contains position levels and corresponding salaries.
Position
Level
Salary
Business Analyst
1
45,000
Junior Consultant
2
50,000
Senior Consultant
3
60,000
Manager
4
80,000
Country Manager
5
110,000
Region Manager
6
150,000
Partner
7
200,000
Senior Partner
8
300,000
C-level
9
500,000
CEO
10
1,000,000
Our goal is to predict salary based on position level.
The example asks whether a candidate claiming a salary of $160,000 for level 6.5 is telling the truth or bluffing. This is why the plot is titled "Truth or Bluff."
Why only one feature? Trees work with many features. We use one here because it’s easy to visualize in 2D.
7.2 Import the libraries
import numpy as npimport matplotlib.pyplot as pltimport pandas as pd
Library
Purpose
NumPy
Working with numerical arrays and grids
Matplotlib
Creating visualizations
Pandas
Loading and handling the dataset
7.3 Create the dataset
Our dataset has only ten observations, so we can create it directly with a Pandas DataFrame instead of loading a CSV file.
data is a Python dictionary. Each key becomes a column name, and each list becomes that column’s values.
All three lists must have the same length (10), or Pandas raises an error.
pd.DataFrame(data) turns the dictionary into a table, the same kind of object pd.read_csv() would give us.
Loading from a CSV instead? For larger datasets, use dataset = pd.read_csv("your-file.csv"). Everything after this step stays the same, because both approaches give a DataFrame. In Google Colab with Drive, mount it first:
from google.colab import drivedrive.mount('/content/drive')
7.4 Separate features (X) and target (y)
target_column = "Salary"X = dataset.drop(columns=[target_column, "Position"]).valuesy = dataset[target_column].valuesX, y # just displays the arrays so you can inspect them
Let’s understand what we did:
y is Salary, the thing we predict.
X is everything else except Position. Position is text (job titles) that just duplicates the numeric Level column, so we drop it. The remaining column is Level.
.values converts pandas objects to NumPy arrays.
Equivalent, and a bit easier to read: X = dataset[["Level"]].values. Both give a 2D array of shape (10, 1).
7.5 Train the Decision Tree Regression model
from sklearn.tree import DecisionTreeRegressorregressor = DecisionTreeRegressor(random_state=0)regressor.fit(X, y)
What does this code do?
DecisionTreeRegressor is the scikit-learn class for predicting numerical values.
random_state=0 helps make results reproducible when randomness is involved, such as breaking ties between equally good splits.
.fit(X, y) trains the model. Internally, it tries split points, scores them by squared error, builds the groups, and stores an average in each leaf.
We train on the whole dataset (no train/test split) because it only has 10 rows and we want to use all of them.
If you want better generalization, tune parameters like max_depth and min_samples_leaf (see Section 8), typically with grid search.
7.6 Predict a new result
Let’s predict the salary for position level 6.5:
pred = regressor.predict([[6.5]])pred
Output:array([150000.])
Why [[6.5]] and not 6.5? scikit-learn expects a 2D array: rows are observations, columns are features.
[[feature_1, feature_2, ...]] # one observation
We have one observation with one feature, so [[6.5]].
Why exactly 150,000?
This is the most important insight of this example.
With default settings, the tree keeps splitting until each leaf holds exactly one training point.
The leaf average of a single point is just that point's value.
The threshold between levels 6 and 7 is 6.5. scikit-learn sends values ≤ threshold to the left branch, so 6.5 lands in the level 6 leaf.
Level 6's salary is 150,000, so that's the prediction.
This depends on the tree actually choosing 6.5 as that threshold; verify it with the plot_tree code in 7.9, as noted below.
So the tree didn't "learn a pattern" here. It memorized the data. This is overfitting, and with only 10 points, there's nothing else it could do.
Verify it yourself: run the plot_tree code in 7.9 and check that the split at Level <= 6.5 sends 6.5 to the left, toward the level-6 leaf.
Is that a good result?
The candidate claimed $160,000, which is above the model's 150,000 prediction, so under this model the claim looks like a bluff. But since the model is just memorizing, we shouldn't trust it too much. The model's output is useful for understanding how a decision tree works, not as proof that the model is a reliable salary predictor.
7.7 Visualizing the Decision Tree Regression Results
Let’s visualize the actual data and the model’s predictions.
X_grid = np.arange(X.min(), X.max(), 0.1)X_grid = X_grid.reshape(len(X_grid), 1)plt.scatter(X, y, color="red")plt.plot(X_grid, regressor.predict(X_grid), color="blue")plt.title("Truth or Bluff (Decision Tree Regression)")plt.xlabel("Position Level")plt.ylabel("Salary")plt.show()
Why a fine grid (X_grid)? The tree's prediction is flat within each region. If we only predicted at levels 1, 2, 3, ..., the plot would connect the dots with straight lines and hide the real shape. A grid with steps of 0.1 reveals it.
np.arange(X.min(), X.max(), 0.1) makes values 1.0, 1.1, 1.2, ... 9.9. (arange excludes the end value, so the grid stops just before 10.)
.reshape(len(X_grid), 1) turns it into a 2D column, as predict requires.
🔴 Red dots = real data. 🔵 Blue line = model predictions.
7.8 Why does the prediction look like a staircase?
Each leaf has one constant prediction.
For example, with a fully grown tree, the thresholds sit at the midpoints between training levels. So for the region between 5.5 and 6.5, the prediction is constant:
Then, at a split threshold, the prediction jumps to another value. That creates a staircase instead of a smooth curve. It may look unusual compared with linear or polynomial regression, but it is exactly how a decision tree works.
7.9 Optional: Visualize the actual tree
We can also display the tree itself:
from sklearn.tree import plot_treeplt.figure(figsize=(12, 6))plot_tree(regressor, feature_names=["Level"], filled=True)plt.show()
This draws the real tree: the thresholds (like Level <= 6.5), the number of samples in each node, and the predicted value. It’s the best way to see that the leaves hold single points.
8. Limitations of Decision Tree Regression
Decision trees are easy to understand, but they have some important limitations.
Problem
What it means
How to reduce it
Overfitting
The tree memorizes the training data and may perform poorly on new data
Limit growth with max_depth, min_samples_split, min_samples_leaf
Poor extrapolation
Its prediction is always an average of training targets, so it can't follow a trend beyond the training range (level 20 would just get the level-10 leaf's value)
Use a model that learns trends, such as linear regression
Instability on small data
Small data changes can change the splits a lot
Use more data, or ensembles (Random Forest)
Controlling overfitting
We can limit the tree’s complexity by setting parameters such as:
A smaller tree may not memorize every training sample. Instead, it creates larger leaves, each containing multiple samples. The prediction for each leaf is then the average of those samples' target values. With max_depth=3, the prediction for 6.5 changes from 150,000 to a blended average; plot it with the Section 7.7 code to see the coarser staircase.
9. Using Decision Tree Regression on Your Own Dataset
Only two things need changing:
The data source: either create a DataFrame like in 7.3, or load your own file with pd.read_csv("your-file.csv"). If you use Colab with Drive, mount it first.
Feature selection: adjust drop(columns=[...]) so X has exactly the feature columns you want.
Then check your data for:
Missing values → handle with, e.g. SimpleImputer.
Categorical (text) features:
order matters (e.g., clothing sizes S < M < L) → LabelEncoder / ordinal encoding
order doesn't matter (e.g., countries) → OneHotEncoder via ColumnTransformer
Feature scaling → ❌ not needed.
Train/test split → optional here, but recommended on larger datasets so you can measure performance on unseen data.
With several features, you can't plot in 2D. Evaluate with metrics (e.g., R², MSE) on a test set instead.
10. Complete Code
Here is the complete implementation in one place.
# Importing Librariesimport numpy as npimport matplotlib.pyplot as pltimport pandas as pd# Creating the Datasetdata = { "Position": [ "Business Analyst", "Junior Consultant", "Senior Consultant", "Manager", "Country Manager", "Region Manager", "Partner", "Senior Partner", "C-level", "CEO" ], "Level": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], "Salary": [ 45000, 50000, 60000, 80000, 110000, 150000, 200000, 300000, 500000, 1000000 ]}dataset = pd.DataFrame(data)# Separating features and targettarget_column = "Salary"X = dataset.drop(columns=[target_column, "Position"]).valuesy = dataset[target_column].values# Training the Decision Tree Regression model on the whole datasetfrom sklearn.tree import DecisionTreeRegressorregressor = DecisionTreeRegressor(random_state=0)regressor.fit(X, y)# Predicting a new resultpred = regressor.predict([[6.5]])pred # array([150000.])# Visualizing the results (higher resolution)X_grid = np.arange(X.min(), X.max(), 0.1)X_grid = X_grid.reshape(len(X_grid), 1)plt.scatter(X, y, color="red")plt.plot(X_grid, regressor.predict(X_grid), color="blue")plt.title("Truth or Bluff (Decision Tree Regression)")plt.xlabel("Position Level")plt.ylabel("Salary")plt.show()
11. Key Takeaways
A regression tree predicts numbers by splitting data into regions with yes/no rules.
Each leaf's prediction = average y of the training points in it.
Splits are chosen to reduce squared error. Candidate thresholds are midpoints between values.
No feature scaling is needed (splits are just threshold comparisons).
The prediction curve is a staircase because predictions are constant inside each leaf.
With default settings, the tree grows until leaves are pure, so on tiny data it memorizes (that's why level 6.5 → 150,000 exactly).
Trees can't extrapolate and can overfit. Control them with max_depth and min_samples_*.
Trees work best with many features. The one-feature example is just for visualization.
Use DecisionTreeRegressor for numbers and DecisionTreeClassifier for categories.
One-sentence memory aid:A decision tree regressor asks a series of questions about the features, lands in a leaf, and returns that leaf's average target value.
Next up: Random Forest Regression, which combines many decision trees to get more stable predictions. 🌲🌲🌲