update on files
This commit is contained in:
@@ -230,19 +230,15 @@ Note also that when you calculate the bias, in all applications you don't know t
|
||||
The aim here is to write your own code for another widely popular
|
||||
resampling technique, the so-called cross-validation method. Again,
|
||||
before you start with cross-validation approach, you should scale your
|
||||
data and split it in test and training data as you did earlier.
|
||||
Perform a resampling of the data where you split the data in training
|
||||
data and test data using for example
|
||||
|
||||
|
||||
data.
|
||||
|
||||
Implement the $k$-fold cross-validation algorithm (write your own
|
||||
code) and evaluate again the MSE function resulting
|
||||
from the test data. You can compare your own code with that from
|
||||
from the test folds. You can compare your own code with that from
|
||||
_Scikit-Learn_ if needed.
|
||||
|
||||
Compare the MSE you get from your cross-validation code with the one you got from your _bootstrap_ code.
|
||||
You can also compare your own cross-validation code with the one provided by _Scikit-Learn_.
|
||||
Compare the MSE you get from your cross-validation code with the one you got from your _bootstrap_ code. Comment your results. Try $5-10$ folds.
|
||||
You can also compare your own cross-validation code with the one provided by _Scikit-Learn_.
|
||||
|
||||
|
||||
=== Part d): Ridge Regression on the Franke function with resampling ===
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
Binary file not shown.
|
After Width: | Height: | Size: 24 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 67 KiB |
@@ -0,0 +1,608 @@
|
||||
TITLE: Week 41 Tensor flow and Deep Learning, Convolutional Neural Networks
|
||||
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
|
||||
===== Convolutional Neural Networks (recognizing images) =====
|
||||
|
||||
|
||||
Convolutional neural networks (CNNs) were developed during the last
|
||||
decade of the previous century, with a focus on character recognition
|
||||
tasks. Nowadays, CNNs are a central element in the spectacular success
|
||||
of dee learning methods. The success in for example image
|
||||
classifications have made them a central tool for most machine
|
||||
learning practitioners.
|
||||
|
||||
CNNs are very similar to ordinary Neural Networks.
|
||||
They are made up of neurons that have learnable weights and
|
||||
biases. Each neuron receives some inputs, performs a dot product and
|
||||
optionally follows it with a non-linearity. The whole network still
|
||||
expresses a single differentiable score function: from the raw image
|
||||
pixels on one end to class scores at the other. And they still have a
|
||||
loss function (for example Softmax) on the last (fully-connected) layer
|
||||
and all the tips/tricks we developed for learning regular Neural
|
||||
Networks still apply (back propagation, gradient descent etc etc).
|
||||
|
||||
What is the difference? _CNN architectures make the explicit assumption that
|
||||
the inputs are images, which allows us to encode certain properties
|
||||
into the architecture. These then make the forward function more
|
||||
efficient to implement and vastly reduce the amount of parameters in
|
||||
the network._
|
||||
|
||||
Here we provide only a superficial overview, for the more interested, we recommend highly the course
|
||||
"IN5400 – Machine Learning for Image Analysis":"https://www.uio.no/studier/emner/matnat/ifi/IN5400/index-eng.html"
|
||||
and the slides of "CS231":"http://cs231n.github.io/convolutional-networks/".
|
||||
|
||||
Another good read is the article here URL:"https://arxiv.org/pdf/1603.07285.pdf".
|
||||
|
||||
!split
|
||||
===== Regular NNs don’t scale well to full images =====
|
||||
|
||||
As an example, consider
|
||||
an image of size $32\times 32\times 3$ (32 wide, 32 high, 3 color channels), so a
|
||||
single fully-connected neuron in a first hidden layer of a regular
|
||||
Neural Network would have $32\times 32\times 3 = 3072$ weights. This amount still
|
||||
seems manageable, but clearly this fully-connected structure does not
|
||||
scale to larger images. For example, an image of more respectable
|
||||
size, say $200\times 200\times 3$, would lead to neurons that have
|
||||
$200\times 200\times 3 = 120,000$ weights.
|
||||
|
||||
We could have
|
||||
several such neurons, and the parameters would add up quickly! Clearly,
|
||||
this full connectivity is wasteful and the huge number of parameters
|
||||
would quickly lead to possible overfitting.
|
||||
|
||||
FIGURE: [figslides/nn.jpeg, width=500 frac=0.6] A regular 3-layer Neural Network.
|
||||
|
||||
!split
|
||||
===== 3D volumes of neurons =====
|
||||
|
||||
Convolutional Neural Networks take advantage of the fact that the
|
||||
input consists of images and they constrain the architecture in a more
|
||||
sensible way.
|
||||
|
||||
In particular, unlike a regular Neural Network, the
|
||||
layers of a CNN have neurons arranged in 3 dimensions: width,
|
||||
height, depth. (Note that the word depth here refers to the third
|
||||
dimension of an activation volume, not to the depth of a full Neural
|
||||
Network, which can refer to the total number of layers in a network.)
|
||||
|
||||
To understand it better, the above example of an image
|
||||
with an input volume of
|
||||
activations has dimensions $32\times 32\times 3$ (width, height,
|
||||
depth respectively).
|
||||
|
||||
The neurons in a layer will
|
||||
only be connected to a small region of the layer before it, instead of
|
||||
all of the neurons in a fully-connected manner. Moreover, the final
|
||||
output layer could for this specific image have dimensions $1\times 1 \times 10$,
|
||||
because by the
|
||||
end of the CNN architecture we will reduce the full image into a
|
||||
single vector of class scores, arranged along the depth
|
||||
dimension.
|
||||
|
||||
FIGURE: [figslides/cnn.jpeg, width=500 frac=0.6] A CNN arranges its neurons in three dimensions (width, height, depth), as visualized in one of the layers. Every layer of a CNN transforms the 3D input volume to a 3D output volume of neuron activations. In this example, the red input layer holds the image, so its width and height would be the dimensions of the image, and the depth would be 3 (Red, Green, Blue channels).
|
||||
|
||||
|
||||
|
||||
!split
|
||||
===== Layers used to build CNNs =====
|
||||
|
||||
|
||||
A simple CNN is a sequence of layers, and every layer of a CNN
|
||||
transforms one volume of activations to another through a
|
||||
differentiable function. We use three main types of layers to build
|
||||
CNN architectures: Convolutional Layer, Pooling Layer, and
|
||||
Fully-Connected Layer (exactly as seen in regular Neural Networks). We
|
||||
will stack these layers to form a full CNN architecture.
|
||||
|
||||
A simple CNN for image classification could have the architecture:
|
||||
|
||||
* _INPUT_ ($32\times 32 \times 3$) will hold the raw pixel values of the image, in this case an image of width 32, height 32, and with three color channels R,G,B.
|
||||
* _CONV_ (convolutional )layer will compute the output of neurons that are connected to local regions in the input, each computing a dot product between their weights and a small region they are connected to in the input volume. This may result in volume such as $[32\times 32\times 12]$ if we decided to use 12 filters.
|
||||
* _RELU_ layer will apply an elementwise activation function, such as the $max(0,x)$ thresholding at zero. This leaves the size of the volume unchanged ($[32\times 32\times 12]$).
|
||||
* _POOL_ (pooling) layer will perform a downsampling operation along the spatial dimensions (width, height), resulting in volume such as $[16\times 16\times 12]$.
|
||||
* _FC_ (i.e. fully-connected) layer will compute the class scores, resulting in volume of size $[1\times 1\times 10]$, where each of the 10 numbers correspond to a class score, such as among the 10 categories of the MNIST images we considered above . As with ordinary Neural Networks and as the name implies, each neuron in this layer will be connected to all the numbers in the previous volume.
|
||||
|
||||
|
||||
!split
|
||||
===== Transforming images =====
|
||||
|
||||
CNNs transform the original image layer by layer from the original
|
||||
pixel values to the final class scores.
|
||||
|
||||
Observe that some layers contain
|
||||
parameters and other don’t. In particular, the CNN layers perform
|
||||
transformations that are a function of not only the activations in the
|
||||
input volume, but also of the parameters (the weights and biases of
|
||||
the neurons). On the other hand, the RELU/POOL layers will implement a
|
||||
fixed function. The parameters in the CONV/FC layers will be trained
|
||||
with gradient descent so that the class scores that the CNN computes
|
||||
are consistent with the labels in the training set for each image.
|
||||
|
||||
|
||||
!split
|
||||
===== CNNs in brief =====
|
||||
|
||||
In summary:
|
||||
|
||||
* A CNN architecture is in the simplest case a list of Layers that transform the image volume into an output volume (e.g. holding the class scores)
|
||||
* There are a few distinct types of Layers (e.g. CONV/FC/RELU/POOL are by far the most popular)
|
||||
* Each Layer accepts an input 3D volume and transforms it to an output 3D volume through a differentiable function
|
||||
* Each Layer may or may not have parameters (e.g. CONV/FC do, RELU/POOL don’t)
|
||||
* Each Layer may or may not have additional hyperparameters (e.g. CONV/FC/POOL do, RELU doesn’t)
|
||||
|
||||
For more material on convolutional networks, we strongly recommend
|
||||
the course
|
||||
"IN5400 – Machine Learning for Image Analysis":"https://www.uio.no/studier/emner/matnat/ifi/IN5400/index-eng.html"
|
||||
and the slides of "CS231":"http://cs231n.github.io/convolutional-networks/" which is taught at Stanford University (consistently ranked as one of the top computer science programs in the world). "Michael Nielsen's book is a must read, in particular chapter 6 which deals with CNNs":"http://neuralnetworksanddeeplearning.com/chap6.html".
|
||||
|
||||
|
||||
!split
|
||||
===== CNNs in more detail, building convolutional neural networks in Tensorflow and Keras =====
|
||||
|
||||
|
||||
As discussed above, CNNs are neural networks built from the assumption that the inputs
|
||||
to the network are 2D images. This is important because the number of features or pixels in images
|
||||
grows very fast with the image size, and an enormous number of weights and biases are needed in order to build an accurate network.
|
||||
|
||||
As before, we still have our input, a hidden layer and an output. What's novel about convolutional networks
|
||||
are the _convolutional_ and _pooling_ layers stacked in pairs between the input and the hidden layer.
|
||||
In addition, the data is no longer represented as a 2D feature matrix, instead each input is a number of 2D
|
||||
matrices, typically 1 for each color dimension (Red, Green, Blue).
|
||||
|
||||
|
||||
!split
|
||||
===== Setting it up =====
|
||||
|
||||
It means that to represent the entire
|
||||
dataset of images, we require a 4D matrix or _tensor_. This tensor has the dimensions:
|
||||
!bt
|
||||
\[
|
||||
(n_{inputs},\, n_{pixels, width},\, n_{pixels, height},\, depth) .
|
||||
\]
|
||||
!et
|
||||
|
||||
!split
|
||||
===== The MNIST dataset again =====
|
||||
|
||||
The MNIST dataset consists of grayscale images with a pixel size of
|
||||
$28\times 28$, meaning we require $28 \times 28 = 724$ weights to each
|
||||
neuron in the first hidden layer.
|
||||
|
||||
If we were to analyze images of size $128\times 128$ we would require
|
||||
$128 \times 128 = 16384$ weights to each neuron. Even worse if we were
|
||||
dealing with color images, as most images are, we have an image matrix
|
||||
of size $128\times 128$ for each color dimension (Red, Green, Blue),
|
||||
meaning 3 times the number of weights $= 49152$ are required for every
|
||||
single neuron in the first hidden layer.
|
||||
|
||||
|
||||
!split
|
||||
===== Strong correlations =====
|
||||
Images typically have strong local correlations, meaning that a small
|
||||
part of the image varies little from its neighboring regions. If for
|
||||
example we have an image of a blue car, we can roughly assume that a
|
||||
small blue part of the image is surrounded by other blue regions.
|
||||
|
||||
Therefore, instead of connecting every single pixel to a neuron in the
|
||||
first hidden layer, as we have previously done with deep neural
|
||||
networks, we can instead connect each neuron to a small part of the
|
||||
image (in all 3 RGB depth dimensions). The size of each small area is
|
||||
fixed, and known as a "receptive":"https://en.wikipedia.org/wiki/Receptive_field".
|
||||
|
||||
|
||||
!split
|
||||
===== Layers of a CNN =====
|
||||
The layers of a convolutional neural network arrange neurons in 3D: width, height and depth.
|
||||
The input image is typically a square matrix of depth 3.
|
||||
|
||||
A _convolution_ is performed on the image which outputs
|
||||
a 3D volume of neurons. The weights to the input are arranged in a number of 2D matrices, known as _filters_.
|
||||
|
||||
|
||||
Each filter slides along the input image, taking the dot product
|
||||
between each small part of the image and the filter, in all depth
|
||||
dimensions. This is then passed through a non-linear function,
|
||||
typically the _Rectified Linear (ReLu)_ function, which serves as the
|
||||
activation of the neurons in the first convolutional layer. This is
|
||||
further passed through a _pooling layer_, which reduces the size of the
|
||||
convolutional layer, e.g. by taking the maximum or average across some
|
||||
small regions, and this serves as input to the next convolutional
|
||||
layer.
|
||||
|
||||
|
||||
!split
|
||||
===== Systematic reduction =====
|
||||
|
||||
By systematically reducing the size of the input volume, through
|
||||
convolution and pooling, the network should create representations of
|
||||
small parts of the input, and then from them assemble representations
|
||||
of larger areas. The final pooling layer is flattened to serve as
|
||||
input to a hidden layer, such that each neuron in the final pooling
|
||||
layer is connected to every single neuron in the hidden layer. This
|
||||
then serves as input to the output layer, e.g. a softmax output for
|
||||
classification.
|
||||
|
||||
|
||||
!split
|
||||
===== Prerequisites: Collect and pre-process data =====
|
||||
!bc pycod
|
||||
# import necessary packages
|
||||
import numpy as np
|
||||
import matplotlib.pyplot as plt
|
||||
from sklearn import datasets
|
||||
|
||||
|
||||
# ensure the same random numbers appear every time
|
||||
np.random.seed(0)
|
||||
|
||||
# display images in notebook
|
||||
%matplotlib inline
|
||||
plt.rcParams['figure.figsize'] = (12,12)
|
||||
|
||||
|
||||
# download MNIST dataset
|
||||
digits = datasets.load_digits()
|
||||
|
||||
# define inputs and labels
|
||||
inputs = digits.images
|
||||
labels = digits.target
|
||||
|
||||
# RGB images have a depth of 3
|
||||
# our images are grayscale so they should have a depth of 1
|
||||
inputs = inputs[:,:,:,np.newaxis]
|
||||
|
||||
print("inputs = (n_inputs, pixel_width, pixel_height, depth) = " + str(inputs.shape))
|
||||
print("labels = (n_inputs) = " + str(labels.shape))
|
||||
|
||||
|
||||
# choose some random images to display
|
||||
n_inputs = len(inputs)
|
||||
indices = np.arange(n_inputs)
|
||||
random_indices = np.random.choice(indices, size=5)
|
||||
|
||||
for i, image in enumerate(digits.images[random_indices]):
|
||||
plt.subplot(1, 5, i+1)
|
||||
plt.axis('off')
|
||||
plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
|
||||
plt.title("Label: %d" % digits.target[random_indices[i]])
|
||||
plt.show()
|
||||
!ec
|
||||
|
||||
|
||||
!split
|
||||
===== Importing Keras and Tensorflow =====
|
||||
!bc pycod
|
||||
from keras.utils import to_categorical
|
||||
from sklearn.model_selection import train_test_split
|
||||
|
||||
# representation of labels
|
||||
labels = to_categorical(labels)
|
||||
|
||||
# split into train and test data
|
||||
# one-liner from scikit-learn library
|
||||
train_size = 0.8
|
||||
test_size = 1 - train_size
|
||||
X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,
|
||||
test_size=test_size)
|
||||
!ec
|
||||
|
||||
!split
|
||||
===== Using TensorFlow backend =====
|
||||
|
||||
We need to define model and architecture and choose cost function and optmizer.
|
||||
!bc pycid
|
||||
|
||||
import tensorflow as tf
|
||||
|
||||
class ConvolutionalNeuralNetworkTensorflow:
|
||||
def __init__(
|
||||
self,
|
||||
X_train,
|
||||
Y_train,
|
||||
X_test,
|
||||
Y_test,
|
||||
n_filters=10,
|
||||
n_neurons_connected=50,
|
||||
n_categories=10,
|
||||
receptive_field=3,
|
||||
stride=1,
|
||||
padding=1,
|
||||
epochs=10,
|
||||
batch_size=100,
|
||||
eta=0.1,
|
||||
lmbd=0.0):
|
||||
|
||||
self.global_step = tf.Variable(0, dtype=tf.int32, trainable=False, name='global_step')
|
||||
|
||||
self.X_train = X_train
|
||||
self.Y_train = Y_train
|
||||
self.X_test = X_test
|
||||
self.Y_test = Y_test
|
||||
|
||||
self.n_inputs, self.input_width, self.input_height, self.depth = X_train.shape
|
||||
|
||||
self.n_filters = n_filters
|
||||
self.n_downsampled = int(self.input_width*self.input_height*n_filters / 4)
|
||||
self.n_neurons_connected = n_neurons_connected
|
||||
self.n_categories = n_categories
|
||||
|
||||
self.receptive_field = receptive_field
|
||||
self.stride = stride
|
||||
self.strides = [stride, stride, stride, stride]
|
||||
self.padding = padding
|
||||
|
||||
self.epochs = epochs
|
||||
self.batch_size = batch_size
|
||||
self.iterations = self.n_inputs // self.batch_size
|
||||
self.eta = eta
|
||||
self.lmbd = lmbd
|
||||
|
||||
self.create_placeholders()
|
||||
self.create_CNN()
|
||||
self.create_loss()
|
||||
self.create_optimiser()
|
||||
self.create_accuracy()
|
||||
|
||||
def create_placeholders(self):
|
||||
with tf.name_scope('data'):
|
||||
self.X = tf.placeholder(tf.float32, shape=(None, self.input_width, self.input_height, self.depth), name='X_data')
|
||||
self.Y = tf.placeholder(tf.float32, shape=(None, self.n_categories), name='Y_data')
|
||||
|
||||
def create_CNN(self):
|
||||
with tf.name_scope('CNN'):
|
||||
|
||||
# Convolutional layer
|
||||
self.W_conv = self.weight_variable([self.receptive_field, self.receptive_field, self.depth, self.n_filters], name='conv', dtype=tf.float32)
|
||||
b_conv = self.weight_variable([self.n_filters], name='conv', dtype=tf.float32)
|
||||
z_conv = tf.nn.conv2d(self.X, self.W_conv, self.strides, padding='SAME', name='conv') + b_conv
|
||||
a_conv = tf.nn.relu(z_conv)
|
||||
|
||||
# 2x2 max pooling
|
||||
a_pool = tf.nn.max_pool(a_conv, [1, 2, 2, 1], [1, 2, 2, 1], padding='SAME', name='pool')
|
||||
|
||||
# Fully connected layer
|
||||
a_pool_flat = tf.reshape(a_pool, [-1, self.n_downsampled])
|
||||
self.W_fc = self.weight_variable([self.n_downsampled, self.n_neurons_connected], name='fc', dtype=tf.float32)
|
||||
b_fc = self.bias_variable([self.n_neurons_connected], name='fc', dtype=tf.float32)
|
||||
a_fc = tf.nn.relu(tf.matmul(a_pool_flat, self.W_fc) + b_fc)
|
||||
|
||||
# Output layer
|
||||
self.W_out = self.weight_variable([self.n_neurons_connected, self.n_categories], name='out', dtype=tf.float32)
|
||||
b_out = self.bias_variable([self.n_categories], name='out', dtype=tf.float32)
|
||||
self.z_out = tf.matmul(a_fc, self.W_out) + b_out
|
||||
|
||||
def create_loss(self):
|
||||
with tf.name_scope('loss'):
|
||||
softmax_loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=self.Y, logits=self.z_out))
|
||||
|
||||
regularizer_loss_conv = tf.nn.l2_loss(self.W_conv)
|
||||
regularizer_loss_fc = tf.nn.l2_loss(self.W_fc)
|
||||
regularizer_loss_out = tf.nn.l2_loss(self.W_out)
|
||||
regularizer_loss = self.lmbd*(regularizer_loss_conv + regularizer_loss_fc + regularizer_loss_out)
|
||||
|
||||
self.loss = softmax_loss + regularizer_loss
|
||||
|
||||
def create_accuracy(self):
|
||||
with tf.name_scope('accuracy'):
|
||||
probabilities = tf.nn.softmax(self.z_out)
|
||||
predictions = tf.argmax(probabilities, 1)
|
||||
labels = tf.argmax(self.Y, 1)
|
||||
|
||||
correct_predictions = tf.equal(predictions, labels)
|
||||
correct_predictions = tf.cast(correct_predictions, tf.float32)
|
||||
self.accuracy = tf.reduce_mean(correct_predictions)
|
||||
|
||||
def create_optimiser(self):
|
||||
with tf.name_scope('optimizer'):
|
||||
self.optimizer = tf.train.GradientDescentOptimizer(learning_rate=self.eta).minimize(self.loss, global_step=self.global_step)
|
||||
|
||||
def weight_variable(self, shape, name='', dtype=tf.float32):
|
||||
initial = tf.truncated_normal(shape, stddev=0.1)
|
||||
return tf.Variable(initial, name=name, dtype=dtype)
|
||||
|
||||
def bias_variable(self, shape, name='', dtype=tf.float32):
|
||||
initial = tf.constant(0.1, shape=shape)
|
||||
return tf.Variable(initial, name=name, dtype=dtype)
|
||||
|
||||
def fit(self):
|
||||
data_indices = np.arange(self.n_inputs)
|
||||
|
||||
with tf.Session() as sess:
|
||||
sess.run(tf.global_variables_initializer())
|
||||
for i in range(self.epochs):
|
||||
for j in range(self.iterations):
|
||||
chosen_datapoints = np.random.choice(data_indices, size=self.batch_size, replace=False)
|
||||
batch_X, batch_Y = self.X_train[chosen_datapoints], self.Y_train[chosen_datapoints]
|
||||
|
||||
sess.run([CNN.loss, CNN.optimizer],
|
||||
feed_dict={CNN.X: batch_X,
|
||||
CNN.Y: batch_Y})
|
||||
accuracy = sess.run(CNN.accuracy,
|
||||
feed_dict={CNN.X: batch_X,
|
||||
CNN.Y: batch_Y})
|
||||
step = sess.run(CNN.global_step)
|
||||
|
||||
self.train_loss, self.train_accuracy = sess.run([CNN.loss, CNN.accuracy],
|
||||
feed_dict={CNN.X: self.X_train,
|
||||
CNN.Y: self.Y_train})
|
||||
|
||||
self.test_loss, self.test_accuracy = sess.run([CNN.loss, CNN.accuracy],
|
||||
feed_dict={CNN.X: self.X_test,
|
||||
CNN.Y: self.Y_test})
|
||||
!ec
|
||||
|
||||
!split
|
||||
===== Train the model =====
|
||||
|
||||
We need now to train the model, evaluate it and test its performance on test data, and eventually include hyperparameters.
|
||||
!bc pycod
|
||||
epochs = 100
|
||||
batch_size = 100
|
||||
n_filters = 10
|
||||
n_neurons_connected = 50
|
||||
n_categories = 10
|
||||
|
||||
eta_vals = np.logspace(-5, 1, 7)
|
||||
lmbd_vals = np.logspace(-5, 1, 7)
|
||||
CNN_tf = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
|
||||
|
||||
for i, eta in enumerate(eta_vals):
|
||||
for j, lmbd in enumerate(lmbd_vals):
|
||||
CNN = ConvolutionalNeuralNetworkTensorflow(X_train, Y_train, X_test, Y_test,
|
||||
n_filters=n_filters, n_neurons_connected=n_neurons_connected,
|
||||
n_categories=n_categories, epochs=epochs, batch_size=batch_size,
|
||||
eta=eta, lmbd=lmbd)
|
||||
CNN.fit()
|
||||
|
||||
print("Learning rate = ", eta)
|
||||
print("Lambda = ", lmbd)
|
||||
print("Test accuracy: %.3f" % CNN.test_accuracy)
|
||||
print()
|
||||
|
||||
CNN_tf[i][j] = CNN
|
||||
!ec
|
||||
|
||||
!split
|
||||
===== Visualizing the results =====
|
||||
|
||||
!bc pycod
|
||||
# visual representation of grid search
|
||||
# uses seaborn heatmap, could probably do this in matplotlib
|
||||
import seaborn as sns
|
||||
|
||||
sns.set()
|
||||
|
||||
train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
|
||||
test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
|
||||
|
||||
for i in range(len(eta_vals)):
|
||||
for j in range(len(lmbd_vals)):
|
||||
CNN = CNN_tf[i][j]
|
||||
|
||||
train_accuracy[i][j] = CNN.train_accuracy
|
||||
test_accuracy[i][j] = CNN.test_accuracy
|
||||
|
||||
|
||||
fig, ax = plt.subplots(figsize = (10, 10))
|
||||
sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
|
||||
ax.set_title("Training Accuracy")
|
||||
ax.set_ylabel("$\eta$")
|
||||
ax.set_xlabel("$\lambda$")
|
||||
plt.show()
|
||||
|
||||
fig, ax = plt.subplots(figsize = (10, 10))
|
||||
sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
|
||||
ax.set_title("Test Accuracy")
|
||||
ax.set_ylabel("$\eta$")
|
||||
ax.set_xlabel("$\lambda$")
|
||||
plt.show()
|
||||
!ec
|
||||
|
||||
!split
|
||||
===== Running with Keras =====
|
||||
|
||||
!bc pycod
|
||||
from keras.models import Sequential
|
||||
from keras.layers.convolutional import Conv2D
|
||||
from keras.layers.convolutional import MaxPooling2D
|
||||
from keras.layers import Flatten
|
||||
from keras.layers import Dense
|
||||
from keras.regularizers import l2
|
||||
from keras.optimizers import SGD
|
||||
|
||||
def create_convolutional_neural_network_keras(input_shape, receptive_field,
|
||||
n_filters, n_neurons_connected, n_categories,
|
||||
eta, lmbd):
|
||||
model = Sequential()
|
||||
model.add(Conv2D(n_filters, (receptive_field, receptive_field), input_shape=input_shape, padding='same',
|
||||
activation='relu', kernel_regularizer=l2(lmbd)))
|
||||
model.add(MaxPooling2D(pool_size=(2, 2)))
|
||||
model.add(Flatten())
|
||||
model.add(Dense(n_neurons_connected, activation='relu', kernel_regularizer=l2(lmbd)))
|
||||
model.add(Dense(n_categories, activation='softmax', kernel_regularizer=l2(lmbd)))
|
||||
|
||||
sgd = SGD(lr=eta)
|
||||
model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])
|
||||
|
||||
return model
|
||||
|
||||
epochs = 100
|
||||
batch_size = 100
|
||||
input_shape = X_train.shape[1:4]
|
||||
receptive_field = 3
|
||||
n_filters = 10
|
||||
n_neurons_connected = 50
|
||||
n_categories = 10
|
||||
|
||||
eta_vals = np.logspace(-5, 1, 7)
|
||||
lmbd_vals = np.logspace(-5, 1, 7)
|
||||
!ec
|
||||
|
||||
!split
|
||||
===== Final part =====
|
||||
|
||||
!bc pycod
|
||||
CNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
|
||||
|
||||
for i, eta in enumerate(eta_vals):
|
||||
for j, lmbd in enumerate(lmbd_vals):
|
||||
CNN = create_convolutional_neural_network_keras(input_shape, receptive_field,
|
||||
n_filters, n_neurons_connected, n_categories,
|
||||
eta, lmbd)
|
||||
CNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0)
|
||||
scores = CNN.evaluate(X_test, Y_test)
|
||||
|
||||
CNN_keras[i][j] = CNN
|
||||
|
||||
print("Learning rate = ", eta)
|
||||
print("Lambda = ", lmbd)
|
||||
print("Test accuracy: %.3f" % scores[1])
|
||||
print()
|
||||
!ec
|
||||
|
||||
!split
|
||||
===== Final visualization =====
|
||||
|
||||
!bc
|
||||
# visual representation of grid search
|
||||
# uses seaborn heatmap, could probably do this in matplotlib
|
||||
import seaborn as sns
|
||||
|
||||
sns.set()
|
||||
|
||||
train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
|
||||
test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
|
||||
|
||||
for i in range(len(eta_vals)):
|
||||
for j in range(len(lmbd_vals)):
|
||||
CNN = CNN_keras[i][j]
|
||||
|
||||
train_accuracy[i][j] = CNN.evaluate(X_train, Y_train)[1]
|
||||
test_accuracy[i][j] = CNN.evaluate(X_test, Y_test)[1]
|
||||
|
||||
|
||||
fig, ax = plt.subplots(figsize = (10, 10))
|
||||
sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
|
||||
ax.set_title("Training Accuracy")
|
||||
ax.set_ylabel("$\eta$")
|
||||
ax.set_xlabel("$\lambda$")
|
||||
plt.show()
|
||||
|
||||
fig, ax = plt.subplots(figsize = (10, 10))
|
||||
sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
|
||||
ax.set_title("Test Accuracy")
|
||||
ax.set_ylabel("$\eta$")
|
||||
ax.set_xlabel("$\lambda$")
|
||||
plt.show()
|
||||
!ec
|
||||
|
||||
!split
|
||||
===== Fun links =====
|
||||
|
||||
o "Self-Driving cars using a convolutional neural network":"https://arxiv.org/abs/1604.07316"
|
||||
o "Abstract art using convolutional neural networks":"https://deepdreamgenerator.com/"
|
||||
|
||||
|
||||
@@ -0,0 +1,616 @@
|
||||
TITLE: Convolutional Neural Networks
|
||||
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
|
||||
===== To do list =====
|
||||
|
||||
* add material about the mathematics, with more explanations
|
||||
* update codes to tensorflow 2
|
||||
* add more elaborated examples
|
||||
* update keras codes and think of pytorch examples?
|
||||
* Example on pollen cases https://journals.plos.org/plosone/article?id=10.1371/journal.pone.0229751
|
||||
* Example on nuclear physics experiments
|
||||
!split
|
||||
===== Convolutional Neural Networks (recognizing images) =====
|
||||
|
||||
|
||||
Convolutional neural networks (CNNs) were developed during the last
|
||||
decade of the previous century, with a focus on character recognition
|
||||
tasks. Nowadays, CNNs are a central element in the spectacular success
|
||||
of dee learning methods. The success in for example image
|
||||
classifications have made them a central tool for most machine
|
||||
learning practitioners.
|
||||
|
||||
CNNs are very similar to ordinary Neural Networks.
|
||||
They are made up of neurons that have learnable weights and
|
||||
biases. Each neuron receives some inputs, performs a dot product and
|
||||
optionally follows it with a non-linearity. The whole network still
|
||||
expresses a single differentiable score function: from the raw image
|
||||
pixels on one end to class scores at the other. And they still have a
|
||||
loss function (for example Softmax) on the last (fully-connected) layer
|
||||
and all the tips/tricks we developed for learning regular Neural
|
||||
Networks still apply (back propagation, gradient descent etc etc).
|
||||
|
||||
What is the difference? _CNN architectures make the explicit assumption that
|
||||
the inputs are images, which allows us to encode certain properties
|
||||
into the architecture. These then make the forward function more
|
||||
efficient to implement and vastly reduce the amount of parameters in
|
||||
the network._
|
||||
|
||||
Here we provide only a superficial overview, for the more interested, we recommend highly the course
|
||||
"IN5400 – Machine Learning for Image Analysis":"https://www.uio.no/studier/emner/matnat/ifi/IN5400/index-eng.html"
|
||||
and the slides of "CS231":"http://cs231n.github.io/convolutional-networks/".
|
||||
|
||||
Another good read is the article here URL:"https://arxiv.org/pdf/1603.07285.pdf".
|
||||
|
||||
!split
|
||||
===== Regular NNs don’t scale well to full images =====
|
||||
|
||||
As an example, consider
|
||||
an image of size $32\times 32\times 3$ (32 wide, 32 high, 3 color channels), so a
|
||||
single fully-connected neuron in a first hidden layer of a regular
|
||||
Neural Network would have $32\times 32\times 3 = 3072$ weights. This amount still
|
||||
seems manageable, but clearly this fully-connected structure does not
|
||||
scale to larger images. For example, an image of more respectable
|
||||
size, say $200\times 200\times 3$, would lead to neurons that have
|
||||
$200\times 200\times 3 = 120,000$ weights.
|
||||
|
||||
We could have
|
||||
several such neurons, and the parameters would add up quickly! Clearly,
|
||||
this full connectivity is wasteful and the huge number of parameters
|
||||
would quickly lead to possible overfitting.
|
||||
|
||||
FIGURE: [figslides/nn.jpeg, width=500 frac=0.6] A regular 3-layer Neural Network.
|
||||
|
||||
!split
|
||||
===== 3D volumes of neurons =====
|
||||
|
||||
Convolutional Neural Networks take advantage of the fact that the
|
||||
input consists of images and they constrain the architecture in a more
|
||||
sensible way.
|
||||
|
||||
In particular, unlike a regular Neural Network, the
|
||||
layers of a CNN have neurons arranged in 3 dimensions: width,
|
||||
height, depth. (Note that the word depth here refers to the third
|
||||
dimension of an activation volume, not to the depth of a full Neural
|
||||
Network, which can refer to the total number of layers in a network.)
|
||||
|
||||
To understand it better, the above example of an image
|
||||
with an input volume of
|
||||
activations has dimensions $32\times 32\times 3$ (width, height,
|
||||
depth respectively).
|
||||
|
||||
The neurons in a layer will
|
||||
only be connected to a small region of the layer before it, instead of
|
||||
all of the neurons in a fully-connected manner. Moreover, the final
|
||||
output layer could for this specific image have dimensions $1\times 1 \times 10$,
|
||||
because by the
|
||||
end of the CNN architecture we will reduce the full image into a
|
||||
single vector of class scores, arranged along the depth
|
||||
dimension.
|
||||
|
||||
FIGURE: [figslides/cnn.jpeg, width=500 frac=0.6] A CNN arranges its neurons in three dimensions (width, height, depth), as visualized in one of the layers. Every layer of a CNN transforms the 3D input volume to a 3D output volume of neuron activations. In this example, the red input layer holds the image, so its width and height would be the dimensions of the image, and the depth would be 3 (Red, Green, Blue channels).
|
||||
|
||||
|
||||
|
||||
!split
|
||||
===== Layers used to build CNNs =====
|
||||
|
||||
|
||||
A simple CNN is a sequence of layers, and every layer of a CNN
|
||||
transforms one volume of activations to another through a
|
||||
differentiable function. We use three main types of layers to build
|
||||
CNN architectures: Convolutional Layer, Pooling Layer, and
|
||||
Fully-Connected Layer (exactly as seen in regular Neural Networks). We
|
||||
will stack these layers to form a full CNN architecture.
|
||||
|
||||
A simple CNN for image classification could have the architecture:
|
||||
|
||||
* _INPUT_ ($32\times 32 \times 3$) will hold the raw pixel values of the image, in this case an image of width 32, height 32, and with three color channels R,G,B.
|
||||
* _CONV_ (convolutional )layer will compute the output of neurons that are connected to local regions in the input, each computing a dot product between their weights and a small region they are connected to in the input volume. This may result in volume such as $[32\times 32\times 12]$ if we decided to use 12 filters.
|
||||
* _RELU_ layer will apply an elementwise activation function, such as the $max(0,x)$ thresholding at zero. This leaves the size of the volume unchanged ($[32\times 32\times 12]$).
|
||||
* _POOL_ (pooling) layer will perform a downsampling operation along the spatial dimensions (width, height), resulting in volume such as $[16\times 16\times 12]$.
|
||||
* _FC_ (i.e. fully-connected) layer will compute the class scores, resulting in volume of size $[1\times 1\times 10]$, where each of the 10 numbers correspond to a class score, such as among the 10 categories of the MNIST images we considered above . As with ordinary Neural Networks and as the name implies, each neuron in this layer will be connected to all the numbers in the previous volume.
|
||||
|
||||
|
||||
!split
|
||||
===== Transforming images =====
|
||||
|
||||
CNNs transform the original image layer by layer from the original
|
||||
pixel values to the final class scores.
|
||||
|
||||
Observe that some layers contain
|
||||
parameters and other don’t. In particular, the CNN layers perform
|
||||
transformations that are a function of not only the activations in the
|
||||
input volume, but also of the parameters (the weights and biases of
|
||||
the neurons). On the other hand, the RELU/POOL layers will implement a
|
||||
fixed function. The parameters in the CONV/FC layers will be trained
|
||||
with gradient descent so that the class scores that the CNN computes
|
||||
are consistent with the labels in the training set for each image.
|
||||
|
||||
|
||||
!split
|
||||
===== CNNs in brief =====
|
||||
|
||||
In summary:
|
||||
|
||||
* A CNN architecture is in the simplest case a list of Layers that transform the image volume into an output volume (e.g. holding the class scores)
|
||||
* There are a few distinct types of Layers (e.g. CONV/FC/RELU/POOL are by far the most popular)
|
||||
* Each Layer accepts an input 3D volume and transforms it to an output 3D volume through a differentiable function
|
||||
* Each Layer may or may not have parameters (e.g. CONV/FC do, RELU/POOL don’t)
|
||||
* Each Layer may or may not have additional hyperparameters (e.g. CONV/FC/POOL do, RELU doesn’t)
|
||||
|
||||
For more material on convolutional networks, we strongly recommend
|
||||
the course
|
||||
"IN5400 – Machine Learning for Image Analysis":"https://www.uio.no/studier/emner/matnat/ifi/IN5400/index-eng.html"
|
||||
and the slides of "CS231":"http://cs231n.github.io/convolutional-networks/" which is taught at Stanford University (consistently ranked as one of the top computer science programs in the world). "Michael Nielsen's book is a must read, in particular chapter 6 which deals with CNNs":"http://neuralnetworksanddeeplearning.com/chap6.html".
|
||||
|
||||
|
||||
!split
|
||||
===== CNNs in more detail, building convolutional neural networks in Tensorflow and Keras =====
|
||||
|
||||
|
||||
As discussed above, CNNs are neural networks built from the assumption that the inputs
|
||||
to the network are 2D images. This is important because the number of features or pixels in images
|
||||
grows very fast with the image size, and an enormous number of weights and biases are needed in order to build an accurate network.
|
||||
|
||||
As before, we still have our input, a hidden layer and an output. What's novel about convolutional networks
|
||||
are the _convolutional_ and _pooling_ layers stacked in pairs between the input and the hidden layer.
|
||||
In addition, the data is no longer represented as a 2D feature matrix, instead each input is a number of 2D
|
||||
matrices, typically 1 for each color dimension (Red, Green, Blue).
|
||||
|
||||
|
||||
!split
|
||||
===== Setting it up =====
|
||||
|
||||
It means that to represent the entire
|
||||
dataset of images, we require a 4D matrix or _tensor_. This tensor has the dimensions:
|
||||
!bt
|
||||
\[
|
||||
(n_{inputs},\, n_{pixels, width},\, n_{pixels, height},\, depth) .
|
||||
\]
|
||||
!et
|
||||
|
||||
!split
|
||||
===== The MNIST dataset again =====
|
||||
|
||||
The MNIST dataset consists of grayscale images with a pixel size of
|
||||
$28\times 28$, meaning we require $28 \times 28 = 724$ weights to each
|
||||
neuron in the first hidden layer.
|
||||
|
||||
If we were to analyze images of size $128\times 128$ we would require
|
||||
$128 \times 128 = 16384$ weights to each neuron. Even worse if we were
|
||||
dealing with color images, as most images are, we have an image matrix
|
||||
of size $128\times 128$ for each color dimension (Red, Green, Blue),
|
||||
meaning 3 times the number of weights $= 49152$ are required for every
|
||||
single neuron in the first hidden layer.
|
||||
|
||||
|
||||
!split
|
||||
===== Strong correlations =====
|
||||
Images typically have strong local correlations, meaning that a small
|
||||
part of the image varies little from its neighboring regions. If for
|
||||
example we have an image of a blue car, we can roughly assume that a
|
||||
small blue part of the image is surrounded by other blue regions.
|
||||
|
||||
Therefore, instead of connecting every single pixel to a neuron in the
|
||||
first hidden layer, as we have previously done with deep neural
|
||||
networks, we can instead connect each neuron to a small part of the
|
||||
image (in all 3 RGB depth dimensions). The size of each small area is
|
||||
fixed, and known as a "receptive":"https://en.wikipedia.org/wiki/Receptive_field".
|
||||
|
||||
|
||||
!split
|
||||
===== Layers of a CNN =====
|
||||
The layers of a convolutional neural network arrange neurons in 3D: width, height and depth.
|
||||
The input image is typically a square matrix of depth 3.
|
||||
|
||||
A _convolution_ is performed on the image which outputs
|
||||
a 3D volume of neurons. The weights to the input are arranged in a number of 2D matrices, known as _filters_.
|
||||
|
||||
|
||||
Each filter slides along the input image, taking the dot product
|
||||
between each small part of the image and the filter, in all depth
|
||||
dimensions. This is then passed through a non-linear function,
|
||||
typically the _Rectified Linear (ReLu)_ function, which serves as the
|
||||
activation of the neurons in the first convolutional layer. This is
|
||||
further passed through a _pooling layer_, which reduces the size of the
|
||||
convolutional layer, e.g. by taking the maximum or average across some
|
||||
small regions, and this serves as input to the next convolutional
|
||||
layer.
|
||||
|
||||
|
||||
!split
|
||||
===== Systematic reduction =====
|
||||
|
||||
By systematically reducing the size of the input volume, through
|
||||
convolution and pooling, the network should create representations of
|
||||
small parts of the input, and then from them assemble representations
|
||||
of larger areas. The final pooling layer is flattened to serve as
|
||||
input to a hidden layer, such that each neuron in the final pooling
|
||||
layer is connected to every single neuron in the hidden layer. This
|
||||
then serves as input to the output layer, e.g. a softmax output for
|
||||
classification.
|
||||
|
||||
|
||||
!split
|
||||
===== Prerequisites: Collect and pre-process data =====
|
||||
!bc pycod
|
||||
# import necessary packages
|
||||
import numpy as np
|
||||
import matplotlib.pyplot as plt
|
||||
from sklearn import datasets
|
||||
|
||||
|
||||
# ensure the same random numbers appear every time
|
||||
np.random.seed(0)
|
||||
|
||||
# display images in notebook
|
||||
%matplotlib inline
|
||||
plt.rcParams['figure.figsize'] = (12,12)
|
||||
|
||||
|
||||
# download MNIST dataset
|
||||
digits = datasets.load_digits()
|
||||
|
||||
# define inputs and labels
|
||||
inputs = digits.images
|
||||
labels = digits.target
|
||||
|
||||
# RGB images have a depth of 3
|
||||
# our images are grayscale so they should have a depth of 1
|
||||
inputs = inputs[:,:,:,np.newaxis]
|
||||
|
||||
print("inputs = (n_inputs, pixel_width, pixel_height, depth) = " + str(inputs.shape))
|
||||
print("labels = (n_inputs) = " + str(labels.shape))
|
||||
|
||||
|
||||
# choose some random images to display
|
||||
n_inputs = len(inputs)
|
||||
indices = np.arange(n_inputs)
|
||||
random_indices = np.random.choice(indices, size=5)
|
||||
|
||||
for i, image in enumerate(digits.images[random_indices]):
|
||||
plt.subplot(1, 5, i+1)
|
||||
plt.axis('off')
|
||||
plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
|
||||
plt.title("Label: %d" % digits.target[random_indices[i]])
|
||||
plt.show()
|
||||
!ec
|
||||
|
||||
|
||||
!split
|
||||
===== Importing Keras and Tensorflow =====
|
||||
!bc pycod
|
||||
from keras.utils import to_categorical
|
||||
from sklearn.model_selection import train_test_split
|
||||
|
||||
# representation of labels
|
||||
labels = to_categorical(labels)
|
||||
|
||||
# split into train and test data
|
||||
# one-liner from scikit-learn library
|
||||
train_size = 0.8
|
||||
test_size = 1 - train_size
|
||||
X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,
|
||||
test_size=test_size)
|
||||
!ec
|
||||
|
||||
!split
|
||||
===== Using TensorFlow backend =====
|
||||
|
||||
We need to define model and architecture and choose cost function and optmizer.
|
||||
!bc pycid
|
||||
|
||||
import tensorflow as tf
|
||||
|
||||
class ConvolutionalNeuralNetworkTensorflow:
|
||||
def __init__(
|
||||
self,
|
||||
X_train,
|
||||
Y_train,
|
||||
X_test,
|
||||
Y_test,
|
||||
n_filters=10,
|
||||
n_neurons_connected=50,
|
||||
n_categories=10,
|
||||
receptive_field=3,
|
||||
stride=1,
|
||||
padding=1,
|
||||
epochs=10,
|
||||
batch_size=100,
|
||||
eta=0.1,
|
||||
lmbd=0.0):
|
||||
|
||||
self.global_step = tf.Variable(0, dtype=tf.int32, trainable=False, name='global_step')
|
||||
|
||||
self.X_train = X_train
|
||||
self.Y_train = Y_train
|
||||
self.X_test = X_test
|
||||
self.Y_test = Y_test
|
||||
|
||||
self.n_inputs, self.input_width, self.input_height, self.depth = X_train.shape
|
||||
|
||||
self.n_filters = n_filters
|
||||
self.n_downsampled = int(self.input_width*self.input_height*n_filters / 4)
|
||||
self.n_neurons_connected = n_neurons_connected
|
||||
self.n_categories = n_categories
|
||||
|
||||
self.receptive_field = receptive_field
|
||||
self.stride = stride
|
||||
self.strides = [stride, stride, stride, stride]
|
||||
self.padding = padding
|
||||
|
||||
self.epochs = epochs
|
||||
self.batch_size = batch_size
|
||||
self.iterations = self.n_inputs // self.batch_size
|
||||
self.eta = eta
|
||||
self.lmbd = lmbd
|
||||
|
||||
self.create_placeholders()
|
||||
self.create_CNN()
|
||||
self.create_loss()
|
||||
self.create_optimiser()
|
||||
self.create_accuracy()
|
||||
|
||||
def create_placeholders(self):
|
||||
with tf.name_scope('data'):
|
||||
self.X = tf.placeholder(tf.float32, shape=(None, self.input_width, self.input_height, self.depth), name='X_data')
|
||||
self.Y = tf.placeholder(tf.float32, shape=(None, self.n_categories), name='Y_data')
|
||||
|
||||
def create_CNN(self):
|
||||
with tf.name_scope('CNN'):
|
||||
|
||||
# Convolutional layer
|
||||
self.W_conv = self.weight_variable([self.receptive_field, self.receptive_field, self.depth, self.n_filters], name='conv', dtype=tf.float32)
|
||||
b_conv = self.weight_variable([self.n_filters], name='conv', dtype=tf.float32)
|
||||
z_conv = tf.nn.conv2d(self.X, self.W_conv, self.strides, padding='SAME', name='conv') + b_conv
|
||||
a_conv = tf.nn.relu(z_conv)
|
||||
|
||||
# 2x2 max pooling
|
||||
a_pool = tf.nn.max_pool(a_conv, [1, 2, 2, 1], [1, 2, 2, 1], padding='SAME', name='pool')
|
||||
|
||||
# Fully connected layer
|
||||
a_pool_flat = tf.reshape(a_pool, [-1, self.n_downsampled])
|
||||
self.W_fc = self.weight_variable([self.n_downsampled, self.n_neurons_connected], name='fc', dtype=tf.float32)
|
||||
b_fc = self.bias_variable([self.n_neurons_connected], name='fc', dtype=tf.float32)
|
||||
a_fc = tf.nn.relu(tf.matmul(a_pool_flat, self.W_fc) + b_fc)
|
||||
|
||||
# Output layer
|
||||
self.W_out = self.weight_variable([self.n_neurons_connected, self.n_categories], name='out', dtype=tf.float32)
|
||||
b_out = self.bias_variable([self.n_categories], name='out', dtype=tf.float32)
|
||||
self.z_out = tf.matmul(a_fc, self.W_out) + b_out
|
||||
|
||||
def create_loss(self):
|
||||
with tf.name_scope('loss'):
|
||||
softmax_loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=self.Y, logits=self.z_out))
|
||||
|
||||
regularizer_loss_conv = tf.nn.l2_loss(self.W_conv)
|
||||
regularizer_loss_fc = tf.nn.l2_loss(self.W_fc)
|
||||
regularizer_loss_out = tf.nn.l2_loss(self.W_out)
|
||||
regularizer_loss = self.lmbd*(regularizer_loss_conv + regularizer_loss_fc + regularizer_loss_out)
|
||||
|
||||
self.loss = softmax_loss + regularizer_loss
|
||||
|
||||
def create_accuracy(self):
|
||||
with tf.name_scope('accuracy'):
|
||||
probabilities = tf.nn.softmax(self.z_out)
|
||||
predictions = tf.argmax(probabilities, 1)
|
||||
labels = tf.argmax(self.Y, 1)
|
||||
|
||||
correct_predictions = tf.equal(predictions, labels)
|
||||
correct_predictions = tf.cast(correct_predictions, tf.float32)
|
||||
self.accuracy = tf.reduce_mean(correct_predictions)
|
||||
|
||||
def create_optimiser(self):
|
||||
with tf.name_scope('optimizer'):
|
||||
self.optimizer = tf.train.GradientDescentOptimizer(learning_rate=self.eta).minimize(self.loss, global_step=self.global_step)
|
||||
|
||||
def weight_variable(self, shape, name='', dtype=tf.float32):
|
||||
initial = tf.truncated_normal(shape, stddev=0.1)
|
||||
return tf.Variable(initial, name=name, dtype=dtype)
|
||||
|
||||
def bias_variable(self, shape, name='', dtype=tf.float32):
|
||||
initial = tf.constant(0.1, shape=shape)
|
||||
return tf.Variable(initial, name=name, dtype=dtype)
|
||||
|
||||
def fit(self):
|
||||
data_indices = np.arange(self.n_inputs)
|
||||
|
||||
with tf.Session() as sess:
|
||||
sess.run(tf.global_variables_initializer())
|
||||
for i in range(self.epochs):
|
||||
for j in range(self.iterations):
|
||||
chosen_datapoints = np.random.choice(data_indices, size=self.batch_size, replace=False)
|
||||
batch_X, batch_Y = self.X_train[chosen_datapoints], self.Y_train[chosen_datapoints]
|
||||
|
||||
sess.run([CNN.loss, CNN.optimizer],
|
||||
feed_dict={CNN.X: batch_X,
|
||||
CNN.Y: batch_Y})
|
||||
accuracy = sess.run(CNN.accuracy,
|
||||
feed_dict={CNN.X: batch_X,
|
||||
CNN.Y: batch_Y})
|
||||
step = sess.run(CNN.global_step)
|
||||
|
||||
self.train_loss, self.train_accuracy = sess.run([CNN.loss, CNN.accuracy],
|
||||
feed_dict={CNN.X: self.X_train,
|
||||
CNN.Y: self.Y_train})
|
||||
|
||||
self.test_loss, self.test_accuracy = sess.run([CNN.loss, CNN.accuracy],
|
||||
feed_dict={CNN.X: self.X_test,
|
||||
CNN.Y: self.Y_test})
|
||||
!ec
|
||||
|
||||
!split
|
||||
===== Train the model =====
|
||||
|
||||
We need now to train the model, evaluate it and test its performance on test data, and eventually include hyperparameters.
|
||||
!bc pycod
|
||||
epochs = 100
|
||||
batch_size = 100
|
||||
n_filters = 10
|
||||
n_neurons_connected = 50
|
||||
n_categories = 10
|
||||
|
||||
eta_vals = np.logspace(-5, 1, 7)
|
||||
lmbd_vals = np.logspace(-5, 1, 7)
|
||||
CNN_tf = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
|
||||
|
||||
for i, eta in enumerate(eta_vals):
|
||||
for j, lmbd in enumerate(lmbd_vals):
|
||||
CNN = ConvolutionalNeuralNetworkTensorflow(X_train, Y_train, X_test, Y_test,
|
||||
n_filters=n_filters, n_neurons_connected=n_neurons_connected,
|
||||
n_categories=n_categories, epochs=epochs, batch_size=batch_size,
|
||||
eta=eta, lmbd=lmbd)
|
||||
CNN.fit()
|
||||
|
||||
print("Learning rate = ", eta)
|
||||
print("Lambda = ", lmbd)
|
||||
print("Test accuracy: %.3f" % CNN.test_accuracy)
|
||||
print()
|
||||
|
||||
CNN_tf[i][j] = CNN
|
||||
!ec
|
||||
|
||||
!split
|
||||
===== Visualizing the results =====
|
||||
|
||||
!bc pycod
|
||||
# visual representation of grid search
|
||||
# uses seaborn heatmap, could probably do this in matplotlib
|
||||
import seaborn as sns
|
||||
|
||||
sns.set()
|
||||
|
||||
train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
|
||||
test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
|
||||
|
||||
for i in range(len(eta_vals)):
|
||||
for j in range(len(lmbd_vals)):
|
||||
CNN = CNN_tf[i][j]
|
||||
|
||||
train_accuracy[i][j] = CNN.train_accuracy
|
||||
test_accuracy[i][j] = CNN.test_accuracy
|
||||
|
||||
|
||||
fig, ax = plt.subplots(figsize = (10, 10))
|
||||
sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
|
||||
ax.set_title("Training Accuracy")
|
||||
ax.set_ylabel("$\eta$")
|
||||
ax.set_xlabel("$\lambda$")
|
||||
plt.show()
|
||||
|
||||
fig, ax = plt.subplots(figsize = (10, 10))
|
||||
sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
|
||||
ax.set_title("Test Accuracy")
|
||||
ax.set_ylabel("$\eta$")
|
||||
ax.set_xlabel("$\lambda$")
|
||||
plt.show()
|
||||
!ec
|
||||
|
||||
!split
|
||||
===== Running with Keras =====
|
||||
|
||||
!bc pycod
|
||||
from keras.models import Sequential
|
||||
from keras.layers.convolutional import Conv2D
|
||||
from keras.layers.convolutional import MaxPooling2D
|
||||
from keras.layers import Flatten
|
||||
from keras.layers import Dense
|
||||
from keras.regularizers import l2
|
||||
from keras.optimizers import SGD
|
||||
|
||||
def create_convolutional_neural_network_keras(input_shape, receptive_field,
|
||||
n_filters, n_neurons_connected, n_categories,
|
||||
eta, lmbd):
|
||||
model = Sequential()
|
||||
model.add(Conv2D(n_filters, (receptive_field, receptive_field), input_shape=input_shape, padding='same',
|
||||
activation='relu', kernel_regularizer=l2(lmbd)))
|
||||
model.add(MaxPooling2D(pool_size=(2, 2)))
|
||||
model.add(Flatten())
|
||||
model.add(Dense(n_neurons_connected, activation='relu', kernel_regularizer=l2(lmbd)))
|
||||
model.add(Dense(n_categories, activation='softmax', kernel_regularizer=l2(lmbd)))
|
||||
|
||||
sgd = SGD(lr=eta)
|
||||
model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])
|
||||
|
||||
return model
|
||||
|
||||
epochs = 100
|
||||
batch_size = 100
|
||||
input_shape = X_train.shape[1:4]
|
||||
receptive_field = 3
|
||||
n_filters = 10
|
||||
n_neurons_connected = 50
|
||||
n_categories = 10
|
||||
|
||||
eta_vals = np.logspace(-5, 1, 7)
|
||||
lmbd_vals = np.logspace(-5, 1, 7)
|
||||
!ec
|
||||
|
||||
!split
|
||||
===== Final part =====
|
||||
|
||||
!bc pycod
|
||||
CNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
|
||||
|
||||
for i, eta in enumerate(eta_vals):
|
||||
for j, lmbd in enumerate(lmbd_vals):
|
||||
CNN = create_convolutional_neural_network_keras(input_shape, receptive_field,
|
||||
n_filters, n_neurons_connected, n_categories,
|
||||
eta, lmbd)
|
||||
CNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0)
|
||||
scores = CNN.evaluate(X_test, Y_test)
|
||||
|
||||
CNN_keras[i][j] = CNN
|
||||
|
||||
print("Learning rate = ", eta)
|
||||
print("Lambda = ", lmbd)
|
||||
print("Test accuracy: %.3f" % scores[1])
|
||||
print()
|
||||
!ec
|
||||
|
||||
!split
|
||||
===== Final visualization =====
|
||||
|
||||
!bc
|
||||
# visual representation of grid search
|
||||
# uses seaborn heatmap, could probably do this in matplotlib
|
||||
import seaborn as sns
|
||||
|
||||
sns.set()
|
||||
|
||||
train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
|
||||
test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
|
||||
|
||||
for i in range(len(eta_vals)):
|
||||
for j in range(len(lmbd_vals)):
|
||||
CNN = CNN_keras[i][j]
|
||||
|
||||
train_accuracy[i][j] = CNN.evaluate(X_train, Y_train)[1]
|
||||
test_accuracy[i][j] = CNN.evaluate(X_test, Y_test)[1]
|
||||
|
||||
|
||||
fig, ax = plt.subplots(figsize = (10, 10))
|
||||
sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
|
||||
ax.set_title("Training Accuracy")
|
||||
ax.set_ylabel("$\eta$")
|
||||
ax.set_xlabel("$\lambda$")
|
||||
plt.show()
|
||||
|
||||
fig, ax = plt.subplots(figsize = (10, 10))
|
||||
sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
|
||||
ax.set_title("Test Accuracy")
|
||||
ax.set_ylabel("$\eta$")
|
||||
ax.set_xlabel("$\lambda$")
|
||||
plt.show()
|
||||
!ec
|
||||
|
||||
!split
|
||||
===== Fun links =====
|
||||
|
||||
o "Self-Driving cars using a convolutional neural network":"https://arxiv.org/abs/1604.07316"
|
||||
o "Abstract art using convolutional neural networks":"https://deepdreamgenerator.com/"
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,57 @@
|
||||
digraph Tree {
|
||||
node [shape=box, style="filled, rounded", color="black", fontname=helvetica] ;
|
||||
edge [fontname=helvetica] ;
|
||||
0 [label="worst perimeter <= 106.05\ngini = 0.465\nsamples = 426\nvalue = [[269, 157]\n[157, 269]]", fillcolor="#e5813908"] ;
|
||||
1 [label="worst concave points <= 0.159\ngini = 0.067\nsamples = 259\nvalue = [[250, 9]\n[9, 250]]", fillcolor="#e58139db"] ;
|
||||
0 -> 1 [labeldistance=2.5, labelangle=45, headlabel="True"] ;
|
||||
2 [label="worst concave points <= 0.135\ngini = 0.031\nsamples = 253\nvalue = [[249, 4]\n[4, 249]]", fillcolor="#e58139ee"] ;
|
||||
1 -> 2 ;
|
||||
3 [label="radius error <= 0.643\ngini = 0.008\nsamples = 242\nvalue = [[241, 1]\n[1, 241]]", fillcolor="#e58139fb"] ;
|
||||
2 -> 3 ;
|
||||
4 [label="gini = 0.0\nsamples = 239\nvalue = [[239, 0]\n[0, 239]]", fillcolor="#e58139ff"] ;
|
||||
3 -> 4 ;
|
||||
5 [label="worst symmetry <= 0.208\ngini = 0.444\nsamples = 3\nvalue = [[2, 1]\n[1, 2]]", fillcolor="#e5813913"] ;
|
||||
3 -> 5 ;
|
||||
6 [label="gini = 0.0\nsamples = 1\nvalue = [[0, 1]\n[1, 0]]", fillcolor="#e58139ff"] ;
|
||||
5 -> 6 ;
|
||||
7 [label="gini = 0.0\nsamples = 2\nvalue = [[2, 0]\n[0, 2]]", fillcolor="#e58139ff"] ;
|
||||
5 -> 7 ;
|
||||
8 [label="worst texture <= 29.455\ngini = 0.397\nsamples = 11\nvalue = [[8, 3]\n[3, 8]]", fillcolor="#e581392c"] ;
|
||||
2 -> 8 ;
|
||||
9 [label="gini = 0.0\nsamples = 8\nvalue = [[8, 0]\n[0, 8]]", fillcolor="#e58139ff"] ;
|
||||
8 -> 9 ;
|
||||
10 [label="gini = 0.0\nsamples = 3\nvalue = [[0, 3]\n[3, 0]]", fillcolor="#e58139ff"] ;
|
||||
8 -> 10 ;
|
||||
11 [label="mean texture <= 16.22\ngini = 0.278\nsamples = 6\nvalue = [[1, 5]\n[5, 1]]", fillcolor="#e581396b"] ;
|
||||
1 -> 11 ;
|
||||
12 [label="gini = 0.0\nsamples = 1\nvalue = [[1, 0]\n[0, 1]]", fillcolor="#e58139ff"] ;
|
||||
11 -> 12 ;
|
||||
13 [label="gini = 0.0\nsamples = 5\nvalue = [[0, 5]\n[5, 0]]", fillcolor="#e58139ff"] ;
|
||||
11 -> 13 ;
|
||||
14 [label="worst texture <= 20.645\ngini = 0.202\nsamples = 167\nvalue = [[19, 148]\n[148, 19]]", fillcolor="#e5813994"] ;
|
||||
0 -> 14 [labeldistance=2.5, labelangle=-45, headlabel="False"] ;
|
||||
15 [label="worst radius <= 17.74\ngini = 0.375\nsamples = 16\nvalue = [[12, 4]\n[4, 12]]", fillcolor="#e5813938"] ;
|
||||
14 -> 15 ;
|
||||
16 [label="gini = 0.0\nsamples = 11\nvalue = [[11, 0]\n[0, 11]]", fillcolor="#e58139ff"] ;
|
||||
15 -> 16 ;
|
||||
17 [label="mean texture <= 13.745\ngini = 0.32\nsamples = 5\nvalue = [[1, 4]\n[4, 1]]", fillcolor="#e5813955"] ;
|
||||
15 -> 17 ;
|
||||
18 [label="gini = 0.0\nsamples = 1\nvalue = [[1, 0]\n[0, 1]]", fillcolor="#e58139ff"] ;
|
||||
17 -> 18 ;
|
||||
19 [label="gini = 0.0\nsamples = 4\nvalue = [[0, 4]\n[4, 0]]", fillcolor="#e58139ff"] ;
|
||||
17 -> 19 ;
|
||||
20 [label="mean concave points <= 0.049\ngini = 0.088\nsamples = 151\nvalue = [[7, 144]\n[144, 7]]", fillcolor="#e58139d0"] ;
|
||||
14 -> 20 ;
|
||||
21 [label="concave points error <= 0.01\ngini = 0.48\nsamples = 15\nvalue = [[6, 9]\n[9, 6]]", fillcolor="#e5813900"] ;
|
||||
20 -> 21 ;
|
||||
22 [label="gini = 0.0\nsamples = 9\nvalue = [[0, 9]\n[9, 0]]", fillcolor="#e58139ff"] ;
|
||||
21 -> 22 ;
|
||||
23 [label="gini = 0.0\nsamples = 6\nvalue = [[6, 0]\n[0, 6]]", fillcolor="#e58139ff"] ;
|
||||
21 -> 23 ;
|
||||
24 [label="worst smoothness <= 0.096\ngini = 0.015\nsamples = 136\nvalue = [[1, 135]\n[135, 1]]", fillcolor="#e58139f7"] ;
|
||||
20 -> 24 ;
|
||||
25 [label="gini = 0.0\nsamples = 1\nvalue = [[1, 0]\n[0, 1]]", fillcolor="#e58139ff"] ;
|
||||
24 -> 25 ;
|
||||
26 [label="gini = 0.0\nsamples = 135\nvalue = [[0, 135]\n[135, 0]]", fillcolor="#e58139ff"] ;
|
||||
24 -> 26 ;
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 216 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 80 KiB |
@@ -0,0 +1,15 @@
|
||||
Outlook,Temperature,Humidity,Wind,Ride
|
||||
0,0,0,0,0
|
||||
0,0,0,1,1
|
||||
1,0,0,0,1
|
||||
2,1,0,0,1
|
||||
2,2,1,0,1
|
||||
2,2,1,1,0
|
||||
1,2,1,1,1
|
||||
0,1,0,0,0
|
||||
0,2,1,0,1
|
||||
2,1,1,0,1
|
||||
0,1,1,1,1
|
||||
1,1,0,1,1
|
||||
1,0,1,0,1
|
||||
2,1,0,1,0
|
||||
|
@@ -0,0 +1,15 @@
|
||||
Outlook,Temperature,Humidity,Wind,Ride
|
||||
Sunny,Hot,High,Weak,0
|
||||
Sunny,Hot,High,Strong,1
|
||||
Overcast,Hot,High,Weak,1
|
||||
Rain,Mild,High,Weak,1
|
||||
Rain,Cool,Normal,Weak,1
|
||||
Rain,Cool,Normal,Strong,0
|
||||
Overcast,Cool,Normal,Strong,1
|
||||
Sunny,Mild,High,Weak,0
|
||||
Sunny,Cool,Normal,Weak,1
|
||||
Rain,Mild,Normal,Weak,1
|
||||
Sunny,Mild,Normal,Strong,1
|
||||
Overcast,Mild,High,Strong,1
|
||||
Overcast,Hot,Normal,Weak,1
|
||||
Rain,Mild,High,Strong,0
|
||||
@@ -0,0 +1,13 @@
|
||||
digraph Tree {
|
||||
node [shape=box, style="filled, rounded", color="black", fontname=helvetica] ;
|
||||
edge [fontname=helvetica] ;
|
||||
0 [label="X[7] <= 0.5\ngini = 0.48\nsamples = 15\nvalue = [4, 10, 1]", fillcolor="#39e5818b"] ;
|
||||
1 [label="X[1] <= 0.5\ngini = 0.408\nsamples = 14\nvalue = [4, 10, 0]", fillcolor="#39e58199"] ;
|
||||
0 -> 1 [labeldistance=2.5, labelangle=45, headlabel="True"] ;
|
||||
2 [label="gini = 0.48\nsamples = 10\nvalue = [4, 6, 0]", fillcolor="#39e58155"] ;
|
||||
1 -> 2 ;
|
||||
3 [label="gini = 0.0\nsamples = 4\nvalue = [0, 4, 0]", fillcolor="#39e581ff"] ;
|
||||
1 -> 3 ;
|
||||
4 [label="gini = 0.0\nsamples = 1\nvalue = [0, 0, 1]", fillcolor="#8139e5ff"] ;
|
||||
0 -> 4 [labeldistance=2.5, labelangle=-45, headlabel="False"] ;
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
Day,Outlook,Temperature,Humidity,Wind,Ride
|
||||
1,Sunny,Hot,High,Weak,0
|
||||
2,Sunny,Hot,High,Strong,1
|
||||
3,Overcast,Hot,High,Weak,1
|
||||
4,Rain,Mild,High,Weak,1
|
||||
5,Rain,Cool,Normal,Weak,1
|
||||
6,Rain,Cool,Normal,Strong,0
|
||||
7,Overcast,Cool,Normal,Strong,1
|
||||
8,Sunny,Mild,High,Weak,0
|
||||
9,Sunny,Cool,Normal,Weak,1
|
||||
10,Rain,Mild,Normal,Weak,1
|
||||
11,Sunny,Mild,Normal,Strong,1
|
||||
12,Overcast,Mild,High,Strong,1
|
||||
13,Overcast,Hot,Normal,Weak,1
|
||||
14,Rain,Mild,High,Strong,0
|
||||
|
@@ -0,0 +1,101 @@
|
||||
aardvark,1,0,0,1,0,0,1,1,1,1,0,0,4,0,0,1,1
|
||||
antelope,1,0,0,1,0,0,0,1,1,1,0,0,4,1,0,1,1
|
||||
bass,0,0,1,0,0,1,1,1,1,0,0,1,0,1,0,0,4
|
||||
bear,1,0,0,1,0,0,1,1,1,1,0,0,4,0,0,1,1
|
||||
boar,1,0,0,1,0,0,1,1,1,1,0,0,4,1,0,1,1
|
||||
buffalo,1,0,0,1,0,0,0,1,1,1,0,0,4,1,0,1,1
|
||||
calf,1,0,0,1,0,0,0,1,1,1,0,0,4,1,1,1,1
|
||||
carp,0,0,1,0,0,1,0,1,1,0,0,1,0,1,1,0,4
|
||||
catfish,0,0,1,0,0,1,1,1,1,0,0,1,0,1,0,0,4
|
||||
cavy,1,0,0,1,0,0,0,1,1,1,0,0,4,0,1,0,1
|
||||
cheetah,1,0,0,1,0,0,1,1,1,1,0,0,4,1,0,1,1
|
||||
chicken,0,1,1,0,1,0,0,0,1,1,0,0,2,1,1,0,2
|
||||
chub,0,0,1,0,0,1,1,1,1,0,0,1,0,1,0,0,4
|
||||
clam,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,7
|
||||
crab,0,0,1,0,0,1,1,0,0,0,0,0,4,0,0,0,7
|
||||
crayfish,0,0,1,0,0,1,1,0,0,0,0,0,6,0,0,0,7
|
||||
crow,0,1,1,0,1,0,1,0,1,1,0,0,2,1,0,0,2
|
||||
deer,1,0,0,1,0,0,0,1,1,1,0,0,4,1,0,1,1
|
||||
dogfish,0,0,1,0,0,1,1,1,1,0,0,1,0,1,0,1,4
|
||||
dolphin,0,0,0,1,0,1,1,1,1,1,0,1,0,1,0,1,1
|
||||
dove,0,1,1,0,1,0,0,0,1,1,0,0,2,1,1,0,2
|
||||
duck,0,1,1,0,1,1,0,0,1,1,0,0,2,1,0,0,2
|
||||
elephant,1,0,0,1,0,0,0,1,1,1,0,0,4,1,0,1,1
|
||||
flamingo,0,1,1,0,1,0,0,0,1,1,0,0,2,1,0,1,2
|
||||
flea,0,0,1,0,0,0,0,0,0,1,0,0,6,0,0,0,6
|
||||
frog,0,0,1,0,0,1,1,1,1,1,0,0,4,0,0,0,5
|
||||
frog,0,0,1,0,0,1,1,1,1,1,1,0,4,0,0,0,5
|
||||
fruitbat,1,0,0,1,1,0,0,1,1,1,0,0,2,1,0,0,1
|
||||
giraffe,1,0,0,1,0,0,0,1,1,1,0,0,4,1,0,1,1
|
||||
girl,1,0,0,1,0,0,1,1,1,1,0,0,2,0,1,1,1
|
||||
gnat,0,0,1,0,1,0,0,0,0,1,0,0,6,0,0,0,6
|
||||
goat,1,0,0,1,0,0,0,1,1,1,0,0,4,1,1,1,1
|
||||
gorilla,1,0,0,1,0,0,0,1,1,1,0,0,2,0,0,1,1
|
||||
gull,0,1,1,0,1,1,1,0,1,1,0,0,2,1,0,0,2
|
||||
haddock,0,0,1,0,0,1,0,1,1,0,0,1,0,1,0,0,4
|
||||
hamster,1,0,0,1,0,0,0,1,1,1,0,0,4,1,1,0,1
|
||||
hare,1,0,0,1,0,0,0,1,1,1,0,0,4,1,0,0,1
|
||||
hawk,0,1,1,0,1,0,1,0,1,1,0,0,2,1,0,0,2
|
||||
herring,0,0,1,0,0,1,1,1,1,0,0,1,0,1,0,0,4
|
||||
honeybee,1,0,1,0,1,0,0,0,0,1,1,0,6,0,1,0,6
|
||||
housefly,1,0,1,0,1,0,0,0,0,1,0,0,6,0,0,0,6
|
||||
kiwi,0,1,1,0,0,0,1,0,1,1,0,0,2,1,0,0,2
|
||||
ladybird,0,0,1,0,1,0,1,0,0,1,0,0,6,0,0,0,6
|
||||
lark,0,1,1,0,1,0,0,0,1,1,0,0,2,1,0,0,2
|
||||
leopard,1,0,0,1,0,0,1,1,1,1,0,0,4,1,0,1,1
|
||||
lion,1,0,0,1,0,0,1,1,1,1,0,0,4,1,0,1,1
|
||||
lobster,0,0,1,0,0,1,1,0,0,0,0,0,6,0,0,0,7
|
||||
lynx,1,0,0,1,0,0,1,1,1,1,0,0,4,1,0,1,1
|
||||
mink,1,0,0,1,0,1,1,1,1,1,0,0,4,1,0,1,1
|
||||
mole,1,0,0,1,0,0,1,1,1,1,0,0,4,1,0,0,1
|
||||
mongoose,1,0,0,1,0,0,1,1,1,1,0,0,4,1,0,1,1
|
||||
moth,1,0,1,0,1,0,0,0,0,1,0,0,6,0,0,0,6
|
||||
newt,0,0,1,0,0,1,1,1,1,1,0,0,4,1,0,0,5
|
||||
octopus,0,0,1,0,0,1,1,0,0,0,0,0,8,0,0,1,7
|
||||
opossum,1,0,0,1,0,0,1,1,1,1,0,0,4,1,0,0,1
|
||||
oryx,1,0,0,1,0,0,0,1,1,1,0,0,4,1,0,1,1
|
||||
ostrich,0,1,1,0,0,0,0,0,1,1,0,0,2,1,0,1,2
|
||||
parakeet,0,1,1,0,1,0,0,0,1,1,0,0,2,1,1,0,2
|
||||
penguin,0,1,1,0,0,1,1,0,1,1,0,0,2,1,0,1,2
|
||||
pheasant,0,1,1,0,1,0,0,0,1,1,0,0,2,1,0,0,2
|
||||
pike,0,0,1,0,0,1,1,1,1,0,0,1,0,1,0,1,4
|
||||
piranha,0,0,1,0,0,1,1,1,1,0,0,1,0,1,0,0,4
|
||||
pitviper,0,0,1,0,0,0,1,1,1,1,1,0,0,1,0,0,3
|
||||
platypus,1,0,1,1,0,1,1,0,1,1,0,0,4,1,0,1,1
|
||||
polecat,1,0,0,1,0,0,1,1,1,1,0,0,4,1,0,1,1
|
||||
pony,1,0,0,1,0,0,0,1,1,1,0,0,4,1,1,1,1
|
||||
porpoise,0,0,0,1,0,1,1,1,1,1,0,1,0,1,0,1,1
|
||||
puma,1,0,0,1,0,0,1,1,1,1,0,0,4,1,0,1,1
|
||||
pussycat,1,0,0,1,0,0,1,1,1,1,0,0,4,1,1,1,1
|
||||
raccoon,1,0,0,1,0,0,1,1,1,1,0,0,4,1,0,1,1
|
||||
reindeer,1,0,0,1,0,0,0,1,1,1,0,0,4,1,1,1,1
|
||||
rhea,0,1,1,0,0,0,1,0,1,1,0,0,2,1,0,1,2
|
||||
scorpion,0,0,0,0,0,0,1,0,0,1,1,0,8,1,0,0,7
|
||||
seahorse,0,0,1,0,0,1,0,1,1,0,0,1,0,1,0,0,4
|
||||
seal,1,0,0,1,0,1,1,1,1,1,0,1,0,0,0,1,1
|
||||
sealion,1,0,0,1,0,1,1,1,1,1,0,1,2,1,0,1,1
|
||||
seasnake,0,0,0,0,0,1,1,1,1,0,1,0,0,1,0,0,3
|
||||
seawasp,0,0,1,0,0,1,1,0,0,0,1,0,0,0,0,0,7
|
||||
skimmer,0,1,1,0,1,1,1,0,1,1,0,0,2,1,0,0,2
|
||||
skua,0,1,1,0,1,1,1,0,1,1,0,0,2,1,0,0,2
|
||||
slowworm,0,0,1,0,0,0,1,1,1,1,0,0,0,1,0,0,3
|
||||
slug,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,7
|
||||
sole,0,0,1,0,0,1,0,1,1,0,0,1,0,1,0,0,4
|
||||
sparrow,0,1,1,0,1,0,0,0,1,1,0,0,2,1,0,0,2
|
||||
squirrel,1,0,0,1,0,0,0,1,1,1,0,0,2,1,0,0,1
|
||||
starfish,0,0,1,0,0,1,1,0,0,0,0,0,5,0,0,0,7
|
||||
stingray,0,0,1,0,0,1,1,1,1,0,1,1,0,1,0,1,4
|
||||
swan,0,1,1,0,1,1,0,0,1,1,0,0,2,1,0,1,2
|
||||
termite,0,0,1,0,0,0,0,0,0,1,0,0,6,0,0,0,6
|
||||
toad,0,0,1,0,0,1,0,1,1,1,0,0,4,0,0,0,5
|
||||
tortoise,0,0,1,0,0,0,0,0,1,1,0,0,4,1,0,1,3
|
||||
tuatara,0,0,1,0,0,0,1,1,1,1,0,0,4,1,0,0,3
|
||||
tuna,0,0,1,0,0,1,1,1,1,0,0,1,0,1,0,1,4
|
||||
vampire,1,0,0,1,1,0,0,1,1,1,0,0,2,1,0,0,1
|
||||
vole,1,0,0,1,0,0,0,1,1,1,0,0,4,1,0,0,1
|
||||
vulture,0,1,1,0,1,0,1,0,1,1,0,0,2,1,0,1,2
|
||||
wallaby,1,0,0,1,0,0,0,1,1,1,0,0,2,1,0,1,1
|
||||
wasp,1,0,1,0,1,0,0,0,0,1,1,0,6,0,0,0,6
|
||||
wolf,1,0,0,1,0,0,1,1,1,1,0,0,4,1,0,1,1
|
||||
worm,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,7
|
||||
wren,0,1,1,0,1,0,0,0,1,1,0,0,2,1,0,0,2
|
||||
|
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,815 @@
|
||||
TITLE: Week 45: Random Forests and Boosting
|
||||
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
|
||||
===== Random forests =====
|
||||
|
||||
Random forests provide an improvement over bagged trees by way of a
|
||||
small tweak that decorrelates the trees.
|
||||
|
||||
As in bagging, we build a
|
||||
number of decision trees on bootstrapped training samples. But when
|
||||
building these decision trees, each time a split in a tree is
|
||||
considered, a random sample of $m$ predictors is chosen as split
|
||||
candidates from the full set of $p$ predictors. The split is allowed to
|
||||
use only one of those $m$ predictors.
|
||||
|
||||
A fresh sample of $m$ predictors is
|
||||
taken at each split, and typically we choose
|
||||
|
||||
!bt
|
||||
\[
|
||||
m\approx \sqrt{p}.
|
||||
\]
|
||||
!et
|
||||
|
||||
In building a random forest, at
|
||||
each split in the tree, the algorithm is not even allowed to consider
|
||||
a majority of the available predictors.
|
||||
|
||||
The reason for this is rather clever. Suppose that there is one very
|
||||
strong predictor in the data set, along with a number of other
|
||||
moderately strong predictors. Then in the collection of bagged
|
||||
variable importance random forest trees, most or all of the trees will
|
||||
use this strong predictor in the top split. Consequently, all of the
|
||||
bagged trees will look quite similar to each other. Hence the
|
||||
predictions from the bagged trees will be highly correlated.
|
||||
Unfortunately, averaging many highly correlated quantities does not
|
||||
lead to as large of a reduction in variance as averaging many
|
||||
uncorrelated quantities. In particular, this means that bagging will
|
||||
not lead to a substantial reduction in variance over a single tree in
|
||||
this setting.
|
||||
|
||||
|
||||
!split
|
||||
===== Random Forest Algorithm =====
|
||||
The algorithm described here can be applied to both classification and regression problems.
|
||||
|
||||
We will grow of forest of say $B$ trees.
|
||||
o For $b=1:B$
|
||||
* Draw a bootstrap sample of from the training data organized in our $\bm{X}$ matrix.
|
||||
* We grow then a random forest tree $T_b$ based on the bootstrapped data by repeating the steps outlined till we reach the maximum node size is reached
|
||||
o we select $m \le p$ variables at random from the $p$ predictors/features
|
||||
o pick the best split point among the $m$ features using either the CART algorithm or the ID3 for classification and create a new node
|
||||
o split the node into daughter nodes
|
||||
o Output then the ensemble of trees $\{T_b\}_1^{B}$ and make predictions for either a regression type of problem or a classification type of problem.
|
||||
|
||||
|
||||
|
||||
!split
|
||||
===== Random Forests Compared with other Methods on the Cancer Data =====
|
||||
!bc pycod
|
||||
import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
from sklearn.model_selection import train_test_split
|
||||
from sklearn.datasets import load_breast_cancer
|
||||
from sklearn.svm import SVC
|
||||
from sklearn.linear_model import LogisticRegression
|
||||
from sklearn.tree import DecisionTreeClassifier
|
||||
|
||||
# Load the data
|
||||
cancer = load_breast_cancer()
|
||||
|
||||
X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
|
||||
print(X_train.shape)
|
||||
print(X_test.shape)
|
||||
# Logistic Regression
|
||||
logreg = LogisticRegression(solver='lbfgs')
|
||||
logreg.fit(X_train, y_train)
|
||||
print("Test set accuracy with Logistic Regression: {:.2f}".format(logreg.score(X_test,y_test)))
|
||||
# Support vector machine
|
||||
svm = SVC(gamma='auto', C=100)
|
||||
svm.fit(X_train, y_train)
|
||||
print("Test set accuracy with SVM: {:.2f}".format(svm.score(X_test,y_test)))
|
||||
# Decision Trees
|
||||
deep_tree_clf = DecisionTreeClassifier(max_depth=None)
|
||||
deep_tree_clf.fit(X_train, y_train)
|
||||
print("Test set accuracy with Decision Trees: {:.2f}".format(deep_tree_clf.score(X_test,y_test)))
|
||||
#now scale the data
|
||||
from sklearn.preprocessing import StandardScaler
|
||||
scaler = StandardScaler()
|
||||
scaler.fit(X_train)
|
||||
X_train_scaled = scaler.transform(X_train)
|
||||
X_test_scaled = scaler.transform(X_test)
|
||||
# Logistic Regression
|
||||
logreg.fit(X_train_scaled, y_train)
|
||||
print("Test set accuracy Logistic Regression with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))
|
||||
# Support Vector Machine
|
||||
svm.fit(X_train_scaled, y_train)
|
||||
print("Test set accuracy SVM with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))
|
||||
# Decision Trees
|
||||
deep_tree_clf.fit(X_train_scaled, y_train)
|
||||
print("Test set accuracy with Decision Trees and scaled data: {:.2f}".format(deep_tree_clf.score(X_test_scaled,y_test)))
|
||||
|
||||
|
||||
from sklearn.ensemble import RandomForestClassifier
|
||||
from sklearn.preprocessing import LabelEncoder
|
||||
from sklearn.model_selection import cross_validate
|
||||
# Data set not specificied
|
||||
#Instantiate the model with 500 trees and entropy as splitting criteria
|
||||
Random_Forest_model = RandomForestClassifier(n_estimators=500,criterion="entropy")
|
||||
Random_Forest_model.fit(X_train_scaled, y_train)
|
||||
#Cross validation
|
||||
accuracy = cross_validate(Random_Forest_model,X_test_scaled,y_test,cv=10)['test_score']
|
||||
print(accuracy)
|
||||
print("Test set accuracy with Random Forests and scaled data: {:.2f}".format(Random_Forest_model.score(X_test_scaled,y_test)))
|
||||
|
||||
|
||||
import scikitplot as skplt
|
||||
y_pred = Random_Forest_model.predict(X_test_scaled)
|
||||
skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)
|
||||
plt.show()
|
||||
y_probas = Random_Forest_model.predict_proba(X_test_scaled)
|
||||
skplt.metrics.plot_roc(y_test, y_probas)
|
||||
plt.show()
|
||||
skplt.metrics.plot_cumulative_gain(y_test, y_probas)
|
||||
plt.show()
|
||||
|
||||
!ec
|
||||
|
||||
|
||||
!split
|
||||
===== Compare Bagging on Trees with Random Forests =====
|
||||
!bc pycod
|
||||
bag_clf = BaggingClassifier(
|
||||
DecisionTreeClassifier(splitter="random", max_leaf_nodes=16, random_state=42),
|
||||
n_estimators=500, max_samples=1.0, bootstrap=True, n_jobs=-1, random_state=42)
|
||||
!ec
|
||||
|
||||
|
||||
|
||||
!bc pycod
|
||||
bag_clf.fit(X_train, y_train)
|
||||
y_pred = bag_clf.predict(X_test)
|
||||
from sklearn.ensemble import RandomForestClassifier
|
||||
rnd_clf = RandomForestClassifier(n_estimators=500, max_leaf_nodes=16, n_jobs=-1, random_state=42)
|
||||
rnd_clf.fit(X_train, y_train)
|
||||
y_pred_rf = rnd_clf.predict(X_test)
|
||||
np.sum(y_pred == y_pred_rf) / len(y_pred)
|
||||
!ec
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
!split
|
||||
===== Boosting, a Bird's Eye View =====
|
||||
|
||||
The basic idea is to combine weak classifiers in order to create a good
|
||||
classifier. With a weak classifier we often intend a classifier which
|
||||
produces results which are only slightly better than we would get by
|
||||
random guesses.
|
||||
|
||||
This is done by applying in an iterative way a weak (or a standard
|
||||
classifier like decision trees) to modify the data. In each iteration
|
||||
we emphasize those observations which are misclassified by weighting
|
||||
them with a factor.
|
||||
|
||||
|
||||
!split
|
||||
===== What is boosting? Additive Modelling/Iterative Fitting =====
|
||||
|
||||
Boosting is a way of fitting an additive expansion in a set of
|
||||
elementary basis functions like for example some simple polynomials.
|
||||
Assume for example that we have a function
|
||||
!bt
|
||||
\[
|
||||
f_M(x) = \sum_{i=1}^M \beta_m b(x;\gamma_m),
|
||||
\]
|
||||
!et
|
||||
|
||||
where $\beta_m$ are the expansion parameters to be determined in a
|
||||
minimization process and $b(x;\gamma_m)$ are some simple functions of
|
||||
the multivariable parameter $x$ which is characterized by the
|
||||
parameters $\gamma_m$.
|
||||
|
||||
As an example, consider the Sigmoid function we used in logistic
|
||||
regression. In that case, we can translate the function
|
||||
$b(x;\gamma_m)$ into the Sigmoid function
|
||||
|
||||
|
||||
!bt
|
||||
\[
|
||||
\sigma(t) = \frac{1}{1+\exp{(-t)}},
|
||||
\]
|
||||
!et
|
||||
|
||||
where $t=\gamma_0+\gamma_1 x$ and the parameters $\gamma_0$ and
|
||||
$\gamma_1$ were determined by the Logistic Regression fitting
|
||||
algorithm.
|
||||
|
||||
As another example, consider the cost function we defined for linear regression
|
||||
!bt
|
||||
\[
|
||||
C(\bm{y},\bm{f}) = \frac{1}{n} \sum_{i=0}^{n-1}(y_i-f(x_i))^2.
|
||||
\]
|
||||
!et
|
||||
|
||||
In this case the function $f(x)$ was replaced by the design matrix
|
||||
$\bm{X}$ and the unknown linear regression parameters $\bm{\beta}$,
|
||||
that is $\bm{f}=\bm{X}\bm{\beta}$. In linear regression we can
|
||||
simply invert a matrix and obtain the parameters $\beta$ by
|
||||
|
||||
!bt
|
||||
\[
|
||||
\bm{\beta}=\left(\bm{X}^T\bm{X}\right)^{-1}\bm{X}^T\bm{y}.
|
||||
\]
|
||||
!et
|
||||
|
||||
In iterative fitting or additive modeling, we minimize the cost function with respect to the parameters $\beta_m$ and $\gamma_m$.
|
||||
|
||||
|
||||
!split
|
||||
===== Iterative Fitting, Regression and Squared-error Cost Function =====
|
||||
|
||||
The way we proceed is as follows (here we specialize to the squared-error cost function)
|
||||
|
||||
o Establish a cost function, here ${\cal C}(\bm{y},\bm{f}) = \frac{1}{n} \sum_{i=0}^{n-1}(y_i-f_M(x_i))^2$ with $f_M(x) = \sum_{i=1}^M \beta_m b(x;\gamma_m)$.
|
||||
o Initialize with a guess $f_0(x)$. It could be one or even zero or some random numbers.
|
||||
o For $m=1:M$
|
||||
o minimize $\sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\beta b(x;\gamma))^2$ wrt $\gamma$ and $\beta$
|
||||
o This gives the optimal values $\beta_m$ and $\gamma_m$
|
||||
o Determine then the new values $f_m(x)=f_{m-1}(x) +\beta_m b(x;\gamma_m)$
|
||||
|
||||
We could use any of the algorithms we have discussed till now. If we
|
||||
use trees, $\gamma$ parameterizes the split variables and split points
|
||||
at the internal nodes, and the predictions at the terminal nodes.
|
||||
|
||||
|
||||
!split
|
||||
===== Squared-Error Example and Iterative Fitting =====
|
||||
|
||||
To better understand what happens, let us develop the steps for the iterative fitting using the above squared error function.
|
||||
|
||||
For simplicity we assume also that our functions $b(x;\gamma)=1+\gamma x$.
|
||||
|
||||
This means that for every iteration $m$, we need to optimize
|
||||
|
||||
!bt
|
||||
\[
|
||||
(\beta_m,\gamma_m) = \mathrm{argmin}_{\beta,\lambda}\hspace{0.1cm} \sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\beta b(x;\gamma))^2=\sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\beta(1+\gamma x_i))^2.
|
||||
\]
|
||||
!et
|
||||
|
||||
We start our iteration by simply setting $f_0(x)=0$.
|
||||
Taking the derivatives with respect to $\beta$ and $\gamma$ we obtain
|
||||
!bt
|
||||
\[
|
||||
\frac{\partial {\cal C}}{\partial \beta} = -2\sum_{i}(1+\gamma x_i)(y_i-\beta(1+\gamma x_i))=0,
|
||||
\]
|
||||
!et
|
||||
and
|
||||
!bt
|
||||
\[
|
||||
\frac{\partial {\cal C}}{\partial \gamma} =-2\sum_{i}\beta x_i(y_i-\beta(1+\gamma x_i))=0.
|
||||
\]
|
||||
!et
|
||||
We can then rewrite these equations as (defining $\bm{w}=\bm{e}+\gamma \bm{x})$ with $\bm{e}$ being the unit vector)
|
||||
!bt
|
||||
\[
|
||||
\gamma \bm{w}^T(\bm{y}-\beta\gamma \bm{w})=0,
|
||||
\]
|
||||
!et
|
||||
which gives us $\beta = \bm{w}^T\bm{y}/(\bm{w}^T\bm{w})$. Similarly we have
|
||||
!bt
|
||||
\[
|
||||
\beta\gamma \bm{x}^T(\bm{y}-\beta(1+\gamma \bm{x}))=0,
|
||||
\]
|
||||
!et
|
||||
|
||||
which leads to $\gamma =(\bm{x}^T\bm{y}-\beta\bm{x}^T\bm{e})/(\beta\bm{x}^T\bm{x})$. Inserting
|
||||
for $\beta$ gives us an equation for $\gamma$. This is a non-linear equation in the unknown $\gamma$ and has to be solved numerically.
|
||||
|
||||
The solution to these two equations gives us in turn $\beta_1$ and $\gamma_1$ leading to the new expression for $f_1(x)$ as
|
||||
$f_1(x) = \beta_1(1+\gamma_1x)$. Doing this $M$ times results in our final estimate for the function $f$.
|
||||
|
||||
|
||||
|
||||
!split
|
||||
===== Iterative Fitting, Classification and AdaBoost =====
|
||||
|
||||
Let us consider a binary classification problem with two outcomes $y_i \in \{-1,1\}$ and $i=0,1,2,\dots,n-1$ as our set of
|
||||
observations. We define a classification function $G(x)$ which produces a prediction taking one or the other of the two values
|
||||
$\{-1,1\}$.
|
||||
|
||||
The error rate of the training sample is then
|
||||
|
||||
!bt
|
||||
\[
|
||||
\mathrm{\overline{err}}=\frac{1}{n} \sum_{i=0}^{n-1} I(y_i\ne G(x_i)).
|
||||
\]
|
||||
!et
|
||||
|
||||
The iterative procedure starts with defining a weak classifier whose
|
||||
error rate is barely better than random guessing. The iterative
|
||||
procedure in boosting is to sequentially apply a weak
|
||||
classification algorithm to repeatedly modified versions of the data
|
||||
producing a sequence of weak classifiers $G_m(x)$.
|
||||
|
||||
Here we will express our function $f(x)$ in terms of $G(x)$. That is
|
||||
!bt
|
||||
\[
|
||||
f_M(x) = \sum_{i=1}^M \beta_m b(x;\gamma_m),
|
||||
\]
|
||||
!et
|
||||
will be a function of
|
||||
!bt
|
||||
\[
|
||||
G_M(x) = \mathrm{sign} \sum_{i=1}^M \alpha_m G_m(x).
|
||||
\]
|
||||
!et
|
||||
|
||||
|
||||
|
||||
!split
|
||||
===== Adaptive Boosting, AdaBoost =====
|
||||
|
||||
In our iterative procedure we define thus
|
||||
!bt
|
||||
\[
|
||||
f_m(x) = f_{m-1}(x)+\beta_mG_m(x).
|
||||
\]
|
||||
!et
|
||||
|
||||
The simplest possible cost function which leads (also simple from a computational point of view) to the AdaBoost algorithm is the
|
||||
exponential cost/loss function defined as
|
||||
!bt
|
||||
\[
|
||||
C(\bm{y},\bm{f}) = \sum_{i=0}^{n-1}\exp{(-y_i(f_{m-1}(x_i)+\beta G(x_i))}.
|
||||
\]
|
||||
!et
|
||||
|
||||
We optimize $\beta$ and $G$ for each value of $m=1:M$ as we did in the regression case.
|
||||
This is normally done in two steps. Let us however first rewrite the cost function as
|
||||
|
||||
!bt
|
||||
\[
|
||||
C(\bm{y},\bm{f}) = \sum_{i=0}^{n-1}w_i^{m}\exp{(-y_i\beta G(x_i))},
|
||||
\]
|
||||
!et
|
||||
where we have defined $w_i^m= \exp{(-y_if_{m-1}(x_i))}$.
|
||||
|
||||
!split
|
||||
===== Building up AdaBoost =====
|
||||
|
||||
First, for any $\beta > 0$, we optimize $G$ by setting
|
||||
!bt
|
||||
\[
|
||||
G_m(x) = \mathrm{sign} \sum_{i=0}^{n-1} w_i^m I(y_i \ne G_(x_i)),
|
||||
\]
|
||||
!et
|
||||
which is the classifier that minimizes the weighted error rate in predicting $y$.
|
||||
|
||||
We can do this by rewriting
|
||||
!bt
|
||||
\[
|
||||
\exp{-(\beta)}\sum_{y_i=G(x_i)}w_i^m+\exp{(\beta)}\sum_{y_i\ne G(x_i)}w_i^m,
|
||||
\]
|
||||
!et
|
||||
which can be rewritten as
|
||||
!bt
|
||||
\[
|
||||
(\exp{(\beta)}-\exp{-(\beta)})\sum_{i=0}^{n-1}w_i^mI(y_i\ne G(x_i))+\exp{(-\beta)}\sum_{i=0}^{n-1}w_i^m=0,
|
||||
\]
|
||||
!et
|
||||
which leads to
|
||||
!bt
|
||||
\[
|
||||
\beta_m = \frac{1}{2}\log{\frac{1-\mathrm{\overline{err}}}{\mathrm{\overline{err}}}},
|
||||
\]
|
||||
!et
|
||||
where we have redefined the error as
|
||||
!bt
|
||||
\[
|
||||
\mathrm{\overline{err}}_m=\frac{1}{n}\frac{\sum_{i=0}^{n-1}w_i^mI(y_i\ne G(x_i)}{\sum_{i=0}^{n-1}w_i^m},
|
||||
\]
|
||||
!et
|
||||
which leads to an update of
|
||||
!bt
|
||||
\[
|
||||
f_m(x) = f_{m-1}(x) +\beta_m G_m(x).
|
||||
\]
|
||||
!et
|
||||
This leads to the new weights
|
||||
!bt
|
||||
\[
|
||||
w_i^{m+1} = w_i^m \exp{(-y_i\beta_m G_m(x_i))}
|
||||
\]
|
||||
!et
|
||||
|
||||
|
||||
!split
|
||||
===== Adaptive boosting: AdaBoost, Basic Algorithm =====
|
||||
|
||||
The algorithm here is rather straightforward. Assume that our weak
|
||||
classifier is a decision tree and we consider a binary set of outputs
|
||||
with $y_i \in \{-1,1\}$ and $i=0,1,2,\dots,n-1$ as our set of
|
||||
observations. Our design matrix is given in terms of the
|
||||
feature/predictor vectors
|
||||
$\bm{X}=[\bm{x}_0\bm{x}_1\dots\bm{x}_{p-1}]$. Finally, we define also a
|
||||
classifier determined by our data via a function $G(x)$. This function tells us how well we are able to classify our outputs/targets $\bm{y}$.
|
||||
|
||||
We have already defined the misclassification error $\mathrm{err}$ as
|
||||
!bt
|
||||
\[
|
||||
\mathrm{err}=\frac{1}{n}\sum_{i=0}^{n-1}I(y_i\ne G(x_i)),
|
||||
\]
|
||||
!et
|
||||
where the function $I()$ is one if we misclassify and zero if we classify correctly.
|
||||
|
||||
!split
|
||||
===== Basic Steps of AdaBoost =====
|
||||
|
||||
With the above definitions we are now ready to set up the algorithm for AdaBoost.
|
||||
The basic idea is to set up weights which will be used to scale the correctly classified and the misclassified cases.
|
||||
o We start by initializing all weights to $w_i = 1/n$, with $i=0,1,2,\dots n-1$. It is easy to see that we must have $\sum_{i=0}^{n-1}w_i = 1$.
|
||||
o We rewrite the misclassification error as
|
||||
!bt
|
||||
\[
|
||||
\mathrm{\overline{err}}_m=\frac{\sum_{i=0}^{n-1}w_i^m I(y_i\ne G(x_i))}{\sum_{i=0}^{n-1}w_i},
|
||||
\]
|
||||
!et
|
||||
o Then we start looping over all attempts at classifying, namely we start an iterative process for $m=1:M$, where $M$ is the final number of classifications. Our given classifier could for example be a plain decision tree.
|
||||
o Fit then a given classifier to the training set using the weights $w_i$.
|
||||
o Compute then $\mathrm{err}$ and figure out which events are classified properly and which are classified wrongly.
|
||||
o Define a quantity $\alpha_{m} = \log{(1-\mathrm{\overline{err}}_m)/\mathrm{\overline{err}}_m}$
|
||||
o Set the new weights to $w_i = w_i\times \exp{(\alpha_m I(y_i\ne G(x_i)}$.
|
||||
o Compute the new classifier $G(x)= \sum_{i=0}^{n-1}\alpha_m I(y_i\ne G(x_i)$.
|
||||
|
||||
For the iterations with $m \le 2$ the weights are modified
|
||||
individually at each steps. The observations which were misclassified
|
||||
at iteration $m-1$ have a weight which is larger than those which were
|
||||
classified properly. As this proceeds, the observations which were
|
||||
difficult to classifiy correctly are given a larger influence. Each
|
||||
new classification step $m$ is then forced to concentrate on those
|
||||
observations that are missed in the previous iterations.
|
||||
|
||||
|
||||
|
||||
!split
|
||||
===== AdaBoost Examples =====
|
||||
|
||||
Using _Scikit-Learn_ it is easy to apply the adaptive boosting algorithm, as done here.
|
||||
|
||||
!bc pycod
|
||||
from sklearn.ensemble import AdaBoostClassifier
|
||||
|
||||
ada_clf = AdaBoostClassifier(
|
||||
DecisionTreeClassifier(max_depth=1), n_estimators=200,
|
||||
algorithm="SAMME.R", learning_rate=0.5, random_state=42)
|
||||
ada_clf.fit(X_train, y_train)
|
||||
|
||||
from sklearn.ensemble import AdaBoostClassifier
|
||||
|
||||
ada_clf = AdaBoostClassifier(
|
||||
DecisionTreeClassifier(max_depth=1), n_estimators=200,
|
||||
algorithm="SAMME.R", learning_rate=0.5, random_state=42)
|
||||
ada_clf.fit(X_train_scaled, y_train)
|
||||
y_pred = ada_clf.predict(X_test_scaled)
|
||||
skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)
|
||||
plt.show()
|
||||
y_probas = ada_clf.predict_proba(X_test_scaled)
|
||||
skplt.metrics.plot_roc(y_test, y_probas)
|
||||
plt.show()
|
||||
skplt.metrics.plot_cumulative_gain(y_test, y_probas)
|
||||
plt.show()
|
||||
!ec
|
||||
|
||||
|
||||
!split
|
||||
===== AdaBoost for Regression =====
|
||||
|
||||
Here we present "Drucker's AdaBoost":"https://pdfs.semanticscholar.org/8d49/e2dedb817f2c3330e74b63c5fc86d2399ce3.pdf" tailored for regression.
|
||||
|
||||
In bagging, each training example is equally likely to be
|
||||
picked. In boosting, the probability of a particular
|
||||
example being in the training set of a particular machine
|
||||
depends on the performance of the prior machines on
|
||||
that example. The following is a modification of
|
||||
Adaboost by Drucker.
|
||||
|
||||
Start by selecting a set of training data $n$ and assign to each entry a weight $w_i=1$ for $i=1,2,\dots,n$. As we have done earlier, we could pick say $80\%$ of the data set for training. The algorithm runs as follows:
|
||||
o We define the probability that the training sample $i$ is in the set by $p_i = w_i/\sum_iw_i$. We pick $n$ samples (with replacement) to form our training set. We pick a number uniformly in the range $[0,\sum_iw_i]$.
|
||||
o We choose then a regression machine (for example plain linear regression or a simple decision tree). A given regression machine makes then a hypothesis.
|
||||
o Using every member of the training set with the chosen regression machine we obtain then a prediction $\tilde{y}_i$.
|
||||
o We calculate then the loss function $L_i$ for each training sample. We can use various types of loss function as long as we have a value
|
||||
$L_i\in [0,1]$.
|
||||
|
||||
!split
|
||||
===== Gradient boosting: Basics with Steepest Descent =====
|
||||
|
||||
Gradient boosting is again a similar technique to Adaptive boosting,
|
||||
it combines so-called weak classifiers or regressors into a strong
|
||||
method via a series of iterations.
|
||||
|
||||
In order to understand the method, let us illustrate its basics by
|
||||
bringing back the essential steps in linear regression, where our cost
|
||||
function was the least squares function.
|
||||
|
||||
!split
|
||||
===== The Squared-Error again! Steepest Descent =====
|
||||
|
||||
We start again with our cost function ${\cal C}(\bm{y}m\bm{f})=\sum_{i=0}^{n-1}{\cal L}(y_i, f(x_i))$ where we want to minimize
|
||||
This means that for every iteration, we need to optimize
|
||||
|
||||
!bt
|
||||
\[
|
||||
(\hat{\bm{f}}) = \mathrm{argmin}_{\bm{f}}\hspace{0.1cm} \sum_{i=0}^{n-1}(y_i-f(x_i))^2.
|
||||
\]
|
||||
!et
|
||||
|
||||
We define a real function $h_m(x)$ that defines our final function $f_M(x)$ as
|
||||
!bt
|
||||
\[
|
||||
f_M(x) = \sum_{m=0}^M h_m(x).
|
||||
\]
|
||||
!et
|
||||
|
||||
In the steepest decent approach we approximate $h_m(x) = -\rho_m g_m(x)$, where $\rho_m$ is a scalar and $g_m(x)$ the gradient defined as
|
||||
!bt
|
||||
\[
|
||||
g_m(x_i) = \left[ \frac{\partial {\cal L}(y_i, f(x_i))}{\partial f(x_i)}\right]_{f(x_i)=f_{m-1}(x_i)}.
|
||||
\]
|
||||
!et
|
||||
|
||||
With the new gradient we can update $f_m(x) = f_{m-1}(x) -\rho_m g_m(x)$. Using the above squared-error function we see that
|
||||
the gradient is $g_m(x_i) = -2(y_i-f(x_i))$.
|
||||
|
||||
Choosing $f_0(x)=0$ we obtain $g_m(x) = -2y_i$ and inserting this into the minimization problem for the cost function we have
|
||||
!bt
|
||||
\[
|
||||
(\rho_1) = \mathrm{argmin}_{\rho}\hspace{0.1cm} \sum_{i=0}^{n-1}(y_i+2\rho y_i)^2.
|
||||
\]
|
||||
!et
|
||||
|
||||
!split
|
||||
===== Steepest Descent Example =====
|
||||
|
||||
Optimizing with respect to $\rho$ we obtain (taking the derivative) that $\rho_1 = -1/2$. We have then that
|
||||
!bt
|
||||
\[
|
||||
f_1(x) = f_{0}(x) -\rho_1 g_1(x)=-y_i.
|
||||
\]
|
||||
!et
|
||||
We can then proceed and compute
|
||||
!bt
|
||||
\[
|
||||
g_2(x_i) = \left[ \frac{\partial {\cal L}(y_i, f(x_i))}{\partial f(x_i)}\right]_{f(x_i)=f_{1}(x_i)=y_i}=-4y_i,
|
||||
\]
|
||||
!et
|
||||
and find a new value for $\rho_2=-1/2$ and continue till we have reached $m=M$. We can modify the steepest descent method, or steepest boosting, by introducing what is called _gradient boosting_.
|
||||
|
||||
!split
|
||||
===== Gradient Boosting, algorithm =====
|
||||
|
||||
Suppose we have a cost function $C(f)=\sum_{i=0}^{n-1}L(y_i, f(x_i))$ where $y_i$ is our target and $f(x_i)$ the function which is meant to model $y_i$. The above cost function could be our standard squared-error function
|
||||
!bt
|
||||
\[
|
||||
C(\bm{y},\bm{f})=\sum_{i=0}^{n-1}(y_i-f(x_i))^2.
|
||||
\]
|
||||
!et
|
||||
|
||||
The way we proceed in an iterative fashion is to
|
||||
o Initialize our estimate $f_0(x)$.
|
||||
o For $m=1:M$, we
|
||||
o compute the negative gradient vector $\bm{u}_m = -\partial C(\bm{y},\bm{f})/\partial \bm{f}(x)$ at $f(x) = f_{m-1}(x)$;
|
||||
o fit the so-called base-learner to the negative gradient $h_m(u_m,x)$;
|
||||
o update the estimate $f_m(x) = f_{m-1}(x)+\nu h_m(u_m,x)$;
|
||||
o The final estimate is then $f_M(x) = \sum_{m=1}^M\nu h_m(u_m,x)$.
|
||||
|
||||
!split
|
||||
===== Gradient Boosting Example, Regression =====
|
||||
|
||||
We discuss here the difference between the steepest descent approach and gradient boosting by repeating our simple regression example above.
|
||||
|
||||
|
||||
!split
|
||||
===== Gradient Boosting, Examples of Regression =====
|
||||
!bc pycod
|
||||
import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
from sklearn.model_selection import train_test_split
|
||||
from sklearn.ensemble import GradientBoostingRegressor
|
||||
from sklearn.preprocessing import StandardScaler
|
||||
import scikitplot as skplt
|
||||
from sklearn.metrics import mean_squared_error
|
||||
|
||||
n = 100
|
||||
maxdegree = 6
|
||||
|
||||
# Make data set.
|
||||
x = np.linspace(-3, 3, n).reshape(-1, 1)
|
||||
y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
|
||||
|
||||
error = np.zeros(maxdegree)
|
||||
bias = np.zeros(maxdegree)
|
||||
variance = np.zeros(maxdegree)
|
||||
polydegree = np.zeros(maxdegree)
|
||||
X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
|
||||
scaler = StandardScaler()
|
||||
scaler.fit(X_train)
|
||||
X_train_scaled = scaler.transform(X_train)
|
||||
X_test_scaled = scaler.transform(X_test)
|
||||
|
||||
for degree in range(1,maxdegree):
|
||||
model = GradientBoostingRegressor(max_depth=degree, n_estimators=100, learning_rate=1.0)
|
||||
model.fit(X_train_scaled,y_train)
|
||||
y_pred = model.predict(X_test_scaled)
|
||||
polydegree[degree] = degree
|
||||
error[degree] = np.mean( np.mean((y_test - y_pred)**2) )
|
||||
bias[degree] = np.mean( (y_test - np.mean(y_pred))**2 )
|
||||
variance[degree] = np.mean( np.var(y_pred) )
|
||||
print('Max depth:', degree)
|
||||
print('Error:', error[degree])
|
||||
print('Bias^2:', bias[degree])
|
||||
print('Var:', variance[degree])
|
||||
print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
|
||||
|
||||
plt.xlim(1,maxdegree-1)
|
||||
plt.plot(polydegree, error, label='Error')
|
||||
plt.plot(polydegree, bias, label='bias')
|
||||
plt.plot(polydegree, variance, label='Variance')
|
||||
plt.legend()
|
||||
save_fig("gdregression")
|
||||
plt.show()
|
||||
!ec
|
||||
|
||||
|
||||
!split
|
||||
===== Gradient Boosting, Classification Example =====
|
||||
!bc pycod
|
||||
import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
from sklearn.model_selection import train_test_split
|
||||
from sklearn.datasets import load_breast_cancer
|
||||
import scikitplot as skplt
|
||||
from sklearn.ensemble import GradientBoostingClassifier
|
||||
from sklearn.model_selection import cross_validate
|
||||
|
||||
# Load the data
|
||||
cancer = load_breast_cancer()
|
||||
|
||||
X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
|
||||
print(X_train.shape)
|
||||
print(X_test.shape)
|
||||
#now scale the data
|
||||
from sklearn.preprocessing import StandardScaler
|
||||
scaler = StandardScaler()
|
||||
scaler.fit(X_train)
|
||||
X_train_scaled = scaler.transform(X_train)
|
||||
X_test_scaled = scaler.transform(X_test)
|
||||
|
||||
gd_clf = GradientBoostingClassifier(max_depth=3, n_estimators=100, learning_rate=1.0)
|
||||
gd_clf.fit(X_train_scaled, y_train)
|
||||
#Cross validation
|
||||
accuracy = cross_validate(gd_clf,X_test_scaled,y_test,cv=10)['test_score']
|
||||
print(accuracy)
|
||||
print("Test set accuracy with Random Forests and scaled data: {:.2f}".format(gd_clf.score(X_test_scaled,y_test)))
|
||||
|
||||
import scikitplot as skplt
|
||||
y_pred = gd_clf.predict(X_test_scaled)
|
||||
skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)
|
||||
save_fig("gdclassiffierconfusion")
|
||||
plt.show()
|
||||
y_probas = gd_clf.predict_proba(X_test_scaled)
|
||||
skplt.metrics.plot_roc(y_test, y_probas)
|
||||
save_fig("gdclassiffierroc")
|
||||
plt.show()
|
||||
skplt.metrics.plot_cumulative_gain(y_test, y_probas)
|
||||
save_fig("gdclassiffiercgain")
|
||||
plt.show()
|
||||
!ec
|
||||
|
||||
|
||||
!split
|
||||
===== XGBoost: Extreme Gradient Boosting =====
|
||||
|
||||
|
||||
"XGBoost":"https://github.com/dmlc/xgboost" or Extreme Gradient
|
||||
Boosting, is an optimized distributed gradient boosting library
|
||||
designed to be highly efficient, flexible and portable. It implements
|
||||
machine learning algorithms under the Gradient Boosting
|
||||
framework. XGBoost provides a parallel tree boosting that solve many
|
||||
data science problems in a fast and accurate way. See the "article by Chen and Guestrin":"https://arxiv.org/abs/1603.02754".
|
||||
|
||||
The authors design and build a highly scalable end-to-end tree
|
||||
boosting system. It has a theoretically justified weighted quantile
|
||||
sketch for efficient proposal calculation. It introduces a novel sparsity-aware algorithm for parallel tree learning and an effective cache-aware block structure for out-of-core tree learning.
|
||||
|
||||
It is now the algorithm which wins essentially all ML competitions!!!
|
||||
|
||||
!split
|
||||
===== Regression Case =====
|
||||
|
||||
!bc pycod
|
||||
import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
from sklearn.model_selection import train_test_split
|
||||
import xgboost as xgb
|
||||
from sklearn.preprocessing import StandardScaler
|
||||
import scikitplot as skplt
|
||||
from sklearn.metrics import mean_squared_error
|
||||
|
||||
n = 100
|
||||
maxdegree = 6
|
||||
|
||||
# Make data set.
|
||||
x = np.linspace(-3, 3, n).reshape(-1, 1)
|
||||
y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
|
||||
|
||||
error = np.zeros(maxdegree)
|
||||
bias = np.zeros(maxdegree)
|
||||
variance = np.zeros(maxdegree)
|
||||
polydegree = np.zeros(maxdegree)
|
||||
X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)
|
||||
scaler = StandardScaler()
|
||||
scaler.fit(X_train)
|
||||
X_train_scaled = scaler.transform(X_train)
|
||||
X_test_scaled = scaler.transform(X_test)
|
||||
|
||||
for degree in range(maxdegree):
|
||||
model = xgb.XGBRegressor(objective ='reg:squarederror', colsaobjective ='reg:squarederror', colsample_bytree = 0.3, learning_rate = 0.1,max_depth = degree, alpha = 10, n_estimators = 200)
|
||||
|
||||
model.fit(X_train_scaled,y_train)
|
||||
y_pred = model.predict(X_test_scaled)
|
||||
polydegree[degree] = degree
|
||||
error[degree] = np.mean( np.mean((y_test - y_pred)**2) )
|
||||
bias[degree] = np.mean( (y_test - np.mean(y_pred))**2 )
|
||||
variance[degree] = np.mean( np.var(y_pred) )
|
||||
print('Max depth:', degree)
|
||||
print('Error:', error[degree])
|
||||
print('Bias^2:', bias[degree])
|
||||
print('Var:', variance[degree])
|
||||
print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))
|
||||
|
||||
plt.xlim(1,maxdegree-1)
|
||||
plt.plot(polydegree, error, label='Error')
|
||||
plt.plot(polydegree, bias, label='bias')
|
||||
plt.plot(polydegree, variance, label='Variance')
|
||||
plt.legend()
|
||||
plt.show()
|
||||
|
||||
!ec
|
||||
|
||||
!split
|
||||
===== Xgboost on the Cancer Data =====
|
||||
|
||||
As you will see from the confusion matrix below, XGBoots does an excellent job on the Wisconsin cancer data and outperforms essentially all agorithms we have discussed till now.
|
||||
!bc pycod
|
||||
|
||||
import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
from sklearn.model_selection import train_test_split
|
||||
from sklearn.datasets import load_breast_cancer
|
||||
from sklearn.preprocessing import LabelEncoder
|
||||
from sklearn.model_selection import cross_validate
|
||||
import scikitplot as skplt
|
||||
import xgboost as xgb
|
||||
# Load the data
|
||||
cancer = load_breast_cancer()
|
||||
|
||||
X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
|
||||
print(X_train.shape)
|
||||
print(X_test.shape)
|
||||
#now scale the data
|
||||
from sklearn.preprocessing import StandardScaler
|
||||
scaler = StandardScaler()
|
||||
scaler.fit(X_train)
|
||||
X_train_scaled = scaler.transform(X_train)
|
||||
X_test_scaled = scaler.transform(X_test)
|
||||
|
||||
xg_clf = xgb.XGBClassifier()
|
||||
xg_clf.fit(X_train_scaled,y_train)
|
||||
|
||||
y_test = xg_clf.predict(X_test_scaled)
|
||||
|
||||
print("Test set accuracy with Random Forests and scaled data: {:.2f}".format(xg_clf.score(X_test_scaled,y_test)))
|
||||
|
||||
import scikitplot as skplt
|
||||
y_pred = xg_clf.predict(X_test_scaled)
|
||||
skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)
|
||||
save_fig("xdclassiffierconfusion")
|
||||
plt.show()
|
||||
y_probas = xg_clf.predict_proba(X_test_scaled)
|
||||
skplt.metrics.plot_roc(y_test, y_probas)
|
||||
save_fig("xdclassiffierroc")
|
||||
plt.show()
|
||||
skplt.metrics.plot_cumulative_gain(y_test, y_probas)
|
||||
save_fig("gdclassiffiercgain")
|
||||
plt.show()
|
||||
|
||||
|
||||
xgb.plot_tree(xg_clf,num_trees=0)
|
||||
plt.rcParams['figure.figsize'] = [50, 10]
|
||||
save_fig("xgtree")
|
||||
plt.show()
|
||||
|
||||
xgb.plot_importance(xg_clf)
|
||||
plt.rcParams['figure.figsize'] = [5, 5]
|
||||
save_fig("xgparams")
|
||||
plt.show()
|
||||
|
||||
!ec
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user