Single logo
  • Courses
  • Blog
  • About
Join for freeJoin free
Learning pathChoose and Tune a Model: Classic Algorithms to a Saved Pipeline
  1. 1
    K-Nearest Neighbours (KNN): Distance, k and Why Scaling Is a Must
  2. 2
    Naive Bayes: Prior Times Likelihood, a Spam Filter by Hand and GaussianNB
  3. 3
    Support Vector Machines (SVM): The Widest Road, C, Kernels and gamma
  4. 4
    Decision Trees: Gini, max_depth and Feature Importances on Rain in Australia
  5. 5
    Bagging and Random Forest: Many Shaky Trees, One Steady Answer
  6. 6
    Boosting: Residuals by Hand, AdaBoost, Gradient Boosting and XGBoost
  7. 7
    Voting and Stacking: Does a Team of Models Beat the Best One?
  8. 8
    Hyperparameter Tuning with GridSearchCV and RandomizedSearchCV
  9. 9
    Which Features Matter? Feature Importances, Permutation Importance and SHAP
  10. 10
    Project: The Classification Master Template, from Raw CSV to a Saved Model
  1. Blog
  2. /
  3. Machine Learning
  4. /
  5. Supervised Learning

Learning path: Choose and Tune a Model: Classic Algorithms to a Saved Pipeline · Step 6 of 10

Boosting: Residuals by Hand, AdaBoost, Gradient Boosting and XGBoost

Each new small tree fixes what the team still gets wrong. Watch the MSE fall from 36.89 to 4.49 in three rounds on six kids, then AdaBoost 0.831, GradientBoosting 0.845 and XGBoost 0.846 on the rain data.

Chaand Sheikh

·27 November 2026Classic Algorithms

What you will learn

  • Run gradient boosting by hand: guess, residuals, a small tree, half a step, repeat
  • Explain how AdaBoost makes mistakes heavier instead
  • Compare AdaBoost, GradientBoosting and XGBoost on the rain data
  • Tune learning_rate and n_estimators as a pair, and predict numbers with XGBRegressor

Before you start

  • Decision Trees: Gini and max_depth
  • Bagging and Random Forest
  • Regression Metrics: MAE, RMSE and R-squared

A student writes a practice test and gets four of ten questions wrong. In round two the student doesn't redo the whole test, only those four questions. Now one is still wrong. In round three, only that last one. Each round spends its effort on the mistakes that are left over.

That's boosting: small trees trained one after another, and each new tree fixes what the team before it still gets wrong. A random forest trains its trees side by side and lets them vote. Boosting trains them in a row.

Round 0: a plain guess and its residuals

Six kids, age as the input and weight as the answer. The first guess is just the average weight, for everyone. The residual is real minus guess: what we still get wrong.

import numpy as np
import pandas as pd
from sklearn.tree import DecisionTreeRegressor

kids = pd.read_csv("kids_age_weight.csv")
X, y = kids[["age"]], kids["weight"]
print(y.tolist())

pred = np.full(len(y), y.mean())
residual = y - pred
print("guess    ", round(y.mean(), 2))
print("residual ", residual.round(2).tolist())
print("MSE      ", round((residual ** 2).mean(), 2))
[12, 15, 18, 22, 25, 30]
guess     20.33
residual  [-8.33, -5.33, -2.33, 1.67, 4.67, 9.67]
MSE       36.89

Everyone is guessed at 20.33. The lightest kid is 8.33 below that, the heaviest 9.67 above. The MSE (see Regression Metrics) is 36.89.

Each round: a small tree learns the residuals

Now the loop. Each round, a stump (a tree with one question) learns the current residuals, and we add half of its answer to the prediction.

pred = np.full(len(y), y.mean())
for r in range(1, 4):
    residual = y - pred
    stump = DecisionTreeRegressor(max_depth=1).fit(X, residual)
    pred = pred + 0.5 * stump.predict(X)
    mse = ((y - pred) ** 2).mean()
    print(f"round {r}:", pred.round(2), " MSE", round(mse, 2))
round 1: [17.67 17.67 17.67 23.   23.   23.  ]  MSE 15.56
round 2: [16.54 16.54 16.54 21.88 25.25 25.25]  MSE 7.96
round 3: [15.02 15.02 17.3  22.64 26.01 26.01]  MSE 4.49
The boosting loop and the falling MSE prediction residual y - pred small tree learns residual pred += 0.5 x tree repeat MSE after each round round 0 36.89 round 1 15.56 round 2 7.96 round 3 4.49
Guess, find the residuals, let a small tree learn them, add half a step, repeat. The MSE falls from 36.89 to 4.49 in three rounds.

After round 1, the three younger kids are guessed at 17.67 and the older three at 23. Every round the residuals shrink, and so does the MSE: 36.89, 15.56, 7.96, 4.49.

The 0.5 is the learning rate. It takes only half a step each round, so no single tree pushes too hard. This is gradient boosting: for squared error, the residuals are exactly the direction that lowers the loss fastest, the same downhill idea as gradient descent.

AdaBoost: mistakes get heavier

The oldest famous booster, AdaBoost, works a little differently. It starts with a stump, a tree with one question. The rows that stump gets wrong are given more weight, so the next stump has to care more about them. At the end all the stumps vote, and better stumps get a bigger say.

So: tiny stumps, heavier mistakes, a weighted vote. Gradient boosting fits the leftover errors; AdaBoost re-weights the rows.

Three boosters on the rain data

The same 10,000-day Rain in Australia sample as in the decision tree article. The labels become 0 and 1, because XGBoost wants numbers.

from sklearn.model_selection import train_test_split
from sklearn.ensemble import AdaBoostClassifier, GradientBoostingClassifier
from sklearn.impute import SimpleImputer
from sklearn.pipeline import make_pipeline
from xgboost import XGBClassifier, XGBRegressor

df = pd.read_csv("weatherAUS.csv").dropna(subset=["RainTomorrow"])
df = df.sample(10_000, random_state=42)
Xr = df.select_dtypes("number").drop(columns=["RISK_MM"])
yr = (df["RainTomorrow"] == "Yes").astype(int)
X_train, X_test, y_train, y_test = train_test_split(
    Xr, yr, test_size=0.2, stratify=yr, random_state=42)
print(X_train.shape, X_test.shape)
(8000, 16) (2000, 16)

scikit-learn's AdaBoostClassifier and GradientBoostingClassifier can't take missing values, so they get a median SimpleImputer in front. XGBoost handles missing values by itself.

fill = SimpleImputer(strategy="median")
ada = AdaBoostClassifier(random_state=42)
gbm = GradientBoostingClassifier(random_state=42)
xgb = XGBClassifier(n_estimators=300,
                    learning_rate=0.05, random_state=42)
models = {
    "AdaBoost": make_pipeline(fill, ada),
    "GradientBoosting": make_pipeline(fill, gbm),
    "XGBoost": xgb,
}
for name, m in models.items():
    m.fit(X_train, y_train)
    acc = m.score(X_test, y_test)
    print(f"{name:<17} test {acc:.3f}")
AdaBoost          test 0.831
GradientBoosting  test 0.845
XGBoost           test 0.846

XGBoost lands at 0.846, right next to the random forest's 0.85 on the same test days. Boosting is strong, but it's not magic.

XGBoost: learning_rate and n_estimators are a pair

XGBoost is the practical default: a classifier and a regressor, fast, and it takes missing values. (scikit-learn's HistGradientBoostingClassifier and LightGBM work on the same idea.) Its two main settings go together: a small learning rate needs more trees.

for lr, n in [(0.5, 20), (0.05, 300)]:
    m = XGBClassifier(n_estimators=n,
                      learning_rate=lr, random_state=42)
    m.fit(X_train, y_train)
    acc = m.score(X_test, y_test)
    print(f"lr {lr:<5} trees {n:<4} test {acc:.3f}")
lr 0.5   trees 20   test 0.836
lr 0.05  trees 300  test 0.846

Big steps with 20 trees get there fast but roughly: 0.836. Small steps with 300 trees land closer: 0.846.

XGBRegressor predicts numbers

houses = pd.read_csv("houses.csv")
cols = ["size_m2", "bedrooms"]
xgr = XGBRegressor(n_estimators=200,
                   learning_rate=0.1, max_depth=2,
                   random_state=42)
xgr.fit(houses[cols], houses["price_k"])
new = pd.DataFrame({"size_m2": [82], "bedrooms": [4]})
print(xgr.predict(new).round(1))
[272.9]

272.9 thousand for the 82 m², 4-bedroom house. With only eight houses, every model guesses differently (KNN 296.7, SVR 315.8, forest 294.0), so take this as one model's call, not the truth.

Common mistakes

  • A big learning rate with many trees. Each tree pushes too hard and the model overfits. Lower the rate and add trees instead.
  • Changing learning_rate without changing n_estimators. Tune them as a pair.
  • Feeding NaNs to scikit-learn's AdaBoost or GradientBoosting. Impute first, or use XGBoost.
  • Expecting boosting to always win. Here XGBoost (0.846) landed just behind the forest (0.85).

Quick recap

IdeaWhat it meansIn this example
ResidualWhat the team still gets wrong-8.33 to 9.67 after round 0
Gradient boostingA small tree learns the residualsMSE 36.89 to 4.49 in 3 rounds
Learning rateTake only part of each tree's answer0.5 by hand
AdaBoostMake mistakes heavier, weighted voteRain test 0.831
XGBoostThe practical default; takes NaNsRain test 0.846
Rate and treesSmall steps need more trees0.5/20: 0.836; 0.05/300: 0.846

Try it yourself

Rerun XGBClassifier with a learning rate of 0.3 and 100 trees, then 0.01 and 1000 trees. Which pair wins on test?

Next: put different models on one team with Voting and Stacking.

Built this? Share your solution in the StudyEasy AI Community.

Join free on Skool →
← Previous
Bagging and Random Forest: Many Shaky Trees, One Steady Answer
Next →
Voting and Stacking: Does a Team of Models Beat the Best One?
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool
Go deeper with a course

Machine Learning Engineer: From First Model to ML Engineer

Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)

Related articles
Linear Regression and the Cost Function: Draw a Line, Score It

Draw a straight line through six kids' ages and weights, measure every miss, and turn the misses into one score, the mean squared error. Then let np.polyfit find the line with the lowest score.

Gradient Descent Explained: Feel the Slope, Step Downhill

Instead of handing over the best line, let the computer walk to it: measure the slope of the cost, step downhill with a learning rate, repeat. Shown step by step on six kids' ages and weights.

Linear Regression in scikit-learn: Fit, Predict and Read the Price Tags

Predict a yearly medical bill with scikit-learn's LinearRegression: first from age alone, then from every column inside a pipeline. Each coefficient reads like a price tag, and smoker_yes is by far the biggest.

Regression Metrics: MAE, RMSE, R-squared and the Baseline to Beat

Score a regression model honestly: MAE, MSE and RMSE from four darts, then the insurance model on 268 test people, a DummyRegressor baseline to beat, R-squared and adjusted R-squared, and a residual plot.

On this page
  • Round 0: a plain guess and its residuals
  • Each round: a small tree learns the residuals
  • AdaBoost: mistakes get heavier
  • Three boosters on the rain data
  • XGBoost: learning_rate and n_estimators are a pair
  • XGBRegressor predicts numbers
  • Common mistakes
  • Quick recap
  • Try it yourself
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool
Go deeper with a course

Machine Learning Engineer: From First Model to ML Engineer

Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.