<jupyter_start><jupyter_text>Week 45: Random Forests and Boosting  **<NAME>**, Department of Physics, University of Oslo and Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State UniversityDate: **Nov 12, 2020**Copyright 1999-2020, <NAME>. Released under CC Attribution-NonCommercial 4.0 license Overview of week 45* **Thursday**: Wrapping up from last week. Bagging and Random forests. Boosting methods. [Link to video of lecture](https://www.uio.no/studier/emner/matnat/fys/FYS-STK4155/h20/forelesningsvideoer/LectureNovember5.mp4?vrtx=view-as-webpage)* **Friday**: Boosting and gradient boosting. [Link to video of lecture](https://www.uio.no/studier/emner/matnat/fys/FYS-STK4155/h20/forelesningsvideoer/LectureNovember6.mp4?vrtx=view-as-webpage)Geron's chapter 7. See also lecture from [STK-IN4300, lecture 9](https://www.uio.no/studier/emner/matnat/math/STK-IN4300/h20/slides/lecture_9.pdf). Chapter 10 (sections 10.1-10.10 are the most relevant ones)  of Hastie et al contains also a good discussion.[Video on boosting methods by Hastie (the textbook author)](https://www.youtube.com/watch?v=wPqtzj5VZus&ab_channel=H2O.ai). ThursdayBagging, voting and random forests.The material on bagging and voting is a repeat from last week and can be found in the slides from week 44.We repeat here the voting approach since this will serve as a motivation for boosting methods later. Why Voting?The idea behind boosting, and voting as well can be phrased as follows:**Can a group of people somehow arrive at highlyreasoned decisions, despite the weak judgement of the individualmembers?**The aim is to create a good classifier by combining several weak classifiers.**A weak classifier is a classifier which is able to produce results that are only slightly better than guessing at random.**The basic approach is to apply repeatedly (in boosting this is done in an iterative way) a weak classifier to modifications of the data.In voting we simply apply the law of large numbers while in boosting we give more weight to misclassified data ineach iteration.  Decision trees play an important role as our weak classifier. They serve as the basic method.  Tossing coinsThe simplest case is a so-called voting ensemble. To illustrate this,think of yourself tossing coins with a biased outcome of 51 per centfor heads and 49% for tails. With only few tosses,you may not clearly see this distribution for heads and tails. However, after somethousands of tosses, there will be a clear majority of heads.  With 2000 tossesyou should see approximately 1020 heads and 980 tails.We can then state that the outcome is a clear majority of heads. Ifyou do this ten thousand times, it is easy to see that there is a 97%likelihood of a majority of heads.Another example would be to collect all polls before anelection. Different polls may show different likelihoods for acandidate winning with say a majority  of the popular vote. The majority votewould then consist in many polls indicating that this candidate willactually win.The example here shows how we can implement the coin tossing case,clealry demostrating that after some tosses we see the [law of large](https://en.wikipedia.org/wiki/Law_of_large_numbers)numbers kicking in. Standard imports first<jupyter_code>%matplotlib inline

# Common imports
from IPython.display import Image 
from pydot import graph_from_dot_data
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
from sklearn.tree import export_graphviz
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.compose import ColumnTransformer
from IPython.display import Image 
from pydot import graph_from_dot_data
import os

# Where to save the figures and data files
PROJECT_ROOT_DIR = "Results"
FIGURE_ID = "Results/FigureFiles"
DATA_ID = "DataFiles/"

if not os.path.exists(PROJECT_ROOT_DIR):
    os.mkdir(PROJECT_ROOT_DIR)

if not os.path.exists(FIGURE_ID):
    os.makedirs(FIGURE_ID)

if not os.path.exists(DATA_ID):
    os.makedirs(DATA_ID)

def image_path(fig_id):
    return os.path.join(FIGURE_ID, fig_id)

def data_path(dat_id):
    return os.path.join(DATA_ID, dat_id)

def save_fig(fig_id):
    plt.savefig(image_path(fig_id) + ".png", format='png')<jupyter_output><empty_output><jupyter_text>Simple Voting Example, head or tail<jupyter_code># Common imports
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
plt.rcParams['axes.labelsize'] = 14
plt.rcParams['xtick.labelsize'] = 12
plt.rcParams['ytick.labelsize'] = 12

heads_proba = 0.51
coin_tosses = (np.random.rand(10000, 10) < heads_proba).astype(np.int32)
cumulative_heads_ratio = np.cumsum(coin_tosses, axis=0) / np.arange(1, 10001).reshape(-1, 1)
plt.figure(figsize=(8,3.5))
plt.plot(cumulative_heads_ratio)
plt.plot([0, 10000], [0.51, 0.51], "k--", linewidth=2, label="51%")
plt.plot([0, 10000], [0.5, 0.5], "k-", label="50%")
plt.xlabel("Number of coin tosses")
plt.ylabel("Heads ratio")
plt.legend(loc="lower right")
plt.axis([0, 10000, 0.42, 0.58])
save_fig("votingsimple")
plt.show()<jupyter_output><empty_output><jupyter_text>Using the Voting ClassifierWe can use the voting classifier on other data sets, here the exciting binary case of two distinct objects using the make moons functionality of **Scikit-Learn**.<jupyter_code>from sklearn.model_selection import train_test_split
from sklearn.datasets import make_moons

X, y = make_moons(n_samples=500, noise=0.30, random_state=42)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)

from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import VotingClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC

log_clf = LogisticRegression(solver="liblinear", random_state=42)
rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42)
svm_clf = SVC(gamma="auto", random_state=42)

voting_clf = VotingClassifier(
    estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
    voting='hard')

voting_clf.fit(X_train, y_train)

from sklearn.metrics import accuracy_score

for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
    clf.fit(X_train, y_train)
    y_pred = clf.predict(X_test)
    print(clf.__class__.__name__, accuracy_score(y_test, y_pred))

log_clf = LogisticRegression(solver="liblinear", random_state=42)
rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42)
svm_clf = SVC(gamma="auto", probability=True, random_state=42)
voting_clf = VotingClassifier(
    estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
    voting='soft')
voting_clf.fit(X_train, y_train)

from sklearn.metrics import accuracy_score

for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
    clf.fit(X_train, y_train)
    y_pred = clf.predict(X_test)
    print(clf.__class__.__name__, accuracy_score(y_test, y_pred))<jupyter_output>LogisticRegression 0.864
RandomForestClassifier 0.872
SVC 0.888
VotingClassifier 0.896
LogisticRegression 0.864
RandomForestClassifier 0.872
SVC 0.888
VotingClassifier 0.912<jupyter_text>Voting and Bagging<jupyter_code>from sklearn.model_selection import train_test_split
from sklearn.datasets import make_moons

X, y = make_moons(n_samples=500, noise=0.30, random_state=42)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import VotingClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC

log_clf = LogisticRegression(random_state=42)
rnd_clf = RandomForestClassifier(random_state=42)
svm_clf = SVC(random_state=42)

voting_clf = VotingClassifier(
    estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
    voting='hard')
voting_clf.fit(X_train, y_train)
from sklearn.metrics import accuracy_score

for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
    clf.fit(X_train, y_train)
    y_pred = clf.predict(X_test)
    print(clf.__class__.__name__, accuracy_score(y_test, y_pred))
log_clf = LogisticRegression(random_state=42)
rnd_clf = RandomForestClassifier(random_state=42)
svm_clf = SVC(probability=True, random_state=42)

voting_clf = VotingClassifier(
    estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],
    voting='soft')
voting_clf.fit(X_train, y_train)
from sklearn.metrics import accuracy_score

for clf in (log_clf, rnd_clf, svm_clf, voting_clf):
    clf.fit(X_train, y_train)
    y_pred = clf.predict(X_test)
    print(clf.__class__.__name__, accuracy_score(y_test, y_pred))<jupyter_output>LogisticRegression 0.864
RandomForestClassifier 0.896
SVC 0.896
VotingClassifier 0.92<jupyter_text>Random forestsRandom forests provide an improvement over bagged trees by way of asmall tweak that decorrelates the trees. As in bagging, we build anumber of decision trees on bootstrapped training samples. But whenbuilding these decision trees, each time a split in a tree isconsidered, a random sample of $m$ predictors is chosen as splitcandidates from the full set of $p$ predictors. The split is allowed touse only one of those $m$ predictors. A fresh sample of $m$ predictors istaken at each split, and typically we choose $$m\approx \sqrt{p}.$$ In building a random forest, ateach split in the tree, the algorithm is not even allowed to considera majority of the available predictors. The reason for this is rather clever. Suppose that there is one verystrong predictor in the data set, along with a number of othermoderately strong predictors. Then in the collection of baggedvariable importance random forest trees, most or all of the trees willuse this strong predictor in the top split. Consequently, all of thebagged trees will look quite similar to each other. Hence thepredictions from the bagged trees will be highly correlated.Unfortunately, averaging many highly correlated quantities does notlead to as large of a reduction in variance as averaging manyuncorrelated quantities. In particular, this means that bagging willnot lead to a substantial reduction in variance over a single tree inthis setting. Random Forest AlgorithmThe algorithm described here can be applied to both classification and regression problems.We will grow of forest of say $B$ trees.1. For $b=1:B$  * Draw a bootstrap sample from the training data organized in our $\boldsymbol{X}$ matrix.  * We grow then a random forest tree $T_b$ based on the bootstrapped data by repeating the steps outlined till we reach the maximum node size is reached1. we select $m \le p$ variables at random from the $p$ predictors/features2. pick the best split point among the $m$ features using for example the CART algorithm and create a new node3. split the node into daughter nodes4. Output then the ensemble of trees $\{T_b\}_1^{B}$ and make predictions for either a regression type of problem or a classification type of problem.  Random Forests Compared with other Methods on the Cancer Data<jupyter_code>import matplotlib.pyplot as plt
import numpy as np
from sklearn.model_selection import  train_test_split 
from sklearn.datasets import load_breast_cancer
from sklearn.svm import SVC
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import BaggingClassifier

# Load the data
cancer = load_breast_cancer()

X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
print(X_train.shape)
print(X_test.shape)
# Logistic Regression
logreg = LogisticRegression(solver='lbfgs')
logreg.fit(X_train, y_train)
print("Test set accuracy with Logistic Regression: {:.2f}".format(logreg.score(X_test,y_test)))
# Support vector machine
svm = SVC(gamma='auto', C=100)
svm.fit(X_train, y_train)
print("Test set accuracy with SVM: {:.2f}".format(svm.score(X_test,y_test)))
# Decision Trees
deep_tree_clf = DecisionTreeClassifier(max_depth=None)
deep_tree_clf.fit(X_train, y_train)
print("Test set accuracy with Decision Trees: {:.2f}".format(deep_tree_clf.score(X_test,y_test)))
#now scale the data
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
scaler.fit(X_train)
X_train_scaled = scaler.transform(X_train)
X_test_scaled = scaler.transform(X_test)
# Logistic Regression
logreg.fit(X_train_scaled, y_train)
print("Test set accuracy Logistic Regression with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))
# Support Vector Machine
svm.fit(X_train_scaled, y_train)
print("Test set accuracy SVM with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))
# Decision Trees
deep_tree_clf.fit(X_train_scaled, y_train)
print("Test set accuracy with Decision Trees and scaled data: {:.2f}".format(deep_tree_clf.score(X_test_scaled,y_test)))


from sklearn.ensemble import RandomForestClassifier
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import cross_validate
# Data set not specificied
#Instantiate the model with 500 trees and entropy as splitting criteria
Random_Forest_model = RandomForestClassifier(n_estimators=500,criterion="entropy")
Random_Forest_model.fit(X_train_scaled, y_train)
#Cross validation
accuracy = cross_validate(Random_Forest_model,X_test_scaled,y_test,cv=10)['test_score']
print(accuracy)
print("Test set accuracy with Random Forests and scaled data: {:.2f}".format(Random_Forest_model.score(X_test_scaled,y_test)))


import scikitplot as skplt
y_pred = Random_Forest_model.predict(X_test_scaled)
skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)
plt.show()
y_probas = Random_Forest_model.predict_proba(X_test_scaled)
skplt.metrics.plot_roc(y_test, y_probas)
plt.show()
skplt.metrics.plot_cumulative_gain(y_test, y_probas)
plt.show()<jupyter_output>(426, 30)
(143, 30)
Test set accuracy with Logistic Regression: 0.95
Test set accuracy with SVM: 0.63
Test set accuracy with Decision Trees: 0.92
Test set accuracy Logistic Regression with scaled data: 0.96
Test set accuracy SVM with scaled data: 0.96
Test set accuracy with Decision Trees and scaled data: 0.90<jupyter_text>Recall that the cumulative gains curve shows the percentage of theoverall number of cases in a given category *gained* by targeting apercentage of the total number of cases.Similarly, the receiver operating characteristic curve, or ROC curve,displays the diagnostic ability of a binary classifier system as itsdiscrimination threshold is varied. It plots the true positive rate against the false positive rate. Compare  Bagging on Trees with Random Forests<jupyter_code>bag_clf = BaggingClassifier(
    DecisionTreeClassifier(splitter="random", max_leaf_nodes=16, random_state=42),
    n_estimators=500, max_samples=1.0, bootstrap=True, n_jobs=-1, random_state=42)
bag_clf.fit(X_train, y_train)
y_pred = bag_clf.predict(X_test)
from sklearn.ensemble import RandomForestClassifier
rnd_clf = RandomForestClassifier(n_estimators=500, max_leaf_nodes=16, n_jobs=-1, random_state=42)
rnd_clf.fit(X_train, y_train)
y_pred_rf = rnd_clf.predict(X_test)
np.sum(y_pred == y_pred_rf) / len(y_pred)<jupyter_output><empty_output><jupyter_text>Boosting, a Bird's Eye ViewThe basic idea is to combine weak classifiers in order to create a goodclassifier. With a weak classifier we often intend a classifier whichproduces results which are only slightly better than we would get byrandom guesses.This is done by applying in an iterative way a weak (or a standardclassifier like decision trees) to modify the data. In each iterationwe emphasize those observations which are misclassified by weightingthem with a factor. What is boosting? Additive Modelling/Iterative FittingBoosting is a way of fitting an additive expansion in a set ofelementary basis functions like for example some simple polynomials.Assume for example that we have a function $$f_M(x) = \sum_{i=1}^M \beta_m b(x;\gamma_m),$$ where $\beta_m$ are the expansion parameters to be determined in aminimization process and $b(x;\gamma_m)$ are some simple functions ofthe multivariable parameter $x$ which is characterized by theparameters $\gamma_m$.As an example, consider the Sigmoid function we used in logisticregression. In that case, we can translate the function$b(x;\gamma_m)$ into the Sigmoid function $$\sigma(t) = \frac{1}{1+\exp{(-t)}},$$ where $t=\gamma_0+\gamma_1 x$ and the parameters $\gamma_0$ and$\gamma_1$ were determined by the Logistic Regression fittingalgorithm.As another example, consider the cost function we defined for linear regression $$C(\boldsymbol{y},\boldsymbol{f}) = \frac{1}{n} \sum_{i=0}^{n-1}(y_i-f(x_i))^2.$$ In this case the function $f(x)$ was replaced by the design matrix$\boldsymbol{X}$ and the unknown linear regression parameters $\boldsymbol{\beta}$,that is $\boldsymbol{f}=\boldsymbol{X}\boldsymbol{\beta}$. In linear regression we can simply invert a matrix and obtain the parameters $\beta$ by $$\boldsymbol{\beta}=\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}.$$ In iterative fitting or additive modeling, we minimize the cost function with respect to the parameters $\beta_m$ and $\gamma_m$. Iterative Fitting, Regression and Squared-error Cost FunctionThe way we proceed is as follows (here we specialize to the squared-error cost function)1. Establish a cost function, here ${\cal C}(\boldsymbol{y},\boldsymbol{f}) = \frac{1}{n} \sum_{i=0}^{n-1}(y_i-f_M(x_i))^2$ with $f_M(x) = \sum_{i=1}^M \beta_m b(x;\gamma_m)$.2. Initialize with a guess $f_0(x)$. It could be one or even zero or some random numbers.3. For $m=1:M$a. minimize $\sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\beta b(x;\gamma))^2$ wrt $\gamma$ and $\beta$b. This gives the optimal values $\beta_m$ and $\gamma_m$c. Determine then the new values $f_m(x)=f_{m-1}(x) +\beta_m b(x;\gamma_m)$We could use any of the algorithms we have discussed till now. If weuse trees, $\gamma$ parameterizes the split variables and split pointsat the internal nodes, and the predictions at the terminal nodes. Squared-Error Example and Iterative FittingTo better understand what happens, let us develop the steps for the iterative fitting using the above squared error function.For simplicity we assume also that our functions $b(x;\gamma)=1+\gamma x$. This means that for every iteration $m$, we need to optimize $$(\beta_m,\gamma_m) = \mathrm{argmin}_{\beta,\lambda}\hspace{0.1cm} \sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\beta b(x;\gamma))^2=\sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\beta(1+\gamma x_i))^2.$$ We start our iteration by simply setting $f_0(x)=0$. Taking the derivatives  with respect to $\beta$ and $\gamma$ we obtain $$\frac{\partial {\cal C}}{\partial \beta} = -2\sum_{i}(1+\gamma x_i)(y_i-\beta(1+\gamma x_i))=0,$$ and $$\frac{\partial {\cal C}}{\partial \gamma} =-2\sum_{i}\beta x_i(y_i-\beta(1+\gamma x_i))=0.$$ We can then rewrite these equations as (defining $\boldsymbol{w}=\boldsymbol{e}+\gamma \boldsymbol{x})$ with $\boldsymbol{e}$ being the unit vector) $$\gamma \boldsymbol{w}^T(\boldsymbol{y}-\beta\gamma \boldsymbol{w})=0,$$ which gives us $\beta = \boldsymbol{w}^T\boldsymbol{y}/(\boldsymbol{w}^T\boldsymbol{w})$. Similarly we have $$\beta\gamma \boldsymbol{x}^T(\boldsymbol{y}-\beta(1+\gamma \boldsymbol{x}))=0,$$ which leads to $\gamma =(\boldsymbol{x}^T\boldsymbol{y}-\beta\boldsymbol{x}^T\boldsymbol{e})/(\beta\boldsymbol{x}^T\boldsymbol{x})$.  Insertingfor $\beta$ gives us an equation for $\gamma$. This is a non-linear equation in the unknown $\gamma$ and has to be solved numerically. The solution to these two equations gives us in turn $\beta_1$ and $\gamma_1$ leading to the new expression for $f_1(x)$ as$f_1(x) = \beta_1(1+\gamma_1x)$. Doing this $M$ times results in our final estimate for the function $f$.  Iterative Fitting, Classification and AdaBoostLet us consider a binary classification problem with two outcomes $y_i \in \{-1,1\}$ and $i=0,1,2,\dots,n-1$ as our set ofobservations. We define a classification function $G(x)$ which produces a prediction taking one or the other of the two values $\{-1,1\}$.The error rate of the training sample is then $$\mathrm{\overline{err}}=\frac{1}{n} \sum_{i=0}^{n-1} I(y_i\ne G(x_i)).$$ The iterative procedure starts with defining a weak classifier whoseerror rate is barely better than random guessing.  The iterativeprocedure in boosting is to sequentially apply a  weakclassification algorithm to repeatedly modified versions of the dataproducing a sequence of weak classifiers $G_m(x)$.Here we will express our  function $f(x)$ in terms of $G(x)$. That is $$f_M(x) = \sum_{i=1}^M \beta_m b(x;\gamma_m),$$ will be a function of $$G_M(x) = \mathrm{sign} \sum_{i=1}^M \alpha_m G_m(x).$$  Adaptive Boosting, AdaBoostIn our iterative procedure we define thus $$f_m(x) = f_{m-1}(x)+\beta_mG_m(x).$$ The simplest possible cost function which leads (also simple from a computational point of view) to the AdaBoost algorithm is theexponential cost/loss function defined as $$C(\boldsymbol{y},\boldsymbol{f}) = \sum_{i=0}^{n-1}\exp{(-y_i(f_{m-1}(x_i)+\beta G(x_i))}.$$ We optimize $\beta$ and $G$ for each value of $m=1:M$ as we did in the regression case.This is normally done in two steps. Let us however first rewrite the cost function as $$C(\boldsymbol{y},\boldsymbol{f}) = \sum_{i=0}^{n-1}w_i^{m}\exp{(-y_i\beta G(x_i))},$$ where we have defined $w_i^m= \exp{(-y_if_{m-1}(x_i))}$. Building up AdaBoostFirst, for any $\beta > 0$, we optimize $G$ by setting $$G_m(x) = \mathrm{sign} \sum_{i=0}^{n-1} w_i^m I(y_i \ne G_(x_i)),$$ which is the classifier that minimizes the weighted error rate in predicting $y$.We can do this by rewriting $$\exp{-(\beta)}\sum_{y_i=G(x_i)}w_i^m+\exp{(\beta)}\sum_{y_i\ne G(x_i)}w_i^m,$$ which can be rewritten as $$(\exp{(\beta)}-\exp{-(\beta)})\sum_{i=0}^{n-1}w_i^mI(y_i\ne G(x_i))+\exp{(-\beta)}\sum_{i=0}^{n-1}w_i^m=0,$$ which leads to $$\beta_m = \frac{1}{2}\log{\frac{1-\mathrm{\overline{err}}}{\mathrm{\overline{err}}}},$$ where we have redefined the error as $$\mathrm{\overline{err}}_m=\frac{1}{n}\frac{\sum_{i=0}^{n-1}w_i^mI(y_i\ne G(x_i)}{\sum_{i=0}^{n-1}w_i^m},$$ which leads to an update of $$f_m(x) = f_{m-1}(x) +\beta_m G_m(x).$$ This leads to the new weights $$w_i^{m+1} = w_i^m \exp{(-y_i\beta_m G_m(x_i))}$$  Adaptive boosting: AdaBoost, Basic AlgorithmThe algorithm here is rather straightforward. Assume that our weakclassifier is a decision tree and we consider a binary set of outputswith $y_i \in \{-1,1\}$ and $i=0,1,2,\dots,n-1$ as our set ofobservations. Our design matrix is given in terms of thefeature/predictor vectors$\boldsymbol{X}=[\boldsymbol{x}_0\boldsymbol{x}_1\dots\boldsymbol{x}_{p-1}]$. Finally, we define also aclassifier determined by our data via a function $G(x)$. This function tells us how well we are able to classify our outputs/targets $\boldsymbol{y}$. We have already defined the misclassification error $\mathrm{err}$ as $$\mathrm{err}=\frac{1}{n}\sum_{i=0}^{n-1}I(y_i\ne G(x_i)),$$ where the function $I()$ is one if we misclassify and zero if we classify correctly.  Basic Steps of AdaBoostWith the above definitions we are now ready to set up the algorithm for AdaBoost.The basic idea is to set up weights which will be used to scale the correctly classified and the misclassified cases.1. We start by initializing all weights to $w_i = 1/n$, with $i=0,1,2,\dots n-1$. It is easy to see that we must have $\sum_{i=0}^{n-1}w_i = 1$.2. We rewrite the misclassification error as $$\mathrm{\overline{err}}_m=\frac{\sum_{i=0}^{n-1}w_i^m I(y_i\ne G(x_i))}{\sum_{i=0}^{n-1}w_i},$$ 1. Then we start looping over all attempts at classifying, namely we start an iterative process for $m=1:M$, where $M$ is the final number of classifications. Our given classifier could for example be a plain decision tree.a. Fit then a given classifier to the training set using the weights $w_i$.b. Compute then $\mathrm{err}$ and figure out which events are classified properly and which are classified wrongly.c. Define a quantity $\alpha_{m} = \log{(1-\mathrm{\overline{err}}_m)/\mathrm{\overline{err}}_m}$d. Set the new weights to $w_i = w_i\times \exp{(\alpha_m I(y_i\ne G(x_i)}$.5. Compute the new classifier $G(x)= \sum_{i=0}^{n-1}\alpha_m I(y_i\ne G(x_i)$.For the iterations with $m \le 2$ the weights are modifiedindividually at each steps. The observations which were misclassifiedat iteration $m-1$ have a weight which is larger than those which wereclassified properly. As this proceeds, the observations which weredifficult to classifiy correctly are given a larger influence. Eachnew classification step $m$ is then forced to concentrate on thoseobservations that are missed in the previous iterations. AdaBoost ExamplesUsing **Scikit-Learn** it is easy to apply the adaptive boosting algorithm, as done here.<jupyter_code>from sklearn.ensemble import AdaBoostClassifier

ada_clf = AdaBoostClassifier(
    DecisionTreeClassifier(max_depth=1), n_estimators=200,
    algorithm="SAMME.R", learning_rate=0.5, random_state=42)
ada_clf.fit(X_train, y_train)

from sklearn.ensemble import AdaBoostClassifier

ada_clf = AdaBoostClassifier(
    DecisionTreeClassifier(max_depth=1), n_estimators=200,
    algorithm="SAMME.R", learning_rate=0.5, random_state=42)
ada_clf.fit(X_train_scaled, y_train)
y_pred = ada_clf.predict(X_test_scaled)
skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)
plt.show()
y_probas = ada_clf.predict_proba(X_test_scaled)
skplt.metrics.plot_roc(y_test, y_probas)
plt.show()
skplt.metrics.plot_cumulative_gain(y_test, y_probas)
plt.show()<jupyter_output><empty_output><jupyter_text>Gradient boosting: Basics with Steepest Descent/Functional Gradient DescentGradient boosting is again a similar technique to Adaptive boosting,it combines so-called weak classifiers or regressors into a strongmethod via a series of iterations.In order to understand the method, let us illustrate its basics bybringing back the essential steps in linear regression, where our costfunction was the least squares function. The Squared-Error again! Steepest DescentWe start again with our cost function ${\cal C}(\boldsymbol{y}m\boldsymbol{f})=\sum_{i=0}^{n-1}{\cal L}(y_i, f(x_i))$ where we want to minimizeThis means that for every iteration, we need to optimize $$(\hat{\boldsymbol{f}}) = \mathrm{argmin}_{\boldsymbol{f}}\hspace{0.1cm} \sum_{i=0}^{n-1}(y_i-f(x_i))^2.$$ We define a real function $h_m(x)$ that defines our final function $f_M(x)$ as $$f_M(x) = \sum_{m=0}^M h_m(x).$$ In the steepest decent approach we approximate $h_m(x) = -\rho_m g_m(x)$, where $\rho_m$ is a scalar and $g_m(x)$ the gradient defined as $$g_m(x_i) = \left[ \frac{\partial {\cal L}(y_i, f(x_i))}{\partial f(x_i)}\right]_{f(x_i)=f_{m-1}(x_i)}.$$ With the new gradient we can update $f_m(x) = f_{m-1}(x) -\rho_m g_m(x)$. Using the above squared-error function we see thatthe gradient is $g_m(x_i) = -2(y_i-f(x_i))$.Choosing $f_0(x)=0$ we obtain $g_m(x) = -2y_i$ and inserting this into the minimization problem for the cost function we have $$(\rho_1) = \mathrm{argmin}_{\rho}\hspace{0.1cm} \sum_{i=0}^{n-1}(y_i+2\rho y_i)^2.$$  Steepest Descent ExampleOptimizing with respect to $\rho$ we obtain (taking the derivative) that $\rho_1 = -1/2$. We have then that $$f_1(x) = f_{0}(x) -\rho_1 g_1(x)=-y_i.$$ We can then proceed and compute $$g_2(x_i) = \left[ \frac{\partial {\cal L}(y_i, f(x_i))}{\partial f(x_i)}\right]_{f(x_i)=f_{1}(x_i)=y_i}=-4y_i,$$ and find a new value for $\rho_2=-1/2$ and continue till we have reached $m=M$. We can modify the steepest descent method, or steepest boosting, by introducing what is called **gradient boosting**.  Gradient Boosting, algorithmSteepest descent is however not much used, since it only optimizes $f$ at a fixed set of $n$ points,so we do not learn a function that can generalize. However, we can modify the algorithm byfitting a weak learner to approximate the negative gradient signal. Suppose we have a cost function $C(f)=\sum_{i=0}^{n-1}L(y_i, f(x_i))$ where $y_i$ is our target and $f(x_i)$ the function which is meant to model $y_i$. The above cost function could be our standard  squared-error  function $$C(\boldsymbol{y},\boldsymbol{f})=\sum_{i=0}^{n-1}(y_i-f(x_i))^2.$$ The way we proceed in an iterative fashion is to1. Initialize our estimate $f_0(x)$.2. For $m=1:M$, wea. compute the negative gradient vector $\boldsymbol{u}_m = -\partial C(\boldsymbol{y},\boldsymbol{f})/\partial \boldsymbol{f}(x)$ at $f(x) = f_{m-1}(x)$;b. fit the so-called base-learner to the negative gradient $h_m(u_m,x)$;c. update the estimate $f_m(x) = f_{m-1}(x)+h_m(u_m,x)$;4. The final estimate is then $f_M(x) = \sum_{m=1}^M h_m(u_m,x)$. Gradient Boosting, Examples of Regression<jupyter_code>import matplotlib.pyplot as plt
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.preprocessing import StandardScaler
import scikitplot as skplt
from sklearn.metrics import mean_squared_error

n = 100
maxdegree = 6

# Make data set.
x = np.linspace(-3, 3, n).reshape(-1, 1)
y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)

error = np.zeros(maxdegree)
bias = np.zeros(maxdegree)
variance = np.zeros(maxdegree)
polydegree = np.zeros(maxdegree)
X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
scaler = StandardScaler()
scaler.fit(X_train)
X_train_scaled = scaler.transform(X_train)
X_test_scaled = scaler.transform(X_test)

for degree in range(1,maxdegree):
    model = GradientBoostingRegressor(max_depth=degree, n_estimators=100, learning_rate=1.0)  
    model.fit(X_train_scaled,y_train)
    y_pred = model.predict(X_test_scaled)
    polydegree[degree] = degree
    error[degree] = np.mean( np.mean((y_test - y_pred)**2) )
    bias[degree] = np.mean( (y_test - np.mean(y_pred))**2 )
    variance[degree] = np.mean( np.var(y_pred) )
    print('Max depth:', degree)
    print('Error:', error[degree])
    print('Bias^2:', bias[degree])
    print('Var:', variance[degree])
    print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))

plt.xlim(1,maxdegree-1)
plt.plot(polydegree, error, label='Error')
plt.plot(polydegree, bias, label='bias')
plt.plot(polydegree, variance, label='Variance')
plt.legend()
save_fig("gdregression")
plt.show()<jupyter_output>/Users/MortenImac/anaconda3/lib/python3.6/site-packages/sklearn/utils/validation.py:73: DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples, ), for example using ravel().
  return f(**kwargs)
/Users/MortenImac/anaconda3/lib/python3.6/site-packages/sklearn/utils/validation.py:73: DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples, ), for example using ravel().
  return f(**kwargs)
/Users/MortenImac/anaconda3/lib/python3.6/site-packages/sklearn/utils/validation.py:73: DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples, ), for example using ravel().
  return f(**kwargs)
/Users/MortenImac/anaconda3/lib/python3.6/site-packages/sklearn/utils/validation.py:73: DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_[...]<jupyter_text>Gradient Boosting, Classification Example<jupyter_code>import matplotlib.pyplot as plt
import numpy as np
from sklearn.model_selection import  train_test_split 
from sklearn.datasets import load_breast_cancer
import scikitplot as skplt
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.model_selection import cross_validate

# Load the data
cancer = load_breast_cancer()

X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
print(X_train.shape)
print(X_test.shape)
#now scale the data
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
scaler.fit(X_train)
X_train_scaled = scaler.transform(X_train)
X_test_scaled = scaler.transform(X_test)

gd_clf = GradientBoostingClassifier(max_depth=3, n_estimators=100, learning_rate=1.0)  
gd_clf.fit(X_train_scaled, y_train)
#Cross validation
accuracy = cross_validate(gd_clf,X_test_scaled,y_test,cv=10)['test_score']
print(accuracy)
print("Test set accuracy with Random Forests and scaled data: {:.2f}".format(gd_clf.score(X_test_scaled,y_test)))

import scikitplot as skplt
y_pred = gd_clf.predict(X_test_scaled)
skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)
save_fig("gdclassiffierconfusion")
plt.show()
y_probas = gd_clf.predict_proba(X_test_scaled)
skplt.metrics.plot_roc(y_test, y_probas)
save_fig("gdclassiffierroc")
plt.show()
skplt.metrics.plot_cumulative_gain(y_test, y_probas)
save_fig("gdclassiffiercgain")
plt.show()<jupyter_output>(426, 30)
(143, 30)
[1.         0.86666667 0.93333333 0.92857143 1.         0.92857143
 1.         0.92857143 0.85714286 0.92857143]
Test set accuracy with Random Forests and scaled data: 0.97<jupyter_text>XGBoost: Extreme Gradient Boosting[XGBoost](https://github.com/dmlc/xgboost) or Extreme GradientBoosting, is an optimized distributed gradient boosting librarydesigned to be highly efficient, flexible and portable. It implementsmachine learning algorithms under the Gradient Boostingframework. XGBoost provides a parallel tree boosting that solve manydata science problems in a fast and accurate way. See the [article by <NAME>](https://arxiv.org/abs/1603.02754).The authors design and build a highly scalable end-to-end treeboosting system. It has  a theoretically justified weighted quantilesketch for efficient proposal calculation. It introduces a novel sparsity-aware algorithm for parallel tree learning and an effective cache-aware block structure for out-of-core tree learning.It is now the algorithm which wins essentially all ML competitions!!! Regression Case<jupyter_code>import matplotlib.pyplot as plt
import numpy as np
from sklearn.model_selection import train_test_split
import xgboost as xgb
from sklearn.preprocessing import StandardScaler
import scikitplot as skplt
from sklearn.metrics import mean_squared_error

n = 100
maxdegree = 6

# Make data set.
x = np.linspace(-3, 3, n).reshape(-1, 1)
y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)

error = np.zeros(maxdegree)
bias = np.zeros(maxdegree)
variance = np.zeros(maxdegree)
polydegree = np.zeros(maxdegree)
X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
scaler = StandardScaler()
scaler.fit(X_train)
X_train_scaled = scaler.transform(X_train)
X_test_scaled = scaler.transform(X_test)

for degree in range(maxdegree):
    model =  xgb.XGBRegressor(objective ='reg:squarederror', colsaobjective ='reg:squarederror', colsample_bytree = 0.3, learning_rate = 0.1,max_depth = degree, alpha = 10, n_estimators = 200)

    model.fit(X_train_scaled,y_train)
    y_pred = model.predict(X_test_scaled)
    polydegree[degree] = degree
    error[degree] = np.mean( np.mean((y_test - y_pred)**2) )
    bias[degree] = np.mean( (y_test - np.mean(y_pred))**2 )
    variance[degree] = np.mean( np.var(y_pred) )
    print('Max depth:', degree)
    print('Error:', error[degree])
    print('Bias^2:', bias[degree])
    print('Var:', variance[degree])
    print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))

plt.xlim(1,maxdegree-1)
plt.plot(polydegree, error, label='Error')
plt.plot(polydegree, bias, label='bias')
plt.plot(polydegree, variance, label='Variance')
plt.legend()
plt.show()<jupyter_output>[11:38:14] WARNING: /Users/travis/build/dmlc/xgboost/src/learner.cc:480: 
Parameters: { colsaobjective } might not be used.

  This may not be accurate due to some parameters are only used in language bindings but
  passed down to XGBoost core.  Or some parameters are not used but slip through this
  verification. Please open an issue if you find above cases.


Max depth: 0
Error: 0.20883861595352154
Bias^2: 0.2088386097729888
Var: 3.552713678800501e-15
0.20883861595352154 >= 0.2088386097729888 + 3.552713678800501e-15 = 0.20883860977299235
[11:38:14] WARNING: /Users/travis/build/dmlc/xgboost/src/learner.cc:480: 
Parameters: { colsaobjective } might not be used.

  This may not be accurate due to some parameters are only used in language bindings but
  passed down to XGBoost core.  Or some parameters are not used but slip through this
  verification. Please open an issue if you find above cases.


Max depth: 1
Error: 0.2554272992317659
Bias^2: 0.21734101860306584
Var: 0.0380862876772880[...]<jupyter_text>Xgboost on the Cancer DataAs you will see from the confusion matrix below, XGBoots does an excellent job on the Wisconsin cancer data and outperforms essentially all agorithms we have discussed till now.<jupyter_code>import matplotlib.pyplot as plt
import numpy as np
from sklearn.model_selection import  train_test_split 
from sklearn.datasets import load_breast_cancer
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import cross_validate
import scikitplot as skplt
import xgboost as xgb
# Load the data
cancer = load_breast_cancer()

X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
print(X_train.shape)
print(X_test.shape)
#now scale the data
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
scaler.fit(X_train)
X_train_scaled = scaler.transform(X_train)
X_test_scaled = scaler.transform(X_test)

xg_clf = xgb.XGBClassifier()
xg_clf.fit(X_train_scaled,y_train)

y_test = xg_clf.predict(X_test_scaled)

print("Test set accuracy with Random Forests and scaled data: {:.2f}".format(xg_clf.score(X_test_scaled,y_test)))

import scikitplot as skplt
y_pred = xg_clf.predict(X_test_scaled)
skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)
save_fig("xdclassiffierconfusion")
plt.show()
y_probas = xg_clf.predict_proba(X_test_scaled)
skplt.metrics.plot_roc(y_test, y_probas)
save_fig("xdclassiffierroc")
plt.show()
skplt.metrics.plot_cumulative_gain(y_test, y_probas)
save_fig("gdclassiffiercgain")
plt.show()


xgb.plot_tree(xg_clf,num_trees=0)
plt.rcParams['figure.figsize'] = [50, 10]
save_fig("xgtree")
plt.show()

xgb.plot_importance(xg_clf)
plt.rcParams['figure.figsize'] = [5, 5]
save_fig("xgparams")
plt.show()<jupyter_output>(426, 30)
(143, 30)
Test set accuracy with Random Forests and scaled data: 1.00
{'fraction_non_alphanumeric': 0.1114083153712312, 'fraction_numerical': 0.023735944114057186, 'mean_word_length': 5.7712326358361175, 'pattern_counts': {'":': 0, '<': 42, '<?xml version=': 0, '>': 45, 'https://': 7, 'lorem ipsum': 0, 'www.': 4, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 1, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '11', 'dir': 'jupyter-structured-clean-dedup', 'id': '414410', 'license': 'CC0-1.0', 'n_tokens_mistral': 13485, 'n_tokens_neox': 12613, 'n_words': 3985, 'path': 'doc/pub/week45/ipynb/week45.ipynb', 'repo_name': 'anacost/MachineLearning', 'size': '38546'}