3119 lines
107 KiB
Plaintext
3119 lines
107 KiB
Plaintext
{
|
||
"cells": [
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "edd99c57",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"<!-- HTML file automatically generated from DocOnce source (https://github.com/doconce/doconce/)\n",
|
||
"doconce format html week44.do.txt --no_mako -->\n",
|
||
"<!-- dom:TITLE: Week 44: Dimensionality Reduction, PCA and Clustering. Decision Trees -->"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "c9d8e8e1",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"# Week 44: Dimensionality Reduction, PCA and Clustering. Decision Trees\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: **Nov 5, 2021**\n",
|
||
"\n",
|
||
"Copyright 1999-2021, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "c92e8e9c",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Overview of week 44\n",
|
||
"\n",
|
||
"* Thursday: Wrapping up PCA from last week, Clustering and basics of decision trees, classification and regression algorithms\n",
|
||
"\n",
|
||
" * [Video of Lecture](https://www.uio.no/studier/emner/matnat/fys/FYS-STK3155/h21/forelesningsvideoer/LectureNovember4.mp4?vrtx=view-as-webpage)\n",
|
||
"\n",
|
||
"* Friday: Decision trees, voting models and bagging\n",
|
||
"\n",
|
||
" * [Video of Lecture](https://www.uio.no/studier/emner/matnat/fys/FYS-STK3155/h21/forelesningsvideoer/LectureNovember5.mp4?vrtx=view-as-webpage)\n",
|
||
"\n",
|
||
"**Videos.**\n",
|
||
"\n",
|
||
"1. [Video on Decision trees](https://www.youtube.com/watch?v=RmajweUFKvM&ab_channel=Simplilearn)\n",
|
||
"\n",
|
||
"2. [Video on Principal Component Analysis](https://www.youtube.com/watch?v=FgakZw6K1QQ&ab_channel=StatQuestwithJoshStarmer)\n",
|
||
"\n",
|
||
"3. [Video on Clustering](https://www.youtube.com/watch?v=esmzYhuFnds&ab_channel=MITOpenCourseWare)\n",
|
||
"\n",
|
||
"**Reading.**\n",
|
||
"\n",
|
||
"1. Decision Trees: Geron's chapter 6 covers decision trees while ensemble models, voting and bagging are discussed in chapter 7. See also lecture from [STK-IN4300, lecture 7](https://www.uio.no/studier/emner/matnat/math/STK-IN4300/h20/slides/lecture_7.pdf). Chapter 9.2 of Hastie et al contains also a good discussion.\n",
|
||
"\n",
|
||
"2. Clustering and PCA, see Geron's chapter 8 and [Lecture notes](https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/chapter8.html). Bishop's chapter 9.1 is also a good read."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "0f3e9a0d",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Digression First\n",
|
||
"\n",
|
||
"For those of you interested in the fast growing areas of applications of Machine Learning, this article about [Applications and techniques for fast machine learning in science](https://arxiv.org/abs/2110.13041) may be interesting.\n",
|
||
"\n",
|
||
"It has several interesting perspectives and highly interesting\n",
|
||
"applications that link scientific discoveries with efficient software\n",
|
||
"and hardware. The emphasis is onintegrating power Machine Learning\n",
|
||
"methods into the real-time experimental data processing loop to\n",
|
||
"accelerate scientific discovery."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "acf64785",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## A short Discussion of Project 2\n",
|
||
"\n",
|
||
"For neural networks and regression, should I use a design matrix with information about a polynomial fit or not?\n",
|
||
"Discuss pros and cons. The example here shows some of these issues."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 1,
|
||
"id": "09a1c0a5",
|
||
"metadata": {
|
||
"collapsed": false,
|
||
"editable": true
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"%matplotlib inline\n",
|
||
"\n",
|
||
"\"\"\"\n",
|
||
"Code to test Ridge and NNs using Scikit-Learn only\n",
|
||
"\"\"\"\n",
|
||
"\n",
|
||
"import numpy as np\n",
|
||
"import pandas as pd\n",
|
||
"import matplotlib.pyplot as plt\n",
|
||
"from sklearn.model_selection import train_test_split\n",
|
||
"from sklearn import linear_model\n",
|
||
"from sklearn.neural_network import MLPRegressor\n",
|
||
"from sklearn.metrics import accuracy_score\n",
|
||
"import seaborn as sns\n",
|
||
"\n",
|
||
"\n",
|
||
"def MSE(y_data,y_model):\n",
|
||
" n = np.size(y_model)\n",
|
||
" return np.sum((y_data-y_model)**2)/n\n",
|
||
"# A seed just to ensure that the random numbers are the same for every run.\n",
|
||
"# Useful for eventual debugging.\n",
|
||
"np.random.seed(315)\n",
|
||
"\n",
|
||
"n = 100\n",
|
||
"x = np.random.rand(n)\n",
|
||
"y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)\n",
|
||
"\n",
|
||
"Maxpolydegree = 5\n",
|
||
"X = np.zeros((n,Maxpolydegree-1))\n",
|
||
"\n",
|
||
"for degree in range(1,Maxpolydegree): #No intercept column\n",
|
||
" X[:,degree-1] = x**(degree)\n",
|
||
"\n",
|
||
"# We split the data in test and training data\n",
|
||
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n",
|
||
"\n",
|
||
"# Decide which values of lambda to use\n",
|
||
"\n",
|
||
"nlambdas = 10\n",
|
||
"lmbd_vals = np.logspace(-4, 0, nlambdas)\n",
|
||
"MSERidgePredict = np.zeros(nlambdas)\n",
|
||
"for i in range(nlambdas):\n",
|
||
" lmb = lmbd_vals[i]\n",
|
||
" RegRidge = linear_model.Ridge(lmb)\n",
|
||
" RegRidge.fit(X_train,y_train)\n",
|
||
" ypredictRidge = RegRidge.predict(X_test)\n",
|
||
" MSERidgePredict[i] = MSE(y_test,ypredictRidge)\n",
|
||
"\n",
|
||
"plt.figure()\n",
|
||
"plt.plot(np.log10(lmbd_vals), MSERidgePredict, 'g--', label = 'MSE SL Ridge Test')\n",
|
||
"plt.xlabel('log10(lambda)')\n",
|
||
"plt.ylabel('MSE')\n",
|
||
"plt.legend()\n",
|
||
"plt.show()\n",
|
||
"\n",
|
||
"# Neural Network part\n",
|
||
"\n",
|
||
"n_hidden_neurons = 50\n",
|
||
"epochs = 100\n",
|
||
"# store models for later use\n",
|
||
"eta_vals = np.logspace(-4, 0, 10)\n",
|
||
"# store the models for later use\n",
|
||
"DNN_scikit = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)\n",
|
||
"test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n",
|
||
"sns.set()\n",
|
||
"for i, eta in enumerate(eta_vals):\n",
|
||
" for j, lmbd in enumerate(lmbd_vals):\n",
|
||
" dnn = MLPRegressor(hidden_layer_sizes=(n_hidden_neurons), activation='logistic',\n",
|
||
" alpha=lmbd, learning_rate_init=eta, max_iter=epochs)\n",
|
||
" dnn.fit(X_train, y_train)\n",
|
||
" ypredictMLP = dnn.predict(X_test)\n",
|
||
" test_accuracy[i][j] = MSE(ypredictMLP, y_test)\n",
|
||
"\n",
|
||
"fig, ax = plt.subplots(figsize = (10, 10))\n",
|
||
"sns.heatmap(test_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n",
|
||
"ax.set_title(\"Training Accuracy\")\n",
|
||
"ax.set_ylabel(\"$\\eta$\")\n",
|
||
"ax.set_xlabel(\"$\\lambda$\")\n",
|
||
"plt.show()\n",
|
||
"\n",
|
||
"# Now we redefine our design matrix to include only the x-values and try out our NN\n",
|
||
"\n",
|
||
"X = np.zeros((n,1))\n",
|
||
"X[:,0] = x\n",
|
||
"\n",
|
||
"# We split the data in test and training data again\n",
|
||
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n",
|
||
"# Repeat the NN calculation\n",
|
||
"DNN_scikit = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)\n",
|
||
"test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n",
|
||
"sns.set()\n",
|
||
"for i, eta in enumerate(eta_vals):\n",
|
||
" for j, lmbd in enumerate(lmbd_vals):\n",
|
||
" dnn = MLPRegressor(hidden_layer_sizes=(n_hidden_neurons), activation='logistic',\n",
|
||
" alpha=lmbd, learning_rate_init=eta, max_iter=epochs)\n",
|
||
" dnn.fit(X_train, y_train)\n",
|
||
" ypredictMLP = dnn.predict(X_test)\n",
|
||
" test_accuracy[i][j] = MSE(ypredictMLP, y_test)\n",
|
||
"\n",
|
||
"fig, ax = plt.subplots(figsize = (10, 10))\n",
|
||
"sns.heatmap(test_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n",
|
||
"ax.set_title(\"Training Accuracy\")\n",
|
||
"ax.set_ylabel(\"$\\eta$\")\n",
|
||
"ax.set_xlabel(\"$\\lambda$\")\n",
|
||
"plt.show()"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "d27a4d7a",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Learning Rate and more\n",
|
||
"\n",
|
||
"When developing your own gradient descent code, it is useful to test\n",
|
||
"it first on a standard ordinary least squares problem. Then the\n",
|
||
"Hessian matrix is determined by the design matrix only, namely\n",
|
||
"$\\boldsymbol{H}\\propto \\boldsymbol{X}^T\\boldsymbol{X}$.\n",
|
||
"\n",
|
||
"The optimal learning rate is determined by the inverse of the largest\n",
|
||
"eigenvalue of $\\boldsymbol{H}$. This can be used as a guideline for the\n",
|
||
"learning rate guess.\n",
|
||
"\n",
|
||
"Keeping this fixed, can aid in studyng the dependence on say the mean\n",
|
||
"square value for OLS as function of the number of batches and epochs\n",
|
||
"in your stochastic gradient descent code. See for example the code\n",
|
||
"examples for week 40 (right before the neural network material)."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "b40cdb70",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Thursday, Principal Component Analysis\n",
|
||
"\n",
|
||
"For the principal component analysis, \n",
|
||
"see slides from [week 43](https://compphysics.github.io/MachineLearning/doc/pub/week43/html/week43-reveal.html), in particular from slide 28 and forward"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "d686ca41",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## A kind of Bird's view on PCA\n",
|
||
"\n",
|
||
"**Why do we maximize variance during Principal Component Analysis?**\n",
|
||
"\n",
|
||
"Variance is a measure of the *variability* of the data you\n",
|
||
"have. Potentially the number of components is infinite, so you want to \"squeeze\" the most\n",
|
||
"information in each component of the finite set you build.\n",
|
||
"\n",
|
||
"If, to exaggerate, you were to select a single principal component,\n",
|
||
"you would want it to account for the most variability possible: hence\n",
|
||
"the search for maximum variance, so that the one component collects\n",
|
||
"the most \"uniqueness\" from the data set.\n",
|
||
"\n",
|
||
"Maximizing the component vector variances is the same as maximizing\n",
|
||
"the 'uniqueness' of those vectors. The vectors are as distant\n",
|
||
"from each other as possible (orthogonal to each other).\n",
|
||
"\n",
|
||
"Take for example a situation where you have 2 lines that are\n",
|
||
"orthogonal in a 3D space. You can capture the environment much more\n",
|
||
"completely with those orthogonal lines than 2 lines that are parallel\n",
|
||
"(or nearly parallel). When applied to very high dimensional states\n",
|
||
"using very few vectors, this becomes a much more important\n",
|
||
"relationship among the vectors to maintain. In a linear algebra sense\n",
|
||
"you want independent rows to be produced by PCA, otherwise some of\n",
|
||
"those rows will be redundant."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "cf3a902b",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Thursday: Clustering and Unsupervised Learning\n",
|
||
"\n",
|
||
"In general terms cluster analysis, or clustering, is the task of grouping a\n",
|
||
"data-set into different distinct categories based on some measure of equality of\n",
|
||
"the data. This measure is often referred to as a **metric** or **similarity\n",
|
||
"measure** in the literature (note: sometimes we deal with a **dissimilarity\n",
|
||
"measure** instead). Usually, these metrics are formulated as some kind of\n",
|
||
"distance function between points in a high-dimensional space.\n",
|
||
"\n",
|
||
"The simplest, and also the most\n",
|
||
"common is the **Euclidean distance**."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "fbbc0619",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Basic Idea of the $k$-means Clustering Algorithm\n",
|
||
"\n",
|
||
"The simplest of all clustering algorithms is the **k-means algorithm**\n",
|
||
", sometimes also referred to as *Lloyds algorithm*. It is the simplest and also\n",
|
||
"the most common. From its simplicity it obtains both strengths and weaknesses.\n",
|
||
"These will be discussed in more detail later. The $k$-means algorithm is a\n",
|
||
"**centroid based** clustering algorithm."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "0b8bd522",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## The $k$-means Algorithm\n",
|
||
"\n",
|
||
"Assume, we are given $n$ data points and we wish to split the data into $K < n$\n",
|
||
"different categories, or clusters. We label each cluster by an integer"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "344e68f0",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"$$\n",
|
||
"k\\in\\{1, \\cdots, K \\}.\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "9ef8dcf3",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"In the basic k-means algorithm each point is assigned to only\n",
|
||
"one cluster $k$, and these assignments are *non-injective* i.e. many-to-one. We\n",
|
||
"can think of these mappings as an encoder $k = C(i)$, which assigns the $i$-th\n",
|
||
"data-point $\\bf x_i$ to the $k$-th cluster.\n",
|
||
"\n",
|
||
"$k$-means algorithm in words:\n",
|
||
"1. We start with guesses / random initializations of our $k$ cluster centers/centroids\n",
|
||
"\n",
|
||
"2. For each centroid the points that are most similar are identified\n",
|
||
"\n",
|
||
"3. Then we move / replace each centroid with a coordinate average of all the points that were assigned to that centroid.\n",
|
||
"\n",
|
||
"4. Iterate 2-3 until the centroids no longer move (to some tolerance)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "50cfcdd3",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Basic Math of the $k$-means Algorithm\n",
|
||
"\n",
|
||
"We assume we have $n$ data-points"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "f1dccb55",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"<!-- Equation labels as ordinary links -->\n",
|
||
"<div id=\"eq:kmeanspoints\"></div>\n",
|
||
"\n",
|
||
"$$\n",
|
||
"\\begin{equation}\\label{eq:kmeanspoints} \\tag{1}\n",
|
||
" \\boldsymbol{x_i} = \\{x_{i, 1}, \\cdots, x_{i, p}\\}\\in\\mathbb{R}^p.\n",
|
||
"\\end{equation}\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "d8e16bc5",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"which we wish to group into $K < n$ clusters. For our dissimilarity measure we\n",
|
||
"use the *squared Euclidean distance*"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "dd222257",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"<!-- Equation labels as ordinary links -->\n",
|
||
"<div id=\"eq:squaredeuclidean\"></div>\n",
|
||
"\n",
|
||
"$$\n",
|
||
"\\begin{equation}\\label{eq:squaredeuclidean} \\tag{2}\n",
|
||
" d(\\boldsymbol{x_i}, \\boldsymbol{x_i'}) = \\sum_{j=1}^p(x_{ij} - x_{i'j})^2\n",
|
||
" = ||\\boldsymbol{x_i} - \\boldsymbol{x_{i'}}||^2\n",
|
||
"\\end{equation}\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "5578c171",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Within Cluster Point Scatter\n",
|
||
"\n",
|
||
"We define the so called *within-cluster point scatter* which gives us a\n",
|
||
"measure of how close each data point assigned to the same cluster tends to be to\n",
|
||
"the all the others."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "474f106f",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"<!-- Equation labels as ordinary links -->\n",
|
||
"<div id=\"eq:withincluster\"></div>\n",
|
||
"\n",
|
||
"$$\n",
|
||
"\\begin{equation}\\label{eq:withincluster} \\tag{3}\n",
|
||
" W(C) = \\frac{1}{2}\\sum_{k=1}^K\\sum_{C(i)=k}\n",
|
||
" \\sum_{C(i')=k}d(\\boldsymbol{x_i}, \\boldsymbol{x_{i'}}) =\n",
|
||
" \\sum_{k=1}^KN_k\\sum_{C(i)=k}||\\boldsymbol{x_i} - \\boldsymbol{\\overline{x_k}}||^2\n",
|
||
"\\end{equation}\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "5cea0534",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"where $\\boldsymbol{\\overline{x_k}}$ is the mean vector associated with the $k$-th\n",
|
||
"cluster, and $N_k = \\sum_{i=1}^nI(C(i) = k)$, where the $I()$ notation is\n",
|
||
"similar to the Kronecker delta (*Commonly used in statistics, it just means that\n",
|
||
"when $i = k$ we have the encoder $C(i)$*). In other words, the within-cluster\n",
|
||
"scatter measures the compactness of each cluster with respect to the data points\n",
|
||
"assigned to each cluster. This is the quantity that the $k$-means algorithm aims\n",
|
||
"to minimize. We refer to this quantity $W(C)$ as the within cluster scatter\n",
|
||
"because of its relation to the *total scatter*."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "cffd78be",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## More Details\n",
|
||
"\n",
|
||
"We have"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "1b9b26b4",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"<!-- Equation labels as ordinary links -->\n",
|
||
"<div id=\"eq:totalscatter\"></div>\n",
|
||
"\n",
|
||
"$$\n",
|
||
"\\begin{equation}\\label{eq:totalscatter} \\tag{4}\n",
|
||
" T = W(C) + B(C) = \\frac{1}{2}\\sum_{i=1}^n\n",
|
||
" \\sum_{i'=1}^nd(\\boldsymbol{x_i}, \\boldsymbol{x_{i'}})\n",
|
||
" = \\frac{1}{2}\\sum_{k=1}^K\\sum_{C(i)=k}\n",
|
||
" \\Big(\\sum_{C(i') = k}d(\\boldsymbol{x_i}, \\boldsymbol{x_{i'}})\n",
|
||
" + \\sum_{C(i')\\neq k}d(\\boldsymbol{x_i}, \\boldsymbol{x_{i'}})\\Big).\n",
|
||
"\\end{equation}\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "2cfcf75c",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"This is a quantity that is conserved throughout the $k$-means algorithm. It can\n",
|
||
"be thought of as the total amount of information in the data, and it is composed\n",
|
||
"of the aforementioned within-cluster scatter and the *between-cluster scatter*\n",
|
||
"$B(C)$. In methods such as principle component analysis the total scatter is not\n",
|
||
"conserved."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "0ccc7514",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Total Cluster Variance\n",
|
||
"Given a cluster mean $\\boldsymbol{m_k}$ we define the **total cluster variance**"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "1962a7bd",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"<!-- Equation labels as ordinary links -->\n",
|
||
"<div id=\"eq:totalclustervariance\"></div>\n",
|
||
"\n",
|
||
"$$\n",
|
||
"\\begin{equation}\\label{eq:totalclustervariance} \\tag{5}\n",
|
||
" \\min_{C, \\{\\boldsymbol{m_k}\\}_1^K}\\sum_{k=1}^KN_k\\sum||\\boldsymbol{x_i} - \\boldsymbol{m_k}||^2\n",
|
||
"\\end{equation}\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "8e9d7070",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"Now we have all the pieces necessary to formally revisit the $k$-means algorithm."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "fb253615",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## The $k$-means Clustering Algorithm\n",
|
||
"\n",
|
||
"The $k$-means clustering algorithm goes as follows \n",
|
||
"\n",
|
||
"1. For a given cluster assignment $C$, and $k$ cluster means $\\left\\{m_1, \\cdots, m_k\\right\\}$. We minimize the total cluster variance with respect to the cluster means $\\{m_k\\}$ yielding the means of the currently assigned clusters.\n",
|
||
"\n",
|
||
"2. Given a current set of $k$ means $\\{m_k\\}$ the total cluster variance is minimized by assigning each observation to the closest (current) cluster mean. That is $$C(i) = \\underset{1\\leq k\\leq K}{\\mathrm{argmin}} ||\\boldsymbol{x_i} - \\boldsymbol{m_k}||^2$$\n",
|
||
"\n",
|
||
"3. Steps 1 and 2 are repeated until the assignments do not change."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "534ace62",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Summarizing\n",
|
||
"\n",
|
||
"1. Before we start we specify a number $k$ which is the number of clusters we want to try to separate our data into.\n",
|
||
"\n",
|
||
"2. We initially choose $k$ random data points in our data as our initial centroids, *or means* (this is where the name comes from).\n",
|
||
"\n",
|
||
"3. Assign each data point to their closest centroid, based on the squared Euclidean distance.\n",
|
||
"\n",
|
||
"4. For each of the $k$ cluster we update the centroid by calculating new mean values for all the data points in the cluster.\n",
|
||
"\n",
|
||
"5. Iteratively minimize the within cluster scatter by performing steps (3, 4) until the new assignments stop changing (can be to some tolerance) or until a maximum number of iterations have passed."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "50c0ed67",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Writing our own Code, the Data Set\n",
|
||
"\n",
|
||
"Let us now program the most basic version of the algorithm using nothing but\n",
|
||
"Python with numpy arrays. This code is kept intentionally simple to gradually\n",
|
||
"progress our understanding. There is no vectorization of any kind, and even most\n",
|
||
"helper functions are not utilized.\n",
|
||
"\n",
|
||
"We need first a dataset to do our cluster analysis on. In our case\n",
|
||
"this is a plain *vanilla* data set using random numbers using a\n",
|
||
"Gaussian distribution."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 2,
|
||
"id": "396531c2",
|
||
"metadata": {
|
||
"collapsed": false,
|
||
"editable": true
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"import time\n",
|
||
"import numpy as np\n",
|
||
"import tensorflow as tf\n",
|
||
"from matplotlib import image\n",
|
||
"import matplotlib.pyplot as plt\n",
|
||
"from sklearn.cluster import KMeans\n",
|
||
"from IPython.display import display\n",
|
||
"\n",
|
||
"np.random.seed(2021)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "56afcdd4",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"Next we define functions, for ease of use later, to generate Gaussians and to\n",
|
||
"set up our toy data set."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 3,
|
||
"id": "e632f8bf",
|
||
"metadata": {
|
||
"collapsed": false,
|
||
"editable": true
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"def gaussian_points(dim=2, n_points=1000, mean_vector=np.array([0, 0]),\n",
|
||
" sample_variance=1):\n",
|
||
" \"\"\"\n",
|
||
" Very simple custom function to generate gaussian distributed point clusters\n",
|
||
" with variable dimension, number of points, means in each direction\n",
|
||
" (must match dim) and sample variance.\n",
|
||
"\n",
|
||
" Inputs:\n",
|
||
" dim (int)\n",
|
||
" n_points (int)\n",
|
||
" mean_vector (np.array) (where index 0 is x, index 1 is y etc.)\n",
|
||
" sample_variance (float)\n",
|
||
"\n",
|
||
" Returns:\n",
|
||
" data (np.array): with dimensions (dim x n_points)\n",
|
||
" \"\"\"\n",
|
||
"\n",
|
||
" mean_matrix = np.zeros(dim) + mean_vector\n",
|
||
" covariance_matrix = np.eye(dim) * sample_variance\n",
|
||
" data = np.random.multivariate_normal(mean_matrix, covariance_matrix,\n",
|
||
" n_points)\n",
|
||
" return data\n",
|
||
"\n",
|
||
"\n",
|
||
"\n",
|
||
"def generate_simple_clustering_dataset(dim=2, n_points=1000, plotting=True,\n",
|
||
" return_data=True):\n",
|
||
" \"\"\"\n",
|
||
" Toy model to illustrate k-means clustering\n",
|
||
" \"\"\"\n",
|
||
"\n",
|
||
" data1 = gaussian_points(mean_vector=np.array([5, 5]))\n",
|
||
" data2 = gaussian_points()\n",
|
||
" data3 = gaussian_points(mean_vector=np.array([1, 4.5]))\n",
|
||
" data4 = gaussian_points(mean_vector=np.array([5, 1]))\n",
|
||
" data = np.concatenate((data1, data2, data3, data4), axis=0)\n",
|
||
"\n",
|
||
" if plotting:\n",
|
||
" fig, ax = plt.subplots()\n",
|
||
" ax.scatter(data[:, 0], data[:, 1], alpha=0.2)\n",
|
||
" ax.set_title('Toy Model Dataset')\n",
|
||
" plt.show()\n",
|
||
"\n",
|
||
"\n",
|
||
" if return_data:\n",
|
||
" return data\n",
|
||
"\n",
|
||
"\n",
|
||
"data = generate_simple_clustering_dataset()"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "1ccc01db",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Implementing the $k$-means Algorithm\n",
|
||
"\n",
|
||
"With the above dataset we start\n",
|
||
"implementing the $k$-means algorithm."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 4,
|
||
"id": "f0999ed1",
|
||
"metadata": {
|
||
"collapsed": false,
|
||
"editable": true
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"\n",
|
||
"n_samples, dimensions = data.shape\n",
|
||
"n_clusters = 4\n",
|
||
"\n",
|
||
"# we randomly initialize our centroids\n",
|
||
"np.random.seed(2021)\n",
|
||
"centroids = data[np.random.choice(n_samples, n_clusters, replace=False), :]\n",
|
||
"distances = np.zeros((n_samples, n_clusters))\n",
|
||
"\n",
|
||
"# first we need to calculate the distance to each centroid from our data\n",
|
||
"for k in range(n_clusters):\n",
|
||
" for n in range(n_samples):\n",
|
||
" dist = 0\n",
|
||
" for d in range(dimensions):\n",
|
||
" dist += np.abs(data[n, d] - centroids[k, d])**2\n",
|
||
" distances[n, k] = dist\n",
|
||
"\n",
|
||
"# we initialize an array to keep track of to which cluster each point belongs\n",
|
||
"# the way we set it up here the index tracks which point and the value which\n",
|
||
"# cluster the point belongs to\n",
|
||
"cluster_labels = np.zeros(n_samples, dtype='int')\n",
|
||
"\n",
|
||
"# next we loop through our samples and for every point assign it to the cluster\n",
|
||
"# to which it has the smallest distance to\n",
|
||
"for n in range(n_samples):\n",
|
||
" # tracking variables (all of this is basically just an argmin)\n",
|
||
" smallest = 1e10\n",
|
||
" smallest_row_index = 1e10\n",
|
||
" for k in range(n_clusters):\n",
|
||
" if distances[n, k] < smallest:\n",
|
||
" smallest = distances[n, k]\n",
|
||
" smallest_row_index = k\n",
|
||
"\n",
|
||
" cluster_labels[n] = smallest_row_index"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "7025d35c",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Plotting"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 5,
|
||
"id": "cd88014d",
|
||
"metadata": {
|
||
"collapsed": false,
|
||
"editable": true
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"fig = plt.figure()\n",
|
||
"ax = fig.add_subplot()\n",
|
||
"unique_cluster_labels = np.unique(cluster_labels)\n",
|
||
"for i in unique_cluster_labels:\n",
|
||
" ax.scatter(data[cluster_labels == i, 0],\n",
|
||
" data[cluster_labels == i, 1],\n",
|
||
" label = i,\n",
|
||
" alpha = 0.2)\n",
|
||
" ax.scatter(centroids[:, 0], centroids[:, 1], c='black')\n",
|
||
"\n",
|
||
"ax.set_title(\"First Grouping of Points to Centroids\")\n",
|
||
"\n",
|
||
"plt.show()"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "a45d1f7c",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"So what do we have so far? We have 'picked' $k$ centroids at random from our\n",
|
||
"data points. There are other ways of more intelligently choosing their\n",
|
||
"initializations, however for our purposes randomly is fine. Then we have\n",
|
||
"initialized an array 'distances' which holds the information of the distance,\n",
|
||
"*or dissimilarity*, of every point to of our centroids. Finally, we have\n",
|
||
"initialized an array 'cluster_labels' which according to our distances array\n",
|
||
"holds the information of to which centroid every point is assigned. This was the\n",
|
||
"first pass of our algorithm. Essentially, all we need to do now is repeat the\n",
|
||
"distance and assignment steps above until we have reached a desired convergence\n",
|
||
"or a maximum amount of iterations."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "e2202d97",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Continuing"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 6,
|
||
"id": "83750434",
|
||
"metadata": {
|
||
"collapsed": false,
|
||
"editable": true
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"\n",
|
||
"max_iterations = 100\n",
|
||
"tolerance = 1e-8\n",
|
||
"\n",
|
||
"for iteration in range(max_iterations):\n",
|
||
" prev_centroids = centroids.copy()\n",
|
||
" for k in range(n_clusters):\n",
|
||
" # this array will be used to update our centroid positions\n",
|
||
" vector_mean = np.zeros(dimensions)\n",
|
||
" mean_divisor = 0\n",
|
||
" for n in range(n_samples):\n",
|
||
" if cluster_labels[n] == k:\n",
|
||
" vector_mean += data[n, :]\n",
|
||
" mean_divisor += 1\n",
|
||
"\n",
|
||
" # update according to the k means\n",
|
||
" centroids[k, :] = vector_mean / mean_divisor\n",
|
||
"\n",
|
||
" # we find the dissimilarity\n",
|
||
" for k in range(n_clusters):\n",
|
||
" for n in range(n_samples):\n",
|
||
" dist = 0\n",
|
||
" for d in range(dimensions):\n",
|
||
" dist += np.abs(data[n, d] - centroids[k, d])**2\n",
|
||
" distances[n, k] = dist\n",
|
||
"\n",
|
||
" # assign each point\n",
|
||
" for n in range(n_samples):\n",
|
||
" smallest = 1e10\n",
|
||
" smallest_row_index = 1e10\n",
|
||
" for k in range(n_clusters):\n",
|
||
" if distances[n, k] < smallest:\n",
|
||
" smallest = distances[n, k]\n",
|
||
" smallest_row_index = k\n",
|
||
"\n",
|
||
" cluster_labels[n] = smallest_row_index\n",
|
||
"\n",
|
||
" # convergence criteria\n",
|
||
" centroid_difference = np.sum(np.abs(centroids - prev_centroids))\n",
|
||
" if centroid_difference < tolerance:\n",
|
||
" print(f'Converged at iteration {iteration}')\n",
|
||
" break\n",
|
||
"\n",
|
||
" elif iteration == max_iterations:\n",
|
||
" print(f'Did not converge in {max_iterations} iterations')"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "c12bc8a6",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Wrapping it up\n",
|
||
"We now have a simple , un-optimized $k$-means\n",
|
||
"clustering implementation. Lets plot the final result"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 7,
|
||
"id": "4ab3fba6",
|
||
"metadata": {
|
||
"collapsed": false,
|
||
"editable": true
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"fig = plt.figure()\n",
|
||
"ax = fig.add_subplot()\n",
|
||
"unique_cluster_labels = np.unique(cluster_labels)\n",
|
||
"for i in unique_cluster_labels:\n",
|
||
" ax.scatter(data[cluster_labels == i, 0],\n",
|
||
" data[cluster_labels == i, 1],\n",
|
||
" label = i,\n",
|
||
" alpha = 0.2)\n",
|
||
" ax.scatter(centroids[:, 0], centroids[:, 1], c='black')\n",
|
||
"\n",
|
||
"ax.set_title(\"Final Result of K-means Clustering\")\n",
|
||
"\n",
|
||
"plt.show()"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 8,
|
||
"id": "f196e068",
|
||
"metadata": {
|
||
"collapsed": false,
|
||
"editable": true
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"def naive_kmeans(data, n_clusters=4, max_iterations=100, tolerance=1e-8):\n",
|
||
" start_time = time.time()\n",
|
||
"\n",
|
||
" n_samples, dimensions = data.shape\n",
|
||
" n_clusters = 4\n",
|
||
" #np.random.seed(2021)\n",
|
||
" centroids = data[np.random.choice(n_samples, n_clusters, replace=False), :]\n",
|
||
" distances = np.zeros((n_samples, n_clusters))\n",
|
||
"\n",
|
||
" for k in range(n_clusters):\n",
|
||
" for n in range(n_samples):\n",
|
||
" dist = 0\n",
|
||
" for d in range(dimensions):\n",
|
||
" dist += np.abs(data[n, d] - centroids[k, d])**2\n",
|
||
" distances[n, k] = dist\n",
|
||
"\n",
|
||
" cluster_labels = np.zeros(n_samples, dtype='int')\n",
|
||
"\n",
|
||
" for n in range(n_samples):\n",
|
||
" smallest = 1e10\n",
|
||
" smallest_row_index = 1e10\n",
|
||
" for k in range(n_clusters):\n",
|
||
" if distances[n, k] < smallest:\n",
|
||
" smallest = distances[n, k]\n",
|
||
" smallest_row_index = k\n",
|
||
"\n",
|
||
" cluster_labels[n] = smallest_row_index\n",
|
||
"\n",
|
||
" for iteration in range(max_iterations):\n",
|
||
" prev_centroids = centroids.copy()\n",
|
||
" for k in range(n_clusters):\n",
|
||
" vector_mean = np.zeros(dimensions)\n",
|
||
" mean_divisor = 0\n",
|
||
" for n in range(n_samples):\n",
|
||
" if cluster_labels[n] == k:\n",
|
||
" vector_mean += data[n, :]\n",
|
||
" mean_divisor += 1\n",
|
||
"\n",
|
||
" centroids[k, :] = vector_mean / mean_divisor\n",
|
||
"\n",
|
||
" for k in range(n_clusters):\n",
|
||
" for n in range(n_samples):\n",
|
||
" dist = 0\n",
|
||
" for d in range(dimensions):\n",
|
||
" dist += np.abs(data[n, d] - centroids[k, d])**2\n",
|
||
" distances[n, k] = dist\n",
|
||
"\n",
|
||
" for n in range(n_samples):\n",
|
||
" smallest = 1e10\n",
|
||
" smallest_row_index = 1e10\n",
|
||
" for k in range(n_clusters):\n",
|
||
" if distances[n, k] < smallest:\n",
|
||
" smallest = distances[n, k]\n",
|
||
" smallest_row_index = k\n",
|
||
"\n",
|
||
" cluster_labels[n] = smallest_row_index\n",
|
||
"\n",
|
||
" centroid_difference = np.sum(np.abs(centroids - prev_centroids))\n",
|
||
" if centroid_difference < tolerance:\n",
|
||
" print(f'Converged at iteration {iteration}')\n",
|
||
" print(f'Runtime: {time.time() - start_time} seconds')\n",
|
||
"\n",
|
||
" return cluster_labels, centroids\n",
|
||
"\n",
|
||
" print(f'Did not converge in {max_iterations} iterations')\n",
|
||
" print(f'Runtime: {time.time() - start_time} seconds')\n",
|
||
"\n",
|
||
" return cluster_labels, centroids"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "9b2b9374",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Decision trees, overarching aims\n",
|
||
"\n",
|
||
"We start here with the most basic algorithm, the so-called decision\n",
|
||
"tree. With this basic algorithm we can in turn build more complex\n",
|
||
"networks, spanning from homogeneous and heterogenous forests (bagging,\n",
|
||
"random forests and more) to one of the most popular supervised\n",
|
||
"algorithms nowadays, the extreme gradient boosting, or just\n",
|
||
"XGBoost. But let us start with the simplest possible ingredient.\n",
|
||
"\n",
|
||
"Decision trees are supervised learning algorithms used for both,\n",
|
||
"classification and regression tasks.\n",
|
||
"\n",
|
||
"The main idea of decision trees\n",
|
||
"is to find those descriptive features which contain the most\n",
|
||
"**information** regarding the target feature and then split the dataset\n",
|
||
"along the values of these features such that the target feature values\n",
|
||
"for the resulting underlying datasets are as pure as possible.\n",
|
||
"\n",
|
||
"The descriptive features which reproduce best the target/output features are normally said\n",
|
||
"to be the most informative ones. The process of finding the **most\n",
|
||
"informative** feature is done until we accomplish a stopping criteria\n",
|
||
"where we then finally end up in so called **leaf nodes**."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "ea71f159",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Basics of a tree\n",
|
||
"\n",
|
||
"A decision tree is typically divided into a **root node**, the **interior nodes**,\n",
|
||
"and the final **leaf nodes** or just **leaves**. These entities are then connected by so-called **branches**.\n",
|
||
"\n",
|
||
"The leaf nodes\n",
|
||
"contain the predictions we will make for new query instances presented\n",
|
||
"to our trained model. This is possible since the model has \n",
|
||
"learned the underlying structure of the training data and hence can,\n",
|
||
"given some assumptions, make predictions about the target feature value\n",
|
||
"(class) of unseen query instances."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "e2aeaba3",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## A Sketch of a Tree, Regression problem\n",
|
||
"\n",
|
||
"<!-- FIGURE: [DataFiles/Regsimpletree.png, width=600 frac=0.8] -->"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "ae9ecf7e",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## A Sketch of a Tree, Classification problem\n",
|
||
"\n",
|
||
"<!-- FIGURE: [DataFiles/Classimpletree.png, width=600 frac=0.8] -->"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "73c2c2a3",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## A typical Decision Tree with its pertinent Jargon, Classification Problem\n",
|
||
"\n",
|
||
"<!-- dom:FIGURE: [DataFiles/cancer.png, width=600 frac=0.8] -->\n",
|
||
"<!-- begin figure -->\n",
|
||
"\n",
|
||
"<img src=\"DataFiles/cancer.png\" width=\"600\"><p style=\"font-size: 0.9em\"><i>Figure 1: </i></p>\n",
|
||
"<!-- end figure -->\n",
|
||
"\n",
|
||
"This tree was produced using the Wisconsin cancer data (discussed here as well, see code examples below) using **Scikit-Learn**'s decision tree classifier. Here we have used the so-called **gini** index (see below) to split the various branches."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "617b4dcd",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## General Features\n",
|
||
"\n",
|
||
"The overarching approach to decision trees is a top-down approach.\n",
|
||
"\n",
|
||
"* A leaf provides the classification of a given instance.\n",
|
||
"\n",
|
||
"* A node specifies a test of some attribute of the instance.\n",
|
||
"\n",
|
||
"* A branch corresponds to a possible values of an attribute.\n",
|
||
"\n",
|
||
"* An instance is classified by starting at the root node of the tree, testing the attribute specified by this node, then moving down the tree branch corresponding to the value of the attribute in the given example.\n",
|
||
"\n",
|
||
"This process is then repeated for the subtree rooted at the new\n",
|
||
"node."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "cd186d54",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## How do we set it up?\n",
|
||
"\n",
|
||
"In simplified terms, the process of training a decision tree and\n",
|
||
"predicting the target features of query instances is as follows:\n",
|
||
"\n",
|
||
"1. Present a dataset containing of a number of training instances characterized by a number of descriptive features and a target feature\n",
|
||
"\n",
|
||
"2. Train the decision tree model by continuously splitting the target feature along the values of the descriptive features using a measure of information gain during the training process\n",
|
||
"\n",
|
||
"3. Grow the tree until we accomplish a stopping criteria create leaf nodes which represent the *predictions* we want to make for new query instances\n",
|
||
"\n",
|
||
"4. Show query instances to the tree and run down the tree until we arrive at leaf nodes\n",
|
||
"\n",
|
||
"Then we are essentially done!"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "a7103bf3",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Decision trees and Regression"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 9,
|
||
"id": "b91836da",
|
||
"metadata": {
|
||
"collapsed": false,
|
||
"editable": true
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"import numpy as np\n",
|
||
"import matplotlib.pyplot as plt\n",
|
||
"from sklearn.preprocessing import PolynomialFeatures\n",
|
||
"from sklearn.linear_model import LinearRegression\n",
|
||
"\n",
|
||
"steps=250\n",
|
||
"\n",
|
||
"distance=0\n",
|
||
"x=0\n",
|
||
"distance_list=[]\n",
|
||
"steps_list=[]\n",
|
||
"while x<steps:\n",
|
||
" distance+=np.random.randint(-1,2)\n",
|
||
" distance_list.append(distance)\n",
|
||
" x+=1\n",
|
||
" steps_list.append(x)\n",
|
||
"plt.plot(steps_list,distance_list, color='green', label=\"Random Walk Data\")\n",
|
||
"\n",
|
||
"steps_list=np.asarray(steps_list)\n",
|
||
"distance_list=np.asarray(distance_list)\n",
|
||
"\n",
|
||
"X=steps_list[:,np.newaxis]\n",
|
||
"\n",
|
||
"#Polynomial fits\n",
|
||
"\n",
|
||
"#Degree 2\n",
|
||
"poly_features=PolynomialFeatures(degree=2, include_bias=False)\n",
|
||
"X_poly=poly_features.fit_transform(X)\n",
|
||
"\n",
|
||
"lin_reg=LinearRegression()\n",
|
||
"poly_fit=lin_reg.fit(X_poly,distance_list)\n",
|
||
"b=lin_reg.coef_\n",
|
||
"c=lin_reg.intercept_\n",
|
||
"print (\"2nd degree coefficients:\")\n",
|
||
"print (\"zero power: \",c)\n",
|
||
"print (\"first power: \", b[0])\n",
|
||
"print (\"second power: \",b[1])\n",
|
||
"\n",
|
||
"z = np.arange(0, steps, .01)\n",
|
||
"z_mod=b[1]*z**2+b[0]*z+c\n",
|
||
"\n",
|
||
"fit_mod=b[1]*X**2+b[0]*X+c\n",
|
||
"plt.plot(z, z_mod, color='r', label=\"2nd Degree Fit\")\n",
|
||
"plt.title(\"Polynomial Regression\")\n",
|
||
"\n",
|
||
"plt.xlabel(\"Steps\")\n",
|
||
"plt.ylabel(\"Distance\")\n",
|
||
"\n",
|
||
"#Degree 10\n",
|
||
"poly_features10=PolynomialFeatures(degree=10, include_bias=False)\n",
|
||
"X_poly10=poly_features10.fit_transform(X)\n",
|
||
"\n",
|
||
"poly_fit10=lin_reg.fit(X_poly10,distance_list)\n",
|
||
"\n",
|
||
"y_plot=poly_fit10.predict(X_poly10)\n",
|
||
"plt.plot(X, y_plot, color='black', label=\"10th Degree Fit\")\n",
|
||
"\n",
|
||
"plt.legend()\n",
|
||
"plt.show()\n",
|
||
"\n",
|
||
"\n",
|
||
"#Decision Tree Regression\n",
|
||
"from sklearn.tree import DecisionTreeRegressor\n",
|
||
"regr_1=DecisionTreeRegressor(max_depth=2)\n",
|
||
"regr_2=DecisionTreeRegressor(max_depth=5)\n",
|
||
"regr_3=DecisionTreeRegressor(max_depth=7)\n",
|
||
"regr_1.fit(X, distance_list)\n",
|
||
"regr_2.fit(X, distance_list)\n",
|
||
"regr_3.fit(X, distance_list)\n",
|
||
"\n",
|
||
"X_test = np.arange(0.0, steps, 0.01)[:, np.newaxis]\n",
|
||
"y_1 = regr_1.predict(X_test)\n",
|
||
"y_2 = regr_2.predict(X_test)\n",
|
||
"y_3=regr_3.predict(X_test)\n",
|
||
"\n",
|
||
"# Plot the results\n",
|
||
"plt.figure()\n",
|
||
"plt.scatter(X, distance_list, s=2.5, c=\"black\", label=\"data\")\n",
|
||
"plt.plot(X_test, y_1, color=\"red\",\n",
|
||
" label=\"max_depth=2\", linewidth=2)\n",
|
||
"plt.plot(X_test, y_2, color=\"green\", label=\"max_depth=5\", linewidth=2)\n",
|
||
"plt.plot(X_test, y_3, color=\"m\", label=\"max_depth=7\", linewidth=2)\n",
|
||
"\n",
|
||
"plt.xlabel(\"Data\")\n",
|
||
"plt.ylabel(\"Darget\")\n",
|
||
"plt.title(\"Decision Tree Regression\")\n",
|
||
"plt.legend()\n",
|
||
"plt.show()"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "a9eb9d5e",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Building a tree, regression\n",
|
||
"\n",
|
||
"There are mainly two steps\n",
|
||
"1. We split the predictor space (the set of possible values $x_1,x_2,\\dots, x_p$) into $J$ distinct and non-non-overlapping regions, $R_1,R_2,\\dots,R_J$. \n",
|
||
"\n",
|
||
"2. For every observation that falls into the region $R_j$ , we make the same prediction, which is simply the mean of the response values for the training observations in $R_j$.\n",
|
||
"\n",
|
||
"How do we construct the regions $R_1,\\dots,R_J$? In theory, the\n",
|
||
"regions could have any shape. However, we choose to divide the\n",
|
||
"predictor space into high-dimensional rectangles, or boxes, for\n",
|
||
"simplicity and for ease of interpretation of the resulting predictive\n",
|
||
"model. The goal is to find boxes $R_1,\\dots,R_J$ that minimize the\n",
|
||
"MSE, given by"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "afefdfd6",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"$$\n",
|
||
"\\sum_{j=1}^J\\sum_{i\\in R_j}(y_i-\\overline{y}_{R_j})^2,\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "f5b8dc1d",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"where $\\overline{y}_{R_j}$ is the mean response for the training observations \n",
|
||
"within box $j$."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "ec5a291d",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## A top-down approach, recursive binary splitting\n",
|
||
"\n",
|
||
"Unfortunately, it is computationally infeasible to consider every\n",
|
||
"possible partition of the feature space into $J$ boxes. The common\n",
|
||
"strategy is to take a top-down approach\n",
|
||
"\n",
|
||
"The approach is top-down because it begins at the top of the tree (all\n",
|
||
"observations belong to a single region) and then successively splits\n",
|
||
"the predictor space; each split is indicated via two new branches\n",
|
||
"further down on the tree. It is greedy because at each step of the\n",
|
||
"tree-building process, the best split is made at that particular step,\n",
|
||
"rather than looking ahead and picking a split that will lead to a\n",
|
||
"better tree in some future step."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "58b762b2",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Making a tree\n",
|
||
"\n",
|
||
"In order to implement the recursive binary splitting we start by selecting\n",
|
||
"the predictor $x_j$ and a cutpoint $s$ that splits the predictor space into two regions $R_1$ and $R_2$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "539de439",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"$$\n",
|
||
"\\left\\{X\\vert x_j < s\\right\\},\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "d8af3fbe",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"and"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "becbbdfa",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"$$\n",
|
||
"\\left\\{X\\vert x_j \\geq s\\right\\},\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "9b87b748",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"so that we obtain the lowest MSE, that is"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "7d61073a",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"$$\n",
|
||
"\\sum_{i:x_i\\in R_j}(y_i-\\overline{y}_{R_1})^2+\\sum_{i:x_i\\in R_2}(y_i-\\overline{y}_{R_2})^2,\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "d0c9f872",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"which we want to minimize by considering all predictors\n",
|
||
"$x_1,x_2,\\dots,x_p$. We consider also all possible values of $s$ for\n",
|
||
"each predictor. These values could be determined by randomly assigned\n",
|
||
"numbers or by starting at the midpoint and then proceed till we find\n",
|
||
"an optimal value.\n",
|
||
"\n",
|
||
"For any $j$ and $s$, we define the pair of half-planes where\n",
|
||
"$\\overline{y}_{R_1}$ is the mean response for the training\n",
|
||
"observations in $R_1(j,s)$, and $\\overline{y}_{R_2}$ is the mean\n",
|
||
"response for the training observations in $R_2(j,s)$.\n",
|
||
"\n",
|
||
"Finding the values of $j$ and $s$ that minimize the above equation can be\n",
|
||
"done quite quickly, especially when the number of features $p$ is not\n",
|
||
"too large.\n",
|
||
"\n",
|
||
"Next, we repeat the process, looking\n",
|
||
"for the best predictor and best cutpoint in order to split the data\n",
|
||
"further so as to minimize the MSE within each of the resulting\n",
|
||
"regions. However, this time, instead of splitting the entire predictor\n",
|
||
"space, we split one of the two previously identified regions. We now\n",
|
||
"have three regions. Again, we look to split one of these three regions\n",
|
||
"further, so as to minimize the MSE. The process continues until a\n",
|
||
"stopping criterion is reached; for instance, we may continue until no\n",
|
||
"region contains more than five observations."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "8356ddf0",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Pruning the tree\n",
|
||
"\n",
|
||
"The above procedure is rather straightforward, but leads often to\n",
|
||
"overfitting and unnecessarily large and complicated trees. The basic\n",
|
||
"idea is to grow a large tree $T_0$ and then prune it back in order to\n",
|
||
"obtain a subtree. A smaller tree with fewer splits (fewer regions) can\n",
|
||
"lead to smaller variance and better interpretation at the cost of a\n",
|
||
"little more bias.\n",
|
||
"\n",
|
||
"The so-called Cost complexity pruning algorithm gives us a\n",
|
||
"way to do just this. Rather than considering every possible subtree,\n",
|
||
"we consider a sequence of trees indexed by a nonnegative tuning\n",
|
||
"parameter $\\alpha$.\n",
|
||
"\n",
|
||
"Read more at the following [Scikit-Learn link on pruning](https://scikit-learn.org/stable/auto_examples/tree/plot_cost_complexity_pruning.html#sphx-glr-auto-examples-tree-plot-cost-complexity-pruning-py)."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "e3bc4531",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Cost complexity pruning\n",
|
||
"\n",
|
||
"For each value of $\\alpha$ there corresponds a subtree $T \\in T_0$ such that"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "e0f86657",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"$$\n",
|
||
"\\sum_{m=1}^{\\overline{T}}\\sum_{i:x_i\\in R_m}(y_i-\\overline{y}_{R_m})^2+\\alpha\\overline{T},\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "240ad8bb",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"is as small as possible. Here $\\overline{T}$ is \n",
|
||
"the number of terminal nodes of the tree $T$ , $R_m$ is the\n",
|
||
"rectangle (i.e. the subset of predictor space) corresponding to the $m$-th terminal node.\n",
|
||
"\n",
|
||
"The tuning parameter $\\alpha$ controls a trade-off between the subtree’s\n",
|
||
"complexity and its fit to the training data. When $\\alpha = 0$, then the\n",
|
||
"subtree $T$ will simply equal $T_0$, \n",
|
||
"because then the above equation just measures the\n",
|
||
"training error. \n",
|
||
"However, as $\\alpha$ increases, there is a price to pay for\n",
|
||
"having a tree with many terminal nodes. The above equation will\n",
|
||
"tend to be minimized for a smaller subtree. \n",
|
||
"\n",
|
||
"It turns out that as we increase $\\alpha$ from zero\n",
|
||
"branches get pruned from the tree in a nested and predictable fashion,\n",
|
||
"so obtaining the whole sequence of subtrees as a function of $\\alpha$ is\n",
|
||
"easy. We can select a value of $\\alpha$ using a validation set or using\n",
|
||
"cross-validation. We then return to the full data set and obtain the\n",
|
||
"subtree corresponding to $\\alpha$."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "24de8711",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Schematic Regression Procedure\n",
|
||
"\n",
|
||
"**Building a Regression Tree.**\n",
|
||
"\n",
|
||
"1. Use recursive binary splitting to grow a large tree on the training data, stopping only when each terminal node has fewer than some minimum number of observations.\n",
|
||
"\n",
|
||
"2. Apply cost complexity pruning to the large tree in order to obtain a sequence of best subtrees, as a function of $\\alpha$.\n",
|
||
"\n",
|
||
"3. Use for example $K$-fold cross-validation to choose $\\alpha$. Divide the training observations into $K$ folds. For each $k=1,2,\\dots,K$ we: \n",
|
||
"\n",
|
||
" * repeat steps 1 and 2 on all but the $k$-th fold of the training data. \n",
|
||
"\n",
|
||
" * Then we valuate the mean squared prediction error on the data in the left-out $k$-th fold, as a function of $\\alpha$.\n",
|
||
"\n",
|
||
" * Finally we average the results for each value of $\\alpha$, and pick $\\alpha$ to minimize the average error.\n",
|
||
"\n",
|
||
"4. Return the subtree from Step 2 that corresponds to the chosen value of $\\alpha$."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "f0b74c5c",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## A Classification Tree\n",
|
||
"\n",
|
||
"A classification tree is very similar to a regression tree, except\n",
|
||
"that it is used to predict a qualitative response rather than a\n",
|
||
"quantitative one. Recall that for a regression tree, the predicted\n",
|
||
"response for an observation is given by the mean response of the\n",
|
||
"training observations that belong to the same terminal node. In\n",
|
||
"contrast, for a classification tree, we predict that each observation\n",
|
||
"belongs to the most commonly occurring class of training observations\n",
|
||
"in the region to which it belongs. In interpreting the results of a\n",
|
||
"classification tree, we are often interested not only in the class\n",
|
||
"prediction corresponding to a particular terminal node region, but\n",
|
||
"also in the class proportions among the training observations that\n",
|
||
"fall into that region."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "957c9d69",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Growing a classification tree\n",
|
||
"\n",
|
||
"The task of growing a\n",
|
||
"classification tree is quite similar to the task of growing a\n",
|
||
"regression tree. Just as in the regression setting, we use recursive\n",
|
||
"binary splitting to grow a classification tree. However, in the\n",
|
||
"classification setting, the MSE cannot be used as a criterion for making\n",
|
||
"the binary splits. A natural alternative to MSE is the **classification\n",
|
||
"error rate**. Since we plan to assign an observation in a given region\n",
|
||
"to the most commonly occurring error rate class of training\n",
|
||
"observations in that region, the classification error rate is simply\n",
|
||
"the fraction of the training observations in that region that do not\n",
|
||
"belong to the most common class. \n",
|
||
"\n",
|
||
"When building a classification tree, either the Gini index or the\n",
|
||
"entropy are typically used to evaluate the quality of a particular\n",
|
||
"split, since these two approaches are more sensitive to node purity\n",
|
||
"than is the classification error rate."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "57a5e827",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Classification tree, how to split nodes\n",
|
||
"\n",
|
||
"If our targets are the outcome of a classification process that takes\n",
|
||
"for example $k=1,2,\\dots,K$ values, the only thing we need to think of\n",
|
||
"is to set up the splitting criteria for each node.\n",
|
||
"\n",
|
||
"We define a PDF $p_{mk}$ that represents the number of observations of\n",
|
||
"a class $k$ in a region $R_m$ with $N_m$ observations. We represent\n",
|
||
"this likelihood function in terms of the proportion $I(y_i=k)$ of\n",
|
||
"observations of this class in the region $R_m$ as"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "4193d006",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"$$\n",
|
||
"p_{mk} = \\frac{1}{N_m}\\sum_{x_i\\in R_m}I(y_i=k).\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "65cb0b6b",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"We let $p_{mk}$ represent the majority class of observations in region\n",
|
||
"$m$. The three most common ways of splitting a node are given by\n",
|
||
"\n",
|
||
"* Misclassification error"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "48b04834",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"$$\n",
|
||
"p_{mk} = \\frac{1}{N_m}\\sum_{x_i\\in R_m}I(y_i\\ne k) = 1-p_{mk}.\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "2ccc5c64",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"* Gini index $g$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "78196ea5",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"$$\n",
|
||
"g = \\sum_{k=1}^K p_{mk}(1-p_{mk}).\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "6f6dad5d",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"* Information entropy or just entropy $s$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "4fc9b106",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"$$\n",
|
||
"s = -\\sum_{k=1}^K p_{mk}\\log{p_{mk}}.\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "c92702f6",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Visualizing the Tree, Classification"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 10,
|
||
"id": "58fa3eab",
|
||
"metadata": {
|
||
"collapsed": false,
|
||
"editable": true
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"import os\n",
|
||
"from sklearn.datasets import load_breast_cancer\n",
|
||
"from sklearn.tree import DecisionTreeClassifier\n",
|
||
"from sklearn.model_selection import train_test_split\n",
|
||
"from sklearn.metrics import confusion_matrix\n",
|
||
"from sklearn.tree import export_graphviz\n",
|
||
"\n",
|
||
"from IPython.display import Image \n",
|
||
"from pydot import graph_from_dot_data\n",
|
||
"import pandas as pd\n",
|
||
"import numpy as np\n",
|
||
"\n",
|
||
"\n",
|
||
"cancer = load_breast_cancer()\n",
|
||
"X = pd.DataFrame(cancer.data, columns=cancer.feature_names)\n",
|
||
"print(X)\n",
|
||
"y = pd.Categorical.from_codes(cancer.target, cancer.target_names)\n",
|
||
"y = pd.get_dummies(y)\n",
|
||
"print(y)\n",
|
||
"X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1)\n",
|
||
"tree_clf = DecisionTreeClassifier(max_depth=5)\n",
|
||
"tree_clf.fit(X_train, y_train)\n",
|
||
"\n",
|
||
"export_graphviz(\n",
|
||
" tree_clf,\n",
|
||
" out_file=\"DataFiles/cancer.dot\",\n",
|
||
" feature_names=cancer.feature_names,\n",
|
||
" class_names=cancer.target_names,\n",
|
||
" rounded=True,\n",
|
||
" filled=True\n",
|
||
")\n",
|
||
"cmd = 'dot -Tpng DataFiles/cancer.dot -o DataFiles/cancer.png'\n",
|
||
"os.system(cmd)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "2f12bf79",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Visualizing the Tree, The Moons"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 11,
|
||
"id": "6987728d",
|
||
"metadata": {
|
||
"collapsed": false,
|
||
"editable": true
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"# Common imports\n",
|
||
"import numpy as np\n",
|
||
"from sklearn.model_selection import train_test_split \n",
|
||
"from sklearn.tree import DecisionTreeClassifier\n",
|
||
"from sklearn.datasets import make_moons\n",
|
||
"from sklearn.tree import export_graphviz\n",
|
||
"from pydot import graph_from_dot_data\n",
|
||
"import pandas as pd\n",
|
||
"import os\n",
|
||
"\n",
|
||
"np.random.seed(42)\n",
|
||
"X, y = make_moons(n_samples=100, noise=0.25, random_state=53)\n",
|
||
"X_train, X_test, y_train, y_test = train_test_split(X,y,random_state=0)\n",
|
||
"tree_clf = DecisionTreeClassifier(max_depth=5)\n",
|
||
"tree_clf.fit(X_train, y_train)\n",
|
||
"\n",
|
||
"export_graphviz(\n",
|
||
" tree_clf,\n",
|
||
" out_file=\"DataFiles/moons.dot\",\n",
|
||
" rounded=True,\n",
|
||
" filled=True\n",
|
||
")\n",
|
||
"cmd = 'dot -Tpng DataFiles/moons.dot -o DataFiles/moons.png'\n",
|
||
"os.system(cmd)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "dad046b8",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Other ways of visualizing the trees\n",
|
||
"\n",
|
||
"**Scikit-Learn** has also another way to visualize the trees which is very useful, here with the Iris data."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 12,
|
||
"id": "1d4f3161",
|
||
"metadata": {
|
||
"collapsed": false,
|
||
"editable": true
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"from sklearn.datasets import load_iris\n",
|
||
"from sklearn import tree\n",
|
||
"X, y = load_iris(return_X_y=True)\n",
|
||
"tree_clf = tree.DecisionTreeClassifier()\n",
|
||
"tree_clf = tree_clf.fit(X, y)\n",
|
||
"# and then plot the tree\n",
|
||
"tree.plot_tree(tree_clf)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "0846fdeb",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Printing out as text\n",
|
||
"\n",
|
||
"Alternatively, the tree can also be exported in textual format with the function exporttext.\n",
|
||
"This method doesn’t require the installation of external libraries and is more compact:"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 13,
|
||
"id": "cec3af4a",
|
||
"metadata": {
|
||
"collapsed": false,
|
||
"editable": true
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"from sklearn.datasets import load_iris\n",
|
||
"from sklearn.tree import DecisionTreeClassifier\n",
|
||
"from sklearn.tree import export_text\n",
|
||
"iris = load_iris()\n",
|
||
"decision_tree = DecisionTreeClassifier(random_state=0, max_depth=2)\n",
|
||
"decision_tree = decision_tree.fit(iris.data, iris.target)\n",
|
||
"r = export_text(decision_tree, feature_names=iris['feature_names'])\n",
|
||
"print(r)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "2c8a67db",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Algorithms for Setting up Decision Trees\n",
|
||
"\n",
|
||
"Two algorithms stand out in the set up of decision trees:\n",
|
||
"1. The CART (Classification And Regression Tree) algorithm for both classification and regression\n",
|
||
"\n",
|
||
"2. The ID3 algorithm based on the computation of the information gain for classification\n",
|
||
"\n",
|
||
"We discuss both algorithms with applications here. The popular library\n",
|
||
"**Scikit-Learn** uses the CART algorithm. For classification problems\n",
|
||
"you can use either the **gini** index or the **entropy** to split a tree\n",
|
||
"in two branches."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "354c280c",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## The CART algorithm for Classification\n",
|
||
"\n",
|
||
"For classification, the CART algorithm splits the data set in two subsets using a single feature $k$ and a threshold $t_k$.\n",
|
||
"This could be for example a threshold set by a number below a certain circumference of a malign tumor.\n",
|
||
"\n",
|
||
"How do we find these two quantities?\n",
|
||
"We search for the pair $(k,t_k)$ that produces the purest subset using for example the **gini** factor $G$.\n",
|
||
"The cost function it tries to minimize is then"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "7228e0b5",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"$$\n",
|
||
"C(k,t_k) = \\frac{m_{\\mathrm{left}}}{m}G_{\\mathrm{left}}+ \\frac{m_{\\mathrm{right}}}{m}G_{\\mathrm{right}},\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "67b083e1",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"where $G_{\\mathrm{left/right}}$ measures the impurity of the left/right subset and $m_{\\mathrm{left/right}}$\n",
|
||
" is the number of instances in the left/right subset\n",
|
||
"\n",
|
||
"Once it has successfully split the training set in two, it splits the subsets using the same logic, then the subsubsets\n",
|
||
"and so on, recursively. It stops recursing once it reaches the maximum depth (defined by the\n",
|
||
"$max\\_depth$ hyperparameter), or if it cannot find a split that will reduce impurity. A few other\n",
|
||
"hyperparameters control additional stopping conditions such as the $min\\_samples\\_split$,\n",
|
||
"$min\\_samples\\_leaf$, $min\\_weight\\_fraction\\_leaf$, and $max\\_leaf\\_nodes$."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "8fdfcd7f",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## The CART algorithm for Regression\n",
|
||
"\n",
|
||
"The CART algorithm for regression works is similar to the one for classification except that instead of trying to split the\n",
|
||
"training set in a way that minimizes say the **gini** or **entropy** impurity, it now tries to split the training set in a way that minimizes our well-known mean-squared error (MSE). The cost function is now"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "80ef07be",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"$$\n",
|
||
"C(k,t_k) = \\frac{m_{\\mathrm{left}}}{m}\\mathrm{MSE}_{\\mathrm{left}}+ \\frac{m_{\\mathrm{right}}}{m}\\mathrm{MSE}_{\\mathrm{right}}.\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "2b96ed0b",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"Here the MSE for a specific node is defined as"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "31573190",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"$$\n",
|
||
"\\mathrm{MSE}_{\\mathrm{node}}=\\frac{1}{m_\\mathrm{node}}\\sum_{i\\in \\mathrm{node}}(\\overline{y}_{\\mathrm{node}}-y_i)^2,\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "2bbfe053",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"with"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "e32e4576",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"$$\n",
|
||
"\\overline{y}_{\\mathrm{node}}=\\frac{1}{m_\\mathrm{node}}\\sum_{i\\in \\mathrm{node}}y_i,\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "1ad8a276",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"the mean value of all observations in a specific node.\n",
|
||
"\n",
|
||
"Without any regularization, the regression task for decision trees, \n",
|
||
"just like for classification tasks, is prone to overfitting."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "21a60563",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Computing the Gini index\n",
|
||
"\n",
|
||
"The example we will look at is a classical one in many Machine\n",
|
||
"Learning applications. Based on various meteorological features, we\n",
|
||
"have several so-called attributes which decide whether we at the end\n",
|
||
"will do some outdoor activity like skiing, going for a bike ride etc\n",
|
||
"etc. The table here contains the feautures **outlook**, **temperature**,\n",
|
||
"**humidity** and **wind**. The target or output is whether we ride\n",
|
||
"(True=1) or whether we do something else that day (False=0). The\n",
|
||
"attributes for each feature are then sunny, overcast and rain for the\n",
|
||
"outlook, hot, cold and mild for temperature, high and normal for\n",
|
||
"humidity and weak and strong for wind.\n",
|
||
"\n",
|
||
"The table here summarizes the various attributes and\n",
|
||
"<table class=\"dotable\" border=\"1\">\n",
|
||
"<thead>\n",
|
||
"<tr><th align=\"center\">Day</th> <th align=\"center\">Outlook </th> <th align=\"center\">Temperature</th> <th align=\"center\">Humidity</th> <th align=\"center\"> Wind </th> <th align=\"center\">Ride</th> </tr>\n",
|
||
"</thead>\n",
|
||
"<tbody>\n",
|
||
"<tr><td align=\"center\"> 1 </td> <td align=\"center\"> Sunny </td> <td align=\"center\"> Hot </td> <td align=\"center\"> High </td> <td align=\"center\"> Weak </td> <td align=\"center\"> 0 </td> </tr>\n",
|
||
"<tr><td align=\"center\"> 2 </td> <td align=\"center\"> Sunny </td> <td align=\"center\"> Hot </td> <td align=\"center\"> High </td> <td align=\"center\"> Strong </td> <td align=\"center\"> 1 </td> </tr>\n",
|
||
"<tr><td align=\"center\"> 3 </td> <td align=\"center\"> Overcast </td> <td align=\"center\"> Hot </td> <td align=\"center\"> High </td> <td align=\"center\"> Weak </td> <td align=\"center\"> 1 </td> </tr>\n",
|
||
"<tr><td align=\"center\"> 4 </td> <td align=\"center\"> Rain </td> <td align=\"center\"> Mild </td> <td align=\"center\"> High </td> <td align=\"center\"> Weak </td> <td align=\"center\"> 1 </td> </tr>\n",
|
||
"<tr><td align=\"center\"> 5 </td> <td align=\"center\"> Rain </td> <td align=\"center\"> Cool </td> <td align=\"center\"> Normal </td> <td align=\"center\"> Weak </td> <td align=\"center\"> 1 </td> </tr>\n",
|
||
"<tr><td align=\"center\"> 6 </td> <td align=\"center\"> Rain </td> <td align=\"center\"> Cool </td> <td align=\"center\"> Normal </td> <td align=\"center\"> Strong </td> <td align=\"center\"> 0 </td> </tr>\n",
|
||
"<tr><td align=\"center\"> 7 </td> <td align=\"center\"> Overcast </td> <td align=\"center\"> Cool </td> <td align=\"center\"> Normal </td> <td align=\"center\"> Strong </td> <td align=\"center\"> 1 </td> </tr>\n",
|
||
"<tr><td align=\"center\"> 8 </td> <td align=\"center\"> Sunny </td> <td align=\"center\"> Mild </td> <td align=\"center\"> High </td> <td align=\"center\"> Weak </td> <td align=\"center\"> 0 </td> </tr>\n",
|
||
"<tr><td align=\"center\"> 9 </td> <td align=\"center\"> Sunny </td> <td align=\"center\"> Cool </td> <td align=\"center\"> Normal </td> <td align=\"center\"> Weak </td> <td align=\"center\"> 1 </td> </tr>\n",
|
||
"<tr><td align=\"center\"> 10 </td> <td align=\"center\"> Rain </td> <td align=\"center\"> Mild </td> <td align=\"center\"> Normal </td> <td align=\"center\"> Weak </td> <td align=\"center\"> 1 </td> </tr>\n",
|
||
"<tr><td align=\"center\"> 11 </td> <td align=\"center\"> Sunny </td> <td align=\"center\"> Mild </td> <td align=\"center\"> Normal </td> <td align=\"center\"> Strong </td> <td align=\"center\"> 1 </td> </tr>\n",
|
||
"<tr><td align=\"center\"> 12 </td> <td align=\"center\"> Overcast </td> <td align=\"center\"> Mild </td> <td align=\"center\"> High </td> <td align=\"center\"> Strong </td> <td align=\"center\"> 1 </td> </tr>\n",
|
||
"<tr><td align=\"center\"> 13 </td> <td align=\"center\"> Overcast </td> <td align=\"center\"> Hot </td> <td align=\"center\"> Normal </td> <td align=\"center\"> Weak </td> <td align=\"center\"> 1 </td> </tr>\n",
|
||
"<tr><td align=\"center\"> 14 </td> <td align=\"center\"> Rain </td> <td align=\"center\"> Mild </td> <td align=\"center\"> High </td> <td align=\"center\"> Strong </td> <td align=\"center\"> 0 </td> </tr>\n",
|
||
"</tbody>\n",
|
||
"</table>"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "0caa4189",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Simple Python Code to read in Data and perform Classification"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 14,
|
||
"id": "ab4c5d94",
|
||
"metadata": {
|
||
"collapsed": false,
|
||
"editable": true
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"# Common imports\n",
|
||
"import numpy as np\n",
|
||
"import pandas as pd\n",
|
||
"import matplotlib.pyplot as plt\n",
|
||
"from sklearn.tree import DecisionTreeClassifier\n",
|
||
"from sklearn.model_selection import train_test_split\n",
|
||
"from sklearn.tree import export_graphviz\n",
|
||
"from sklearn.preprocessing import StandardScaler, OneHotEncoder\n",
|
||
"from sklearn.compose import ColumnTransformer\n",
|
||
"from IPython.display import Image \n",
|
||
"from pydot import graph_from_dot_data\n",
|
||
"import os\n",
|
||
"\n",
|
||
"# Where to save the figures and data files\n",
|
||
"PROJECT_ROOT_DIR = \"Results\"\n",
|
||
"FIGURE_ID = \"Results/FigureFiles\"\n",
|
||
"DATA_ID = \"DataFiles/\"\n",
|
||
"\n",
|
||
"if not os.path.exists(PROJECT_ROOT_DIR):\n",
|
||
" os.mkdir(PROJECT_ROOT_DIR)\n",
|
||
"\n",
|
||
"if not os.path.exists(FIGURE_ID):\n",
|
||
" os.makedirs(FIGURE_ID)\n",
|
||
"\n",
|
||
"if not os.path.exists(DATA_ID):\n",
|
||
" os.makedirs(DATA_ID)\n",
|
||
"\n",
|
||
"def image_path(fig_id):\n",
|
||
" return os.path.join(FIGURE_ID, fig_id)\n",
|
||
"\n",
|
||
"def data_path(dat_id):\n",
|
||
" return os.path.join(DATA_ID, dat_id)\n",
|
||
"\n",
|
||
"def save_fig(fig_id):\n",
|
||
" plt.savefig(image_path(fig_id) + \".png\", format='png')\n",
|
||
"\n",
|
||
"infile = open(data_path(\"rideclass.csv\"),'r')\n",
|
||
"\n",
|
||
"# Read the experimental data with Pandas\n",
|
||
"from IPython.display import display\n",
|
||
"ridedata = pd.read_csv(infile,names = ('Outlook','Temperature','Humidity','Wind','Ride'))\n",
|
||
"ridedata = pd.DataFrame(ridedata)\n",
|
||
"\n",
|
||
"# Features and targets\n",
|
||
"X = ridedata.loc[:, ridedata.columns != 'Ride'].values\n",
|
||
"y = ridedata.loc[:, ridedata.columns == 'Ride'].values\n",
|
||
"\n",
|
||
"# Create the encoder.\n",
|
||
"encoder = OneHotEncoder(handle_unknown=\"ignore\")\n",
|
||
"# Assume for simplicity all features are categorical.\n",
|
||
"encoder.fit(X) \n",
|
||
"# Apply the encoder.\n",
|
||
"X = encoder.transform(X)\n",
|
||
"print(X)\n",
|
||
"# Then do a Classification tree\n",
|
||
"tree_clf = DecisionTreeClassifier(max_depth=2)\n",
|
||
"tree_clf.fit(X, y)\n",
|
||
"print(\"Train set accuracy with Decision Tree: {:.2f}\".format(tree_clf.score(X,y)))\n",
|
||
"#transfer to a decision tree graph\n",
|
||
"export_graphviz(\n",
|
||
" tree_clf,\n",
|
||
" out_file=\"DataFiles/ride.dot\",\n",
|
||
" rounded=True,\n",
|
||
" filled=True\n",
|
||
")\n",
|
||
"cmd = 'dot -Tpng DataFiles/cancer.dot -o DataFiles/cancer.png'\n",
|
||
"os.system(cmd)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "70c2a16d",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Computing the Gini Factor\n",
|
||
"\n",
|
||
"The above functions (gini, entropy and misclassification error) are\n",
|
||
"important components of the so-called CART algorithm. We will discuss\n",
|
||
"this algorithm below after we have discussed the information gain\n",
|
||
"algorithm ID3.\n",
|
||
"\n",
|
||
"In the example here we have converted all our attributes into numerical values $0,1,2$ etc."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 15,
|
||
"id": "40e079d4",
|
||
"metadata": {
|
||
"collapsed": false,
|
||
"editable": true
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"# Split a dataset based on an attribute and an attribute value\n",
|
||
"def test_split(index, value, dataset):\n",
|
||
"\tleft, right = list(), list()\n",
|
||
"\tfor row in dataset:\n",
|
||
"\t\tif row[index] < value:\n",
|
||
"\t\t\tleft.append(row)\n",
|
||
"\t\telse:\n",
|
||
"\t\t\tright.append(row)\n",
|
||
"\treturn left, right\n",
|
||
" \n",
|
||
"# Calculate the Gini index for a split dataset\n",
|
||
"def gini_index(groups, classes):\n",
|
||
"\t# count all samples at split point\n",
|
||
"\tn_instances = float(sum([len(group) for group in groups]))\n",
|
||
"\t# sum weighted Gini index for each group\n",
|
||
"\tgini = 0.0\n",
|
||
"\tfor group in groups:\n",
|
||
"\t\tsize = float(len(group))\n",
|
||
"\t\t# avoid divide by zero\n",
|
||
"\t\tif size == 0:\n",
|
||
"\t\t\tcontinue\n",
|
||
"\t\tscore = 0.0\n",
|
||
"\t\t# score the group based on the score for each class\n",
|
||
"\t\tfor class_val in classes:\n",
|
||
"\t\t\tp = [row[-1] for row in group].count(class_val) / size\n",
|
||
"\t\t\tscore += p * p\n",
|
||
"\t\t# weight the group score by its relative size\n",
|
||
"\t\tgini += (1.0 - score) * (size / n_instances)\n",
|
||
"\treturn gini\n",
|
||
"\n",
|
||
"# Select the best split point for a dataset\n",
|
||
"def get_split(dataset):\n",
|
||
"\tclass_values = list(set(row[-1] for row in dataset))\n",
|
||
"\tb_index, b_value, b_score, b_groups = 999, 999, 999, None\n",
|
||
"\tfor index in range(len(dataset[0])-1):\n",
|
||
"\t\tfor row in dataset:\n",
|
||
"\t\t\tgroups = test_split(index, row[index], dataset)\n",
|
||
"\t\t\tgini = gini_index(groups, class_values)\n",
|
||
"\t\t\tprint('X%d < %.3f Gini=%.3f' % ((index+1), row[index], gini))\n",
|
||
"\t\t\tif gini < b_score:\n",
|
||
"\t\t\t\tb_index, b_value, b_score, b_groups = index, row[index], gini, groups\n",
|
||
"\treturn {'index':b_index, 'value':b_value, 'groups':b_groups}\n",
|
||
" \n",
|
||
"dataset = [[0,0,0,0,0],\n",
|
||
" [0,0,0,1,1],\n",
|
||
" [1,0,0,0,1],\n",
|
||
" [2,1,0,0,1],\n",
|
||
" [2,2,1,0,1],\n",
|
||
" [2,2,1,1,0],\n",
|
||
" [1,2,1,1,1],\n",
|
||
" [0,1,0,0,0],\n",
|
||
" [0,2,1,0,1],\n",
|
||
" [2,1,1,0,1],\n",
|
||
" [0,1,1,1,1],\n",
|
||
" [1,1,0,1,1],\n",
|
||
" [1,0,1,0,1],\n",
|
||
" [2,1,0,1,0]]\n",
|
||
"\n",
|
||
"split = get_split(dataset)\n",
|
||
"print('Split: [X%d < %.3f]' % ((split['index']+1), split['value']))"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "4095e4a7",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Entropy and the ID3 algorithm\n",
|
||
"\n",
|
||
"The ID3 algorithm learns decision trees by constructing\n",
|
||
"them in a top down way, beginning with the question **which attribute should be tested at the root of the tree**?\n",
|
||
"\n",
|
||
"1. Each instance attribute is evaluated using a statistical test to determine how well it alone classifies the training examples.\n",
|
||
"\n",
|
||
"2. The best attribute is selected and used as the test at the root node of the tree.\n",
|
||
"\n",
|
||
"3. A descendant of the root node is then created for each possible value of this attribute.\n",
|
||
"\n",
|
||
"4. Training examples are sorted to the appropriate descendant node.\n",
|
||
"\n",
|
||
"5. The entire process is then repeated using the training examples associated with each descendant node to select the best attribute to test at that point in the tree.\n",
|
||
"\n",
|
||
"6. This forms a greedy search for an acceptable decision tree, in which the algorithm never backtracks to reconsider earlier choices. \n",
|
||
"\n",
|
||
"The ID3 algorithm selects which attribute to test at each node in the\n",
|
||
"tree.\n",
|
||
"\n",
|
||
"We would like to select the attribute that is most useful for classifying\n",
|
||
"examples.\n",
|
||
"\n",
|
||
"What is a good quantitative measure of the worth of an attribute?\n",
|
||
"\n",
|
||
"Information gain measures how well a given attribute separates the\n",
|
||
"training examples according to their target classification.\n",
|
||
"\n",
|
||
"The ID3 algorithm uses this information gain measure to select among the candidate\n",
|
||
"attributes at each step while growing the tree."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "ef376633",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Cancer Data again now with Decision Trees and other Methods"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 16,
|
||
"id": "118884b2",
|
||
"metadata": {
|
||
"collapsed": false,
|
||
"editable": true
|
||
},
|
||
"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",
|
||
"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)))"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "fa9f54b6",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Another example, the moons again"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 17,
|
||
"id": "205c19aa",
|
||
"metadata": {
|
||
"collapsed": false,
|
||
"editable": true
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"from __future__ import division, print_function, unicode_literals\n",
|
||
"\n",
|
||
"# Common imports\n",
|
||
"import numpy as np\n",
|
||
"import os\n",
|
||
"\n",
|
||
"# to make this notebook's output stable across runs\n",
|
||
"np.random.seed(42)\n",
|
||
"\n",
|
||
"# To plot pretty figures\n",
|
||
"import matplotlib\n",
|
||
"import matplotlib.pyplot as plt\n",
|
||
"from matplotlib.colors import ListedColormap\n",
|
||
"plt.rcParams['axes.labelsize'] = 14\n",
|
||
"plt.rcParams['xtick.labelsize'] = 12\n",
|
||
"plt.rcParams['ytick.labelsize'] = 12\n",
|
||
"\n",
|
||
"\n",
|
||
"from sklearn.svm import SVC\n",
|
||
"from sklearn import datasets\n",
|
||
"from sklearn.tree import DecisionTreeClassifier\n",
|
||
"from sklearn.datasets import make_moons\n",
|
||
"from sklearn.tree import export_graphviz\n",
|
||
"\n",
|
||
"Xm, ym = make_moons(n_samples=100, noise=0.25, random_state=53)\n",
|
||
"\n",
|
||
"deep_tree_clf1 = DecisionTreeClassifier(random_state=42)\n",
|
||
"deep_tree_clf2 = DecisionTreeClassifier(min_samples_leaf=4, random_state=42)\n",
|
||
"deep_tree_clf1.fit(Xm, ym)\n",
|
||
"deep_tree_clf2.fit(Xm, ym)\n",
|
||
"\n",
|
||
"\n",
|
||
"def plot_decision_boundary(clf, X, y, axes=[0, 7.5, 0, 3], iris=True, legend=False, plot_training=True):\n",
|
||
" x1s = np.linspace(axes[0], axes[1], 100)\n",
|
||
" x2s = np.linspace(axes[2], axes[3], 100)\n",
|
||
" x1, x2 = np.meshgrid(x1s, x2s)\n",
|
||
" X_new = np.c_[x1.ravel(), x2.ravel()]\n",
|
||
" y_pred = clf.predict(X_new).reshape(x1.shape)\n",
|
||
" custom_cmap = ListedColormap(['#fafab0','#9898ff','#a0faa0'])\n",
|
||
" plt.contourf(x1, x2, y_pred, alpha=0.3, cmap=custom_cmap)\n",
|
||
" if not iris:\n",
|
||
" custom_cmap2 = ListedColormap(['#7d7d58','#4c4c7f','#507d50'])\n",
|
||
" plt.contour(x1, x2, y_pred, cmap=custom_cmap2, alpha=0.8)\n",
|
||
" if plot_training:\n",
|
||
" plt.plot(X[:, 0][y==0], X[:, 1][y==0], \"yo\", label=\"Iris-Setosa\")\n",
|
||
" plt.plot(X[:, 0][y==1], X[:, 1][y==1], \"bs\", label=\"Iris-Versicolor\")\n",
|
||
" plt.plot(X[:, 0][y==2], X[:, 1][y==2], \"g^\", label=\"Iris-Virginica\")\n",
|
||
" plt.axis(axes)\n",
|
||
" if iris:\n",
|
||
" plt.xlabel(\"Petal length\", fontsize=14)\n",
|
||
" plt.ylabel(\"Petal width\", fontsize=14)\n",
|
||
" else:\n",
|
||
" plt.xlabel(r\"$x_1$\", fontsize=18)\n",
|
||
" plt.ylabel(r\"$x_2$\", fontsize=18, rotation=0)\n",
|
||
" if legend:\n",
|
||
" plt.legend(loc=\"lower right\", fontsize=14)\n",
|
||
"plt.figure(figsize=(11, 4))\n",
|
||
"plt.subplot(121)\n",
|
||
"plot_decision_boundary(deep_tree_clf1, Xm, ym, axes=[-1.5, 2.5, -1, 1.5], iris=False)\n",
|
||
"plt.title(\"No restrictions\", fontsize=16)\n",
|
||
"plt.subplot(122)\n",
|
||
"plot_decision_boundary(deep_tree_clf2, Xm, ym, axes=[-1.5, 2.5, -1, 1.5], iris=False)\n",
|
||
"plt.title(\"min_samples_leaf = {}\".format(deep_tree_clf2.min_samples_leaf), fontsize=14)\n",
|
||
"plt.show()"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "3067d1e9",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Playing around with regions"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 18,
|
||
"id": "18ca2b62",
|
||
"metadata": {
|
||
"collapsed": false,
|
||
"editable": true
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"np.random.seed(6)\n",
|
||
"Xs = np.random.rand(100, 2) - 0.5\n",
|
||
"ys = (Xs[:, 0] > 0).astype(np.float32) * 2\n",
|
||
"\n",
|
||
"angle = np.pi/4\n",
|
||
"rotation_matrix = np.array([[np.cos(angle), -np.sin(angle)], [np.sin(angle), np.cos(angle)]])\n",
|
||
"Xsr = Xs.dot(rotation_matrix)\n",
|
||
"\n",
|
||
"tree_clf_s = DecisionTreeClassifier(random_state=42)\n",
|
||
"tree_clf_s.fit(Xs, ys)\n",
|
||
"tree_clf_sr = DecisionTreeClassifier(random_state=42)\n",
|
||
"tree_clf_sr.fit(Xsr, ys)\n",
|
||
"\n",
|
||
"plt.figure(figsize=(11, 4))\n",
|
||
"plt.subplot(121)\n",
|
||
"plot_decision_boundary(tree_clf_s, Xs, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False)\n",
|
||
"plt.subplot(122)\n",
|
||
"plot_decision_boundary(tree_clf_sr, Xsr, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False)\n",
|
||
"\n",
|
||
"plt.show()"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "3428a271",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Regression trees"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 19,
|
||
"id": "2a8ee09c",
|
||
"metadata": {
|
||
"collapsed": false,
|
||
"editable": true
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"# Quadratic training set + noise\n",
|
||
"np.random.seed(42)\n",
|
||
"m = 200\n",
|
||
"X = np.random.rand(m, 1)\n",
|
||
"y = 4 * (X - 0.5) ** 2\n",
|
||
"y = y + np.random.randn(m, 1) / 10"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 20,
|
||
"id": "7bd7a8fe",
|
||
"metadata": {
|
||
"collapsed": false,
|
||
"editable": true
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"from sklearn.tree import DecisionTreeRegressor\n",
|
||
"\n",
|
||
"tree_reg = DecisionTreeRegressor(max_depth=2, random_state=42)\n",
|
||
"tree_reg.fit(X, y)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "7cd9b121",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Final regressor code"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 21,
|
||
"id": "9f73e61d",
|
||
"metadata": {
|
||
"collapsed": false,
|
||
"editable": true
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"from sklearn.tree import DecisionTreeRegressor\n",
|
||
"\n",
|
||
"tree_reg1 = DecisionTreeRegressor(random_state=42, max_depth=2)\n",
|
||
"tree_reg2 = DecisionTreeRegressor(random_state=42, max_depth=3)\n",
|
||
"tree_reg1.fit(X, y)\n",
|
||
"tree_reg2.fit(X, y)\n",
|
||
"\n",
|
||
"def plot_regression_predictions(tree_reg, X, y, axes=[0, 1, -0.2, 1], ylabel=\"$y$\"):\n",
|
||
" x1 = np.linspace(axes[0], axes[1], 500).reshape(-1, 1)\n",
|
||
" y_pred = tree_reg.predict(x1)\n",
|
||
" plt.axis(axes)\n",
|
||
" plt.xlabel(\"$x_1$\", fontsize=18)\n",
|
||
" if ylabel:\n",
|
||
" plt.ylabel(ylabel, fontsize=18, rotation=0)\n",
|
||
" plt.plot(X, y, \"b.\")\n",
|
||
" plt.plot(x1, y_pred, \"r.-\", linewidth=2, label=r\"$\\hat{y}$\")\n",
|
||
"\n",
|
||
"plt.figure(figsize=(11, 4))\n",
|
||
"plt.subplot(121)\n",
|
||
"plot_regression_predictions(tree_reg1, X, y)\n",
|
||
"for split, style in ((0.1973, \"k-\"), (0.0917, \"k--\"), (0.7718, \"k--\")):\n",
|
||
" plt.plot([split, split], [-0.2, 1], style, linewidth=2)\n",
|
||
"plt.text(0.21, 0.65, \"Depth=0\", fontsize=15)\n",
|
||
"plt.text(0.01, 0.2, \"Depth=1\", fontsize=13)\n",
|
||
"plt.text(0.65, 0.8, \"Depth=1\", fontsize=13)\n",
|
||
"plt.legend(loc=\"upper center\", fontsize=18)\n",
|
||
"plt.title(\"max_depth=2\", fontsize=14)\n",
|
||
"\n",
|
||
"plt.subplot(122)\n",
|
||
"plot_regression_predictions(tree_reg2, X, y, ylabel=None)\n",
|
||
"for split, style in ((0.1973, \"k-\"), (0.0917, \"k--\"), (0.7718, \"k--\")):\n",
|
||
" plt.plot([split, split], [-0.2, 1], style, linewidth=2)\n",
|
||
"for split in (0.0458, 0.1298, 0.2873, 0.9040):\n",
|
||
" plt.plot([split, split], [-0.2, 1], \"k:\", linewidth=1)\n",
|
||
"plt.text(0.3, 0.5, \"Depth=2\", fontsize=13)\n",
|
||
"plt.title(\"max_depth=3\", fontsize=14)\n",
|
||
"\n",
|
||
"plt.show()"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 22,
|
||
"id": "9217ab82",
|
||
"metadata": {
|
||
"collapsed": false,
|
||
"editable": true
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"tree_reg1 = DecisionTreeRegressor(random_state=42)\n",
|
||
"tree_reg2 = DecisionTreeRegressor(random_state=42, min_samples_leaf=10)\n",
|
||
"tree_reg1.fit(X, y)\n",
|
||
"tree_reg2.fit(X, y)\n",
|
||
"\n",
|
||
"x1 = np.linspace(0, 1, 500).reshape(-1, 1)\n",
|
||
"y_pred1 = tree_reg1.predict(x1)\n",
|
||
"y_pred2 = tree_reg2.predict(x1)\n",
|
||
"\n",
|
||
"plt.figure(figsize=(11, 4))\n",
|
||
"\n",
|
||
"plt.subplot(121)\n",
|
||
"plt.plot(X, y, \"b.\")\n",
|
||
"plt.plot(x1, y_pred1, \"r.-\", linewidth=2, label=r\"$\\hat{y}$\")\n",
|
||
"plt.axis([0, 1, -0.2, 1.1])\n",
|
||
"plt.xlabel(\"$x_1$\", fontsize=18)\n",
|
||
"plt.ylabel(\"$y$\", fontsize=18, rotation=0)\n",
|
||
"plt.legend(loc=\"upper center\", fontsize=18)\n",
|
||
"plt.title(\"No restrictions\", fontsize=14)\n",
|
||
"\n",
|
||
"plt.subplot(122)\n",
|
||
"plt.plot(X, y, \"b.\")\n",
|
||
"plt.plot(x1, y_pred2, \"r.-\", linewidth=2, label=r\"$\\hat{y}$\")\n",
|
||
"plt.axis([0, 1, -0.2, 1.1])\n",
|
||
"plt.xlabel(\"$x_1$\", fontsize=18)\n",
|
||
"plt.title(\"min_samples_leaf={}\".format(tree_reg2.min_samples_leaf), fontsize=14)\n",
|
||
"\n",
|
||
"plt.show()"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "0b3f13c6",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Pros and cons of trees, pros\n",
|
||
"\n",
|
||
"* White box, easy to interpret model. Some people believe that decision trees more closely mirror human decision-making than do the regression and classification approaches discussed earlier (think of support vector machines)\n",
|
||
"\n",
|
||
"* Trees are very easy to explain to people. In fact, they are even easier to explain than linear regression!\n",
|
||
"\n",
|
||
"* No feature normalization needed\n",
|
||
"\n",
|
||
"* Tree models can handle both continuous and categorical data (Classification and Regression Trees)\n",
|
||
"\n",
|
||
"* Can model nonlinear relationships\n",
|
||
"\n",
|
||
"* Can model interactions between the different descriptive features\n",
|
||
"\n",
|
||
"* Trees can be displayed graphically, and are easily interpreted even by a non-expert (especially if they are small)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "f0bbefac",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Disadvantages\n",
|
||
"\n",
|
||
"* Unfortunately, trees generally do not have the same level of predictive accuracy as some of the other regression and classification approaches\n",
|
||
"\n",
|
||
"* If continuous features are used the tree may become quite large and hence less interpretable\n",
|
||
"\n",
|
||
"* Decision trees are prone to overfit the training data and hence do not well generalize the data if no stopping criteria or improvements like pruning, boosting or bagging are implemented\n",
|
||
"\n",
|
||
"* Small changes in the data may lead to a completely different tree. This issue can be addressed by using ensemble methods like bagging, boosting or random forests\n",
|
||
"\n",
|
||
"* Unbalanced datasets where some target feature values occur much more frequently than others may lead to biased trees since the frequently occurring feature values are preferred over the less frequently occurring ones. \n",
|
||
"\n",
|
||
"* If the number of features is relatively large (high dimensional) and the number of instances is relatively low, the tree might overfit the data\n",
|
||
"\n",
|
||
"* Features with many levels may be preferred over features with less levels since for them it is *more easy* to split the dataset such that the sub datasets only contain pure target feature values. This issue can be addressed by preferring for instance the information gain ratio as splitting criteria over information gain\n",
|
||
"\n",
|
||
"However, by aggregating many decision trees, using methods like\n",
|
||
"bagging, random forests, and boosting, the predictive performance of\n",
|
||
"trees can be substantially improved."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "e902924d",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Ensemble Methods: From a Single Tree to Many Trees and Extreme Boosting, Meet the Jungle of Methods\n",
|
||
"\n",
|
||
"As stated above and seen in many of the examples discussed here about\n",
|
||
"a single decision tree, we often end up overfitting our training\n",
|
||
"data. This normally means that we have a high variance. Can we reduce\n",
|
||
"the variance of a statistical learning method?\n",
|
||
"\n",
|
||
"This leads us to a set of different methods that can combine different\n",
|
||
"machine learning algorithms or just use one of them to construct\n",
|
||
"forests and jungles of trees, homogeneous ones or heterogenous\n",
|
||
"ones. These methods are recognized by different names which we will\n",
|
||
"try to explain here. These are\n",
|
||
"\n",
|
||
"1. Voting classifiers\n",
|
||
"\n",
|
||
"2. Bagging and Pasting\n",
|
||
"\n",
|
||
"3. Random forests\n",
|
||
"\n",
|
||
"4. Boosting methods, from adaptive to Extreme Gradient Boosting (XGBoost)\n",
|
||
"\n",
|
||
"We discuss these methods here."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "73f6e3a6",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## An Overview of Ensemble Methods\n",
|
||
"\n",
|
||
"<!-- dom:FIGURE: [DataFiles/ensembleoverview.png, width=600 frac=0.8] -->\n",
|
||
"<!-- begin figure -->\n",
|
||
"\n",
|
||
"<img src=\"DataFiles/ensembleoverview.png\" width=\"600\"><p style=\"font-size: 0.9em\"><i>Figure 1: </i></p>\n",
|
||
"<!-- end figure -->"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "4b2c2032",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Bagging\n",
|
||
"\n",
|
||
"The **plain** decision trees suffer from high\n",
|
||
"variance. This means that if we split the training data into two parts\n",
|
||
"at random, and fit a decision tree to both halves, the results that we\n",
|
||
"get could be quite different. In contrast, a procedure with low\n",
|
||
"variance will yield similar results if applied repeatedly to distinct\n",
|
||
"data sets; linear regression tends to have low variance, if the ratio\n",
|
||
"of $n$ to $p$ is moderately large. \n",
|
||
"\n",
|
||
"**Bootstrap aggregation**, or just **bagging**, is a\n",
|
||
"general-purpose procedure for reducing the variance of a statistical\n",
|
||
"learning method."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "8bbfa991",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## More bagging\n",
|
||
"\n",
|
||
"Bagging typically results in improved accuracy\n",
|
||
"over prediction using a single tree. Unfortunately, however, it can be\n",
|
||
"difficult to interpret the resulting model. Recall that one of the\n",
|
||
"advantages of decision trees is the attractive and easily interpreted\n",
|
||
"diagram that results.\n",
|
||
"\n",
|
||
"However, when we bag a large number of trees, it is no longer\n",
|
||
"possible to represent the resulting statistical learning procedure\n",
|
||
"using a single tree, and it is no longer clear which variables are\n",
|
||
"most important to the procedure. Thus, bagging improves prediction\n",
|
||
"accuracy at the expense of interpretability. Although the collection\n",
|
||
"of bagged trees is much more difficult to interpret than a single\n",
|
||
"tree, one can obtain an overall summary of the importance of each\n",
|
||
"predictor using the MSE (for bagging regression trees) or the Gini\n",
|
||
"index (for bagging classification trees). In the case of bagging\n",
|
||
"regression trees, we can record the total amount that the MSE is\n",
|
||
"decreased due to splits over a given predictor, averaged over all $B$ possible\n",
|
||
"trees. A large value indicates an important predictor. Similarly, in\n",
|
||
"the context of bagging classification trees, we can add up the total\n",
|
||
"amount that the Gini index is decreased by splits over a given\n",
|
||
"predictor, averaged over all $B$ trees."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "a0ee40c7",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Simple Voting Example, head or tail"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 23,
|
||
"id": "9d71a00f",
|
||
"metadata": {
|
||
"collapsed": false,
|
||
"editable": true
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"heads_proba = 0.51\n",
|
||
"coin_tosses = (np.random.rand(10000, 10) < heads_proba).astype(np.int32)\n",
|
||
"cumulative_heads_ratio = np.cumsum(coin_tosses, axis=0) / np.arange(1, 10001).reshape(-1, 1)\n",
|
||
"plt.figure(figsize=(8,3.5))\n",
|
||
"plt.plot(cumulative_heads_ratio)\n",
|
||
"plt.plot([0, 10000], [0.51, 0.51], \"k--\", linewidth=2, label=\"51%\")\n",
|
||
"plt.plot([0, 10000], [0.5, 0.5], \"k-\", label=\"50%\")\n",
|
||
"plt.xlabel(\"Number of coin tosses\")\n",
|
||
"plt.ylabel(\"Heads ratio\")\n",
|
||
"plt.legend(loc=\"lower right\")\n",
|
||
"plt.axis([0, 10000, 0.42, 0.58])\n",
|
||
"save_fig(\"votingsimple\")\n",
|
||
"plt.show()"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "bd4ba90d",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Using the Voting Classifier"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 24,
|
||
"id": "d4c3e9d8",
|
||
"metadata": {
|
||
"collapsed": false,
|
||
"editable": true
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"from sklearn.model_selection import train_test_split\n",
|
||
"from sklearn.datasets import make_moons\n",
|
||
"\n",
|
||
"X, y = make_moons(n_samples=500, noise=0.30, random_state=42)\n",
|
||
"X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)\n",
|
||
"\n",
|
||
"from sklearn.ensemble import RandomForestClassifier\n",
|
||
"from sklearn.ensemble import VotingClassifier\n",
|
||
"from sklearn.linear_model import LogisticRegression\n",
|
||
"from sklearn.svm import SVC\n",
|
||
"\n",
|
||
"log_clf = LogisticRegression(solver=\"liblinear\", random_state=42)\n",
|
||
"rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42)\n",
|
||
"svm_clf = SVC(gamma=\"auto\", random_state=42)\n",
|
||
"\n",
|
||
"voting_clf = VotingClassifier(\n",
|
||
" estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],\n",
|
||
" voting='hard')\n",
|
||
"\n",
|
||
"voting_clf.fit(X_train, y_train)\n",
|
||
"\n",
|
||
"from sklearn.metrics import accuracy_score\n",
|
||
"\n",
|
||
"for clf in (log_clf, rnd_clf, svm_clf, voting_clf):\n",
|
||
" clf.fit(X_train, y_train)\n",
|
||
" y_pred = clf.predict(X_test)\n",
|
||
" print(clf.__class__.__name__, accuracy_score(y_test, y_pred))\n",
|
||
"\n",
|
||
"log_clf = LogisticRegression(solver=\"liblinear\", random_state=42)\n",
|
||
"rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42)\n",
|
||
"svm_clf = SVC(gamma=\"auto\", probability=True, random_state=42)\n",
|
||
"\n",
|
||
"voting_clf = VotingClassifier(\n",
|
||
" estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],\n",
|
||
" voting='soft')\n",
|
||
"voting_clf.fit(X_train, y_train)\n",
|
||
"\n",
|
||
"from sklearn.metrics import accuracy_score\n",
|
||
"\n",
|
||
"for clf in (log_clf, rnd_clf, svm_clf, voting_clf):\n",
|
||
" clf.fit(X_train, y_train)\n",
|
||
" y_pred = clf.predict(X_test)\n",
|
||
" print(clf.__class__.__name__, accuracy_score(y_test, y_pred))"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "2a5acbf8",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Please, not the moons again! Voting and Bagging"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 25,
|
||
"id": "e1831a75",
|
||
"metadata": {
|
||
"collapsed": false,
|
||
"editable": true
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"from sklearn.model_selection import train_test_split\n",
|
||
"from sklearn.datasets import make_moons\n",
|
||
"\n",
|
||
"X, y = make_moons(n_samples=500, noise=0.30, random_state=42)\n",
|
||
"X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)\n",
|
||
"from sklearn.ensemble import RandomForestClassifier\n",
|
||
"from sklearn.ensemble import VotingClassifier\n",
|
||
"from sklearn.linear_model import LogisticRegression\n",
|
||
"from sklearn.svm import SVC\n",
|
||
"\n",
|
||
"log_clf = LogisticRegression(random_state=42)\n",
|
||
"rnd_clf = RandomForestClassifier(random_state=42)\n",
|
||
"svm_clf = SVC(random_state=42)\n",
|
||
"\n",
|
||
"voting_clf = VotingClassifier(\n",
|
||
" estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],\n",
|
||
" voting='hard')\n",
|
||
"voting_clf.fit(X_train, y_train)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 26,
|
||
"id": "793e7482",
|
||
"metadata": {
|
||
"collapsed": false,
|
||
"editable": true
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"from sklearn.metrics import accuracy_score\n",
|
||
"\n",
|
||
"for clf in (log_clf, rnd_clf, svm_clf, voting_clf):\n",
|
||
" clf.fit(X_train, y_train)\n",
|
||
" y_pred = clf.predict(X_test)\n",
|
||
" print(clf.__class__.__name__, accuracy_score(y_test, y_pred))"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 27,
|
||
"id": "1f391b0d",
|
||
"metadata": {
|
||
"collapsed": false,
|
||
"editable": true
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"log_clf = LogisticRegression(random_state=42)\n",
|
||
"rnd_clf = RandomForestClassifier(random_state=42)\n",
|
||
"svm_clf = SVC(probability=True, random_state=42)\n",
|
||
"\n",
|
||
"voting_clf = VotingClassifier(\n",
|
||
" estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)],\n",
|
||
" voting='soft')\n",
|
||
"voting_clf.fit(X_train, y_train)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 28,
|
||
"id": "4e3b40bb",
|
||
"metadata": {
|
||
"collapsed": false,
|
||
"editable": true
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"from sklearn.metrics import accuracy_score\n",
|
||
"\n",
|
||
"for clf in (log_clf, rnd_clf, svm_clf, voting_clf):\n",
|
||
" clf.fit(X_train, y_train)\n",
|
||
" y_pred = clf.predict(X_test)\n",
|
||
" print(clf.__class__.__name__, accuracy_score(y_test, y_pred))"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "1180219b",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Bagging Examples"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 29,
|
||
"id": "491ecd58",
|
||
"metadata": {
|
||
"collapsed": false,
|
||
"editable": true
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"from sklearn.ensemble import BaggingClassifier\n",
|
||
"from sklearn.tree import DecisionTreeClassifier\n",
|
||
"\n",
|
||
"bag_clf = BaggingClassifier(\n",
|
||
" DecisionTreeClassifier(random_state=42), n_estimators=500,\n",
|
||
" max_samples=100, bootstrap=True, n_jobs=-1, random_state=42)\n",
|
||
"bag_clf.fit(X_train, y_train)\n",
|
||
"y_pred = bag_clf.predict(X_test)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 30,
|
||
"id": "0ac9524d",
|
||
"metadata": {
|
||
"collapsed": false,
|
||
"editable": true
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"from sklearn.metrics import accuracy_score\n",
|
||
"print(accuracy_score(y_test, y_pred))"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 31,
|
||
"id": "d335bc9a",
|
||
"metadata": {
|
||
"collapsed": false,
|
||
"editable": true
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"tree_clf = DecisionTreeClassifier(random_state=42)\n",
|
||
"tree_clf.fit(X_train, y_train)\n",
|
||
"y_pred_tree = tree_clf.predict(X_test)\n",
|
||
"print(accuracy_score(y_test, y_pred_tree))"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 32,
|
||
"id": "a89a9e6d",
|
||
"metadata": {
|
||
"collapsed": false,
|
||
"editable": true
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"from matplotlib.colors import ListedColormap\n",
|
||
"\n",
|
||
"def plot_decision_boundary(clf, X, y, axes=[-1.5, 2.5, -1, 1.5], alpha=0.5, contour=True):\n",
|
||
" x1s = np.linspace(axes[0], axes[1], 100)\n",
|
||
" x2s = np.linspace(axes[2], axes[3], 100)\n",
|
||
" x1, x2 = np.meshgrid(x1s, x2s)\n",
|
||
" X_new = np.c_[x1.ravel(), x2.ravel()]\n",
|
||
" y_pred = clf.predict(X_new).reshape(x1.shape)\n",
|
||
" custom_cmap = ListedColormap(['#fafab0','#9898ff','#a0faa0'])\n",
|
||
" plt.contourf(x1, x2, y_pred, alpha=0.3, cmap=custom_cmap)\n",
|
||
" if contour:\n",
|
||
" custom_cmap2 = ListedColormap(['#7d7d58','#4c4c7f','#507d50'])\n",
|
||
" plt.contour(x1, x2, y_pred, cmap=custom_cmap2, alpha=0.8)\n",
|
||
" plt.plot(X[:, 0][y==0], X[:, 1][y==0], \"yo\", alpha=alpha)\n",
|
||
" plt.plot(X[:, 0][y==1], X[:, 1][y==1], \"bs\", alpha=alpha)\n",
|
||
" plt.axis(axes)\n",
|
||
" plt.xlabel(r\"$x_1$\", fontsize=18)\n",
|
||
" plt.ylabel(r\"$x_2$\", fontsize=18, rotation=0)\n",
|
||
"plt.figure(figsize=(11,4))\n",
|
||
"plt.subplot(121)\n",
|
||
"plot_decision_boundary(tree_clf, X, y)\n",
|
||
"plt.title(\"Decision Tree\", fontsize=14)\n",
|
||
"plt.subplot(122)\n",
|
||
"plot_decision_boundary(bag_clf, X, y)\n",
|
||
"plt.title(\"Decision Trees with Bagging\", fontsize=14)\n",
|
||
"save_fig(\"baggingtree\")\n",
|
||
"plt.show()"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "9fe3e801",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Making your own Bootstrap: Changing the Level of the Decision Tree\n",
|
||
"\n",
|
||
"Let us bring up our good old boostrap example from the linear regression lectures. We change the linerar regression algorithm with\n",
|
||
"a decision tree wth different depths and perform a bootstrap aggregate (in this case we perform as many bootstraps as data points $n$)."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 33,
|
||
"id": "7b755579",
|
||
"metadata": {
|
||
"collapsed": false,
|
||
"editable": true
|
||
},
|
||
"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.pipeline import make_pipeline\n",
|
||
"from sklearn.utils import resample\n",
|
||
"from sklearn.tree import DecisionTreeRegressor\n",
|
||
"\n",
|
||
"n = 100\n",
|
||
"n_boostraps = 100\n",
|
||
"maxdepth = 8\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",
|
||
"error = np.zeros(maxdepth)\n",
|
||
"bias = np.zeros(maxdepth)\n",
|
||
"variance = np.zeros(maxdepth)\n",
|
||
"polydegree = np.zeros(maxdepth)\n",
|
||
"X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)\n",
|
||
"\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",
|
||
"# we produce a simple tree first as benchmark\n",
|
||
"simpletree = DecisionTreeRegressor(max_depth=3) \n",
|
||
"simpletree.fit(X_train_scaled, y_train)\n",
|
||
"simpleprediction = simpletree.predict(X_test_scaled)\n",
|
||
"for degree in range(1,maxdepth):\n",
|
||
" model = DecisionTreeRegressor(max_depth=degree) \n",
|
||
" y_pred = np.empty((y_test.shape[0], n_boostraps))\n",
|
||
" for i in range(n_boostraps):\n",
|
||
" x_, y_ = resample(X_train_scaled, y_train)\n",
|
||
" model.fit(x_, y_)\n",
|
||
" y_pred[:, i] = model.predict(X_test_scaled)#.ravel()\n",
|
||
"\n",
|
||
" polydegree[degree] = degree\n",
|
||
" error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )\n",
|
||
" bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )\n",
|
||
" variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )\n",
|
||
" print('Polynomial degree:', 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",
|
||
"mse_simpletree= np.mean( np.mean((y_test - simpleprediction)**2)\n",
|
||
"print(mse_simpletree)\n",
|
||
"plt.xlim(1,maxdepth)\n",
|
||
"plt.plot(polydegree, error, label='MSE')\n",
|
||
"plt.plot(polydegree, bias, label='bias')\n",
|
||
"plt.plot(polydegree, variance, label='Variance')\n",
|
||
"plt.legend()\n",
|
||
"save_fig(\"baggingboot\")\n",
|
||
"plt.show()"
|
||
]
|
||
}
|
||
],
|
||
"metadata": {},
|
||
"nbformat": 4,
|
||
"nbformat_minor": 5
|
||
}
|