close

DEV Community

Devanshu Biswas
Devanshu Biswas

Posted on

Gradient Boosting From Scratch: Weak Trees Fixing Each Other

Random forests build many trees in parallel and average them. Gradient boosting builds trees one at a time, each one fixing the previous trees' mistakes β€” and it's what wins most Kaggle competitions on tabular data. Here it is, fitting residuals live.

🌲 Watch it boost (add trees one by one): https://dev48v.infy.uk/ml/day15-gradient-boosting.html

The core loop

  1. Start with a constant prediction (the mean).
  2. Compute the residuals β€” how far off you are at each point.
  3. Fit a small, shallow tree to those residuals.
  4. Add it to the ensemble, scaled by a learning rate.
  5. Repeat. Each tree chips away at the remaining error.

In the demo you watch the prediction curve bend toward the data and the residual bars shrink while the MSE drops every round.

Forest vs boosting

  • Random forest: independent trees, built in parallel, averaged. Reduces variance.
  • Boosting: dependent trees, built sequentially, summed. Reduces bias by correcting errors.

Learning rate = shrinkage

Small steps (e.g. 0.1) generalize better than big ones β€” but need more trees. Too many trees / too high a rate β†’ overfitting, so use early stopping.

The "gradient" part: fitting residuals is just gradient descent on squared error; swap the loss and it generalizes (that's XGBoost / LightGBM / CatBoost).

πŸ”¨ Built from scratch (mean β†’ residuals β†’ tree β†’ add lrΓ—tree β†’ repeat) on the page: https://dev48v.infy.uk/ml/day15-gradient-boosting.html

Part of MachineLearningFromZero. 🌐 https://dev48v.infy.uk

Top comments (0)