Regression Tree with MSE and MAE Criteria

Quick Overview

Implement a regression tree from scratch with mean squared error and mean absolute error split criteria, including node impurity, best-split search, tie-breaking and stopping rules. It tests greedy tree growth, choosing leaf values that minimize each loss, and matching the behavior of scikit-learn's regressor.

Regression Tree with MSE and MAE Criteria

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Implement three pieces of a regression tree that supports two split criteria, `"mse"` and `"mae"`: a function `node_impurity(y, criterion)`, a function `best_split(X, y, criterion, min_samples_leaf)`, and a class `RegressionTree` with the methods `fit`, `predict`, `get_depth` and `get_n_leaves`. Requirements: - Impurity: `mse` is the mean squared deviation from the mean, and `mae` is the mean absolute deviation from the median. An empty target array has impurity `0.0`. An unknown criterion raises `ValueError` in all three APIs. - `best_split` tries the midpoints of consecutive unique values of each feature and sends `x <= t` to the left. The gain of a split is the parent impurity minus the size-weighted impurity of the two children. Return `(feature, threshold, gain)`, or `None` when no split is valid. On ties, keep the lowest feature index, then the lowest threshold. - Leaves are dicts `{"value", "n_samples"}`, where the value is the mean for `mse` and the median for `mae`. Internal nodes are dicts `{"feature", "threshold", "n_samples", "left", "right"}`. The root is stored in `tree_`. - Growth stops at `max_depth`, when a node has fewer than `min_samples_split` samples, on a pure node, or when no split has gain greater than `1e-12`. Each child needs at least `min_samples_leaf` samples. - A root-only tree has depth `0` and `1` leaf. - With `mse`, predictions should match scikit-learn's `DecisionTreeRegressor(criterion="squared_error")` trained with the same hyperparameters on typical data. Example: ```python X = [[1], [2], [3], [4]]; y = [1, 2, 3, 10] node_impurity(y, "mse") # 12.5 node_impurity(y, "mae") # 2.5 best_split(X, y, "mse") # (0, 3.5, 12.0) best_split(X, y, "mae") # (0, 3.5, 2.0) ``` ```hint Tie order Look at the order in which you visit features and thresholds, and at whether the comparison that replaces the current best is strict. Together they can enforce the tie rule without extra bookkeeping. ``` ```hint Stopping Some stopping checks need only the node itself, and one needs the result of the split search. Keep in mind that `best_split` can return a valid split whose gain is zero. ``` ### Constraints & Assumptions - `X` is an n by d array of real numbers (a list of lists is fine), and `y` holds n real values. - The constructor defaults follow scikit-learn: `RegressionTree(criterion="mse", max_depth=None, min_samples_split=2, min_samples_leaf=1)`. - NumPy is available. ### What a Strong Answer Covers - Impurity and leaf values that match each criterion's loss, with `ValueError` for an unknown criterion in every entry point. - A split search over midpoints that honors `min_samples_leaf`, the `x <= t` convention and the tie rule. - A recursive build that applies every stopping rule, stores nodes in the required dict shapes, and reports depth and leaf count correctly, including for a root-only tree. - The running time of the naive split search and why `mae` costs more than `mse`. - How the result lines up with scikit-learn's `squared_error` tree, and the cases where the two can disagree. ### Follow-up Questions - Why is `mae` splitting so much slower than `mse`, and how would you speed it up? - When would you prefer the MAE criterion over MSE? - How would you add cost-complexity pruning to this tree?

Overview: Implement a regression tree from scratch with mean squared error and mean absolute error split criteria, including node impurity, best-split search, tie-breaking and stopping rules. It tests greedy tree growth, choosing leaf values that minimize each loss, and matching the behavior of scikit-learn's regressor.

PracHub logo
General
Nov 24, 2026
mediumMachine Learning EngineerOtherMachine Learning
0
0

Implement three pieces of a regression tree that supports two split criteria, "mse" and "mae": a function node_impurity(y, criterion), a function best_split(X, y, criterion, min_samples_leaf), and a class RegressionTree with the methods fit, predict, get_depth and get_n_leaves.

Requirements:

  • Impurity: mse is the mean squared deviation from the mean, and mae is the mean absolute deviation from the median. An empty target array has impurity 0.0 . An unknown criterion raises ValueError in all three APIs.
  • best_split tries the midpoints of consecutive unique values of each feature and sends x <= t to the left. The gain of a split is the parent impurity minus the size-weighted impurity of the two children. Return (feature, threshold, gain) , or None when no split is valid. On ties, keep the lowest feature index, then the lowest threshold.
  • Leaves are dicts {"value", "n_samples"} , where the value is the mean for mse and the median for mae . Internal nodes are dicts {"feature", "threshold", "n_samples", "left", "right"} . The root is stored in tree_ .
  • Growth stops at max_depth , when a node has fewer than min_samples_split samples, on a pure node, or when no split has gain greater than 1e-12 . Each child needs at least min_samples_leaf samples.
  • A root-only tree has depth 0 and 1 leaf.
  • With mse , predictions should match scikit-learn's DecisionTreeRegressor(criterion="squared_error") trained with the same hyperparameters on typical data.

Example:

X = [[1], [2], [3], [4]]; y = [1, 2, 3, 10]
node_impurity(y, "mse")  # 12.5
node_impurity(y, "mae")  # 2.5
best_split(X, y, "mse")  # (0, 3.5, 12.0)
best_split(X, y, "mae")  # (0, 3.5, 2.0)

Constraints & Assumptions

  • X is an n by d array of real numbers (a list of lists is fine), and y holds n real values.
  • The constructor defaults follow scikit-learn: RegressionTree(criterion="mse", max_depth=None, min_samples_split=2, min_samples_leaf=1) .
  • NumPy is available.

What a Strong Answer Covers Guidance

  • Impurity and leaf values that match each criterion's loss, with ValueError for an unknown criterion in every entry point.
  • A split search over midpoints that honors min_samples_leaf , the x <= t convention and the tie rule.
  • A recursive build that applies every stopping rule, stores nodes in the required dict shapes, and reports depth and leaf count correctly, including for a root-only tree.
  • The running time of the naive split search and why mae costs more than mse .
  • How the result lines up with scikit-learn's squared_error tree, and the cases where the two can disagree.

Follow-up Questions Guidance

  • Why is mae splitting so much slower than mse , and how would you speed it up?
  • When would you prefer the MAE criterion over MSE?
  • How would you add cost-complexity pruning to this tree?