Understand the idea
A regression tree repeatedly splits rows using thresholds. Each terminal leaf predicts an average training target. Threshold order matters; feature scaling is unnecessary.
Illustrative data
| Column | Values |
|---|---|
x | 1, 2, 3, 6, 7, 8 |
target | 3, 5, 7, 12, 14, 16 |
Click the highlighted code to change the result.
example_model = DecisionTreeRegressor(max_depth=1, random_state=42)
example_model.fit(example[["x"]], example["target"])
example_model.predict(pd.DataFrame({"x": []})) # 5r2: x=2 → prediction 5, residual 0.
What the syntax does
DecisionTreeRegressor- Creates a regression tree whose terminal leaves predict fitted target averages.
plot_tree(model)- Draws the fitted split structure, leaf values and sample counts.
Supplied for this practice
These objects are prepared afresh before your editor runs.
X- Feature dataframe for the declared population, preserving row indices.
X = df[['x']] y- Target series, aligned with
X.y = df.y X_train/X_test/y_train/y_test- Training feature rows from the declared split. Final-test feature rows from the declared split. Training targets, aligned with
X_train. Final-test targets, aligned withX_test.X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
Outputs you create
answer- The requested result, with the values, labels and row order described by this task.
x | y |
|---|---|
| 0 | 10.4571 |
| 0.169492 | 8.44002 |
| 0.338983 | 11.1257 |
| 0.508475 | 11.4108 |
| 0.677966 | 7.07345 |
| 0.847458 | 8.04673 |
| 1.01695 | 10.1918 |
| 1.18644 | 9.52564 |
- Fit a depth-three tree to STEP60 and draw its splits and leaf values.
answerHints
Think: Each leaf predicts a quantity learned from the training outcomes reaching it.
Tools: DecisionTreeRegressor, max_depth and plot_tree.
Approach: Fit the declared tree, render its labelled splits and predict the held-away rows.
Explained solution
from sklearn.tree import DecisionTreeRegressor,plot_tree
import matplotlib.pyplot as plt
model=DecisionTreeRegressor(max_depth=3,random_state=42).fit(X_train,y_train)
fig,ax=plt.subplots(figsize=(9,4))
plot_tree(model,feature_names=['x'],ax=ax)
answer=model.predict(X_test)
The diagram connects threshold decisions to leaf values; the depth cap limits how finely the training population is partitioned.