Machine Learning from Scratch – Day 17: Understanding XGBoost
Understanding XGBoost
Series: Machine Learning From Scratch (18 articles)
- …
- 17Machine Learning from Scratch – Day 17: Understanding XGBoost This article
Yesterday, we explored Gradient Boosting, an ensemble learning technique that builds models sequentially, with each new model attempting to improve the predictions of the existing ensemble.
Today, let's take that concept one step further.
Have you ever wondered how machine learning models can achieve excellent performance on structured datasets while remaining computationally efficient?
One popular answer is XGBoost.
XGBoost is widely used in machine learning competitions, business applications, financial prediction and many other data-driven tasks.
Let's understand how it works!
1. What is XGBoost?
XGBoost stands for Extreme Gradient Boosting.
It is an optimized implementation of the Gradient Boosting algorithm that uses decision trees as its base learners.
Like traditional Gradient Boosting, XGBoost builds trees sequentially. Each new tree helps improve the predictions made by the existing ensemble.
However, XGBoost introduces several improvements, including:
- Regularization to control model complexity.
- Efficient handling of missing values.
- Optimized tree-building techniques.
- Support for parallel processing during parts of training.
- Techniques that improve computational efficiency.
In simple terms:
Gradient Boosting provides the core learning approach, while XGBoost adds optimizations and additional controls to make the process more efficient and robust.
2. Why Do We Need XGBoost?
Let's consider a simple example.
Suppose an online shopping company wants to predict whether a customer will purchase a product.
The dataset contains:
- Customer age
- Previous purchases
- Time spent on the website
- Product price
- Customer location
- Purchase history
A single decision tree might produce reasonable predictions, but it may not capture all the complex relationships in the dataset.
Gradient Boosting improves predictions by combining multiple decision trees.
However, traditional Gradient Boosting can face challenges:
- Training can become computationally expensive.
- Complex trees may overfit the training data.
- Large datasets may require significant resources.
- Missing values need appropriate handling.
XGBoost addresses many of these challenges through its optimized implementation and regularization techniques.
It does not guarantee better performance on every dataset, but it provides a powerful set of tools for building predictive models.
3. How Does XGBoost Work?
XGBoost follows the boosting approach we learned yesterday.
Let's break down the process.
Step 1: Start with an initial prediction
The model begins with an initial estimate for the target variable.
Step 2: Calculate prediction errors
It evaluates how far its current predictions are from the actual values using a loss function.
Step 3: Calculate gradients
The algorithm calculates gradients that indicate how the predictions should change to reduce the loss.
It can also use second-order derivatives, called Hessians, to estimate how the loss changes around the current prediction.
Step 4: Build a new decision tree
A new tree is constructed to improve the existing predictions.
Step 5: Apply regularization
XGBoost considers model complexity while selecting tree structures. This helps prevent unnecessarily complex trees.
Step 6: Update predictions
The new tree contributes to the existing ensemble, and the process continues until the stopping condition is reached.
4. Important Features of XGBoost
Let's understand the features that make XGBoost particularly useful.
A. Regularization
One of the important features of XGBoost is its ability to penalize model complexity.
Remember overfitting from Day 5?
A model overfits when it learns the training data too closely and performs poorly on unseen data.
XGBoost uses regularization to discourage overly complex trees.
Its objective function can be represented as:
\[ Obj = L + \Omega \]
Where:
- \(L\) = Training loss.
- \(\Omega\) = Regularization term.
A simplified tree complexity penalty is:
\[ \Omega(f)=\gamma T+\frac{1}{2}\lambda\sum_{j=1}^{T}w_j^2 \]
Where:
- \(T\) = Number of leaves.
- \(w_j\) = Score associated with each leaf.
- \(\gamma\) = Penalty for adding leaves.
- \(\lambda\) = L2 regularization parameter.
The algorithm tries to minimize both prediction error and unnecessary model complexity.
B. Handling Missing Values
Real-world datasets often contain missing values.
For example:
Age | Income | Purchase |
|---|---|---|
22 | 25000 | Yes |
30 | Missing | No |
27 | 35000 | Yes |
35 | Missing | No |
XGBoost can learn default directions for missing values when constructing tree splits.
This means you do not always need to manually fill every missing value before training.
However, understanding why values are missing and whether preprocessing is appropriate remains important.
C. Parallel Processing
XGBoost uses optimized computation and parallel processing for parts of its training process.
For example, it can evaluate candidate feature splits efficiently.
One important distinction: boosting iterations still depend on the predictions from previous iterations, so the entire sequence of trees is not trained independently in parallel.
D. Tree Pruning
XGBoost evaluates whether adding more branches improves the model sufficiently.
Its regularization mechanisms help discourage splits that do not provide enough improvement.
This helps control unnecessary tree complexity.
5. Important XGBoost Hyperparameters
Hyperparameters control how the algorithm learns.
Hyperparameter | Purpose |
|---|---|
n_estimators | Number of boosting rounds |
learning_rate | Controls the contribution of each new tree |
max_depth | Maximum depth of a tree |
subsample | Fraction of training samples used per boosting round |
colsample_bytree | Fraction of features sampled for each tree |
reg_alpha | L1 regularization |
reg_lambda | L2 regularization |
gamma | Minimum loss reduction required for a split |
Two important parameters deserve special attention.
Learning Rate
A smaller learning rate reduces the contribution of each tree.
This can improve generalization, but usually requires more boosting rounds.
Max Depth
A deeper tree can learn more complex patterns, but excessive depth can increase overfitting.
The goal is not to maximize every hyperparameter. It is to find a configuration that performs well on unseen data.
6. Implementing XGBoost Using Python
Now let's build an XGBoost classification model.
We'll use the Iris dataset, which contains measurements of flowers from three different species.
Step 1: Install XGBoost
Run this command in your terminal or Jupyter Notebook:
pip install xgboost scikit-learnStep 2: Import the required libraries
from sklearn.datasets import load_irisfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import accuracy_score, classification_reportfrom xgboost import XGBClassifierStep 3: Load the dataset
iris = load_iris()X = iris.datay = iris.targetStep 4: 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)We use 80% of the data for training and 20% for testing.
Step 5: Create the XGBoost model
model = XGBClassifier( n_estimators=100, learning_rate=0.1, max_depth=3, subsample=0.8, colsample_bytree=0.8, objective="multi:softprob", num_class=3, eval_metric="mlogloss", random_state=42)Step 6: Train the model
model.fit(X_train, y_train)Step 7: Make predictions
y_pred = model.predict(X_test)Step 8: Evaluate the model
print("Accuracy:", accuracy_score(y_test, y_pred))print( classification_report( y_test, y_pred, target_names=iris.target_names ))That's it! We have successfully trained an XGBoost classification model.
Remember that accuracy alone does not tell the complete story. For classification problems, precision, recall and F1-score can also provide useful insights.
7. Gradient Boosting vs XGBoost
You might be wondering: If both algorithms use boosting, what makes them different?
Let's compare them.
Feature | Gradient Boosting (Scikit-learn) | XGBoost |
|---|---|---|
Core approach | Gradient boosting | Gradient boosting |
Regularization | Supported through model controls | Explicit L1 and L2 regularization |
Missing values | Depends on implementation | Learns default split directions |
Optimization | Standard implementation | Highly optimized implementation |
Parallelization | More limited | Parallelizes parts of training |
Advanced controls | Available | Extensive training and regularization controls |
XGBoost is not a completely different learning principle. It is an optimized and extended gradient boosting implementation.
8. Advantages and Limitations
Advantages
- Strong performance on many structured datasets.
- Built-in regularization.
- Can handle missing values.
- Supports classification and regression.
- Provides feature importance information.
- Offers several options for controlling model complexity.
Limitations
- Requires hyperparameter tuning.
- Can overfit if configured poorly.
- May require significant computational resources for large models.
- Less interpretable than a simple decision tree.
- Not necessarily the best choice for every dataset or problem.
9. Real-World Applications
XGBoost is useful in several industries.
- Banking: Predicting loan defaults and assessing credit risk.
- E-commerce: Predicting customer purchasing behavior.
- Healthcare: Predicting patient risks using structured clinical data.
- Cybersecurity: Detecting suspicious activities.
- Finance: Fraud detection and risk modelling.
- Marketing: Predicting customer churn.
It is especially popular in machine learning competitions involving structured datasets.
10. What Should You Remember?
Let's summarize today's learning:
- XGBoost stands for Extreme Gradient Boosting.
- It is an optimized implementation of gradient boosting.
- It builds decision trees sequentially.
- It uses gradients and second-order information to improve predictions.
- Regularization helps control model complexity.
- It supports missing-value handling and efficient computation.
- It can be used for classification and regression.
Key takeaway: XGBoost combines the learning strategy of Gradient Boosting with optimization techniques and regularization to build powerful predictive models.
What's Next? Day 18
We've now explored several supervised learning algorithms and ensemble methods.
In the next article, we'll understand LightGBM and CatBoost — two other powerful gradient boosting frameworks.
We'll compare their approaches, understand when to use them and implement them using Python.
Series: Machine Learning From Scratch (18 articles)
- …
- 17Machine Learning from Scratch – Day 17: Understanding XGBoost This article
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article