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
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
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:
predict: 1.80When to use it
- Use it when the relationship is a few thresholds, not a smooth line.
- Limit
max_depthormin_samples_leafso a leaf is not a single odd row. - A single tree is easy to read and easy to overfit.
Loading playground…