Files
FYS-STK4155/doc/pub/week45/ipynb/week45.ipynb
T
2020-09-16 18:51:56 +02:00

1213 lines
41 KiB
Plaintext

{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<!-- dom:TITLE: Week 45: Random Forests and Boosting -->\n",
"# Week 45: Random Forests and Boosting\n",
"<!-- dom:AUTHOR: Morten Hjorth-Jensen at Department of Physics, University of Oslo & Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University -->\n",
"<!-- Author: --> \n",
"**Morten Hjorth-Jensen**, Department of Physics, University of Oslo and Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University\n",
"\n",
"Date: **Sep 16, 2020**\n",
"\n",
"Copyright 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"## Random forests\n",
"\n",
"Random forests provide an improvement over bagged trees by way of a\n",
"small tweak that decorrelates the trees. \n",
"\n",
"As in bagging, we build a\n",
"number of decision trees on bootstrapped training samples. But when\n",
"building these decision trees, each time a split in a tree is\n",
"considered, a random sample of $m$ predictors is chosen as split\n",
"candidates from the full set of $p$ predictors. The split is allowed to\n",
"use only one of those $m$ predictors. \n",
"\n",
"A fresh sample of $m$ predictors is\n",
"taken at each split, and typically we choose"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"m\\approx \\sqrt{p}.\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In building a random forest, at\n",
"each split in the tree, the algorithm is not even allowed to consider\n",
"a majority of the available predictors. \n",
"\n",
"The reason for this is rather clever. Suppose that there is one very\n",
"strong predictor in the data set, along with a number of other\n",
"moderately strong predictors. Then in the collection of bagged\n",
"variable importance random forest trees, most or all of the trees will\n",
"use this strong predictor in the top split. Consequently, all of the\n",
"bagged trees will look quite similar to each other. Hence the\n",
"predictions from the bagged trees will be highly correlated.\n",
"Unfortunately, averaging many highly correlated quantities does not\n",
"lead to as large of a reduction in variance as averaging many\n",
"uncorrelated quantities. In particular, this means that bagging will\n",
"not lead to a substantial reduction in variance over a single tree in\n",
"this setting.\n",
"\n",
"\n",
"## Random Forest Algorithm\n",
"The algorithm described here can be applied to both classification and regression problems.\n",
"\n",
"We will grow of forest of say $B$ trees.\n",
"1. For $b=1:B$\n",
"\n",
" * Draw a bootstrap sample of from the training data organized in our $\\boldsymbol{X}$ matrix.\n",
"\n",
" * 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 reached\n",
"\n",
"1. we select $m \\le p$ variables at random from the $p$ predictors/features\n",
"\n",
"2. pick the best split point among the $m$ features using either the CART algorithm or the ID3 for classification and create a new node\n",
"\n",
"3. split the node into daughter nodes\n",
"\n",
"\n",
"\n",
"4. 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. \n",
"\n",
"## Random Forests Compared with other Methods on the Cancer Data"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline\n",
"\n",
"import matplotlib.pyplot as plt\n",
"import numpy as np\n",
"from sklearn.model_selection import train_test_split \n",
"from sklearn.datasets import load_breast_cancer\n",
"from sklearn.svm import SVC\n",
"from sklearn.linear_model import LogisticRegression\n",
"from sklearn.tree import DecisionTreeClassifier\n",
"\n",
"# Load the data\n",
"cancer = load_breast_cancer()\n",
"\n",
"X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)\n",
"print(X_train.shape)\n",
"print(X_test.shape)\n",
"# Logistic Regression\n",
"logreg = LogisticRegression(solver='lbfgs')\n",
"logreg.fit(X_train, y_train)\n",
"print(\"Test set accuracy with Logistic Regression: {:.2f}\".format(logreg.score(X_test,y_test)))\n",
"# Support vector machine\n",
"svm = SVC(gamma='auto', C=100)\n",
"svm.fit(X_train, y_train)\n",
"print(\"Test set accuracy with SVM: {:.2f}\".format(svm.score(X_test,y_test)))\n",
"# Decision Trees\n",
"deep_tree_clf = DecisionTreeClassifier(max_depth=None)\n",
"deep_tree_clf.fit(X_train, y_train)\n",
"print(\"Test set accuracy with Decision Trees: {:.2f}\".format(deep_tree_clf.score(X_test,y_test)))\n",
"#now scale the data\n",
"from sklearn.preprocessing import StandardScaler\n",
"scaler = StandardScaler()\n",
"scaler.fit(X_train)\n",
"X_train_scaled = scaler.transform(X_train)\n",
"X_test_scaled = scaler.transform(X_test)\n",
"# Logistic Regression\n",
"logreg.fit(X_train_scaled, y_train)\n",
"print(\"Test set accuracy Logistic Regression with scaled data: {:.2f}\".format(logreg.score(X_test_scaled,y_test)))\n",
"# Support Vector Machine\n",
"svm.fit(X_train_scaled, y_train)\n",
"print(\"Test set accuracy SVM with scaled data: {:.2f}\".format(logreg.score(X_test_scaled,y_test)))\n",
"# Decision Trees\n",
"deep_tree_clf.fit(X_train_scaled, y_train)\n",
"print(\"Test set accuracy with Decision Trees and scaled data: {:.2f}\".format(deep_tree_clf.score(X_test_scaled,y_test)))\n",
"\n",
"\n",
"from sklearn.ensemble import RandomForestClassifier\n",
"from sklearn.preprocessing import LabelEncoder\n",
"from sklearn.model_selection import cross_validate\n",
"# Data set not specificied\n",
"#Instantiate the model with 500 trees and entropy as splitting criteria\n",
"Random_Forest_model = RandomForestClassifier(n_estimators=500,criterion=\"entropy\")\n",
"Random_Forest_model.fit(X_train_scaled, y_train)\n",
"#Cross validation\n",
"accuracy = cross_validate(Random_Forest_model,X_test_scaled,y_test,cv=10)['test_score']\n",
"print(accuracy)\n",
"print(\"Test set accuracy with Random Forests and scaled data: {:.2f}\".format(Random_Forest_model.score(X_test_scaled,y_test)))\n",
"\n",
"\n",
"import scikitplot as skplt\n",
"y_pred = Random_Forest_model.predict(X_test_scaled)\n",
"skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)\n",
"plt.show()\n",
"y_probas = Random_Forest_model.predict_proba(X_test_scaled)\n",
"skplt.metrics.plot_roc(y_test, y_probas)\n",
"plt.show()\n",
"skplt.metrics.plot_cumulative_gain(y_test, y_probas)\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Compare Bagging on Trees with Random Forests"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"bag_clf = BaggingClassifier(\n",
" DecisionTreeClassifier(splitter=\"random\", max_leaf_nodes=16, random_state=42),\n",
" n_estimators=500, max_samples=1.0, bootstrap=True, n_jobs=-1, random_state=42)"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"bag_clf.fit(X_train, y_train)\n",
"y_pred = bag_clf.predict(X_test)\n",
"from sklearn.ensemble import RandomForestClassifier\n",
"rnd_clf = RandomForestClassifier(n_estimators=500, max_leaf_nodes=16, n_jobs=-1, random_state=42)\n",
"rnd_clf.fit(X_train, y_train)\n",
"y_pred_rf = rnd_clf.predict(X_test)\n",
"np.sum(y_pred == y_pred_rf) / len(y_pred)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Boosting, a Bird's Eye View\n",
"\n",
"The basic idea is to combine weak classifiers in order to create a good\n",
"classifier. With a weak classifier we often intend a classifier which\n",
"produces results which are only slightly better than we would get by\n",
"random guesses.\n",
"\n",
"This is done by applying in an iterative way a weak (or a standard\n",
"classifier like decision trees) to modify the data. In each iteration\n",
"we emphasize those observations which are misclassified by weighting\n",
"them with a factor.\n",
"\n",
"\n",
"## What is boosting? Additive Modelling/Iterative Fitting\n",
"\n",
"Boosting is a way of fitting an additive expansion in a set of\n",
"elementary basis functions like for example some simple polynomials.\n",
"Assume for example that we have a function"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"f_M(x) = \\sum_{i=1}^M \\beta_m b(x;\\gamma_m),\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"where $\\beta_m$ are the expansion parameters to be determined in a\n",
"minimization process and $b(x;\\gamma_m)$ are some simple functions of\n",
"the multivariable parameter $x$ which is characterized by the\n",
"parameters $\\gamma_m$.\n",
"\n",
"As an example, consider the Sigmoid function we used in logistic\n",
"regression. In that case, we can translate the function\n",
"$b(x;\\gamma_m)$ into the Sigmoid function"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\sigma(t) = \\frac{1}{1+\\exp{(-t)}},\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"where $t=\\gamma_0+\\gamma_1 x$ and the parameters $\\gamma_0$ and\n",
"$\\gamma_1$ were determined by the Logistic Regression fitting\n",
"algorithm.\n",
"\n",
"As another example, consider the cost function we defined for linear regression"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"C(\\boldsymbol{y},\\boldsymbol{f}) = \\frac{1}{n} \\sum_{i=0}^{n-1}(y_i-f(x_i))^2.\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In this case the function $f(x)$ was replaced by the design matrix\n",
"$\\boldsymbol{X}$ and the unknown linear regression parameters $\\boldsymbol{\\beta}$,\n",
"that is $\\boldsymbol{f}=\\boldsymbol{X}\\boldsymbol{\\beta}$. In linear regression we can \n",
"simply invert a matrix and obtain the parameters $\\beta$ by"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\boldsymbol{\\beta}=\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}.\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In iterative fitting or additive modeling, we minimize the cost function with respect to the parameters $\\beta_m$ and $\\gamma_m$.\n",
"\n",
"\n",
"## Iterative Fitting, Regression and Squared-error Cost Function\n",
"\n",
"The way we proceed is as follows (here we specialize to the squared-error cost function)\n",
"\n",
"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)$.\n",
"\n",
"2. Initialize with a guess $f_0(x)$. It could be one or even zero or some random numbers.\n",
"\n",
"3. For $m=1:M$\n",
"\n",
"a. minimize $\\sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\\beta b(x;\\gamma))^2$ wrt $\\gamma$ and $\\beta$\n",
"\n",
"b. This gives the optimal values $\\beta_m$ and $\\gamma_m$\n",
"\n",
"c. Determine then the new values $f_m(x)=f_{m-1}(x) +\\beta_m b(x;\\gamma_m)$\n",
"\n",
"\n",
"We could use any of the algorithms we have discussed till now. If we\n",
"use trees, $\\gamma$ parameterizes the split variables and split points\n",
"at the internal nodes, and the predictions at the terminal nodes.\n",
"\n",
"\n",
"## Squared-Error Example and Iterative Fitting\n",
"\n",
"To better understand what happens, let us develop the steps for the iterative fitting using the above squared error function.\n",
"\n",
"For simplicity we assume also that our functions $b(x;\\gamma)=1+\\gamma x$. \n",
"\n",
"This means that for every iteration $m$, we need to optimize"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"(\\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.\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We start our iteration by simply setting $f_0(x)=0$. \n",
"Taking the derivatives with respect to $\\beta$ and $\\gamma$ we obtain"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\frac{\\partial {\\cal C}}{\\partial \\beta} = -2\\sum_{i}(1+\\gamma x_i)(y_i-\\beta(1+\\gamma x_i))=0,\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"and"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\frac{\\partial {\\cal C}}{\\partial \\gamma} =-2\\sum_{i}\\beta x_i(y_i-\\beta(1+\\gamma x_i))=0.\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can then rewrite these equations as (defining $\\boldsymbol{w}=\\boldsymbol{e}+\\gamma \\boldsymbol{x})$ with $\\boldsymbol{e}$ being the unit vector)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\gamma \\boldsymbol{w}^T(\\boldsymbol{y}-\\beta\\gamma \\boldsymbol{w})=0,\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"which gives us $\\beta = \\boldsymbol{w}^T\\boldsymbol{y}/(\\boldsymbol{w}^T\\boldsymbol{w})$. Similarly we have"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\beta\\gamma \\boldsymbol{x}^T(\\boldsymbol{y}-\\beta(1+\\gamma \\boldsymbol{x}))=0,\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"which leads to $\\gamma =(\\boldsymbol{x}^T\\boldsymbol{y}-\\beta\\boldsymbol{x}^T\\boldsymbol{e})/(\\beta\\boldsymbol{x}^T\\boldsymbol{x})$. Inserting\n",
"for $\\beta$ gives us an equation for $\\gamma$. This is a non-linear equation in the unknown $\\gamma$ and has to be solved numerically. \n",
"\n",
"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\n",
"$f_1(x) = \\beta_1(1+\\gamma_1x)$. Doing this $M$ times results in our final estimate for the function $f$. \n",
"\n",
"\n",
"\n",
"## Iterative Fitting, Classification and AdaBoost\n",
"\n",
"Let 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 of\n",
"observations. We define a classification function $G(x)$ which produces a prediction taking one or the other of the two values \n",
"$\\{-1,1\\}$.\n",
"\n",
"The error rate of the training sample is then"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\mathrm{\\overline{err}}=\\frac{1}{n} \\sum_{i=0}^{n-1} I(y_i\\ne G(x_i)).\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The iterative procedure starts with defining a weak classifier whose\n",
"error rate is barely better than random guessing. The iterative\n",
"procedure in boosting is to sequentially apply a weak\n",
"classification algorithm to repeatedly modified versions of the data\n",
"producing a sequence of weak classifiers $G_m(x)$.\n",
"\n",
"Here we will express our function $f(x)$ in terms of $G(x)$. That is"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"f_M(x) = \\sum_{i=1}^M \\beta_m b(x;\\gamma_m),\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"will be a function of"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"G_M(x) = \\mathrm{sign} \\sum_{i=1}^M \\alpha_m G_m(x).\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Adaptive Boosting, AdaBoost\n",
"\n",
"In our iterative procedure we define thus"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"f_m(x) = f_{m-1}(x)+\\beta_mG_m(x).\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The simplest possible cost function which leads (also simple from a computational point of view) to the AdaBoost algorithm is the\n",
"exponential cost/loss function defined as"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"C(\\boldsymbol{y},\\boldsymbol{f}) = \\sum_{i=0}^{n-1}\\exp{(-y_i(f_{m-1}(x_i)+\\beta G(x_i))}.\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We optimize $\\beta$ and $G$ for each value of $m=1:M$ as we did in the regression case.\n",
"This is normally done in two steps. Let us however first rewrite the cost function as"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"C(\\boldsymbol{y},\\boldsymbol{f}) = \\sum_{i=0}^{n-1}w_i^{m}\\exp{(-y_i\\beta G(x_i))},\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"where we have defined $w_i^m= \\exp{(-y_if_{m-1}(x_i))}$.\n",
"\n",
"## Building up AdaBoost\n",
"\n",
"First, for any $\\beta > 0$, we optimize $G$ by setting"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"G_m(x) = \\mathrm{sign} \\sum_{i=0}^{n-1} w_i^m I(y_i \\ne G_(x_i)),\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"which is the classifier that minimizes the weighted error rate in predicting $y$.\n",
"\n",
"We can do this by rewriting"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\exp{-(\\beta)}\\sum_{y_i=G(x_i)}w_i^m+\\exp{(\\beta)}\\sum_{y_i\\ne G(x_i)}w_i^m,\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"which can be rewritten as"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"(\\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,\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"which leads to"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\beta_m = \\frac{1}{2}\\log{\\frac{1-\\mathrm{\\overline{err}}}{\\mathrm{\\overline{err}}}},\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"where we have redefined the error as"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\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},\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"which leads to an update of"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"f_m(x) = f_{m-1}(x) +\\beta_m G_m(x).\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This leads to the new weights"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"w_i^{m+1} = w_i^m \\exp{(-y_i\\beta_m G_m(x_i))}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Adaptive boosting: AdaBoost, Basic Algorithm\n",
"\n",
"The algorithm here is rather straightforward. Assume that our weak\n",
"classifier is a decision tree and we consider a binary set of outputs\n",
"with $y_i \\in \\{-1,1\\}$ and $i=0,1,2,\\dots,n-1$ as our set of\n",
"observations. Our design matrix is given in terms of the\n",
"feature/predictor vectors\n",
"$\\boldsymbol{X}=[\\boldsymbol{x}_0\\boldsymbol{x}_1\\dots\\boldsymbol{x}_{p-1}]$. Finally, we define also a\n",
"classifier 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}$. \n",
"\n",
"We have already defined the misclassification error $\\mathrm{err}$ as"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\mathrm{err}=\\frac{1}{n}\\sum_{i=0}^{n-1}I(y_i\\ne G(x_i)),\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"where the function $I()$ is one if we misclassify and zero if we classify correctly. \n",
"\n",
"## Basic Steps of AdaBoost\n",
"\n",
"With the above definitions we are now ready to set up the algorithm for AdaBoost.\n",
"The basic idea is to set up weights which will be used to scale the correctly classified and the misclassified cases.\n",
"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$.\n",
"\n",
"2. We rewrite the misclassification error as"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"\\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},\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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.\n",
"\n",
"a. Fit then a given classifier to the training set using the weights $w_i$.\n",
"\n",
"b. Compute then $\\mathrm{err}$ and figure out which events are classified properly and which are classified wrongly.\n",
"\n",
"c. Define a quantity $\\alpha_{m} = \\log{(1-\\mathrm{\\overline{err}}_m)/\\mathrm{\\overline{err}}_m}$\n",
"\n",
"d. Set the new weights to $w_i = w_i\\times \\exp{(\\alpha_m I(y_i\\ne G(x_i)}$.\n",
"\n",
"\n",
"5. Compute the new classifier $G(x)= \\sum_{i=0}^{n-1}\\alpha_m I(y_i\\ne G(x_i)$.\n",
"\n",
"For the iterations with $m \\le 2$ the weights are modified\n",
"individually at each steps. The observations which were misclassified\n",
"at iteration $m-1$ have a weight which is larger than those which were\n",
"classified properly. As this proceeds, the observations which were\n",
"difficult to classifiy correctly are given a larger influence. Each\n",
"new classification step $m$ is then forced to concentrate on those\n",
"observations that are missed in the previous iterations.\n",
"\n",
"\n",
"\n",
"## AdaBoost Examples\n",
"\n",
"Using **Scikit-Learn** it is easy to apply the adaptive boosting algorithm, as done here."
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"from sklearn.ensemble import AdaBoostClassifier\n",
"\n",
"ada_clf = AdaBoostClassifier(\n",
" DecisionTreeClassifier(max_depth=1), n_estimators=200,\n",
" algorithm=\"SAMME.R\", learning_rate=0.5, random_state=42)\n",
"ada_clf.fit(X_train, y_train)\n",
"\n",
"from sklearn.ensemble import AdaBoostClassifier\n",
"\n",
"ada_clf = AdaBoostClassifier(\n",
" DecisionTreeClassifier(max_depth=1), n_estimators=200,\n",
" algorithm=\"SAMME.R\", learning_rate=0.5, random_state=42)\n",
"ada_clf.fit(X_train_scaled, y_train)\n",
"y_pred = ada_clf.predict(X_test_scaled)\n",
"skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)\n",
"plt.show()\n",
"y_probas = ada_clf.predict_proba(X_test_scaled)\n",
"skplt.metrics.plot_roc(y_test, y_probas)\n",
"plt.show()\n",
"skplt.metrics.plot_cumulative_gain(y_test, y_probas)\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## AdaBoost for Regression\n",
"\n",
"Here we present [Drucker's AdaBoost](https://pdfs.semanticscholar.org/8d49/e2dedb817f2c3330e74b63c5fc86d2399ce3.pdf) tailored for regression.\n",
"\n",
"In bagging, each training example is equally likely to be\n",
"picked. In boosting, the probability of a particular\n",
"example being in the training set of a particular machine\n",
"depends on the performance of the prior machines on\n",
"that example. The following is a modification of\n",
"Adaboost by Drucker.\n",
"\n",
"Start by selecting a set of training data $n$ and assign to each entry a weight $w_i=1$ for $i=1,2,\\dots,n$. As we have done earlier, we could pick say $80\\%$ of the data set for training. The algorithm runs as follows:\n",
"1. We define the probability that the training sample $i$ is in the set by $p_i = w_i/\\sum_iw_i$. We pick $n$ samples (with replacement) to form our training set. We pick a number uniformly in the range $[0,\\sum_iw_i]$.\n",
"\n",
"2. We choose then a regression machine (for example plain linear regression or a simple decision tree). A given regression machine makes then a hypothesis.\n",
"\n",
"3. Using every member of the training set with the chosen regression machine we obtain then a prediction $\\tilde{y}_i$.\n",
"\n",
"4. We calculate then the loss function $L_i$ for each training sample. We can use various types of loss function as long as we have a value\n",
"\n",
"$L_i\\in [0,1]$. \n",
"\n",
"## Gradient boosting: Basics with Steepest Descent\n",
"\n",
"Gradient boosting is again a similar technique to Adaptive boosting,\n",
"it combines so-called weak classifiers or regressors into a strong\n",
"method via a series of iterations.\n",
"\n",
"In order to understand the method, let us illustrate its basics by\n",
"bringing back the essential steps in linear regression, where our cost\n",
"function was the least squares function.\n",
"\n",
"## The Squared-Error again! Steepest Descent\n",
"\n",
"We 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 minimize\n",
"This means that for every iteration, we need to optimize"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"(\\hat{\\boldsymbol{f}}) = \\mathrm{argmin}_{\\boldsymbol{f}}\\hspace{0.1cm} \\sum_{i=0}^{n-1}(y_i-f(x_i))^2.\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We define a real function $h_m(x)$ that defines our final function $f_M(x)$ as"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"f_M(x) = \\sum_{m=0}^M h_m(x).\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"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)}.\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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 that\n",
"the gradient is $g_m(x_i) = -2(y_i-f(x_i))$.\n",
"\n",
"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"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"(\\rho_1) = \\mathrm{argmin}_{\\rho}\\hspace{0.1cm} \\sum_{i=0}^{n-1}(y_i+2\\rho y_i)^2.\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Steepest Descent Example\n",
"\n",
"Optimizing with respect to $\\rho$ we obtain (taking the derivative) that $\\rho_1 = -1/2$. We have then that"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"f_1(x) = f_{0}(x) -\\rho_1 g_1(x)=-y_i.\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can then proceed and compute"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"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,\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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**. \n",
"\n",
"## Gradient Boosting, algorithm\n",
"\n",
"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"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$\n",
"C(\\boldsymbol{y},\\boldsymbol{f})=\\sum_{i=0}^{n-1}(y_i-f(x_i))^2.\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The way we proceed in an iterative fashion is to\n",
"1. Initialize our estimate $f_0(x)$.\n",
"\n",
"2. For $m=1:M$, we\n",
"\n",
"a. 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)$;\n",
"\n",
"b. fit the so-called base-learner to the negative gradient $h_m(u_m,x)$;\n",
"\n",
"c. update the estimate $f_m(x) = f_{m-1}(x)+\\nu h_m(u_m,x)$;\n",
"\n",
"\n",
"4. The final estimate is then $f_M(x) = \\sum_{m=1}^M\\nu h_m(u_m,x)$.\n",
"\n",
"## Gradient Boosting Example, Regression\n",
"\n",
"We discuss here the difference between the steepest descent approach and gradient boosting by repeating our simple regression example above. \n",
"\n",
"\n",
"## Gradient Boosting, Examples of Regression"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import matplotlib.pyplot as plt\n",
"import numpy as np\n",
"from sklearn.model_selection import train_test_split\n",
"from sklearn.ensemble import GradientBoostingRegressor\n",
"from sklearn.preprocessing import StandardScaler\n",
"import scikitplot as skplt\n",
"from sklearn.metrics import mean_squared_error\n",
"\n",
"n = 100\n",
"maxdegree = 6\n",
"\n",
"# Make data set.\n",
"x = np.linspace(-3, 3, n).reshape(-1, 1)\n",
"y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)\n",
"\n",
"error = np.zeros(maxdegree)\n",
"bias = np.zeros(maxdegree)\n",
"variance = np.zeros(maxdegree)\n",
"polydegree = np.zeros(maxdegree)\n",
"X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)\n",
"scaler = StandardScaler()\n",
"scaler.fit(X_train)\n",
"X_train_scaled = scaler.transform(X_train)\n",
"X_test_scaled = scaler.transform(X_test)\n",
"\n",
"for degree in range(1,maxdegree):\n",
" model = GradientBoostingRegressor(max_depth=degree, n_estimators=100, learning_rate=1.0) \n",
" model.fit(X_train_scaled,y_train)\n",
" y_pred = model.predict(X_test_scaled)\n",
" polydegree[degree] = degree\n",
" error[degree] = np.mean( np.mean((y_test - y_pred)**2) )\n",
" bias[degree] = np.mean( (y_test - np.mean(y_pred))**2 )\n",
" variance[degree] = np.mean( np.var(y_pred) )\n",
" print('Max depth:', degree)\n",
" print('Error:', error[degree])\n",
" print('Bias^2:', bias[degree])\n",
" print('Var:', variance[degree])\n",
" print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))\n",
"\n",
"plt.xlim(1,maxdegree-1)\n",
"plt.plot(polydegree, error, label='Error')\n",
"plt.plot(polydegree, bias, label='bias')\n",
"plt.plot(polydegree, variance, label='Variance')\n",
"plt.legend()\n",
"save_fig(\"gdregression\")\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Gradient Boosting, Classification Example"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import matplotlib.pyplot as plt\n",
"import numpy as np\n",
"from sklearn.model_selection import train_test_split \n",
"from sklearn.datasets import load_breast_cancer\n",
"import scikitplot as skplt\n",
"from sklearn.ensemble import GradientBoostingClassifier\n",
"from sklearn.model_selection import cross_validate\n",
"\n",
"# Load the data\n",
"cancer = load_breast_cancer()\n",
"\n",
"X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)\n",
"print(X_train.shape)\n",
"print(X_test.shape)\n",
"#now scale the data\n",
"from sklearn.preprocessing import StandardScaler\n",
"scaler = StandardScaler()\n",
"scaler.fit(X_train)\n",
"X_train_scaled = scaler.transform(X_train)\n",
"X_test_scaled = scaler.transform(X_test)\n",
"\n",
"gd_clf = GradientBoostingClassifier(max_depth=3, n_estimators=100, learning_rate=1.0) \n",
"gd_clf.fit(X_train_scaled, y_train)\n",
"#Cross validation\n",
"accuracy = cross_validate(gd_clf,X_test_scaled,y_test,cv=10)['test_score']\n",
"print(accuracy)\n",
"print(\"Test set accuracy with Random Forests and scaled data: {:.2f}\".format(gd_clf.score(X_test_scaled,y_test)))\n",
"\n",
"import scikitplot as skplt\n",
"y_pred = gd_clf.predict(X_test_scaled)\n",
"skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)\n",
"save_fig(\"gdclassiffierconfusion\")\n",
"plt.show()\n",
"y_probas = gd_clf.predict_proba(X_test_scaled)\n",
"skplt.metrics.plot_roc(y_test, y_probas)\n",
"save_fig(\"gdclassiffierroc\")\n",
"plt.show()\n",
"skplt.metrics.plot_cumulative_gain(y_test, y_probas)\n",
"save_fig(\"gdclassiffiercgain\")\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## XGBoost: Extreme Gradient Boosting\n",
"\n",
"\n",
"[XGBoost](https://github.com/dmlc/xgboost) or Extreme Gradient\n",
"Boosting, is an optimized distributed gradient boosting library\n",
"designed to be highly efficient, flexible and portable. It implements\n",
"machine learning algorithms under the Gradient Boosting\n",
"framework. XGBoost provides a parallel tree boosting that solve many\n",
"data science problems in a fast and accurate way. See the [article by Chen and Guestrin](https://arxiv.org/abs/1603.02754).\n",
"\n",
"The authors design and build a highly scalable end-to-end tree\n",
"boosting system. It has a theoretically justified weighted quantile\n",
"sketch 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.\n",
"\n",
"It is now the algorithm which wins essentially all ML competitions!!!\n",
"\n",
"## Regression Case"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import matplotlib.pyplot as plt\n",
"import numpy as np\n",
"from sklearn.model_selection import train_test_split\n",
"import xgboost as xgb\n",
"from sklearn.preprocessing import StandardScaler\n",
"import scikitplot as skplt\n",
"from sklearn.metrics import mean_squared_error\n",
"\n",
"n = 100\n",
"maxdegree = 6\n",
"\n",
"# Make data set.\n",
"x = np.linspace(-3, 3, n).reshape(-1, 1)\n",
"y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)\n",
"\n",
"error = np.zeros(maxdegree)\n",
"bias = np.zeros(maxdegree)\n",
"variance = np.zeros(maxdegree)\n",
"polydegree = np.zeros(maxdegree)\n",
"X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)\n",
"scaler = StandardScaler()\n",
"scaler.fit(X_train)\n",
"X_train_scaled = scaler.transform(X_train)\n",
"X_test_scaled = scaler.transform(X_test)\n",
"\n",
"for degree in range(maxdegree):\n",
" 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)\n",
"\n",
" model.fit(X_train_scaled,y_train)\n",
" y_pred = model.predict(X_test_scaled)\n",
" polydegree[degree] = degree\n",
" error[degree] = np.mean( np.mean((y_test - y_pred)**2) )\n",
" bias[degree] = np.mean( (y_test - np.mean(y_pred))**2 )\n",
" variance[degree] = np.mean( np.var(y_pred) )\n",
" print('Max depth:', degree)\n",
" print('Error:', error[degree])\n",
" print('Bias^2:', bias[degree])\n",
" print('Var:', variance[degree])\n",
" print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))\n",
"\n",
"plt.xlim(1,maxdegree-1)\n",
"plt.plot(polydegree, error, label='Error')\n",
"plt.plot(polydegree, bias, label='bias')\n",
"plt.plot(polydegree, variance, label='Variance')\n",
"plt.legend()\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Xgboost on the Cancer Data\n",
"\n",
"As 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."
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"\n",
"import matplotlib.pyplot as plt\n",
"import numpy as np\n",
"from sklearn.model_selection import train_test_split \n",
"from sklearn.datasets import load_breast_cancer\n",
"from sklearn.preprocessing import LabelEncoder\n",
"from sklearn.model_selection import cross_validate\n",
"import scikitplot as skplt\n",
"import xgboost as xgb\n",
"# Load the data\n",
"cancer = load_breast_cancer()\n",
"\n",
"X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)\n",
"print(X_train.shape)\n",
"print(X_test.shape)\n",
"#now scale the data\n",
"from sklearn.preprocessing import StandardScaler\n",
"scaler = StandardScaler()\n",
"scaler.fit(X_train)\n",
"X_train_scaled = scaler.transform(X_train)\n",
"X_test_scaled = scaler.transform(X_test)\n",
"\n",
"xg_clf = xgb.XGBClassifier()\n",
"xg_clf.fit(X_train_scaled,y_train)\n",
"\n",
"y_test = xg_clf.predict(X_test_scaled)\n",
"\n",
"print(\"Test set accuracy with Random Forests and scaled data: {:.2f}\".format(xg_clf.score(X_test_scaled,y_test)))\n",
"\n",
"import scikitplot as skplt\n",
"y_pred = xg_clf.predict(X_test_scaled)\n",
"skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)\n",
"save_fig(\"xdclassiffierconfusion\")\n",
"plt.show()\n",
"y_probas = xg_clf.predict_proba(X_test_scaled)\n",
"skplt.metrics.plot_roc(y_test, y_probas)\n",
"save_fig(\"xdclassiffierroc\")\n",
"plt.show()\n",
"skplt.metrics.plot_cumulative_gain(y_test, y_probas)\n",
"save_fig(\"gdclassiffiercgain\")\n",
"plt.show()\n",
"\n",
"\n",
"xgb.plot_tree(xg_clf,num_trees=0)\n",
"plt.rcParams['figure.figsize'] = [50, 10]\n",
"save_fig(\"xgtree\")\n",
"plt.show()\n",
"\n",
"xgb.plot_importance(xg_clf)\n",
"plt.rcParams['figure.figsize'] = [5, 5]\n",
"save_fig(\"xgparams\")\n",
"plt.show()"
]
}
],
"metadata": {},
"nbformat": 4,
"nbformat_minor": 2
}