In Linear Models, the Explainable Boosting Machine (EBM) algorithm was presented. As mentioned, it used decision trees to approximate the functions from the Generalized Additive Models (GAMs) using decision trees. Here, more tree-based models are going to be introduced.
Decision Tree (DT)
A Decision Tree (DT) is formally defined as a directed acyclic graph – also called a tree –, possessing two types of nodes: decision and leaf nodes. Decision nodes present conditional tests based on a certain feature. Observations that satisfy the condition moves to the left child node, while the other go to the right child. Each decision node separates the observations in two subsets, doing the same in feature space. On the other hand, leaf nodes represent a certain region in feature space, without having child nodes. They are at the end of the trees and represent the regions formed by specific paths generated by following the decision nodes. Figure 1 depicts a DT.
Figure 1: Diagram of a DT. Decision nodes are depicted in blue and are denoted by \(\mathcal C\), while leaf nodes are in red and are denoted by \(l\).
During training, the decision nodes in the DT are formed by maximizing the purity of its child nodes. The intuition is that each conditional test should separate the data as much as possible, effectively grouping observations that are present in similar regions in space. To measure how pure a node is, impurity functions are used. For classification, one of the most common impurity functions is the entropy of the data. Let the class proportions in a certain node \(\mathcal C_i\) be \(\{p_i\}_{i=1}^n\). The entropy \(\mathcal H\) of that node is defined as: \[
\mathcal H(\mathcal C) = -\sum_{i=1}^{n} p_i \log p_i.
\tag{1}\] Note that this function is maximized when the proportion of all classes is the same, and minimized when there is only a single class in the node. The splits are chosen so that the information gain is maximized, being defined as: \[
\mathcal I(\mathcal C_i, \mathcal C_j) = \mathcal H(\mathcal C_i) - \mathcal H(\mathcal C_i \mid \mathcal C_j),
\tag{2}\] where \(\mathcal H(\mathcal C_i \mid \mathcal C_j)\) denotes the conditional entropy after the split made in \(\mathcal C_j\). The splits that maximize the function \(\mathcal I\) produce the purest child nodes. For regression, the same ideia is valid, though the impurity function to be minimized is generally the variance of the targets.
After training, the inference uses an aggregation function \(g: \mathbb R^{L\times n} \to \mathbb R\) to combine the targets from the \(L\) training observations that lied in each node. This combined value is set as the prediction of the new data points.
Note that DTs do not assume any distribution for the data, and are also invariant to transformations that do not change the sequence of the elements in any given interval. Another important fact is that by maximizing purity of the child nodes, it automatically selects the most important attributes for predicting the target – as the first ones are the ones that most separate the observations.
Code: Decision Tree
Importing packages for the DT.
import numpy as npimport matplotlib.pyplot as pltfrom sklearn.datasets import load_breast_cancerfrom sklearn.tree import DecisionTreeClassifier, plot_treefrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import classification_report
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
A DT is a model with low bias and high variance, overfitting the training data. To avoid this, the Random Forest (RF) (Breiman 2001) model ensembles various DTs, aggregating their predictions. This increases bias and decreases variance, leading to more robust models.
RF operates through a process called Bootstrap Aggregating – also know as bagging. Multiple subsets of the training data \(\mathcal D^{(\text{Train})}_{i}\subseteq \mathcal D^{(\text{Train})}\) are created by drawing random samples with replacement. Each subset is used to train a separate decision tree. During the construction of each tree, the algorithm is not allowed to choose from all features. Instead, it must select from a random subset of features, forcing the trees to be different. Then, each tree is grown to its maximum depth, to ensure each one has low bias. Finally, the predictions of each tree are combined using a suitable operator. Figure 2 depicts a RF.
Figure 2: Diagram of a RF with \(3\) DTs.
Code: Random Forest
Importing packages for the RF.
import numpy as npimport matplotlib.pyplot as pltfrom sklearn.datasets import load_breast_cancerfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import classification_report
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
Unlike Random Forests, which rely on the independence of trees to reduce variance, Gradient Boosting Machines (GBMs) build an ensemble of decision trees sequentially. Each new tree is designed to correct the residuals of the preceding ensemble. This approach is framed as a functional gradient descent, where the model minimizes a loss function \(\mathcal L(y, \mathcal F(\boldsymbol{x}))\) by adding weak learners that point in the direction of the negative gradient.
Let \(\mathcal F_0(\boldsymbol{x})\) be an initial constant prediction. For each iteration \(t = \{1, \dots, T\}\), the algorithm calculates the pseudo-residuals \(r_{i}^{(t)}\), which are the negative gradients of the loss function with respect to the current predictions: \[
r_{i}^{(t)} = -\left[ \frac{\partial \mathcal L(y_i, \mathcal F_{t-1}(\boldsymbol{x}_i))}{\partial \mathcal F_{t-1}(\boldsymbol{x}_i)} \right].
\tag{3}\] A new weak learner \(h_t(\boldsymbol{x})\) – typically a decision tree – is then trained to fit these residuals. The ensemble is updated as: \[
\mathcal F_t(\boldsymbol{x}) = \mathcal F_{t-1}(\boldsymbol{x}) + \eta \cdot h_t(\boldsymbol{x}),
\tag{4}\] where \(\eta \in (0, 1]\) is the learning rate, which controls the contribution of each tree to prevent overfitting. There are several implementations of GBMs, such as XGBoost (Chen and Guestrin 2016), LightGBM (Ke et al. 2017) and CatBoost (Prokhorenkova et al. 2018).
Code: Gradient Boosting Machines
Importing packages for the GBMs.
import timeimport pandas as pdimport numpy as npimport matplotlib.pyplot as pltfrom sklearn.datasets import fetch_california_housingfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import mean_squared_errorfrom xgboost import XGBRegressorfrom lightgbm import LGBMRegressorfrom catboost import CatBoostRegressor
Tree-based models can also be utilized to Symbolic Regression (SR). It searches the space of mathematical expressions to simultaneously discover both the structure of the model and its parameters.
Given a training set \(\mathcal{D}^{(\text{Train})} = \{(\boldsymbol{x}_i^{(\text{Train})}, y_i^{(\text{Train})})\}_{i=1}^N\), SR seeks an optimal function \(f\) from a space of possible mathematical expressions \(\mathcal{E}\). This space is constructed by combining mathematical primitives, which include the features, constants and a predefined set of operators. They are combined in trees, such as depicted in Figure 3.
Figure 3: Diagram of a tree that represents the equation \(f(x_1, x_2) = x_2\left(x_1 - \frac{2.2}{x_3}\right)\).
The optimization objective is to find the expression \(f \in \mathcal{E}\) that minimizes a given loss function \(\mathcal L\) while simultaneously penalizing the complexity of the expression \(C(f)\) to prevent overfitting and encourage interpretability: \[
\hat{f} = \underset{f \in \mathcal{E}}{\arg\min} \ \sum_{i=1}^N \mathcal L\left(y_i^{(\text{Train})}, f(\boldsymbol{x}_i^{(\text{Train})})\right) + \lambda C(f),
\tag{5}\] where \(\lambda\) controls the tradeoff between accuracy and simplicity. The complexity \(C(f)\) is often defined as the number of nodes in the expression tree.
Because the search space \(\mathcal{E}\) is discrete, infinite, and non-differentiable, SR uses EAs to search the best possible functions. After the training, the model is described by a single mathematical equation, making it a highly interpretable model.
Code: Symbolic Regression
Importing libraries for the SR.
import numpy as npimport matplotlib.pyplot as pltfrom gplearn.genetic import SymbolicRegressorimport graphviz
Creating a function and drawing noisy observations from it.
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
Parameters
population_size
2000
generations
20
tournament_size
20
stopping_criteria
0.01
const_range
(-1.0, ...)
init_depth
(2, ...)
init_method
'half and half'
function_set
('add', ...)
metric
'mean absolute error'
parsimony_coefficient
0.01
p_crossover
0.7
p_subtree_mutation
0.1
p_hoist_mutation
0.05
p_point_mutation
0.1
p_point_replace
0.05
max_samples
0.9
feature_names
None
warm_start
False
low_memory
False
n_jobs
1
verbose
1
random_state
42
Plotting the prediction against the true values, and printing the best equation found.
Chen, Tianqi, and Carlos Guestrin. 2016. “Xgboost: A Scalable Tree Boosting System.” In International Conference on Knowledge Discovery and Data Mining, 785–94.
Ke, Guolin, Qi Meng, Thomas Finley, Taifeng Wang, Wei Chen, Weidong Ma, Qiwei Ye, and Tie-Yan Liu. 2017. “Lightgbm: A Highly Efficient Gradient Boosting Decision Tree.”Advances in Neural Information Processing Systems 30.
Prokhorenkova, Liudmila, Gleb Gusev, Aleksandr Vorobev, Anna Veronika Dorogush, and Andrey Gulin. 2018. “CatBoost: Unbiased Boosting with Categorical Features.”Advances in Neural Information Processing Systems 31.