Lesson 3 of 9
Gradient Boosting Principles: Sequential Pseudo-Residual Optimization
Gradient Boosting is an optimization framework in functional space. Unlike AdaBoost (which reweights misclassified sample points), Gradient Boosting fits each new tree to the negative gradient (pseudo-residuals) of the loss function with respect to the current ensemble's predictions: r_im = - [โL(y_i, F(x_i)) / โF(x_i)]. This allows Gradient Boosting to optimize any differentiable loss function: Mean Squared Error, Log-Loss, Huber loss, Quantile loss, or Poisson deviance.
Gradient Boosting from Scratch: Fitting Pseudo-Residuals
import numpy as np
from sklearn.tree import DecisionTreeRegressor
from sklearn.metrics import mean_squared_error
# 1. SYNTHETIC 1D REGRESSION PROBLEM
np.random.seed(42)
X = np.sort(np.random.uniform(0, 10, 100)).reshape(-1, 1)
y = np.sin(X.ravel()) * 3.0 + np.random.normal(0, 0.4, 100)
# 2. GRADIENT BOOSTING REPUTED FROM FIRST PRINCIPLES (Squared Error Loss: L = 0.5 * (y - F)^2)
# Negative Gradient (Pseudo-Residual): - dL/dF = (y - F)
learning_rate = 0.1
n_iterations = 50
# Step 1: Initialize model with constant prediction (mean of y)
F0 = np.mean(y)
F_current = np.full_like(y, fill_value=F0)
trees = []
print("=== STEP-BY-STEP GRADIENT BOOSTING CONVERGENCE ===")
for m in range(1, n_iterations + 1):
# Step 2: Compute pseudo-residuals
residuals = y - F_current
# Step 3: Fit a weak regression tree to the residuals
tree = DecisionTreeRegressor(max_depth=2, random_state=42)
tree.fit(X, residuals)
trees.append(tree)
# Step 4: Update ensemble prediction with shrinkage (learning rate)
update = tree.predict(X)
F_current += learning_rate * update
if m in [1, 5, 20, 50]:
mse = mean_squared_error(y, F_current)
print(f"Iteration {m:2d} | Ensemble Training MSE: {mse:.4f} (Residuals shrinking!)")
print(f"\nFinal 50-Tree Ensemble MSE: {mean_squared_error(y, F_current):.4f}")Pro Tip: The Shrinkage Principle (Learning Rate)
Never train gradient boosting with a learning rate of 1.0. Multiplying each tree's output by a small shrinkage parameter `eta` (e.g. 0.01 to 0.1) forces the model to take small gradient steps in function space, leaving headroom for future trees to correct remaining patterns and drastically improving test set generalization.
MlGradientBoosting Visual Representation
Hands-On Challenge: Gradient Boosting for Binary Cross-Entropy
Derive the pseudo-residual for binary Log-Loss `L(y, p) = - [y ln(p) + (1-y) ln(1-p)]`. Prove mathematically that `- dL/dz = y - p`, showing that logistic boosting fits trees directly to prediction probability errors `(y_i - p_i)`.
Quick Quiz & Key Concept Checks
Common Pitfall: Forgetting Early Stopping in Gradient Boosting
Training gradient boosted models with 5,000 trees without early stopping guarantees overfitting. In Scikit-Learn, LightGBM, and XGBoost, always configure early stopping on an untouched validation set (`n_iter_no_change=20`).