AWS Builder Center

Machine Learning from Scratch – Day 16: Understanding Gradient Boosting

Understanding Gradient Boosting

Series: Machine Learning From Scratch (18 articles)

  1. …
  2. 16
    Machine Learning from Scratch – Day 16: Understanding Gradient Boosting This article
In our previous articles, we explored PCA, a technique used to reduce the number of features in a dataset while preserving important information.
Today, let's move back to ensemble learning and explore a powerful algorithm: Gradient Boosting.
Imagine you're preparing for an exam. You take a practice test and make several mistakes. Instead of studying everything again, you focus on the questions you answered incorrectly. After another test, you identify the remaining mistakes and work on those.
What if machine learning models could learn in a similar way?
That's the central idea behind Gradient Boosting.

1. What is Gradient Boosting?

Gradient Boosting is a supervised machine learning algorithm that combines multiple weak learners to create a strong predictive model.
A weak learner is a model that performs only slightly better than random guessing or provides limited predictive power on its own.
Gradient Boosting usually uses small decision trees as its weak learners.
Instead of training all the trees independently, it builds them sequentially. Each new tree focuses on improving the predictions made by the existing collection of trees.
It can be used for:
  • Classification – predicting categories.
  • Regression – predicting numerical values.
Example: Suppose we want to predict house prices.
Our first model might make predictions that are too high for some houses and too low for others. The next model focuses on correcting the remaining prediction errors. Additional models continue improving the overall prediction.
The final prediction combines the contributions of all the trees.

2. Understanding Ensemble Learning

Before understanding Gradient Boosting, let's revisit ensemble learning.
Ensemble learning combines multiple models to produce a better overall prediction.
Two important approaches are:
Bagging (Bootstrap Aggregating)
  • Models are trained independently, often on different bootstrap samples.
  • Their predictions are combined through voting or averaging.
  • Random Forest is a popular example.
Boosting
  • Models are trained sequentially.
  • Each new model focuses on the errors or shortcomings of the existing ensemble.
  • Gradient Boosting is a popular example.
Feature
Random Forest
Gradient Boosting
Approach
Bagging
Boosting
Training
Mostly independent trees
Sequential trees
Main objective
Reduce variance
Improve predictions by correcting errors
Model combination
Voting or averaging
Additive combination
Overfitting
Often robust
Needs careful tuning
Neither approach is universally better. The right choice depends on the dataset, computational requirements and evaluation results.

3. How Does Gradient Boosting Work?

Let's understand the process step by step.
Step 1: Build an initial model
The algorithm starts with a simple prediction.
For a regression problem, this might be the average value of the target variable.
Step 2: Calculate the errors
The model compares its predictions with the actual values.
For example:
Actual price
Predicted price
Error
₹50 lakh
₹45 lakh
₹5 lakh
₹60 lakh
₹65 lakh
-₹5 lakh
₹70 lakh
₹60 lakh
₹10 lakh
These errors show where the current model needs improvement.
Step 3: Train another decision tree
A new tree is trained to improve the existing model's predictions.
For squared-error regression, this often means learning the residuals (actual values minus predicted values).
For other loss functions, the algorithm generally uses the negative gradients of the loss function instead.
Step 4: Update the predictions
The new tree's contribution is added to the existing model's predictions.
Step 5: Repeat the process
Additional trees are trained, each improving the current ensemble.
The final model combines the predictions from all the trees.

4. Why is it Called Gradient Boosting?

The word Gradient comes from gradient descent, an optimization technique used to minimize a loss function.
A loss function measures how far the model's predictions are from the actual values.
For example, Mean Squared Error (MSE) is commonly used in regression:
\[ MSE=\frac{1}{n}\sum_{i=1}^{n}(y_i-\hat y_i)^2 \]
Here:
  • \(y_i\) = Actual value
  • \(\hat y_i\) = Predicted value
  • \(n\) = Number of observations
Gradient Boosting improves the model by adding new learners in directions that reduce the loss.
In simplified terms:
  1. Calculate the current prediction error.
  1. Determine the direction in which the loss should decrease.
  1. Train a new learner to capture that improvement.
  1. Update the existing model.
  1. Repeat until the model reaches a stopping condition.
This is why Gradient Boosting is more than simply adding decision trees together.

5. Important Hyperparameters

Gradient Boosting has several hyperparameters that influence model performance.
Hyperparameter
Purpose
 n_estimators 
Number of boosting stages or trees
 learning_rate 
Controls each tree's contribution
 max_depth 
Controls the depth of individual trees
 subsample 
Controls the fraction of training samples used per tree
 min_samples_split 
Minimum samples required to split a node
Let's understand two particularly important parameters.
Learning Rate
The learning rate controls how much each new tree contributes to the overall model.
  • Higher learning rate: Larger updates, potentially faster learning but increased risk of overfitting.
  • Lower learning rate: Smaller updates, often requiring more trees.
Number of Estimators
This determines how many boosting stages are performed.
Increasing the number of trees can improve performance, but adding too many may cause overfitting and increase training time.
The learning rate and number of estimators should generally be tuned together.

6. Implementing Gradient Boosting Using Python

Now let's implement Gradient Boosting using Scikit-learn.
We'll use the Iris dataset to classify flowers into three species.
Step 1: Import the required libraries
from sklearn.datasets import load_irisfrom sklearn.model_selection import train_test_splitfrom sklearn.ensemble import GradientBoostingClassifierfrom sklearn.metrics import accuracy_score, classification_report
Step 2: Load the dataset
iris = load_iris()X = iris.datay = iris.target
Step 3: Split the dataset
X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=42, stratify=y)
Here, 80% of the data is used for training and 20% for testing.
Step 4: Create the Gradient Boosting model
model = GradientBoostingClassifier( n_estimators=100, learning_rate=0.1, max_depth=3, random_state=42)
Step 5: Train the model
model.fit(X_train, y_train)
Step 6: Make predictions
y_pred = model.predict(X_test)
Step 7: Evaluate the model
print("Accuracy:", accuracy_score(y_test, y_pred))print(classification_report(y_test, y_pred, target_names=iris.target_names))
The model's accuracy depends on the data split and configuration. Always evaluate it on unseen test data rather than assuming that a particular accuracy is guaranteed.
One useful detail: tree-based Gradient Boosting generally does not require feature scaling, unlike algorithms such as KNN and SVM.

7. Gradient Boosting vs AdaBoost vs Random Forest

These three algorithms belong to the ensemble learning family, but they use different strategies.
Algorithm
Main idea
Random Forest
Combines independently trained decision trees
AdaBoost
Increases attention to incorrectly classified training examples
Gradient Boosting
Sequentially minimizes a loss function using gradient information
All three can be useful, but their performance depends on the problem and dataset.

8. Advantages and Limitations

Advantages
  • Can capture complex relationships in data.
  • Works for both classification and regression.
  • Often provides strong predictive performance on structured datasets.
  • Can model nonlinear relationships.
  • Supports feature importance analysis in tree-based implementations.
Limitations
  • Sequential training can be slower than parallel tree training.
  • Requires careful hyperparameter tuning.
  • Can overfit if the model becomes too complex.
  • Sensitive to noisy data and unsuitable parameter choices.
  • Less straightforward to interpret than a single decision tree.

9. Real-World Applications

Gradient Boosting is commonly used in several industries.
  • Banking: Credit risk assessment and loan default prediction.
  • Healthcare: Risk prediction and patient outcome analysis.
  • E-commerce: Customer purchase prediction and recommendation-related tasks.
  • Finance: Fraud detection and financial forecasting.
  • Marketing: Customer churn prediction and campaign response analysis.
It is particularly popular for structured or tabular datasets.

10. What Should You Remember?

Let's summarize today's learning:
  1. Gradient Boosting is an ensemble learning algorithm.
  1. It combines multiple weak learners, usually shallow decision trees.
  1. Trees are built sequentially rather than independently.
  1. Each new learner attempts to reduce the existing model's loss.
  1. Learning rate and number of estimators are important hyperparameters.
  1. It supports both classification and regression.
The important takeaway is that Gradient Boosting doesn't simply create many trees. It creates them in a sequence where each new learner contributes to improving the overall model.

What's Next? Day 17

In the next article, we'll explore XGBoost (Extreme Gradient Boosting).
We'll understand how XGBoost improves upon traditional Gradient Boosting through regularization, optimized training and additional performance improvements.

Series: Machine Learning From Scratch (18 articles)

  1. …
  2. 16
    Machine Learning from Scratch – Day 16: Understanding Gradient Boosting This article
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article