From bc2c9e95d791bf9926e9f52ca0a7410da5ad155b Mon Sep 17 00:00:00 2001 From: Morten Hjorth-Jensen Date: Sat, 29 Oct 2022 22:03:12 +0200 Subject: [PATCH] update week 44 --- doc/src/week44/Backup2021.do.txt | 2015 ++++++++++++++++++++++++++++++ doc/src/week44/week44.do.txt | 2 +- 2 files changed, 2016 insertions(+), 1 deletion(-) create mode 100644 doc/src/week44/Backup2021.do.txt diff --git a/doc/src/week44/Backup2021.do.txt b/doc/src/week44/Backup2021.do.txt new file mode 100644 index 000000000..8e0fab535 --- /dev/null +++ b/doc/src/week44/Backup2021.do.txt @@ -0,0 +1,2015 @@ +TITLE: Week 44: Decision Trees and Random Forests +AUTHOR: Morten Hjorth-Jensen {copyright, 1999-present|CC BY-NC} at Department of Physics, University of Oslo & Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University +DATE: today + + +!split +===== Overview of week 44 ===== + +* Thursday: Wrapping up PCA from last week, Clustering and basics of decision trees, classification and regression algorithms +* Friday: Decision trees, voting models and bagging + +!bblock Videos +o "Video on Decision trees":"https://www.youtube.com/watch?v=RmajweUFKvM&ab_channel=Simplilearn" +o "Video on Principal Component Analysis":"https://www.youtube.com/watch?v=FgakZw6K1QQ&ab_channel=StatQuestwithJoshStarmer" +o "Video on Clustering":"https://www.youtube.com/watch?v=esmzYhuFnds&ab_channel=MITOpenCourseWare" +!eblock + +!bblock Reading +o 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. +o 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. +!eblock + +!split +===== Digression First ===== + +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. + +It has several interesting perspectives and highly interesting +applications that link scientific discoveries with efficient software +and hardware. The emphasis is onintegrating power Machine Learning +methods into the real-time experimental data processing loop to +accelerate scientific discovery. + + +!split +===== A short Discussion of Project 2 ===== + +For neural networks and regression, should I use a design matrix with information about a polynomial fit or not? +Discuss pros and cons. The example here shows some of these issues. + +!bc pycod +""" +Code to test Ridge and NNs using Scikit-Learn only +""" + +import numpy as np +import pandas as pd +import matplotlib.pyplot as plt +from sklearn.model_selection import train_test_split +from sklearn import linear_model +from sklearn.neural_network import MLPRegressor +from sklearn.metrics import accuracy_score +import seaborn as sns + + +def MSE(y_data,y_model): + n = np.size(y_model) + return np.sum((y_data-y_model)**2)/n +# A seed just to ensure that the random numbers are the same for every run. +# Useful for eventual debugging. +np.random.seed(315) + +n = 100 +x = np.random.rand(n) +y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2) + +Maxpolydegree = 5 +X = np.zeros((n,Maxpolydegree-1)) + +for degree in range(1,Maxpolydegree): #No intercept column + X[:,degree-1] = x**(degree) + +# We split the data in test and training data +X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2) + +# Decide which values of lambda to use + +nlambdas = 10 +lmbd_vals = np.logspace(-4, 0, nlambdas) +MSERidgePredict = np.zeros(nlambdas) +for i in range(nlambdas): + lmb = lmbd_vals[i] + RegRidge = linear_model.Ridge(lmb) + RegRidge.fit(X_train,y_train) + ypredictRidge = RegRidge.predict(X_test) + MSERidgePredict[i] = MSE(y_test,ypredictRidge) + +plt.figure() +plt.plot(np.log10(lmbd_vals), MSERidgePredict, 'g--', label = 'MSE SL Ridge Test') +plt.xlabel('log10(lambda)') +plt.ylabel('MSE') +plt.legend() +plt.show() + +# Neural Network part + +n_hidden_neurons = 50 +epochs = 100 +# store models for later use +eta_vals = np.logspace(-4, 0, 10) +# store the models for later use +DNN_scikit = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object) +test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals))) +sns.set() +for i, eta in enumerate(eta_vals): + for j, lmbd in enumerate(lmbd_vals): + dnn = MLPRegressor(hidden_layer_sizes=(n_hidden_neurons), activation='logistic', + alpha=lmbd, learning_rate_init=eta, max_iter=epochs) + dnn.fit(X_train, y_train) + ypredictMLP = dnn.predict(X_test) + test_accuracy[i][j] = MSE(ypredictMLP, y_test) + +fig, ax = plt.subplots(figsize = (10, 10)) +sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis") +ax.set_title("Training Accuracy") +ax.set_ylabel("$\eta$") +ax.set_xlabel("$\lambda$") +plt.show() + +# Now we redefine our design matrix to include only the x-values and try out our NN + +X = np.zeros((n,1)) +X[:,0] = x + +# We split the data in test and training data again +X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2) +# Repeat the NN calculation +DNN_scikit = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object) +test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals))) +sns.set() +for i, eta in enumerate(eta_vals): + for j, lmbd in enumerate(lmbd_vals): + dnn = MLPRegressor(hidden_layer_sizes=(n_hidden_neurons), activation='logistic', + alpha=lmbd, learning_rate_init=eta, max_iter=epochs) + dnn.fit(X_train, y_train) + ypredictMLP = dnn.predict(X_test) + test_accuracy[i][j] = MSE(ypredictMLP, y_test) + +fig, ax = plt.subplots(figsize = (10, 10)) +sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis") +ax.set_title("Training Accuracy") +ax.set_ylabel("$\eta$") +ax.set_xlabel("$\lambda$") +plt.show() + +!ec + +!split +===== Learning Rate and more ===== + +When developing your own gradient descent code, it is useful to test +it first on a standard ordinary least squares problem. Then the +Hessian matrix is determined by the design matrix only, namely +$\bm{H}\propto \bm{X}^T\bm{X}$. + +The optimal learning rate is determined by the inverse of the largest +eigenvalue of $\bm{H}$. This can be used as a guideline for the +learning rate guess. + +Keeping this fixed, can aid in studyng the dependence on say the mean +square value for OLS as function of the number of batches and epochs +in your stochastic gradient descent code. See for example the code +examples for week 40 (right before the neural network material). + + + +!split +===== Thursday, Principal Component Analysis ===== + +For the principal component analysis, +see slides from "week 43":"https://compphysics.github.io/MachineLearning/doc/pub/week43/html/week43-reveal.html", in particular from slide 28 and forward + +!split +===== A kind of Bird's view on PCA ===== + + +_Why do we maximize variance during Principal Component Analysis?_ + +Variance is a measure of the *variability* of the data you +have. Potentially the number of components is infinite, so you want to "squeeze" the most +information in each component of the finite set you build. + +If, to exaggerate, you were to select a single principal component, +you would want it to account for the most variability possible: hence +the search for maximum variance, so that the one component collects +the most "uniqueness" from the data set. + + +Maximizing the component vector variances is the same as maximizing +the 'uniqueness' of those vectors. The vectors are as distant +from each other as possible (orthogonal to each other). + + +Take for example a situation where you have 2 lines that are +orthogonal in a 3D space. You can capture the environment much more +completely with those orthogonal lines than 2 lines that are parallel +(or nearly parallel). When applied to very high dimensional states +using very few vectors, this becomes a much more important +relationship among the vectors to maintain. In a linear algebra sense +you want independent rows to be produced by PCA, otherwise some of +those rows will be redundant. + +!split +===== Thursday: Clustering and Unsupervised Learning ===== + +In general terms cluster analysis, or clustering, is the task of grouping a +data-set into different distinct categories based on some measure of equality of +the data. This measure is often referred to as a _metric_ or _similarity +measure_ in the literature (note: sometimes we deal with a _dissimilarity +measure_ instead). Usually, these metrics are formulated as some kind of +distance function between points in a high-dimensional space. + +The simplest, and also the most +common is the _Euclidean distance_. + +!split +===== Basic Idea of the $k$-means Clustering Algorithm ===== + +The simplest of all clustering algorithms is the _k-means algorithm_ +, sometimes also referred to as *Lloyds algorithm*. It is the simplest and also +the most common. From its simplicity it obtains both strengths and weaknesses. +These will be discussed in more detail later. The $k$-means algorithm is a +_centroid based_ clustering algorithm. + +!split +===== The $k$-means Algorithm ===== + +Assume, we are given $n$ data points and we wish to split the data into $K < n$ +different categories, or clusters. We label each cluster by an integer + +!bt +\[ k\in\{1, \cdots, K \}. +\] +!et + +In the basic k-means algorithm each point is assigned to only +one cluster $k$, and these assignments are *non-injective* i.e. many-to-one. We +can think of these mappings as an encoder $k = C(i)$, which assigns the $i$-th +data-point $\bf x_i$ to the $k$-th cluster. + +$k$-means algorithm in words: +o We start with guesses / random initializations of our $k$ cluster centers/centroids +o For each centroid the points that are most similar are identified +o Then we move / replace each centroid with a coordinate average of all the points that were assigned to that centroid. +o Iterate 2-3 until the centroids no longer move (to some tolerance) + +!split +===== Basic Math of the $k$-means Algorithm ===== + +We assume we have $n$ data-points +!bt +\begin{equation}\label{eq:kmeanspoints} + \bm{x_i} = \{x_{i, 1}, \cdots, x_{i, p}\}\in\mathbb{R}^p. +\end{equation} +!et +which we wish to group into $K < n$ clusters. For our dissimilarity measure we +use the *squared Euclidean distance* +!bt +\begin{equation}\label{eq:squaredeuclidean} + d(\bm{x_i}, \bm{x_i'}) = \sum_{j=1}^p(x_{ij} - x_{i'j})^2 + = ||\bm{x_i} - \bm{x_{i'}}||^2 +\end{equation} +!et + +!split +===== Within Cluster Point Scatter ===== + +We define the so called *within-cluster point scatter* which gives us a +measure of how close each data point assigned to the same cluster tends to be to +the all the others. +!bt +\begin{equation}\label{eq:withincluster} + W(C) = \frac{1}{2}\sum_{k=1}^K\sum_{C(i)=k} + \sum_{C(i')=k}d(\bm{x_i}, \bm{x_{i'}}) = + \sum_{k=1}^KN_k\sum_{C(i)=k}||\bm{x_i} - \bm{\overline{x_k}}||^2 +\end{equation} +!et +where $\bm{\overline{x_k}}$ is the mean vector associated with the $k$-th +cluster, and $N_k = \sum_{i=1}^nI(C(i) = k)$, where the $I()$ notation is +similar to the Kronecker delta (*Commonly used in statistics, it just means that +when $i = k$ we have the encoder $C(i)$*). In other words, the within-cluster +scatter measures the compactness of each cluster with respect to the data points +assigned to each cluster. This is the quantity that the $k$-means algorithm aims +to minimize. We refer to this quantity $W(C)$ as the within cluster scatter +because of its relation to the *total scatter*. + + +!split +===== More Details ===== + +We have +!bt +\begin{equation}\label{eq:totalscatter} + T = W(C) + B(C) = \frac{1}{2}\sum_{i=1}^n + \sum_{i'=1}^nd(\bm{x_i}, \bm{x_{i'}}) + = \frac{1}{2}\sum_{k=1}^K\sum_{C(i)=k} + \Big(\sum_{C(i') = k}d(\bm{x_i}, \bm{x_{i'}}) + + \sum_{C(i')\neq k}d(\bm{x_i}, \bm{x_{i'}})\Big). +\end{equation} +!et + +This is a quantity that is conserved throughout the $k$-means algorithm. It can +be thought of as the total amount of information in the data, and it is composed +of the aforementioned within-cluster scatter and the *between-cluster scatter* +$B(C)$. In methods such as principle component analysis the total scatter is not +conserved. + +!split +===== Total Cluster Variance ===== +Given a cluster mean $\bm{m_k}$ we define the _total cluster variance_ +!bt +\begin{equation}\label{eq:totalclustervariance} + \min_{C, \{\bm{m_k}\}_1^K}\sum_{k=1}^KN_k\sum||\bm{x_i} - \bm{m_k}||^2 +\end{equation} +!et +Now we have all the pieces necessary to formally revisit the $k$-means algorithm. + + +!split +===== The $k$-means Clustering Algorithm ===== + +The $k$-means clustering algorithm goes as follows + +o 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. +o 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}} ||\bm{x_i} - \bm{m_k}||^2$$ +o Steps 1 and 2 are repeated until the assignments do not change. + + +!split +===== Summarizing ===== + + +o Before we start we specify a number $k$ which is the number of clusters we want to try to separate our data into. +o We initially choose $k$ random data points in our data as our initial centroids, *or means* (this is where the name comes from). +o Assign each data point to their closest centroid, based on the squared Euclidean distance. +o For each of the $k$ cluster we update the centroid by calculating new mean values for all the data points in the cluster. +o 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. + + +!split +===== Writing our own Code, the Data Set ===== + +Let us now program the most basic version of the algorithm using nothing but +Python with numpy arrays. This code is kept intentionally simple to gradually +progress our understanding. There is no vectorization of any kind, and even most +helper functions are not utilized. + +We need first a dataset to do our cluster analysis on. In our case +this is a plain *vanilla* data set using random numbers using a +Gaussian distribution. + +!bc pycod +import time +import numpy as np +import tensorflow as tf +from matplotlib import image +import matplotlib.pyplot as plt +from sklearn.cluster import KMeans +from IPython.display import display + +np.random.seed(2021) + +!ec + +Next we define functions, for ease of use later, to generate Gaussians and to +set up our toy data set. +!bc pycod +def gaussian_points(dim=2, n_points=1000, mean_vector=np.array([0, 0]), + sample_variance=1): + """ + Very simple custom function to generate gaussian distributed point clusters + with variable dimension, number of points, means in each direction + (must match dim) and sample variance. + + Inputs: + dim (int) + n_points (int) + mean_vector (np.array) (where index 0 is x, index 1 is y etc.) + sample_variance (float) + + Returns: + data (np.array): with dimensions (dim x n_points) + """ + + mean_matrix = np.zeros(dim) + mean_vector + covariance_matrix = np.eye(dim) * sample_variance + data = np.random.multivariate_normal(mean_matrix, covariance_matrix, + n_points) + return data + + + +def generate_simple_clustering_dataset(dim=2, n_points=1000, plotting=True, + return_data=True): + """ + Toy model to illustrate k-means clustering + """ + + data1 = gaussian_points(mean_vector=np.array([5, 5])) + data2 = gaussian_points() + data3 = gaussian_points(mean_vector=np.array([1, 4.5])) + data4 = gaussian_points(mean_vector=np.array([5, 1])) + data = np.concatenate((data1, data2, data3, data4), axis=0) + + if plotting: + fig, ax = plt.subplots() + ax.scatter(data[:, 0], data[:, 1], alpha=0.2) + ax.set_title('Toy Model Dataset') + plt.show() + + + if return_data: + return data + + +data = generate_simple_clustering_dataset() +!ec + + +!split +===== Implementing the $k$-means Algorithm ===== + +With the above dataset we start +implementing the $k$-means algorithm. + +!bc pycod + +n_samples, dimensions = data.shape +n_clusters = 4 + +# we randomly initialize our centroids +np.random.seed(2021) +centroids = data[np.random.choice(n_samples, n_clusters, replace=False), :] +distances = np.zeros((n_samples, n_clusters)) + +# first we need to calculate the distance to each centroid from our data +for k in range(n_clusters): + for n in range(n_samples): + dist = 0 + for d in range(dimensions): + dist += np.abs(data[n, d] - centroids[k, d])**2 + distances[n, k] = dist + +# we initialize an array to keep track of to which cluster each point belongs +# the way we set it up here the index tracks which point and the value which +# cluster the point belongs to +cluster_labels = np.zeros(n_samples, dtype='int') + +# next we loop through our samples and for every point assign it to the cluster +# to which it has the smallest distance to +for n in range(n_samples): + # tracking variables (all of this is basically just an argmin) + smallest = 1e10 + smallest_row_index = 1e10 + for k in range(n_clusters): + if distances[n, k] < smallest: + smallest = distances[n, k] + smallest_row_index = k + + cluster_labels[n] = smallest_row_index + +!ec + +!split +===== Plotting ===== +!bc pycod +fig = plt.figure() +ax = fig.add_subplot() +unique_cluster_labels = np.unique(cluster_labels) +for i in unique_cluster_labels: + ax.scatter(data[cluster_labels == i, 0], + data[cluster_labels == i, 1], + label = i, + alpha = 0.2) + ax.scatter(centroids[:, 0], centroids[:, 1], c='black') + +ax.set_title("First Grouping of Points to Centroids") + +plt.show() +!ec + +So what do we have so far? We have 'picked' $k$ centroids at random from our +data points. There are other ways of more intelligently choosing their +initializations, however for our purposes randomly is fine. Then we have +initialized an array 'distances' which holds the information of the distance, +*or dissimilarity*, of every point to of our centroids. Finally, we have +initialized an array 'cluster_labels' which according to our distances array +holds the information of to which centroid every point is assigned. This was the +first pass of our algorithm. Essentially, all we need to do now is repeat the +distance and assignment steps above until we have reached a desired convergence +or a maximum amount of iterations. + +!split +===== Continuing ===== + +!bc pycod + +max_iterations = 100 +tolerance = 1e-8 + +for iteration in range(max_iterations): + prev_centroids = centroids.copy() + for k in range(n_clusters): + # this array will be used to update our centroid positions + vector_mean = np.zeros(dimensions) + mean_divisor = 0 + for n in range(n_samples): + if cluster_labels[n] == k: + vector_mean += data[n, :] + mean_divisor += 1 + + # update according to the k means + centroids[k, :] = vector_mean / mean_divisor + + # we find the dissimilarity + for k in range(n_clusters): + for n in range(n_samples): + dist = 0 + for d in range(dimensions): + dist += np.abs(data[n, d] - centroids[k, d])**2 + distances[n, k] = dist + + # assign each point + for n in range(n_samples): + smallest = 1e10 + smallest_row_index = 1e10 + for k in range(n_clusters): + if distances[n, k] < smallest: + smallest = distances[n, k] + smallest_row_index = k + + cluster_labels[n] = smallest_row_index + + # convergence criteria + centroid_difference = np.sum(np.abs(centroids - prev_centroids)) + if centroid_difference < tolerance: + print(f'Converged at iteration {iteration}') + break + + elif iteration == max_iterations: + print(f'Did not converge in {max_iterations} iterations') +!ec + +!split +===== Wrapping it up ===== +We now have a simple , un-optimized $k$-means +clustering implementation. Lets plot the final result + +!bc pycod +fig = plt.figure() +ax = fig.add_subplot() +unique_cluster_labels = np.unique(cluster_labels) +for i in unique_cluster_labels: + ax.scatter(data[cluster_labels == i, 0], + data[cluster_labels == i, 1], + label = i, + alpha = 0.2) + ax.scatter(centroids[:, 0], centroids[:, 1], c='black') + +ax.set_title("Final Result of K-means Clustering") + +plt.show() +!ec + +!bc pycod +def naive_kmeans(data, n_clusters=4, max_iterations=100, tolerance=1e-8): + start_time = time.time() + + n_samples, dimensions = data.shape + n_clusters = 4 + #np.random.seed(2021) + centroids = data[np.random.choice(n_samples, n_clusters, replace=False), :] + distances = np.zeros((n_samples, n_clusters)) + + for k in range(n_clusters): + for n in range(n_samples): + dist = 0 + for d in range(dimensions): + dist += np.abs(data[n, d] - centroids[k, d])**2 + distances[n, k] = dist + + cluster_labels = np.zeros(n_samples, dtype='int') + + for n in range(n_samples): + smallest = 1e10 + smallest_row_index = 1e10 + for k in range(n_clusters): + if distances[n, k] < smallest: + smallest = distances[n, k] + smallest_row_index = k + + cluster_labels[n] = smallest_row_index + + for iteration in range(max_iterations): + prev_centroids = centroids.copy() + for k in range(n_clusters): + vector_mean = np.zeros(dimensions) + mean_divisor = 0 + for n in range(n_samples): + if cluster_labels[n] == k: + vector_mean += data[n, :] + mean_divisor += 1 + + centroids[k, :] = vector_mean / mean_divisor + + for k in range(n_clusters): + for n in range(n_samples): + dist = 0 + for d in range(dimensions): + dist += np.abs(data[n, d] - centroids[k, d])**2 + distances[n, k] = dist + + for n in range(n_samples): + smallest = 1e10 + smallest_row_index = 1e10 + for k in range(n_clusters): + if distances[n, k] < smallest: + smallest = distances[n, k] + smallest_row_index = k + + cluster_labels[n] = smallest_row_index + + centroid_difference = np.sum(np.abs(centroids - prev_centroids)) + if centroid_difference < tolerance: + print(f'Converged at iteration {iteration}') + print(f'Runtime: {time.time() - start_time} seconds') + + return cluster_labels, centroids + + print(f'Did not converge in {max_iterations} iterations') + print(f'Runtime: {time.time() - start_time} seconds') + + return cluster_labels, centroids + +!ec + + +!split +===== Decision trees, overarching aims ===== + + +We start here with the most basic algorithm, the so-called decision +tree. With this basic algorithm we can in turn build more complex +networks, spanning from homogeneous and heterogenous forests (bagging, +random forests and more) to one of the most popular supervised +algorithms nowadays, the extreme gradient boosting, or just +XGBoost. But let us start with the simplest possible ingredient. + +Decision trees are supervised learning algorithms used for both, +classification and regression tasks. + + +The main idea of decision trees +is to find those descriptive features which contain the most +_information_ regarding the target feature and then split the dataset +along the values of these features such that the target feature values +for the resulting underlying datasets are as pure as possible. + +The descriptive features which reproduce best the target/output features are normally said +to be the most informative ones. The process of finding the _most +informative_ feature is done until we accomplish a stopping criteria +where we then finally end up in so called _leaf nodes_. + +!split +===== Basics of a tree ===== + +A decision tree is typically divided into a _root node_, the _interior nodes_, +and the final _leaf nodes_ or just _leaves_. These entities are then connected by so-called _branches_. + +The leaf nodes +contain the predictions we will make for new query instances presented +to our trained model. This is possible since the model has +learned the underlying structure of the training data and hence can, +given some assumptions, make predictions about the target feature value +(class) of unseen query instances. + +!split +===== A Sketch of a Tree, Regression problem ===== + + + +#FIGURE: [DataFiles/Regsimpletree.png, width=600 frac=0.8] + +!split +===== A Sketch of a Tree, Classification problem ===== + +#FIGURE: [DataFiles/Classimpletree.png, width=600 frac=0.8] + + + +!split +===== A typical Decision Tree with its pertinent Jargon, Classification Problem ===== + +FIGURE: [DataFiles/cancer.png, width=600 frac=0.8] + +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. + + + +!split +===== General Features ===== + +The overarching approach to decision trees is a top-down approach. + +* A leaf provides the classification of a given instance. +* A node specifies a test of some attribute of the instance. +* A branch corresponds to a possible values of an attribute. +* 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. + + +This process is then repeated for the subtree rooted at the new +node. + + +!split +===== How do we set it up? ===== + + +In simplified terms, the process of training a decision tree and +predicting the target features of query instances is as follows: + +o Present a dataset containing of a number of training instances characterized by a number of descriptive features and a target feature + +o 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 + +o Grow the tree until we accomplish a stopping criteria create leaf nodes which represent the *predictions* we want to make for new query instances + +o Show query instances to the tree and run down the tree until we arrive at leaf nodes + +Then we are essentially done! + + + + + +!split +===== Decision trees and Regression ===== +!bc pycod +import numpy as np +import matplotlib.pyplot as plt +from sklearn.preprocessing import PolynomialFeatures +from sklearn.linear_model import LinearRegression + +steps=250 + +distance=0 +x=0 +distance_list=[] +steps_list=[] +while x 0).astype(np.float32) * 2 + +angle = np.pi/4 +rotation_matrix = np.array([[np.cos(angle), -np.sin(angle)], [np.sin(angle), np.cos(angle)]]) +Xsr = Xs.dot(rotation_matrix) + +tree_clf_s = DecisionTreeClassifier(random_state=42) +tree_clf_s.fit(Xs, ys) +tree_clf_sr = DecisionTreeClassifier(random_state=42) +tree_clf_sr.fit(Xsr, ys) + +plt.figure(figsize=(11, 4)) +plt.subplot(121) +plot_decision_boundary(tree_clf_s, Xs, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False) +plt.subplot(122) +plot_decision_boundary(tree_clf_sr, Xsr, ys, axes=[-0.7, 0.7, -0.7, 0.7], iris=False) + +plt.show() +!ec + +!split +===== Regression trees ===== +!bc pycod +# Quadratic training set + noise +np.random.seed(42) +m = 200 +X = np.random.rand(m, 1) +y = 4 * (X - 0.5) ** 2 +y = y + np.random.randn(m, 1) / 10 +!ec + +!bc pycod +from sklearn.tree import DecisionTreeRegressor + +tree_reg = DecisionTreeRegressor(max_depth=2, random_state=42) +tree_reg.fit(X, y) +!ec + +!split +===== Final regressor code ===== +!bc pycod +from sklearn.tree import DecisionTreeRegressor + +tree_reg1 = DecisionTreeRegressor(random_state=42, max_depth=2) +tree_reg2 = DecisionTreeRegressor(random_state=42, max_depth=3) +tree_reg1.fit(X, y) +tree_reg2.fit(X, y) + +def plot_regression_predictions(tree_reg, X, y, axes=[0, 1, -0.2, 1], ylabel="$y$"): + x1 = np.linspace(axes[0], axes[1], 500).reshape(-1, 1) + y_pred = tree_reg.predict(x1) + plt.axis(axes) + plt.xlabel("$x_1$", fontsize=18) + if ylabel: + plt.ylabel(ylabel, fontsize=18, rotation=0) + plt.plot(X, y, "b.") + plt.plot(x1, y_pred, "r.-", linewidth=2, label=r"$\hat{y}$") + +plt.figure(figsize=(11, 4)) +plt.subplot(121) +plot_regression_predictions(tree_reg1, X, y) +for split, style in ((0.1973, "k-"), (0.0917, "k--"), (0.7718, "k--")): + plt.plot([split, split], [-0.2, 1], style, linewidth=2) +plt.text(0.21, 0.65, "Depth=0", fontsize=15) +plt.text(0.01, 0.2, "Depth=1", fontsize=13) +plt.text(0.65, 0.8, "Depth=1", fontsize=13) +plt.legend(loc="upper center", fontsize=18) +plt.title("max_depth=2", fontsize=14) + +plt.subplot(122) +plot_regression_predictions(tree_reg2, X, y, ylabel=None) +for split, style in ((0.1973, "k-"), (0.0917, "k--"), (0.7718, "k--")): + plt.plot([split, split], [-0.2, 1], style, linewidth=2) +for split in (0.0458, 0.1298, 0.2873, 0.9040): + plt.plot([split, split], [-0.2, 1], "k:", linewidth=1) +plt.text(0.3, 0.5, "Depth=2", fontsize=13) +plt.title("max_depth=3", fontsize=14) + +plt.show() +!ec + +!bc pycod +tree_reg1 = DecisionTreeRegressor(random_state=42) +tree_reg2 = DecisionTreeRegressor(random_state=42, min_samples_leaf=10) +tree_reg1.fit(X, y) +tree_reg2.fit(X, y) + +x1 = np.linspace(0, 1, 500).reshape(-1, 1) +y_pred1 = tree_reg1.predict(x1) +y_pred2 = tree_reg2.predict(x1) + +plt.figure(figsize=(11, 4)) + +plt.subplot(121) +plt.plot(X, y, "b.") +plt.plot(x1, y_pred1, "r.-", linewidth=2, label=r"$\hat{y}$") +plt.axis([0, 1, -0.2, 1.1]) +plt.xlabel("$x_1$", fontsize=18) +plt.ylabel("$y$", fontsize=18, rotation=0) +plt.legend(loc="upper center", fontsize=18) +plt.title("No restrictions", fontsize=14) + +plt.subplot(122) +plt.plot(X, y, "b.") +plt.plot(x1, y_pred2, "r.-", linewidth=2, label=r"$\hat{y}$") +plt.axis([0, 1, -0.2, 1.1]) +plt.xlabel("$x_1$", fontsize=18) +plt.title("min_samples_leaf={}".format(tree_reg2.min_samples_leaf), fontsize=14) + +plt.show() +!ec + + + +!split +===== Pros and cons of trees, pros ===== + +* 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) +* Trees are very easy to explain to people. In fact, they are even easier to explain than linear regression! +* No feature normalization needed +* Tree models can handle both continuous and categorical data (Classification and Regression Trees) +* Can model nonlinear relationships +* Can model interactions between the different descriptive features +* Trees can be displayed graphically, and are easily interpreted even by a non-expert (especially if they are small) + + +!split +===== Disadvantages ===== + +* Unfortunately, trees generally do not have the same level of predictive accuracy as some of the other regression and classification approaches +* If continuous features are used the tree may become quite large and hence less interpretable +* 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 +* 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 +* 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. +* If the number of features is relatively large (high dimensional) and the number of instances is relatively low, the tree might overfit the data +* 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 + +However, by aggregating many decision trees, using methods like +bagging, random forests, and boosting, the predictive performance of +trees can be substantially improved. + + +!split +===== Ensemble Methods: From a Single Tree to Many Trees and Extreme Boosting, Meet the Jungle of Methods ===== + +As stated above and seen in many of the examples discussed here about +a single decision tree, we often end up overfitting our training +data. This normally means that we have a high variance. Can we reduce +the variance of a statistical learning method? + +This leads us to a set of different methods that can combine different +machine learning algorithms or just use one of them to construct +forests and jungles of trees, homogeneous ones or heterogenous +ones. These methods are recognized by different names which we will +try to explain here. These are + +o Voting classifiers +o Bagging and Pasting +o Random forests +o Boosting methods, from adaptive to Extreme Gradient Boosting (XGBoost) + +We discuss these methods here. + + +!split +===== An Overview of Ensemble Methods ===== + +FIGURE: [DataFiles/ensembleoverview.png, width=600 frac=0.8] + + + +!split +===== Bagging ===== + +The _plain_ decision trees suffer from high +variance. This means that if we split the training data into two parts +at random, and fit a decision tree to both halves, the results that we +get could be quite different. In contrast, a procedure with low +variance will yield similar results if applied repeatedly to distinct +data sets; linear regression tends to have low variance, if the ratio +of $n$ to $p$ is moderately large. + +_Bootstrap aggregation_, or just _bagging_, is a +general-purpose procedure for reducing the variance of a statistical +learning method. + + +!split +===== More bagging ===== + +Bagging typically results in improved accuracy +over prediction using a single tree. Unfortunately, however, it can be +difficult to interpret the resulting model. Recall that one of the +advantages of decision trees is the attractive and easily interpreted +diagram that results. + +However, when we bag a large number of trees, it is no longer +possible to represent the resulting statistical learning procedure +using a single tree, and it is no longer clear which variables are +most important to the procedure. Thus, bagging improves prediction +accuracy at the expense of interpretability. Although the collection +of bagged trees is much more difficult to interpret than a single +tree, one can obtain an overall summary of the importance of each +predictor using the MSE (for bagging regression trees) or the Gini +index (for bagging classification trees). In the case of bagging +regression trees, we can record the total amount that the MSE is +decreased due to splits over a given predictor, averaged over all $B$ possible +trees. A large value indicates an important predictor. Similarly, in +the context of bagging classification trees, we can add up the total +amount that the Gini index is decreased by splits over a given +predictor, averaged over all $B$ trees. + +!split +===== Simple Voting Example, head or tail ===== +!bc pycod +heads_proba = 0.51 +coin_tosses = (np.random.rand(10000, 10) < heads_proba).astype(np.int32) +cumulative_heads_ratio = np.cumsum(coin_tosses, axis=0) / np.arange(1, 10001).reshape(-1, 1) +plt.figure(figsize=(8,3.5)) +plt.plot(cumulative_heads_ratio) +plt.plot([0, 10000], [0.51, 0.51], "k--", linewidth=2, label="51%") +plt.plot([0, 10000], [0.5, 0.5], "k-", label="50%") +plt.xlabel("Number of coin tosses") +plt.ylabel("Heads ratio") +plt.legend(loc="lower right") +plt.axis([0, 10000, 0.42, 0.58]) +save_fig("votingsimple") +plt.show() + +!ec + +!split +===== Using the Voting Classifier ===== +!bc pycod +from sklearn.model_selection import train_test_split +from sklearn.datasets import make_moons + +X, y = make_moons(n_samples=500, noise=0.30, random_state=42) +X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42) + +from sklearn.ensemble import RandomForestClassifier +from sklearn.ensemble import VotingClassifier +from sklearn.linear_model import LogisticRegression +from sklearn.svm import SVC + +log_clf = LogisticRegression(solver="liblinear", random_state=42) +rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42) +svm_clf = SVC(gamma="auto", random_state=42) + +voting_clf = VotingClassifier( + estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)], + voting='hard') + +voting_clf.fit(X_train, y_train) + +from sklearn.metrics import accuracy_score + +for clf in (log_clf, rnd_clf, svm_clf, voting_clf): + clf.fit(X_train, y_train) + y_pred = clf.predict(X_test) + print(clf.__class__.__name__, accuracy_score(y_test, y_pred)) + +log_clf = LogisticRegression(solver="liblinear", random_state=42) +rnd_clf = RandomForestClassifier(n_estimators=10, random_state=42) +svm_clf = SVC(gamma="auto", probability=True, random_state=42) + +voting_clf = VotingClassifier( + estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)], + voting='soft') +voting_clf.fit(X_train, y_train) + +from sklearn.metrics import accuracy_score + +for clf in (log_clf, rnd_clf, svm_clf, voting_clf): + clf.fit(X_train, y_train) + y_pred = clf.predict(X_test) + print(clf.__class__.__name__, accuracy_score(y_test, y_pred)) + +!ec + +!split +===== Please, not the moons again! Voting and Bagging ===== + +!bc pycod +from sklearn.model_selection import train_test_split +from sklearn.datasets import make_moons + +X, y = make_moons(n_samples=500, noise=0.30, random_state=42) +X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42) +from sklearn.ensemble import RandomForestClassifier +from sklearn.ensemble import VotingClassifier +from sklearn.linear_model import LogisticRegression +from sklearn.svm import SVC + +log_clf = LogisticRegression(random_state=42) +rnd_clf = RandomForestClassifier(random_state=42) +svm_clf = SVC(random_state=42) + +voting_clf = VotingClassifier( + estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)], + voting='hard') +voting_clf.fit(X_train, y_train) +!ec + +!bc pycod +from sklearn.metrics import accuracy_score + +for clf in (log_clf, rnd_clf, svm_clf, voting_clf): + clf.fit(X_train, y_train) + y_pred = clf.predict(X_test) + print(clf.__class__.__name__, accuracy_score(y_test, y_pred)) +!ec + +!bc pycod +log_clf = LogisticRegression(random_state=42) +rnd_clf = RandomForestClassifier(random_state=42) +svm_clf = SVC(probability=True, random_state=42) + +voting_clf = VotingClassifier( + estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)], + voting='soft') +voting_clf.fit(X_train, y_train) +!ec + +!bc pycod +from sklearn.metrics import accuracy_score + +for clf in (log_clf, rnd_clf, svm_clf, voting_clf): + clf.fit(X_train, y_train) + y_pred = clf.predict(X_test) + print(clf.__class__.__name__, accuracy_score(y_test, y_pred)) +!ec + +!split +===== Bagging Examples ===== + +!bc pycod +from sklearn.ensemble import BaggingClassifier +from sklearn.tree import DecisionTreeClassifier + +bag_clf = BaggingClassifier( + DecisionTreeClassifier(random_state=42), n_estimators=500, + max_samples=100, bootstrap=True, n_jobs=-1, random_state=42) +bag_clf.fit(X_train, y_train) +y_pred = bag_clf.predict(X_test) +!ec + + +!bc pycod +from sklearn.metrics import accuracy_score +print(accuracy_score(y_test, y_pred)) +!ec + +!bc pycod +tree_clf = DecisionTreeClassifier(random_state=42) +tree_clf.fit(X_train, y_train) +y_pred_tree = tree_clf.predict(X_test) +print(accuracy_score(y_test, y_pred_tree)) +!ec + +!bc pycod +from matplotlib.colors import ListedColormap + +def plot_decision_boundary(clf, X, y, axes=[-1.5, 2.5, -1, 1.5], alpha=0.5, contour=True): + x1s = np.linspace(axes[0], axes[1], 100) + x2s = np.linspace(axes[2], axes[3], 100) + x1, x2 = np.meshgrid(x1s, x2s) + X_new = np.c_[x1.ravel(), x2.ravel()] + y_pred = clf.predict(X_new).reshape(x1.shape) + custom_cmap = ListedColormap(['#fafab0','#9898ff','#a0faa0']) + plt.contourf(x1, x2, y_pred, alpha=0.3, cmap=custom_cmap) + if contour: + custom_cmap2 = ListedColormap(['#7d7d58','#4c4c7f','#507d50']) + plt.contour(x1, x2, y_pred, cmap=custom_cmap2, alpha=0.8) + plt.plot(X[:, 0][y==0], X[:, 1][y==0], "yo", alpha=alpha) + plt.plot(X[:, 0][y==1], X[:, 1][y==1], "bs", alpha=alpha) + plt.axis(axes) + plt.xlabel(r"$x_1$", fontsize=18) + plt.ylabel(r"$x_2$", fontsize=18, rotation=0) +plt.figure(figsize=(11,4)) +plt.subplot(121) +plot_decision_boundary(tree_clf, X, y) +plt.title("Decision Tree", fontsize=14) +plt.subplot(122) +plot_decision_boundary(bag_clf, X, y) +plt.title("Decision Trees with Bagging", fontsize=14) +save_fig("baggingtree") +plt.show() +!ec + + + +!split +===== Making your own Bootstrap: Changing the Level of the Decision Tree ===== + +Let us bring up our good old boostrap example from the linear regression lectures. We change the linerar regression algorithm with +a decision tree wth different depths and perform a bootstrap aggregate (in this case we perform as many bootstraps as data points $n$). +!bc pycod + +import matplotlib.pyplot as plt +import numpy as np +from sklearn.model_selection import train_test_split +from sklearn.pipeline import make_pipeline +from sklearn.utils import resample +from sklearn.tree import DecisionTreeRegressor + +n = 100 +n_boostraps = 100 +maxdepth = 8 + +# Make data set. +x = np.linspace(-3, 3, n).reshape(-1, 1) +y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape) +error = np.zeros(maxdepth) +bias = np.zeros(maxdepth) +variance = np.zeros(maxdepth) +polydegree = np.zeros(maxdepth) +X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2) + +from sklearn.preprocessing import StandardScaler +scaler = StandardScaler() +scaler.fit(X_train) +X_train_scaled = scaler.transform(X_train) +X_test_scaled = scaler.transform(X_test) + +# we produce a simple tree first as benchmark +simpletree = DecisionTreeRegressor(max_depth=3) +simpletree.fit(X_train_scaled, y_train) +simpleprediction = simpletree.predict(X_test_scaled) +for degree in range(1,maxdepth): + model = DecisionTreeRegressor(max_depth=degree) + y_pred = np.empty((y_test.shape[0], n_boostraps)) + for i in range(n_boostraps): + x_, y_ = resample(X_train_scaled, y_train) + model.fit(x_, y_) + y_pred[:, i] = model.predict(X_test_scaled)#.ravel() + + polydegree[degree] = degree + error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) ) + bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 ) + variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) ) + print('Polynomial degree:', degree) + print('Error:', error[degree]) + print('Bias^2:', bias[degree]) + print('Var:', variance[degree]) + print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree])) + +mse_simpletree= np.mean( np.mean((y_test - simpleprediction)**2) +print(mse_simpletree) +plt.xlim(1,maxdepth) +plt.plot(polydegree, error, label='MSE') +plt.plot(polydegree, bias, label='bias') +plt.plot(polydegree, variance, label='Variance') +plt.legend() +save_fig("baggingboot") +plt.show() + +!ec + + diff --git a/doc/src/week44/week44.do.txt b/doc/src/week44/week44.do.txt index 599745da2..8e0fab535 100644 --- a/doc/src/week44/week44.do.txt +++ b/doc/src/week44/week44.do.txt @@ -1,4 +1,4 @@ -TITLE: Week 44: Dimensionality Reduction, PCA and Clustering. Decision Trees +TITLE: Week 44: Decision Trees and Random Forests AUTHOR: Morten Hjorth-Jensen {copyright, 1999-present|CC BY-NC} at Department of Physics, University of Oslo & Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University DATE: today