Implement Binary Log-Loss Gradient Boosting with Newton Leaf Values
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Complete `NewtonLogLossBoosting`, a binary classifier trained by gradient boosting under log loss. The model works in log-odds space. Each stage fits a regression tree to the residuals `y - p`, keeps the tree's partition of the samples, and replaces each leaf value with a one-step Newton estimate. Predictions must match sklearn's `GradientBoostingClassifier` for the same hyperparameters.
```python
class NewtonLogLossBoosting:
def __init__(self, n_estimators=100, learning_rate=0.1, max_depth=3, random_state=0): ...
def fit(self, X, y): ...
def decision_function(self, X): ...
def predict_proba(self, X): ...
def predict(self, X): ...
```
Requirements:
- `fit` sets `init_ = log(p0 / (1 - p0))`, where `p0` is the fraction of positive labels. It raises `ValueError` when a label is not 0 or 1, when `y` has a single class, or when `X` is not 2-D or its row count differs from the length of `y`.
- Each stage fits `DecisionTreeRegressor(criterion="friedman_mse", max_depth=max_depth, random_state=random_state)` to `y - p`, sets each leaf to `sum(y - p) / sum(p * (1 - p))` over the samples in that leaf (0 when the denominator is below `1e-150` in absolute value), and adds `learning_rate` times the leaf value to each sample's margin.
- `fit` stores `train_loss_`, an array of shape `(n_estimators,)` holding the mean log loss on the training data after each stage, and returns `self`.
- `decision_function(X)` returns the raw margin $f(x)$. `predict_proba(X)` returns shape `(n, 2)` with columns ${1 - \sigma(f)}$ and $\sigma(f)$.
- `predict(X)` returns integer labels: 1 when the positive-class probability is greater than 0.5, else 0.
Example:
```python
X = [[0], [1], [2], [3]]
y = [0, 1, 1, 1]
m = NewtonLogLossBoosting(n_estimators=1, learning_rate=0.5, max_depth=1).fit(X, y)
m.init_ # log(3) ≈ 1.0986
# leaf values: -0.75 / 0.1875 = -4 and 0.75 / 0.5625 = 4/3
m.decision_function(X) # [log(3) - 2, log(3) + 2/3, log(3) + 2/3, log(3) + 2/3]
# ≈ [-0.9014, 1.7653, 1.7653, 1.7653]
```
```hint Stable loss
For a large margin, `log(1 + exp(f))` overflows. Look for a numpy function that computes it without forming `exp(f)`.
```
```hint Replaying stages
`decision_function` has to reproduce the training margins on new rows, so each stage must keep the Newton values it applied. Calling `tree.predict` on an untouched tree returns the mean residual of the leaf.
```
### Constraints & Assumptions
- Labels are 0 or 1, and valid training data contains both classes.
- `X` is a 2-D array with one row per label.
- numpy, scipy and sklearn's `DecisionTreeRegressor` are available.
### What a Strong Answer Covers
- The log-odds initialization from the base rate and the input checks that raise `ValueError`
- Residuals and Hessian terms from the current margin at each stage, and the Newton leaf value with its zero-denominator guard
- Storing the per-leaf values so `decision_function` replays exactly the training updates on new data
- A numerically stable mean log loss for `train_loss_`, and the 0.5 threshold in `predict`
- Time and space cost in terms of stages, samples, features and tree depth
### Follow-up Questions
- Why are leaves refit with a Newton step instead of using the tree's mean residual?
- How would you extend this to multiclass classification?
- How does XGBoost's leaf value differ from this one?
Overview: Build a binary gradient boosting classifier under log loss that fits regression trees to the residuals and replaces each leaf value with a Newton step, matching sklearn. It tests the gradient and Hessian of log loss, input validation, stable loss tracking, and replaying stored trees at prediction time.