The Wayback Machine - https://web.archive.org/web/20240906010208/https://www.geeksforgeeks.org/xgboost/
Open In App

XGBoost

Last Updated : 06 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

XGBoost is an optimized distributed gradient boosting library designed for efficient and scalable training of machine learning models. It is an ensemble learning method that combines the predictions of multiple weak models to produce a stronger prediction. XGBoost stands for “Extreme Gradient Boosting” and it has become one of the most popular and widely used machine learning algorithms due to its ability to handle large datasets and its ability to achieve state-of-the-art performance in many machine learning tasks such as classification and regression.

One of the key features of XGBoost is its efficient handling of missing values, which allows it to handle real-world data with missing values without requiring significant pre-processing. Additionally, XGBoost has built-in support for parallel processing, making it possible to train models on large datasets in a reasonable amount of time.

XGBoost can be used in a variety of applications, including Kaggle competitions, recommendation systems, and click-through rate prediction, among others. It is also highly customizable and allows for fine-tuning of various model parameters to optimize performance.

XgBoost stands for Extreme Gradient Boosting, which was proposed by the researchers at the University of Washington. It is a library written in C++ which optimizes the training for Gradient Boosting.

Before understanding the XGBoost, we first need to understand the trees especially the decision tree:

Decision Tree:

A Decision tree is a flowchart-like tree structure, where each internal node denotes a test on an attribute, each branch represents an outcome of the test, and each leaf node (terminal node) holds a class label. 

A tree can be “learned” by splitting the source set into subsets based on an attribute value test. This process is repeated on each derived subset in a recursive manner called recursive partitioning. The recursion is completed when the subset at a node all has the same value of the target variable, or when splitting no longer adds value to the predictions.

Bagging:

A Bagging classifier is an ensemble meta-estimator that fits base classifiers each on random subsets of the original dataset and then aggregate their individual predictions (either by voting or by averaging) to form a final prediction. Such a meta-estimator can typically be used as a way to reduce the variance of a black-box estimator (e.g., a decision tree), by introducing randomization into its construction procedure and then making an ensemble out of it.
Each base classifier is trained in parallel with a training set which is generated by randomly drawing, with replacement, N examples(or data) from the original training dataset, where N is the size of the original training set. The training set for each of the base classifiers is independent of each other. Many of the original data may be repeated in the resulting training set while others may be left out.

Bagging reduces overfitting (variance) by averaging or voting, however, this leads to an increase in bias, which is compensated by the reduction in variance though.

Bagging classifier

Random Forest:

Every decision tree has high variance, but when we combine all of them together in parallel then the resultant variance is low as each decision tree gets perfectly trained on that particular sample data and hence the output doesn’t depend on one decision tree but multiple decision trees. In the case of a classification problem, the final output is taken by using the majority voting classifier. In the case of a regression problem, the final output is the mean of all the outputs. This part is Aggregation.
 

The basic idea behind this is to combine multiple decision trees in determining the final output rather than relying on individual decision trees.
Random Forest has multiple decision trees as base learning models. We randomly perform row sampling and feature sampling from the dataset forming sample datasets for every model. This part is called Bootstrap.

Boosting:

Boosting is an ensemble modelling, technique that attempts to build a strong classifier from the number of weak classifiers. It is done by building a model by using weak models in series. Firstly, a model is built from the training data. Then the second model is built which tries to correct the errors present in the first model. This procedure is continued and models are added until either the complete training data set is predicted correctly or the maximum number of models are added.

Boosting

Gradient Boosting 

Gradient Boosting is a popular boosting algorithm. In gradient boosting, each predictor corrects its predecessor’s error. In contrast to Adaboost, the weights of the training instances are not tweaked, instead, each predictor is trained using the residual errors of predecessor as labels.

There is a technique called the Gradient Boosted Trees whose base learner is CART (Classification and Regression Trees).

XGBoost 

XGBoost is an implementation of Gradient Boosted decision trees. XGBoost models majorly dominate in many Kaggle Competitions.

In this algorithm, decision trees are created in sequential form. Weights play an important role in XGBoost. Weights are assigned to all the independent variables which are then fed into the decision tree which predicts results. The weight of variables predicted wrong by the tree is increased and these variables are then fed to the second decision tree. These individual classifiers/predictors then ensemble to give a strong and more precise model. It can work on regression, classification, ranking, and user-defined prediction problems.

Mathematics behind XgBoost

Before beginning with mathematics about Gradient Boosting, Here’s a simple example of a CART that classifies whether someone will like a hypothetical computer game X. The example of tree is below:

The prediction scores of each individual decision tree then sum up to get  If you look at the example, an important fact is that the two trees try to complement each other. Mathematically, we can write our model in the form

\hat{y}_{i} =  \sum_{k=1}^{K} f_k(x_i), f_k \epsilon \mathcal{F} \\

where, K is the number of trees, f is the functional space of F, F is the set of possible CARTs. The objective function for the above model is given by:

obj(\theta) = \sum_{i}^{n} l(y_{i}, \hat{y}_{i}) + \sum_{k=1}^K \Omega(f_{k}) \\

where, first term is the loss function and the second is the regularization parameter. Now, Instead of learning the tree all at once which makes the optimization harder, we apply the additive stretegy, minimize the loss what we have learned and add a new tree which can be summarised below:

\hat{y}_i^{(0)} =0\\ \hat{y}_i^{(1)} =  f_1(x_i) = \hat{y}_i^{(0)} + f_1(x_i)\\ \hat{y}_i^{(2)} = f_1(x_i) + f_2(x_i)= \hat{y}_i^{(1)} + f_2(x_i)\\ ....\\ \hat{y}_i^{(t)} = \sum_{k=1}^t f_k(x_i)= \hat{y}_i^{(t-1)} + f_t(x_i)

The objective function of the above model can be defined as:

obj^{(t)}  = \sum_{i=1}^{n} l(y_i, \hat{y}_{i}^{(t)}) + \sum_{i=1}^t\Omega(f_i) \\           = \sum_{i=1}^{n} l(y_i, \hat{y}_{i}^{(t-1)} + f_{t}(x_i)) + \Omega(f_t) + constant

obj^{(t)}  = \sum_{i=1}^n (y_{i} - (\hat{y}_{i}^{(t-1)} + f_t(x_i)))^2 + \sum_{i=1}^t\Omega(f_i) \\           = \sum_{i=1}^n [2(\hat{y}_i^{(t-1)} - y_i)f_t(x_i) + f_t(x_i)^2] + \Omega(f_t) + constant

Now, let’s apply taylor series expansion upto second order:

obj^{(t)} = \sum_{i=1}^{n} [l(y_i, \hat{y}_i^{(t-1)}) + g_i f_t(x_i) + \frac{1}{2} h_{i} f_{t}^2(x_i)] + \Omega(f_t) + constant

where g_i and h_i can be defined as:

g_i = \partial_{\hat{y}_i^{(t-1)}} l(y_i, \hat{y}_i^{(t-1)})\\ h_i = \partial_{\hat{y}_i^{(t-1)}}^2 l(y_i, \hat{y}_i^{(t-1)})

Simplifying and removing the constant:

\sum_{i=1}^n [g_{i} f_{t}(x_i) + \frac{1}{2} h_{i} f_{t}^2(x_i)] + \Omega(f_t)

Now, we define the regularization term, but first we need to define the model:

f_t(x) = w_{q(x)}, w \in R^{T}, q:R^d\rightarrow \{1,2,...,T\}

Here, w is the vector of scores on leaves of tree, q is the function assigning each data point to the corresponding leaf, and T is the number of leaves. The regularization term is then defined by:

\Omega(f) = \gamma T + \frac{1}{2}\lambda \sum_{j=1}^T w_j^2

Now, our objective function becomes:

obj^{(t)} \approx \sum_{i=1}^n [g_i w_{q(x_i)} + \frac{1}{2} h_i w_{q(x_i)}^2] + \gamma T + \frac{1}{2}\lambda \sum_{j=1}^T w_j^2\\ = \sum^T_{j=1} [(\sum_{i\in I_j} g_i) w_j + \frac{1}{2} (\sum_{i\in I_j} h_i + \lambda) w_j^2 ] + \gamma T

Now, we simplify the above expression:

obj^{(t)} = \sum^T_{j=1} [G_jw_j + \frac{1}{2} (H_j+\lambda) w_j^2] +\gamma T

where, 

G_j = \sum_{i\in I_j} g_i\\ H_j = \sum_{i\in I_j} h_i

In this equation, w_j are independent of each other, the best w_j                 for a given structure q(x) and the best objective reduction we can get is:

w_j^{\ast} = -\frac{G_j}{H_j+\lambda}\\ \text{obj}^{\ast} = -\frac{1}{2} \sum_{j=1}^T \frac{G_j^2}{H_j+\lambda} + \gamma T

where, \gamma is pruning parameter, i.e the least information gain to perform split.

Now, we try to measure how good the tree is, we can’t directly optimize the tree, we will try to optimize one level of the tree at a time. Specifically we try to split a leaf into two leaves, and the score it gains is

Gain = \frac{1}{2} \left[\frac{G_L^2}{H_L+\lambda}+\frac{G_R^2}{H_R+\lambda}-\frac{(G_L+G_R)^2}{H_L+H_R+\lambda}\right] - \gamma

Calculation of Information Gain

Examples

Let’s consider an example dataset:

Years of ExperienceGap Annual salary (in 100k)
1N4
1.5Y4
2.5Y5.5
3N7
5N7.5
6N8
  • First we take the base learner, by default the base model always take the average salary i.e F_0 =6              (100k). Now, we calculate the residual values:
Years of ExperienceGap Annual salary (in 100k)Residuals
1N4-2
1.5Y4-2
2.5Y5.5-0.5
3N71
5N7.51.5
6N82
  • Now, let’s consider the decision tree, we will be splitting the data based on experience <=2 or otherwise.

  • Now, let’s calculate the similarity metrices of left and right side. Since, it is the regression problem the similarity metric will be:

S_m  = \frac{\sum (res)^{2}}{n_{res} + \lambda}

where, \lambda = hyperparameter

and for the classification problem:

S = \frac{\sum (res)^{2}}{P_{r} + (1-P_{r})}

where, P_r = probability of either left side of right side. Let’s take \lambda = 1               ,the similarity metrics of the left side: 

S_{L} = \frac{(-4)^2}{2+1} = \frac{16}{3} =5.33               and for the right side.

S_{R} = \frac{(4)^2}{4+1} = \frac{16}{5} =3.2               and for the top branch:

S_{T} = \frac{1}{7} =0.143              .

  • Now, the information gain from this split is:

GAIN  = S_{L} + S_{R}- S_{T} = 6.33 +3.2 -0.143 = 9.328

Similarly, we can try multiple splits and calculate the information gain. We will take the split with the highest information gain. Let’s for now take this information gain. Further, we will split the decision tree if there is a gap or not.

  • Now, As you can notice that I didn’t split into the left side because the information Gain becomes negative. So, we only perform split on the right side.
  • To calculate the particular output, we follow the decision tree multiplied with a learning rate \alpha (let’s take 0.5) and add with the previous learner (base learner for the first tree) i.e for data point 1: o/p  = 6 + 0.5 *-2 =5. So our table becomes.
  • Similarly, the algorithm produces more than one decision tree and combine them additively to generate better estimates

Optimization and Improvement

System Optimization:

  1. Regularization: Since the ensembling of decisions, trees can sometimes lead to very complex. XGBoost uses both Lasso and Ridge Regression regularization to penalize the highly complex model.
  2. Parallelization and Cache block: In, XGboost, we cannot train multiple trees parallel, but it can generate the different nodes of tree parallel. For that, data needs to be sorted in order. In order to reduce the cost of sorting, it stores the data in blocks. It stored the data in the compressed column format, with each column sorted by the corresponding feature value. This switch improves algorithmic performance by offsetting any parallelization overheads in computation.
  3. Tree Pruning:  XGBoost uses max_depth parameter as specified the stopping criteria for the splitting of the branch, and starts pruning trees backward. This depth-first approach improves computational performance significantly.
  4. Cache-Awareness and Out-of-score computation: This algorithm has been designed to make use of hardware resources efficiently. This is accomplished by cache awareness by allocating internal buffers in each thread to store gradient statistics. Further enhancements such as ‘out-of-core computing optimize available disk space while handling big data-frames that do not fit into memory. In out-of-core computation, Xgboost tries to minimize the dataset by compressing it.
  5. Sparsity Awareness: XGBoost can handle sparse data that may be generated from preprocessing steps or missing values. It uses a special split finding algorithm that is incorporated into it that can handle different types of sparsity patterns.
  6. Weighted Quantile Sketch: XGBoost has in-built the distributed weighted quantile sketch algorithm that makes it easier to effectively find the optimal split points among weighted datasets.
  7. Cross-validation: XGboost implementation comes with a built-in cross-validation method. This helps the algorithm prevents overfitting when the dataset is not that big,

Advantages Or Disadvantages:
 

Advantages of XGBoost:

  1. Performance: XGBoost has a strong track record of producing high-quality results in various machine learning tasks, especially in Kaggle competitions, where it has been a popular choice for winning solutions.
  2. Scalability: XGBoost is designed for efficient and scalable training of machine learning models, making it suitable for large datasets.
  3. Customizability: XGBoost has a wide range of hyperparameters that can be adjusted to optimize performance, making it highly customizable.
  4. Handling of Missing Values: XGBoost has built-in support for handling missing values, making it easy to work with real-world data that often has missing values.
  5. Interpretability: Unlike some machine learning algorithms that can be difficult to interpret, XGBoost provides feature importances, allowing for a better understanding of which variables are most important in making predictions.

Disadvantages of XGBoost:

  1. Computational Complexity: XGBoost can be computationally intensive, especially when training large models, making it less suitable for resource-constrained systems.
  2. Overfitting: XGBoost can be prone to overfitting, especially when trained on small datasets or when too many trees are used in the model.
  3. Hyperparameter Tuning: XGBoost has many hyperparameters that can be adjusted, making it important to properly tune the parameters to optimize performance. However, finding the optimal set of parameters can be time-consuming and requires expertise.
  4. Memory Requirements: XGBoost can be memory-intensive, especially when working with large datasets, making it less suitable for systems with limited memory resources.

References:



Previous Article
Next Article

Similar Reads

XGBoost for Regression
The results of the regression problems are continuous or real values. Some commonly used regression algorithms are Linear Regression and Decision Trees. There are several metrics involved in regression like root-mean-squared error (RMSE) and mean-squared-error (MSE). These are some key members of XGBoost models, each plays an important role. RMSE:
7 min read
LightGBM vs XGBOOST - Which algorithm is better
There are a lot of Data Enthusiasts who are taking part in a number of online competitive competitions in the domain of Machine Learning. Everyone has their own unique independent approach to determine the best model and predict the accurate output of the given problem statement. In Machine Learning, Feature Engineering is very much an integral par
9 min read
GradientBoosting vs AdaBoost vs XGBoost vs CatBoost vs LightGBM
Boosting algorithms are one of the best-performing algorithms among all the other Machine Learning algorithms with the best performance and higher accuracies. All the boosting algorithms work on the basis of learning from the errors of the previous model trained and tried avoiding the same mistakes made by the previously trained weak learning algor
7 min read
ML | XGBoost (eXtreme Gradient Boosting)
XGBoost, short for eXtreme Gradient Boosting, is a powerful machine learning algorithm known for its efficiency, speed, and accuracy. It belongs to the family of boosting algorithms, which are ensemble learning techniques that combine the predictions of multiple weak learners. In this article, we will explore XGBoost step by step, building on exist
12 min read
What is the Need of XGBoost and Random Forest?
Answer: XGBoost and Random Forest are ensemble learning algorithms that enhance predictive accuracy and handle complex relationships in machine learning by leveraging multiple decision trees.Random Forest: High Predictive Accuracy:Random Forest is an ensemble learning method that builds multiple decision trees and combines their predictions. This e
3 min read
Difference Between Random Forest and XGBoost
Random Forest and XGBoost are both powerful machine learning algorithms widely used for classification and regression tasks. While they share some similarities in their ensemble-based approaches, they differ in their algorithmic techniques, handling of overfitting, performance, flexibility, and parameter tuning. In this tutorial, we will understand
6 min read
Confidence Intervals for XGBoost
Confidence intervals provide a range within which we expect the true value of a parameter to lie, with a certain level of confidence. In the context of XGBoost, confidence intervals can be used to quantify the uncertainty of predictions. In this article we explain how to compute confidence intervals for predictions made by an XGBoost model. What ar
4 min read
How to Get Access of Individual Trees of a XGBoost Model in R
XGBoost is a powerful and popular machine-learning algorithm used for regression and classification tasks. It stands out for its performance and efficiency, making it a top choice for data scientists. Understanding the structure of individual trees in an XGBoost model can be crucial for interpretation and debugging purposes. This article will guide
4 min read
XGBoost in R: How Does xgb.cv Pass the Optimal Parameters into xgb.train
XGBoost is a powerful gradient-boosting algorithm known for its efficiency and effectiveness in handling structured data. When tuning hyperparameters for an XGBoost model, cross-validation (CV) is commonly used to find the optimal combination of parameters. The xgb.cv function in R performs cross-validation to identify the best parameters, but how
5 min read
Saving and Loading XGBoost Models
XGBoost is a powerful and widely-used gradient boosting library that has become a staple in machine learning. Its ability to handle large datasets and provide accurate results makes it a popular choice among data scientists. However, one crucial aspect of working with XGBoost models is saving and loading them for future use. In this article, we wil
7 min read
Difference between Objective and feval in xgboost in R
XGBoost is a powerful machine-learning library that efficiently implements gradient boosting. It is widely used for its performance and flexibility. In XGBoost, two key parameters that often come up during model training are objective and feval. Understanding their differences is crucial for effectively leveraging the library's capabilities. Overvi
6 min read
How to use XGBoost algorithm for regression in R?
XGBoost (Extreme Gradient Boosting) is a powerful machine learning algorithm based on gradient boosting that is widely used for classification and regression tasks. In this article, we will explain how to use XGBoost for regression in R. What is XGBoost?The XGBoost stands for "Extreme Gradient Boosting." It is a powerful machine learning technique
4 min read
Different Results: “xgboost” vs. “caret” in R
When working with machine learning models in R, you may encounter different results depending on whether you use the xgboost package directly or through the caret package. This article explores why these differences occur and how to manage them to ensure consistent and reliable model performance. Introduction to xgboost and Caretxgboost is a powerf
4 min read
Confidence interval for xgboost regression in R
XGBoost is Designed to be highly efficient, versatile, and portable, it is an optimized distributed gradient boosting library. Under the Gradient Boosting framework, it puts machine learning techniques into practice. Many data science problems can be swiftly and precisely resolved with XGBoost's parallel tree boosting, also referred to as GBDT or G
4 min read
Understanding num_classes for xgboost in R
One of the most well-liked and effective machine learning libraries for a range of applications, including regression and classification, is called XGBoost (Extreme Gradient Boosting). Data scientists and machine learning practitioners use it because of its excellent accuracy and capacity to handle massive datasets. One crucial parameter to compreh
5 min read
Partial Dependence Plot from an XGBoost Model in R
Partial Dependence Plots (PDPs) are a powerful tool for interpreting complex machine-learning models. They help visualize the relationship between a subset of features and the predicted outcome, holding other features constant. In the context of XGBoost models, PDPs can provide insights into how specific features influence the model's predictions.
4 min read
What is the Difference Between eval_metric and feval in XGBoost in R?
When using XGBoost in R, two important parameters that often confuse are eval_metric and feval. These parameters play a crucial role in model evaluation, but they serve different purposes. In this article, we'll delve into the theory behind eval_metric and feval, explore their differences, and provide examples to illustrate how to use them in pract
5 min read
Machine Learning Tutorial
Machine Learning tutorial covers basic and advanced concepts, specially designed to cater to both students and experienced working professionals. This machine learning tutorial helps you gain a solid introduction to the fundamentals of machine learning and explore a wide range of techniques, including supervised, unsupervised, and reinforcement lea
8 min read
Types of Machine Learning
Machine learning is the branch of Artificial Intelligence that focuses on developing models and algorithms that let computers learn from data and improve from previous experience without being explicitly programmed for every task. In simple words, ML teaches the systems to think and understand like humans by learning from the data. In this article,
13 min read
100+ Machine Learning Projects with Source Code [2024]
Machine Learning gained a lot of popularity and become a necessary tool for research purposes as well as for Business. It is a revolutionary field that helps us to make better decisions and automate tasks. Machine Learning is the field of study that gives computers the capability to learn without being explicitly programmed. In this article, you'll
6 min read
Support Vector Machine (SVM) Algorithm
Support Vector Machine (SVM) is a powerful machine learning algorithm used for linear or nonlinear classification, regression, and even outlier detection tasks. SVMs can be used for a variety of tasks, such as text classification, image classification, spam detection, handwriting identification, gene expression analysis, face detection, and anomaly
10 min read
Adding new column to existing DataFrame in Pandas
Adding new columns to an existing DataFrame is a fundamental task in data analysis using Pandas . It allows you to enrich your data with additional information and facilitate further analysis and manipulation. This article will explore various methods for adding new columns, including simple assignment, the insert() method, the assign() method. Let
7 min read
Linear Regression in Machine learning
Machine Learning is a branch of Artificial intelligence that focuses on the development of algorithms and statistical models that can learn from and make predictions on data. Linear regression is also a type of machine-learning algorithm more specifically a supervised machine-learning algorithm that learns from the labelled datasets and maps the da
15+ min read
Principal Component Analysis(PCA)
As the number of features or dimensions in a dataset increases, the amount of data required to obtain a statistically significant result increases exponentially. This can lead to issues such as overfitting, increased computation time, and reduced accuracy of machine learning models this is known as the curse of dimensionality problems that arise wh
13 min read
Digital Image Processing Basics
Digital Image Processing means processing digital image by means of a digital computer. We can also say that it is a use of computer algorithms, in order to get enhanced image either to extract some useful information. Digital image processing is the use of algorithms and mathematical models to process and analyze digital images. The goal of digita
7 min read
Supervised and Unsupervised learning
Machine learning is a field of computer science that gives computers the ability to learn without being explicitly programmed. Supervised learning and unsupervised learning are two main types of machine learning. In supervised learning, the machine is trained on a set of labeled data, which means that the input data is paired with the desired outpu
15 min read
Introduction to Convolution Neural Network
A Convolutional Neural Network (CNN) is a type of Deep Learning neural network architecture commonly used in Computer Vision. Computer vision is a field of Artificial Intelligence that enables a computer to understand and interpret the image or visual data.  When it comes to Machine Learning, Artificial Neural Networks perform really well. Neural N
10 min read
Logistic Regression in Machine Learning
Logistic regression is a supervised machine learning algorithm used for classification tasks where the goal is to predict the probability that an instance belongs to a given class or not. Logistic regression is a statistical algorithm which analyze the relationship between two data factors. The article explores the fundamentals of logistic regressi
13 min read
K-Nearest Neighbor(KNN) Algorithm
The K-Nearest Neighbors (KNN) algorithm is a supervised machine learning method employed to tackle classification and regression problems. Evelyn Fix and Joseph Hodges developed this algorithm in 1951, which was subsequently expanded by Thomas Cover. The article explores the fundamentals, workings, and implementation of the KNN algorithm. What is t
15+ min read
Naive Bayes Classifiers
A Naive Bayes classifiers, a family of algorithms based on Bayes' Theorem. Despite the "naive" assumption of feature independence, these classifiers are widely utilized for their simplicity and efficiency in machine learning. The article delves into theory, implementation, and applications, shedding light on their practical utility despite oversimp
12 min read
Article Tags :
Practice Tags :