google.com, pub-5261878156775240, DIRECT, f08c47fec0942fa0 Integrated Knowledge Solutions

Integrated Knowledge Solutions

A blog about machine learning and deep learning

Pages

  • Home
  • Privacy Policy
  • Contact Us

Gradient Boosted Regression and Classification Trees

 A long while ago I had posted about how a "A Bunch of Weak Classifiers Working Together Can Outperform a Single Strong Classifier." Such a bunch of classifiers/regressors is called an ensemble. As mentioned in that post, bagging and boosting are two techniques that are used to create an ensemble of classifiers/regressors. In this post, I will explain how to build an ensemble of decision trees using gradient boosting. Before going into the details, however, let us first understand boosting, gradient boosting, and why the decision tree classifiers and regression trees are the most suitable candidates for creating an ensemble.

The individual units in an ensemble are known as weak learners. Such learners are brittle in nature, i.e. a small change in the training data can have a major impact on their performance. This brittle nature helps to ensure that the weak learners are not well-correlated with each other. The choice of the tree model for weak learners is popular because tree models exhibit decent brittleness and such models are easily trained without much computation effort.

Boosting is one technique to combine weak learners to obtain a single strong learner or model. Bagging is another such technique. In bagging, all weak learners learn in parallel and independent of other learners. Every learner in bagging looks at only a part of the training data or a subset of features or both. In boosting, the weak learners are build sequentially using the full training data and the results from the preceding weak learners. Thus, boosting builds an additive model and the output of the ensemble is taken as the weighted sum of the predictions of the weak learners.

In the original boosting algorithm AdaBoost, the successive weak learners try to improve the accuracy by giving more importance to those training examples that are misclassified by the prior weak learners. In gradient boosting, the results from the preceding weak learners are compared with the desired output to obtain a measure of the error which the next weak learner tries to minimize. Thus, the focus in gradient boost is on the residuals, i.e. the difference between the desired output and the actual output, rather than on those specific examples that were misclassified by the earlier learners. The term gradient is used because the error minimization is carried out by using the gradient of the error function. The sequence of successive trees are of identical depth from 1 (stump) to 4.


A Walk Through Example to Build a Gradient Boosted Regression Tree

Let us work through an example to clearly understand how gradient boosted trees are build. We will take a regression example because building a gradient boosted regression tree is easier to understand than a gradient boosted classification tree. The example consists of two predictors, fertilizer input (x0) and insecticide input (x1), and the output variable is the crop yield (y). The goal is to build a gradient boosted regression tree to predict the crop yield given the input numbers for x0 and x1.

This image has an empty alt attribute; its file name is screen-shot-2022-02-15-at-1.26.17-pm.png

We will build a tree that minimizes the squared error (mse) between the actual output and the predicted output. We begin by building a base learner that yields the same prediction irrespective of the values of the predictor variables. This base prediction, let us denote it as y_hat_0, equals average of the output variable y, y_bar. Next, we calculate the residuals, the difference between the actual output y and the predicted output to obtain the residuals as shown below.

This image has an empty alt attribute; its file name is screen-shot-2022-02-15-at-2.01.27-pm.png

The next step is to adjust the predictions by relating the residuals with x0 and x1. We do this by fitting a regression tree to the residuals. We will use a tree of depth 1. To build the tree, we find the feature and the cut-off or the threshold value that best partitions the training data to minimize the mean squared error (mse). For the root node, such a combination consists of predictor x1 and the cut-off value of 11.5. The resulting tree is shown below. This tree was build using the DecisionTreeRegressor of the Sklearn library. Let's look at the meanings of different entries shown in the tree diagram. The mse value of 181.889 in the internal node of the tree is nothing but the error value if the residuals_0 column is approximated by the column average which is being shown by "value = 0." The number of examples associated with a node in the tree is given by "samples."

This image has an empty alt attribute; its file name is image-3.png

The above tree shows residual approximation by -11.667 for those training examples whose x1 value is less than or equal to 11.5 and the approximation by 11.667 when x1 is greater than 11.5. Assuming a learning rate of 0.75, we combine the above tree with the base tree (stump) to obtain updated predictions and the next set of residuals as shown below. To understand how the updated predictions were calculated, consider the predictor variables x0=6 and x1=4. The above tree tells us that for x1=4, the residual should be approximated by -11.667. The previous prediction for this particular x0,x1 combination is 57.667. Thus, the new prediction in this case becomes 57.667+0.75*(-11.667) which equals 48.916.

This image has an empty alt attribute; its file name is screen-shot-2022-02-15-at-5.36.20-pm.png

With the new set of residuals, we again build a tree to relate x0, x1 with residuals_1. This tree is shown below.

This image has an empty alt attribute; its file name is image-4.png

We update the predictions. For the first training example, the updating leads to the prediction 48.916+0.75*(-2.717) which equals 46.879. These updated predictions, y_hat2, and the new residuals, residuals_2 are shown below.

This image has an empty alt attribute; its file name is screen-shot-2022-02-15-at-8.37.10-pm.png

The tree building process continues in this fashion to generate either the specified number of weak learners or to the acceptable level of error.

Now that we know how gradient boosted trees are created, let us finish the above example using the GradientBoostingRegressor from the Sklearn library as shown below. The number of learners has been specified as 10 and the depth is set to 1.

import numpy as np
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.metrics import mean_squared_error
# Create data for illustration
X = np.array([[6,4],[12,5], [16,9],[22,14],[24,20],[32,24]])
y = np.array([40, 46, 52, 60, 68,80])
regressor = GradientBoostingRegressor(
    max_depth=1,
    n_estimators=10,
    learning_rate=0.75
)
gbt = regressor.fit(X, y)
gbt.predict(X)


array([40.18852649, 46.37977649, 49.56846063, 62.91676214, 67.36073713,
       79.58573713])


How about Gradient Boosted Classification Trees?

Let us convert the above regression example to a classification example by considering whether the crop yield was profitable or not based on fertilizer and insecticide costs. Thus, the output variable y now has two values, 0 (loss) and 1 (gain) as shown below.

This image has an empty alt attribute; its file name is screen-shot-2022-02-20-at-6.32.41-pm.png

Just like the procedure for building gradient boosted regression trees, we begin with a crude approximation for the output variable. The initial probability of class 1 over all the training examples, equal to 0.667, is taken as this approximation. The gradient boosted classifier is built using regression trees just like it is done while building gradient regression trees. The successive learners try to reduce the residuals, the difference between the y and the predicted probability.

Log Likelihood Loss Function and Log(odds)

The loss function minimized in the gradient boosted classification tree algorithm is the negative log likelihood. For a classification problem with two classes as we have, the negative log likelihood for the i-th training example is expressed by the following formula where p stands for the probability that the example is from class 1.

This image has an empty alt attribute; its file name is screen-shot-2022-02-21-at-4.38.03-pm.png

The loss is summed over all training examples to get the over all loss. The ratio p/(1-p) is called the odds or odds ratio, and often is expressed in terms of log(odds) by taking the natural log of the odds ratio. The probability p of an event and its log(odds) are related through the following equation:

This image has an empty alt attribute; its file name is screen-shot-2022-02-24-at-4.27.43-pm.png

Through some simple algebraic manipulation, we can also express the loss function as

This image has an empty alt attribute; its file name is screen-shot-2022-02-21-at-4.46.00-pm.png

Instead of calculating the gradient of the loss function with respect to p, it turns out that adjusting log(odds) offers a better way to minimize the loss function. Thus, taking the gradient of the loss function with respect to log(odd) results in the following expression:

This image has an empty alt attribute; its file name is screen-shot-2022-02-21-at-7.08.24-pm.png

The first term on the RHS of the equation is the negative of the desired output while the second term corresponds to the predicted probability (see the relationship between p and log(odds) above). The negative of the RHS in the above equation defines the residuals that we try to minimize by building successive trees via regression.

Back to Example

Coming back to our example, since the initial probability attached to every training example is 0.667 (ratio of class 1 labels and class 0 labels), the residuals are:

-0.667,  0.333,  0.333,  0.333,  0.333, -0.667

Let us try to fit a regression tree to the residuals at hand. Again, we will fit a tree of unit depth using the DecisionTreeRegressor from the Sklearn. The resulting tree shown below.

This image has an empty alt attribute; its file name is image-7.png

While in the case of the gradient regression trees, the "value" from the leaf nodes were directly used in the calculations of the updated residuals, we need to map "value" into log(odds) for calculating a new set of residuals in the present case. This mapping is done using the following relationship:

This image has an empty alt attribute; its file name is image-8.png

Let us try to understand the quantities in the RHS of the above expression. We will do so by referring to the right leaf node of the above tree. This leaf node has 5 samples that refer to the index "i" in the above expression. The item "value" in the leaf nodes is the residual for each example in the leaf node. There are five examples associated with the right leaf node; these are all but the first example of our data set. The previous probability is 0.667 for each of these examples. Thus, the mapped_log(odds) for these five examples are 5*0.133/(5*0.667*0.333), which equals 0.599. With 0.75 as the learning rate, the new log(odds) values for these five examples become 0.693(old log(odds)) + 0.75*(0.599) resulting in 1.142 for each of the five examples of the data set for which x0<9. Converting these log(odds) to probabilities, we see that 0.758 is the probability for the last five examples in the right leaf node to be from class 1. Carrying out similar calculations for the left leaf node, we end up with -1.559 as the updated log(odds) which translates to 0.174 as the probability that our first example in the data set is from class 1 or from the positive class.

Subtracting the updated probabilities from column y, we get a new set of residuals as shown below:

[-0.174,  0.242,  0.242,  0.242,  0.242, -0.758]

The regression tree built to fit these residuals is shown below.

This image has an empty alt attribute; its file name is image-9.png

We need to calculate the mapped_log(odds) again. The example associated with the right leaf in this case is the last example of the data set. The mapped log(odds) value for this example comes out as -4.132 following the formula for mapping shown above. The updated log(odds) value is then the 1.142(prior value) + 0.75* (-4.132). Converting the result into the probability, we get 0.123 as the probability that the last example in our data set comes from the positive class. Thus, it is classified as belonging to the negative (label 0) class. Let us now map the left leaf node value to log(odds) using the mapping formula.

= 5*0.159/((4*0.758*(1-0.758)+0.174*(1-0.174)))
= 0.906

This results in 0.906. Out of the five examples associated with the left leaf node, the four examples(all with y = 1) were together in the previous tree and had the updated log(odds) value 1.142 at that instance. The current log(odds) value for these four examples is then 1.142+0.75*0.906, equal to 1.821 which yields a probability value of 0.860. Thus, these four examples are correctly assigned the probability of 0.860 for the positive class. The remaining fifth example in the left node has a prior log(odds) value of -1.559. Thus, its updated log(odds) becomes -1.559+0.75*0.906, equal to -0.879. This gives 0.293 as the probability of this example from the positive class. Since the probability for the negative class is higher, this example is also correctly classified. At this stage, there is no need to add anymore learner because all examples have been correctly classified.

The above example was done to illustrate how the gradient boosted classifier builds its learners. Let us apply the GradientBoostingClassifier from the Sklearn library to check our step by step assembly of the learners explained above. We will print out the probability values to compare against our calculations.

from sklearn.ensemble import GradientBoostingClassifier
clf = GradientBoostingClassifier(
    criterion='mse', max_depth=1,
    n_estimators=2,
    learning_rate=0.75
)
gbdt = clf.fit(X, y)
list(gbdt.predict_proba(X))
[array([0.70657313, 0.29342687]),
 array([0.13928973, 0.86071027]),
 array([0.13928973, 0.86071027]),
 array([0.13928973, 0.86071027]),
 array([0.13928973, 0.86071027]),
 array([0.87645946, 0.12354054])]

You can see that these probabilities are identical to those calculated earlier. Thus, you now know how to build a gradient boosted classifier.

Before You Leave

Let us summarize the post before you leave. Boosting relies on an ensemble of trees to perform regression and classification. The gradient boosted trees for regression and classification give excellent performance. Using the Sklearn library without paying much attention to the number of learners and tree depth can lead to over-fitting; so care must be taken. One disadvantage common to all ensemble methods is that the simplicity of understanding model that one gets using a single tree is lost. A speedier and more accurate and scalable version of gradient boosted trees is the extreme gradient boosted trees (XGBoost). The performance of XGBoost algorithm is at par with deep learning models and this model is very popular. 

Image

Insert an image to make a visual statement.

Settings

Describe the purpose of the image.(opens in a new tab)


Leave empty if decorative.

px
px
Scale

Select the size of the source image.

Looking for other block settings? They've moved to the styles tab.

  • Image








at February 20, 2024 No comments:
Email ThisBlogThis!Share to XShare to FacebookShare to Pinterest
Labels: classification trees, Decision trees, ensemble learning, gradient boosted trees, log(odds), Machine Learning, regression trees

Information Retrieval Vs. Data Retrieval

Often there is a confusion about data retrieval and information retrieval. This short post will attempt to clarify the difference between the two. 

Information retrieval (IR) is a field of study dealing with the representation, storage, organization of, and access to documents. The documents may be books, reports, pictures, videos, web pages or multimedia files. The whole point of an IR system is to provide a user easy access to documents containing the desired information. One of the best known example of an IR system is Google search engine. A data retrieval system is a database management system (DBMS).

The difference between an information retrieval system and a data retrieval system is that

– IR deals with unstructured/semi-structured data while a data retrieval (a database management system or DBMS) deals with structured data with well-defined semantics

– Querying a DBMS system produces exact/precise results or no results if no exact match is found

– Querying an IR system produces multiple results with ranking. Partial match is allowed.

Document Characterization

Three kinds of characteristics are associated with a document.

    Metadata characterization

This kind of characterization refers to ownership, authorship and other items of information about a document. The Library of Congress subject coding is also an example of metadata. Another example of metadata is the category headings at Internet search engine Yahoo. To standardize category headings, many areas use specific ontologies, which are hierarchical taxonomies of terms describing certain knowledge topics.



    Presentation Characterization


This refers to attributes that control the formatting or presentation of a document.

Content Characterization

This refers to attributes that denote the semantic content of a document. Content characterization is of primary interest in imageIR. The common practice in IR is to represent a textual document by a set of keywords called index terms or simply terms. An index term is a word or a phrase in a document whose semantics give an indication of the document’s theme. The index terms, in general, are mainly nouns because nouns have meaning by themselves.

The same concept can be applied to images/multimedia documents to characterize them in terms of words using the representation known aptly as the Bag of Word (BoW) representation.

image

However, what are the words for images is a tricky question. One way to define such words for images is through the use of vector quantization which yields a set of code words (A code word is simply an image patch of certain size) that can be used to assemble given images. Once we are able to characterize images in terms of code words, various attributes such as frequencies and joint frequencies of code words occurrences can be computed to group images into meaningful groups. An example of one such grouping is shown in the figure below where the grouping of pictures is shown in the form of a graph. 









at February 17, 2024 No comments:
Email ThisBlogThis!Share to XShare to FacebookShare to Pinterest
Labels: bag of words (BoW), Data retrieval, document characterization, image grouping, information retrieval

How Similar are Two Clustering Results?

While performing clustering, it is not uncommon to try a few different clustering methods. In such situations, we want to find out how similar are the results produced by different clustering methods. In some other situations, we may be interested in developing a new clustering algorithm or might be interested in evaluating a particular algorithm for our use. To do so, we make use of data sets with known ground truth so that we can compare the results against the ground truth. One way to evaluate the clustering results in all these situations is to make use of a numerical measure known as Rand index (RI). It is a measure of how similar two clustering results or groupings are.

Rand Index (RI)

RI works by looking at all possible unordered pairs of examples. If the number of examples or data vectors for clustering is n, then there are $\binom{n}{2}(=n(n-1)/2)$ pairs. For every example pair, there are three possibilities in terms of grouping. The first possibility is that the paired examples are always placed in the same group as a result of clustering. Lets count how often this happens over all pairs and represent that count by a. The second possibility is that the paired examples are never grouped together. Let's use b to represent the count of all pairs that are never grouped together. The third possibility is that the paired examples are sometimes grouped and sometimes not grouped together. The first two possibilities are treated as paired examples in agreement while the third possibility represents pairs in confusion. The RI of two groupings is then calculated by the following formula:

$\text{RI} = \frac{\text{Count of Pairs in Agreement}}{\text{Total Number of Pairs}} = \frac{(a+b)}{\binom{n}{2}}$

We can notice from the formula that RI can never exceed 1 and its possible lowest value is 0.

Let's take an example to illustrate RI calculation. Say we have five examples clustered into two clusters using two different clustering methods. The first method groups examples A, B, and C into one group and examples D and E into another group. The second clustering method groups A and B together and C, D, and E together. To compute RI for this example, lets first list all possible unordered pairs of five examples at hand. We have 10 (n*(n-1)/2) such pairs. These are: {A, B}, {A, C},  {A, D}, {A, E}, {B, C}, {B, D}, {B, E}, {C, D}, {C, E}, and {D, E}. Examining these pairs, we notice that the pair {A, B} and {D, E} are always grouped together by the both clustering methods. Thus, the value of a is two. We also notice that four pairs, {A, D}, {A, E}, {B, D}, and {B, E}, never occur together in any clustering result. Thus, the value of b is four. The Rand index (RI) is then 0.6.

Adjusted Rand Index (ARI)

RI suffers from one drawback; it yields a high value for pairs of random partitions of a given set of examples. To understand this drawback, think about randomly grouping a number of examples. When the number of partitions in each grouping, that is when the number of clusters, is increased, more and more example pairs are going to be in agreement because they are more likely to be not grouped together. This will result in a high RI value. Thus, RI is not able to take into consideration effects of random groupings. To counter this drawback, an adjustment is made to the calculations by taking into consideration grouping by chance. This is done by using a specialized distribution, the generalized hyper-geometric distribution, for modeling the randomness. The resulting measure is known as the adjusted Rand index (ARI).

ARI is best understood using an example. So let's look at the example of two clustering results used earlier. Let's create a contingency table summarizing the results of two clustering methods. In this case, it is a 2x2 table wherein each cell of the table shows the number of times an example occurs in two clusters referenced by the corresponding row and column. M1C1 and M1C2 refer to two clusters formed by a hypothetical method-1. M2C1 and M2C2 similarly refer to two clusters formed by method-2. For clarity sake, I have included the examples forming the respective clusters next to M1C1, M1C2 etc. The top left cell has an entry of 2 because the clusters M1C1 and M2C1 share two examples, A and B. Entries in the other cells have similar meaning. The numbers to the right and below the contingency table show the sums along respective rows and columns.

To write the formula for ARI, lets generalize the entries of the contingency table using the following notation:

$n_{ij} = \text{Number of examples common to cluster i and cluster j}$

$a_i = \text{Sum of contingency cells in row i}$

$b_j = \text{Sum of contingency cells in column j}$

The ARI is then expressed as:

The first term in the numerator is known as index, and the second term as expected index. The first term in the denominator is called maximum index, and the second term of the denominator is same as the second term of the numerator. With these designations of the terms, the ARI is often expressed as

$\text{ARI} = \frac{\text{index - expected index}}{\text{maximum index - expected index}}$

Now lets go back to the contingency table for our example and calculate the different parts of the ARI formula first. We have:

$\sum_{ij}\binom{n_{ij}}{2} = \binom{2}{2} + \binom{1}{2} + \binom{0}{2} + \binom{2}{2} = (1 + 0 + 0 + 1)=2$

$\sum_i\binom{a_i}{2} = (\binom{3}{2}+\binom{2}{2}) = (3 + 1)=4$

$latex \sum_j\binom{b_j}{2} = (\binom{2}{2}+\binom{3}{2}) = (1 + 3) = 4$

Thus the index value for our example is 2; the expected index value is 1.6 (4*4/(5*4/2)). The maximum index value is 4. Therefore, the ARI for our example is (2 - 1.6)/(4 - 1.6), which equals 0.1666. We see that RI is much higher than ARI; this is typical of these indices. While RI always lies in 0-1; ARI can achieve a negative value also.

ARI is not the only measure to compare two sets of groupings. Mutual information based measure, adjusted mutual information (AMI), is also used for this purpose. May be in one of the future posts, I will describe this measure.

 





at February 03, 2024 No comments:
Email ThisBlogThis!Share to XShare to FacebookShare to Pinterest
Labels: Adjusted Rand Index, Cluster similarity, Rand Index
Newer Posts Older Posts Home
Subscribe to: Posts (Atom)
  • January 2025 (4)
  • September 2024 (1)
  • April 2024 (6)
  • March 2024 (1)
  • February 2024 (6)
  • January 2024 (2)
  • December 2023 (2)
  • October 2023 (3)
  • September 2023 (1)
  • August 2023 (3)
  • July 2023 (2)
  • June 2023 (3)

Labels

  • (CBOW)
  • Adjacency matrix Degree Matrix Graph Distance Graph similarity Laplacian Matrix Spectral graph distance
  • Adjusted Rand Index
  • AI
  • Air Transportation Dataset DeltaCon Graph similarity netrd Network Portrait Portrait Divergence Spectral graph distance
  • bag of words (BoW)
  • Bard
  • Bernoulli NB
  • BERT
  • Binary Cross Entropy Cross Entropy Loss Functions Negative Log Likelihood Loss
  • Canonical Correlation
  • canonical variates
  • CCA
  • ChatGPT
  • Class Labels
  • classification trees
  • Claude2
  • Cluster similarity
  • coding on the fly
  • Constitutional AI
  • Constitutional Interactive Reward
  • context words
  • Continuous Bag of Words
  • Cora
  • Correlation
  • cosine similarity
  • CountVectorizer
  • Covariance
  • Cross Entropy
  • Data retrieval
  • Decision trees
  • Deep Graph Learning Library
  • DGL
  • Dimensionality reduction
  • document characterization
  • Domain-Specific LLMs
  • ensemble learning
  • Entropy
  • feature hashing
  • feature independence
  • Fourier Neural operator (FNO)
  • Function Spaces mapping
  • GCN
  • Generative AI
  • GNN
  • gradient boosted trees
  • Graph Classification
  • Graph Neural Networks
  • GraphSAGE
  • Hidden Relationships
  • hybrid AI
  • image grouping
  • information retrieval
  • interactive learning
  • Inverse document frequency
  • Knowledge graphs
  • Language Models
  • Laplace Smoothing
  • Linear Regression
  • LLaMA 2
  • LLMs
  • log(odds)
  • LoRA
  • Low Rank matrix Approximation
  • Machine Learning
  • masking
  • matrix factorization
  • Modern BERT
  • Multinomial NB
  • MUTAG
  • N-grams features
  • Naive Bayes
  • neural language modelling
  • neural networks
  • Neural operators
  • Neuro-symbolic
  • NLP
  • NNM Factorization
  • Node Classification
  • Node Embeddings
  • OpenAI
  • Parameter Efficient fine tuning
  • partial differential equations
  • PCA
  • PDE
  • Permutation invariance
  • Physics Informed Neural Networks (PINNs)
  • Physics Informed Neural operators (PNO)
  • Physics loss function
  • PINNs
  • PYG
  • RAG
  • Rand Index
  • Random Walks
  • Regression
  • regression trees
  • Reinforcement learning
  • Reinforcement learning with human feedback
  • Retrieval Augmented Generation
  • reward modeling
  • SBERT
  • Scikit-learn
  • scikit-network
  • Self-supervised learning
  • semantic networks
  • semi-supervised classification
  • semi-supervised clustering
  • Semi-supervised learning
  • sentence embeddings
  • skip-gram model
  • softmax
  • Stock Prediction App
  • SVD
  • symbolic reasoning
  • Symbolic regression
  • target words
  • term weighting
  • textVectorizer
  • tf-idf
  • TfidfVectorizer
  • Transductive training set
  • transfer learning
  • unsupervised learning
  • vector space
  • Word Embedding
  • Word Embeddings
  • word vectors
  • Word2vec

Search This Blog

Powered by Blogger.