The Wayback Machine - https://web.archive.org/web/20250323014207/https://www.geeksforgeeks.org/ml-xgboost-extreme-gradient-boosting/
Open In App

ML | XGBoost (eXtreme Gradient Boosting)

Last Updated : 12 Feb, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

In machine learning we often combine different algorithms to get better and optimize results. Our main goal is to minimize loss function for which, one of the famous algorithm is XGBoost (Extreme boosting) technique which works by building an ensemble of decision trees sequentially where each new tree corrects the errors made by the previous one. It uses advanced optimization techniques and regularization methods that reduce overfitting and improve model performance.

In this article, we move beyond the basics and focus on the practical implementation of XGBoost, exploring how to apply it effectively in real-world machine learning tasks.

Parameters in XGBoost

Before jumping to the implementation of XG Boost we need to understand about the parameters used in XGBoost for model optimization.

  • Learning Rate (eta): An important variable that modifies how much each tree contributes to the final prediction. While more trees are needed smaller values frequently result in more accurate models.
  • Max Depth: This parameter controls the depth of every tree, avoiding overfitting and being essential to controlling the model’s complexity.
  • Gamma: Based on the decrease in loss it determines when a node in the tree will split. The algorithm becomes more conservative with a higher gamma value, avoiding splits that don’t decreases the loss. It helps in managing tree complexity.
  • Subsample: Manages the percentage of data that is sampled at random to grow each tree hence lowering variance and enhancing generalization. Setting it too low could result in underfitting.
  • Colsample Bytree: Establishes the percentage of features that will be sampled at random for growing each tree.
  • n_estimators: Specifies the number of boosting rounds.
  • lambda (L2 regularization term) and alpha (L1 regularization term): Control the strength of L2 and L1 regularization respectively. A higher value results in stronger regularization.
  • min_child_weight: Influences the tree structure by controlling the minimum amount of data required to create a new node.
  • scale_pos_weight: Useful in imbalanced class scenarios to control the balance of positive and negative weights.

XGboost Implementaion using Python

Let’s build and train a model for classification task using XGboost.

Step 1: Importing necessary libraries

Python
from sklearn.metrics import accuracy_score
import xgboost as xgb
from sklearn.model_selection import train_test_split
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

Step 2: Loading and splitting the dataset

You need to load the dataset from this link present Churn_Modelling Dataset

Python
dataset = pd.read_csv('Churn_Modelling.csv')
X = dataset.iloc[:, 3:13].values
y = dataset.iloc[:, 13].values

Step3: Converting categorical Columns

Since, XGBoost can internally handle categorical features. The code converts the specified columns to the categorical data type. While internally representing categories with integers, the categorical type retains the semantic meaning of the categories.

Python
X['Geography'] = X['Geography'].astype('category')
X['Gender'] = X['Gender'].astype('category')

Output:

<class ‘pandas.core.frame.DataFrame’>
RangeIndex: 10000 entries, 0 to 9999
Data columns (total 10 columns):
# Column Non-Null Count Dtype
— —— ————– —–
0 CreditScore 10000 non-null int64
1 Geography 10000 non-null category
2 Gender 10000 non-null category
3 Age 10000 non-null int64
4 Tenure 10000 non-null int64
5 Balance 10000 non-null float64
6 NumOfProducts 10000 non-null int64
7 HasCrCard 10000 non-null int64
8 IsActiveMember 10000 non-null int64
9 EstimatedSalary 10000 non-null float64
dtypes: category(2), float64(2), int64(6)
memory usage: 644.9 KB

Step 4: Splitting the dataset into training and testing

Python
X_train, X_test, y_train, y_test = train_test_split(X,y, test_size=0.25, random_state=0)

Step 5: Converting Dataset into Dmatrix

XGBoost presents the DMatrix class, which optimizes speed and memory for effective dataset storage. To use the XGBoost API, datasets must be converted to this format. Labels and training features are both accepted by DMatrix. enable_categorical is set to True to encrypt Pandas category columns automatically.

Python
xgb_train = xgb.DMatrix(X_train, y_train, enable_categorical=True)
xgb_test = xgb.DMatrix(X_test, y_test, enable_categorical=True)

Step 6: Create XGboost Model

  • The code initializes an XGBoost model with hyperparameters like a binary logistic objective, a maximum tree depth of 3, and a learning rate of 0.1.
  • It then trains the model using the `xgb_train` dataset for 50 boosting rounds.

The specified hyperparameters define the model’s structure and training behavior, impacting its accuracy and generalization on the given dataset. Adjusting these hyperparameters may be necessary for optimal performance in different scenarios.

Python
n=50
params = {
    'objective': 'binary:logistic',
    'max_depth': 3,
    'learning_rate': 0.1,
}

model = xgb.train(params=params,dtrain=xgb_train,num_boost_round=n)

Step 7: Make Predictions and Evaluate

The code predicts labels and then converts the predicted probabilities (preds) to integer labels allowing for a straightforward accuracy comparison with the true labels.

Python
preds = model.predict(xgb_test)
preds = preds.astype(int)
accuracy= accuracy_score(y_test,preds)
print('Accuracy of the model is:', accuracy*100)

Output:

Accuracy of the model is: 79.64

Note: If you’re interested in contributing to open source, you can install XGBoost locally and start exploring ways to contribute.

How to install XGboost?

Steps to Install Windows XGBoost uses Git submodules to manage dependencies. So when you clone the repo, remember to specify –recursive option:

git clone –recursive https://github.com/dmlc/xgboost

For Windows users who use Github tools, you can open the git-shell and type the following command:

git submodule init
git submodule update

OSX(Mac) First, obtain gcc-8 with Homebrew (https://brew.sh/) to enable multi-threading (i.e. using multiple CPU threads for training). The default Apple Clang compiler does not support OpenMP, so using the default compiler would have disabled multi-threading.

brew install gcc@8

Then install XGBoost with pip:

pip3 install xgboost

You might need to run the command with –user flag if you run into permission errors. 

ML | XGBoost (eXtreme Gradient Boosting – FAQs

How does XGBoost work?

XGBoost constructs a robust predictive model by sequentially adding weak learners, often decision trees, to correct errors made by previous models. It employs gradient optimization to minimize a cost function, introducing regularization for better generalization. Key features include cache-aware access, approximate greedy algorithms, and sparsity-aware split finding for efficiency.

What is the difference between XGBoost and other boosting algorithms?

The main differences between XGBoost and other boosting algorithms like AdaBoost and Gradient Boosting are that XGBoost uses a more sophisticated algorithm for splitting trees, and it also includes a number of regularization techniques that help to prevent overfitting. As a result, XGBoost is often more accurate than other boosting algorithms, but it can also be more computationally expensive to train.

How do I install XGBoost in Python?

To install XGBoost in Python, you can use the pip package manager. Open a terminal window and type the following command: !pip install xgboost

How do I tune the hyperparameters of XGBoost in Python?

Tuning the hyperparameters of an XGBoost model in Python involves using a method like grid search or random search to evaluate different combinations of hyperparameter values and select the combination that produces the best results. There are several libraries available for hyperparameter tuning, such as `sklearn.model_selection` and `Optuna`.

How to save a python xgboost model to a file?

To save a Python XGBoost model to a file, use the `save_model` method. For example: `model.save_model(‘model_filename.model’)`. This saves the trained model to the specified file.



Similar Reads

three90RightbarBannerImg