Implement a Multiclass Softmax Gradient Boosting Step

Quick Overview

Implement one round of multiclass gradient boosting under multinomial log-loss, with softmax probabilities, one regression tree per class fit on the residuals, and Newton leaf values written into sklearn trees. It tests numerical stability, the gradient and Hessian of the softmax loss, and careful array handling.

Implement a Multiclass Softmax Gradient Boosting Step

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Implement one iteration of multiclass gradient boosting under multinomial log-loss. The model keeps a raw score for every sample and class, turns the scores into probabilities with a row-wise softmax, and each iteration fits one regression tree per class on the residuals. The tree fitting and the leaf values follow sklearn's `GradientBoostingClassifier`. Write four functions: - `softmax(raw)` returns a numerically stable row-wise softmax of an `(n_samples, n_classes)` array. - `initial_raw_predictions(y, n_classes)` returns the log class priors, clipped to `[eps, 1]` with `eps = np.finfo(float).eps`, tiled to shape `(n_samples, n_classes)`. - `softmax_residuals(y, raw, n_classes)` returns `one_hot(y) - softmax(raw)`. - `boosting_step(X, y, raw, n_classes, learning_rate, max_depth, random_state)` runs one iteration and returns `(new_raw, trees)`. Leaf values use one Newton step. With $K$ = `n_classes`, the value of a leaf in the tree for class $k$ is $$ \gamma_{k} = \frac{K-1}{K} \cdot \frac{\sum_{i \in \text{leaf}} r_{ik}}{\sum_{i \in \text{leaf}} p_{ik}(1 - p_{ik})} $$ where $r_{ik}$ and $p_{ik}$ are the residual and the probability of sample $i$ for class $k$, both computed from the input `raw`. Use `0` when the absolute value of the denominator is below `1e-150`. In `boosting_step`, for each class $k$: 1. Fit `DecisionTreeRegressor(criterion="friedman_mse", max_depth=max_depth, random_state=random_state)` on column $k$ of the residuals. 2. Overwrite each leaf's value in `tree.tree_.value` with $\gamma_k$. 3. Set column $k$ of `new_raw` to `raw[:, k] + learning_rate * tree.predict(X)`. `raw` must not be mutated, and `trees` is the list of the $K$ fitted trees in class order. Example: ```python X = [[0.], [1.], [2.], [3.]] y = [0, 0, 1, 2] raw = np.zeros((4, 3)) new_raw, trees = boosting_step(X, y, raw, 3, learning_rate=0.5, max_depth=1, random_state=0) # new_raw: # [[ 1.0, -0.5, -0.5], # [ 1.0, -0.5, -0.5], # [-0.5, 0.25, -0.5], # [-0.5, 0.25, 1.0]] # len(trees) == 3 ``` ```hint Shared probabilities Compute the probabilities once from the input scores. If they change between classes, the later trees see different residuals. ``` ```hint Grouping by leaf `tree.apply(X)` returns the leaf index of every sample, which lets you sum residuals and Hessian terms per leaf. ``` ### Constraints & Assumptions - Labels `y` are integers in `[0, n_classes)`. - `X` has shape `(n_samples, n_features)` and `raw` has shape `(n_samples, n_classes)`. - `numpy` and sklearn's `DecisionTreeRegressor` are available. ### What a Strong Answer Covers - A softmax that subtracts the row maximum, and why that leaves the probabilities unchanged - Residuals and Hessian terms computed once from the pre-step scores and used by all K trees - The leaf value with the (K-1)/K factor and the guard for a near-zero denominator - Overwriting `tree_.value` so that `tree.predict` returns exactly the value applied to the scores - A copy of `raw` for the output, and the cost of one step in terms of samples, features and classes ### Follow-up Questions - Where does the (K-1)/K factor come from, and what happens to training if you drop it? - How would sample weights change the prior, the tree fit and the leaf values? - Adding the same constant to every class score of a sample leaves the softmax unchanged. What does that mean for the initial scores and for the trees? - How would you build a full `fit` and `predict_proba` on top of this step, with early stopping on a validation set?

Overview: Implement one round of multiclass gradient boosting under multinomial log-loss, with softmax probabilities, one regression tree per class fit on the residuals, and Newton leaf values written into sklearn trees. It tests numerical stability, the gradient and Hessian of the softmax loss, and careful array handling.

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

Implement one iteration of multiclass gradient boosting under multinomial log-loss. The model keeps a raw score for every sample and class, turns the scores into probabilities with a row-wise softmax, and each iteration fits one regression tree per class on the residuals. The tree fitting and the leaf values follow sklearn's GradientBoostingClassifier.

Write four functions:

  • softmax(raw) returns a numerically stable row-wise softmax of an (n_samples, n_classes) array.
  • initial_raw_predictions(y, n_classes) returns the log class priors, clipped to [eps, 1] with eps = np.finfo(float).eps , tiled to shape (n_samples, n_classes) .
  • softmax_residuals(y, raw, n_classes) returns one_hot(y) - softmax(raw) .
  • boosting_step(X, y, raw, n_classes, learning_rate, max_depth, random_state) runs one iteration and returns (new_raw, trees) .

Leaf values use one Newton step. With KK = n_classes, the value of a leaf in the tree for class kk is

γk=K−1K⋅∑i∈leafrik∑i∈leafpik(1−pik)\gamma_{k} = \frac{K-1}{K} \cdot \frac{\sum_{i \in \text{leaf}} r_{ik}}{\sum_{i \in \text{leaf}} p_{ik}(1 - p_{ik})}

where rikr_{ik} and pikp_{ik} are the residual and the probability of sample ii for class kk, both computed from the input raw. Use 0 when the absolute value of the denominator is below 1e-150.

In boosting_step, for each class kk:

  1. Fit DecisionTreeRegressor(criterion="friedman_mse", max_depth=max_depth, random_state=random_state) on column kk of the residuals.
  2. Overwrite each leaf's value in tree.tree_.value with γk\gamma_k .
  3. Set column kk of new_raw to raw[:, k] + learning_rate * tree.predict(X) .

raw must not be mutated, and trees is the list of the KK fitted trees in class order.

Example:

X = [[0.], [1.], [2.], [3.]]
y = [0, 0, 1, 2]
raw = np.zeros((4, 3))
new_raw, trees = boosting_step(X, y, raw, 3, learning_rate=0.5, max_depth=1, random_state=0)
# new_raw:
# [[ 1.0, -0.5,  -0.5],
#  [ 1.0, -0.5,  -0.5],
#  [-0.5,  0.25, -0.5],
#  [-0.5,  0.25,  1.0]]
# len(trees) == 3

Constraints & Assumptions

  • Labels y are integers in [0, n_classes) .
  • X has shape (n_samples, n_features) and raw has shape (n_samples, n_classes) .
  • numpy and sklearn's DecisionTreeRegressor are available.

What a Strong Answer Covers Guidance

  • A softmax that subtracts the row maximum, and why that leaves the probabilities unchanged
  • Residuals and Hessian terms computed once from the pre-step scores and used by all K trees
  • The leaf value with the (K-1)/K factor and the guard for a near-zero denominator
  • Overwriting tree_.value so that tree.predict returns exactly the value applied to the scores
  • A copy of raw for the output, and the cost of one step in terms of samples, features and classes

Follow-up Questions Guidance

  • Where does the (K-1)/K factor come from, and what happens to training if you drop it?
  • How would sample weights change the prior, the tree fit and the leaf values?
  • Adding the same constant to every class score of a sample leaves the softmax unchanged. What does that mean for the initial scores and for the trees?
  • How would you build a full fit and predict_proba on top of this step, with early stopping on a validation set?