Grow a depth-limited regression tree

Why it matters Every boosted-tree model in production ranking, ads and fraud is a sum of trees grown like this.

A regression tree splits the data recursively on the feature and threshold that most reduce squared error.

Write tree_predict(X_train, y_train, X_test, max_depth, min_leaf). Grow greedily: at a node, try every feature j and every midpoint between consecutive distinct sorted values of that feature. A split is allowed only if both children have at least min_leaf rows. Pick the split with the lowest total squared error (sum of each child's squared deviations from its mean); on ties keep the first found (features in order, thresholds ascending). Stop when depth reaches max_depth, no split is allowed, or no split improves on the node's own error. Leaves predict the mean of their y. Send x[j] <= t left. Return predictions for X_test.

Signaturedef tree_predict(X_train, y_train, X_test, max_depth, min_leaf)

Example

X = [[1], [2], [3], [4]], y = [0, 0, 10, 10], depth 1 predicts [0, 10] for [[0], [5]].

Understand the idea

A regression tree keeps cutting the data into boxes so the targets inside each box are close to their mean. At every node it tries every feature and every midpoint, keeps the cut with the lowest total squared error, and repeats on each side until a stopping rule fires. Worked example: X = [1, 2, 3, 4], y = [1, 3, 8, 8], max_depth 1, min_leaf 1. Cut at 1.5: left [1] error 0, right [3, 8, 8] has mean 6.33 and error about 16.67. Cut at 2.5: left [1, 3] has mean 2 and error 2, right [8, 8] error 0, total 2. Cut at 3.5: left [1, 3, 8] has mean 4 and error 26. So 2.5 wins and the leaves predict 2 and 8. With min_leaf 3 no cut is allowed, so the root is a leaf predicting 5. Rule: child error = sum of (y - child mean)^2; a split needs both children to have at least min_leaf rows and must beat the parent's own error; go left when x[j] <= t; keep the first best on ties. Used in: random forests and every gradient boosting library.

Shapes and data flow

node(idx) -> try j in 0..d-1, t in midpoints
  left = idx[X[idx, j] <= t], right = the rest
leaf -> mean(y[idx])
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: exampletree_predict([[1], [2], [3], [4]], [0, 0, 10, 10], [[0], [5]], 1, 1)
  • Sample 2: depth 2tree_predict(_X, _y, _T, 2, 2)