Decision Tree vs Linear Regression Extrapolation on a 1D Trend
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: easy
Interview Round: Other
Given 1-D arrays `x_train`, `y_train` and `x_test`, fit a scikit-learn `DecisionTreeRegressor` and a `LinearRegression` and compare their predictions outside the training range. Implement the three functions below.
- `fit_tree_and_linear(x_train, y_train, max_depth=None, random_state=0)`: reshape x to a column and return `(tree, linear)`, both fitted. Pass `max_depth` and `random_state` to the tree.
- `predict_out_of_range(x_train, y_train, x_test, max_depth=None, random_state=0)`: return `{'tree': preds, 'linear': preds}`, each a float array of shape `(len(x_test),)`.
- `max_split_threshold(tree)`: return the largest threshold over the tree's internal nodes as a `float`, or `nan` if the tree has no splits.
Example:
```python
x = np.arange(10.0); y = 2*x + 1
predict_out_of_range(x, y, [-5, 15, 1000])
# {'tree': [1., 19., 19.], 'linear': [-9., 31., 1999.]}
max_split_threshold(fit_tree_and_linear(x, y)[0]) # 8.5
max_split_threshold(fit_tree_and_linear(x, y, max_depth=1)[0]) # 4.5
```
```hint Reading the fitted tree
A fitted tree exposes its node arrays through `tree_`. Check what leaf nodes store in the threshold array before you take a maximum over it.
```
### Constraints & Assumptions
- `x_train` and `y_train` have equal length, at least 2 points, and finite values.
- Inputs may be Python lists or 1-D NumPy arrays.
### What a Strong Answer Covers
- Reshaping the 1-D inputs into the 2-D feature matrix scikit-learn expects, for both training and test data.
- Fitting both models with the requested hyperparameters and returning the predictions as a dict of float arrays.
- A threshold lookup that ignores leaf nodes and handles a tree with no splits.
- Why the tree's predictions go flat outside the training range while the linear model keeps following the trend.
### Follow-up Questions
- Why are tree predictions constant beyond the largest threshold?
- How could you get a tree-based model that extrapolates trends?
- Would a random forest or gradient-boosted trees fix the extrapolation problem?
Overview: Fit a decision tree regressor and a linear regression on a one-dimensional linear trend and compare their predictions outside the training range. It tests why trees are piecewise constant and cannot extrapolate, scikit-learn input shapes, and reading split thresholds from a fitted tree.