Skip to main content
MahiDev — Learn. Build. Become AI-ready.

Lesson 23

Decision Tree Regressor

Predict a number by splitting inputs into leaves, where each leaf returns the average target of its rows. One example is on this page.

Intermediate12 min
Decision Tree Regressor MahiDev

What You Will Learn

  • Idea
  • Example
  • When to use it

Idea

A decision tree asks yes or no questions. Each question sends a row left or right. The prediction is the average target of the training rows that landed in the same leaf. Deep trees fit the training set closely and then fail on new rows.

Example

python
import numpy as np
from sklearn.tree import DecisionTreeRegressor

x = np.array([1, 2, 3, 8, 9], dtype=float).reshape(-1, 1)
y = np.array([2.0, 2.2, 1.8, 9.0, 9.4])
pred = DecisionTreeRegressor(max_depth=2, random_state=0).fit(x, y).predict([[3]])[0]
print(f"predict: {pred:.2f}")

Output:

text
predict: 1.80

When to use it

  • Use it when the relationship is a few thresholds, not a smooth line.
  • Limit max_depth or min_samples_leaf so a leaf is not a single odd row.
  • A single tree is easy to read and easy to overfit.

Loading playground…