updating week41
This commit is contained in:
+189
-478
@@ -7,7 +7,7 @@ DATE: today
|
||||
===== Plan for week 40 =====
|
||||
|
||||
* Thursday: Building our own Feed-forward Neural Network
|
||||
* Friday: Playing around with our own Feed-forward Neural Network and introduction to TensorFlow. Start convolutional Neural Networks.
|
||||
* Friday: Playing around with our own Feed-forward Neural Network and introduction to TensorFlow. Start convolutional Neural Networks (CNN).
|
||||
|
||||
Reading suggestions for both days: "Aurelien Geron's chapters 10-11":"https://github.com/CompPhysics/MachineLearning/blob/master/doc/T\
|
||||
extbooks/TensorflowML.pdf" and Hastie et al chapter 11.
|
||||
@@ -1385,7 +1385,6 @@ writer = tf.summary.FileWriter('logs/')
|
||||
writer.add_graph(tf.get_default_graph())
|
||||
!ec
|
||||
|
||||
|
||||
!split
|
||||
===== Using Keras =====
|
||||
|
||||
@@ -1400,23 +1399,26 @@ conda install keras
|
||||
Alternatively, if you have Tensorflow or one of the other supported backends install you may use the pip package manager:
|
||||
|
||||
!bc pycod
|
||||
pip3 install keras
|
||||
pip install keras
|
||||
!ec
|
||||
or look up the "instructions here":"https://keras.io/".
|
||||
|
||||
!bc pycod
|
||||
from keras.models import Sequential
|
||||
from keras.layers import Dense
|
||||
from keras.regularizers import l2
|
||||
from keras.optimizers import SGD
|
||||
import tensorflow as tf
|
||||
from tensorflow.keras.layers import Input
|
||||
from tensorflow.keras.models import Sequential #This allows appending layers to existing models
|
||||
from tensorflow.keras.layers import Dense #This allows defining the characteristics of a particular layer
|
||||
from tensorflow.keras import optimizers #This allows using whichever optimiser we want (sgd,adam,RMSprop)
|
||||
from tensorflow.keras import regularizers #This allows using whichever regularizer we want (l1,l2,l1_l2)
|
||||
from tensorflow.keras.utils import to_categorical #This allows using categorical cross entropy as the cost function
|
||||
|
||||
def create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories, eta, lmbd):
|
||||
model = Sequential()
|
||||
model.add(Dense(n_neurons_layer1, activation='sigmoid', kernel_regularizer=l2(lmbd)))
|
||||
model.add(Dense(n_neurons_layer2, activation='sigmoid', kernel_regularizer=l2(lmbd)))
|
||||
model.add(Dense(n_neurons_layer1, activation='sigmoid', kernel_regularizer=regularizers.l2(lmbd)))
|
||||
model.add(Dense(n_neurons_layer2, activation='sigmoid', kernel_regularizer=regularizers.l2(lmbd)))
|
||||
model.add(Dense(n_categories, activation='softmax'))
|
||||
|
||||
sgd = SGD(lr=eta)
|
||||
sgd = optimizers.SGD(lr=eta)
|
||||
model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])
|
||||
|
||||
return model
|
||||
@@ -1440,6 +1442,8 @@ for i, eta in enumerate(eta_vals):
|
||||
print()
|
||||
!ec
|
||||
|
||||
|
||||
|
||||
!bc pycod
|
||||
# optional
|
||||
# visual representation of grid search
|
||||
@@ -1476,6 +1480,180 @@ plt.show()
|
||||
|
||||
|
||||
|
||||
!split
|
||||
===== The Breast Cancer Data, now with Keras =====
|
||||
|
||||
!bc pycod
|
||||
|
||||
import tensorflow as tf
|
||||
from tensorflow.keras.layers import Input
|
||||
from tensorflow.keras.models import Sequential #This allows appending layers to existing models
|
||||
from tensorflow.keras.layers import Dense #This allows defining the characteristics of a particular layer
|
||||
from tensorflow.keras import optimizers #This allows using whichever optimiser we want (sgd,adam,RMSprop)
|
||||
from tensorflow.keras import regularizers #This allows using whichever regularizer we want (l1,l2,l1_l2)
|
||||
from tensorflow.keras.utils import to_categorical #This allows using categorical cross entropy as the cost function
|
||||
import numpy as np
|
||||
import matplotlib.pyplot as plt
|
||||
import seaborn as sns
|
||||
from sklearn.model_selection import train_test_split as splitter
|
||||
from sklearn.datasets import load_breast_cancer
|
||||
import pickle
|
||||
import os
|
||||
|
||||
|
||||
"""Load breast cancer dataset"""
|
||||
|
||||
np.random.seed(0) #create same seed for random number every time
|
||||
|
||||
cancer=load_breast_cancer() #Download breast cancer dataset
|
||||
|
||||
inputs=cancer.data #Feature matrix of 569 rows (samples) and 30 columns (parameters)
|
||||
outputs=cancer.target #Label array of 569 rows (0 for benign and 1 for malignant)
|
||||
labels=cancer.feature_names[0:30]
|
||||
|
||||
print('The content of the breast cancer dataset is:') #Print information about the datasets
|
||||
print(labels)
|
||||
print('-------------------------')
|
||||
print("inputs = " + str(inputs.shape))
|
||||
print("outputs = " + str(outputs.shape))
|
||||
print("labels = "+ str(labels.shape))
|
||||
|
||||
x=inputs #Reassign the Feature and Label matrices to other variables
|
||||
y=outputs
|
||||
|
||||
#%%
|
||||
|
||||
# Visualisation of dataset (for correlation analysis)
|
||||
|
||||
plt.figure()
|
||||
plt.scatter(x[:,0],x[:,2],s=40,c=y,cmap=plt.cm.Spectral)
|
||||
plt.xlabel('Mean radius',fontweight='bold')
|
||||
plt.ylabel('Mean perimeter',fontweight='bold')
|
||||
plt.show()
|
||||
|
||||
plt.figure()
|
||||
plt.scatter(x[:,5],x[:,6],s=40,c=y, cmap=plt.cm.Spectral)
|
||||
plt.xlabel('Mean compactness',fontweight='bold')
|
||||
plt.ylabel('Mean concavity',fontweight='bold')
|
||||
plt.show()
|
||||
|
||||
|
||||
plt.figure()
|
||||
plt.scatter(x[:,0],x[:,1],s=40,c=y,cmap=plt.cm.Spectral)
|
||||
plt.xlabel('Mean radius',fontweight='bold')
|
||||
plt.ylabel('Mean texture',fontweight='bold')
|
||||
plt.show()
|
||||
|
||||
plt.figure()
|
||||
plt.scatter(x[:,2],x[:,1],s=40,c=y,cmap=plt.cm.Spectral)
|
||||
plt.xlabel('Mean perimeter',fontweight='bold')
|
||||
plt.ylabel('Mean compactness',fontweight='bold')
|
||||
plt.show()
|
||||
|
||||
|
||||
# Generate training and testing datasets
|
||||
|
||||
#Select features relevant to classification (texture,perimeter,compactness and symmetery)
|
||||
#and add to input matrix
|
||||
|
||||
temp1=np.reshape(x[:,1],(len(x[:,1]),1))
|
||||
temp2=np.reshape(x[:,2],(len(x[:,2]),1))
|
||||
X=np.hstack((temp1,temp2))
|
||||
temp=np.reshape(x[:,5],(len(x[:,5]),1))
|
||||
X=np.hstack((X,temp))
|
||||
temp=np.reshape(x[:,8],(len(x[:,8]),1))
|
||||
X=np.hstack((X,temp))
|
||||
|
||||
X_train,X_test,y_train,y_test=splitter(X,y,test_size=0.1) #Split datasets into training and testing
|
||||
|
||||
y_train=to_categorical(y_train) #Convert labels to categorical when using categorical cross entropy
|
||||
y_test=to_categorical(y_test)
|
||||
|
||||
del temp1,temp2,temp
|
||||
|
||||
# %%
|
||||
|
||||
# Define tunable parameters"
|
||||
|
||||
eta=np.logspace(-3,-1,3) #Define vector of learning rates (parameter to SGD optimiser)
|
||||
lamda=0.01 #Define hyperparameter
|
||||
n_layers=2 #Define number of hidden layers in the model
|
||||
n_neuron=np.logspace(0,3,4,dtype=int) #Define number of neurons per layer
|
||||
epochs=100 #Number of reiterations over the input data
|
||||
batch_size=100 #Number of samples per gradient update
|
||||
|
||||
# %%
|
||||
|
||||
"""Define function to return Deep Neural Network model"""
|
||||
|
||||
def NN_model(inputsize,n_layers,n_neuron,eta,lamda):
|
||||
model=Sequential()
|
||||
for i in range(n_layers): #Run loop to add hidden layers to the model
|
||||
if (i==0): #First layer requires input dimensions
|
||||
model.add(Dense(n_neuron,activation='relu',kernel_regularizer=regularizers.l2(lamda),input_dim=inputsize))
|
||||
else: #Subsequent layers are capable of automatic shape inferencing
|
||||
model.add(Dense(n_neuron,activation='relu',kernel_regularizer=regularizers.l2(lamda)))
|
||||
model.add(Dense(2,activation='softmax')) #2 outputs - ordered and disordered (softmax for prob)
|
||||
sgd=optimizers.SGD(lr=eta)
|
||||
model.compile(loss='categorical_crossentropy',optimizer=sgd,metrics=['accuracy'])
|
||||
return model
|
||||
|
||||
|
||||
Train_accuracy=np.zeros((len(n_neuron),len(eta))) #Define matrices to store accuracy scores as a function
|
||||
Test_accuracy=np.zeros((len(n_neuron),len(eta))) #of learning rate and number of hidden neurons for
|
||||
|
||||
for i in range(len(n_neuron)): #run loops over hidden neurons and learning rates to calculate
|
||||
for j in range(len(eta)): #accuracy scores
|
||||
DNN_model=NN_model(X_train.shape[1],n_layers,n_neuron[i],eta[j],lamda)
|
||||
DNN_model.fit(X_train,y_train,epochs=epochs,batch_size=batch_size,verbose=1)
|
||||
Train_accuracy[i,j]=DNN_model.evaluate(X_train,y_train)[1]
|
||||
Test_accuracy[i,j]=DNN_model.evaluate(X_test,y_test)[1]
|
||||
|
||||
|
||||
def plot_data(x,y,data,title=None):
|
||||
|
||||
# plot results
|
||||
fontsize=16
|
||||
|
||||
|
||||
fig = plt.figure()
|
||||
ax = fig.add_subplot(111)
|
||||
cax = ax.matshow(data, interpolation='nearest', vmin=0, vmax=1)
|
||||
|
||||
cbar=fig.colorbar(cax)
|
||||
cbar.ax.set_ylabel('accuracy (%)',rotation=90,fontsize=fontsize)
|
||||
cbar.set_ticks([0,.2,.4,0.6,0.8,1.0])
|
||||
cbar.set_ticklabels(['0%','20%','40%','60%','80%','100%'])
|
||||
|
||||
# put text on matrix elements
|
||||
for i, x_val in enumerate(np.arange(len(x))):
|
||||
for j, y_val in enumerate(np.arange(len(y))):
|
||||
c = "${0:.1f}\\%$".format( 100*data[j,i])
|
||||
ax.text(x_val, y_val, c, va='center', ha='center')
|
||||
|
||||
# convert axis vaues to to string labels
|
||||
x=[str(i) for i in x]
|
||||
y=[str(i) for i in y]
|
||||
|
||||
|
||||
ax.set_xticklabels(['']+x)
|
||||
ax.set_yticklabels(['']+y)
|
||||
|
||||
ax.set_xlabel('$\\mathrm{learning\\ rate}$',fontsize=fontsize)
|
||||
ax.set_ylabel('$\\mathrm{hidden\\ neurons}$',fontsize=fontsize)
|
||||
if title is not None:
|
||||
ax.set_title(title)
|
||||
|
||||
plt.tight_layout()
|
||||
|
||||
plt.show()
|
||||
|
||||
plot_data(eta,n_neuron,Train_accuracy, 'training')
|
||||
plot_data(eta,n_neuron,Test_accuracy, 'testing')
|
||||
|
||||
!ec
|
||||
|
||||
|
||||
|
||||
!split
|
||||
===== Which activation function should I use? =====
|
||||
@@ -1678,7 +1856,7 @@ Some of these remarks are particular to DNNs, others are shared by all supervise
|
||||
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
|
||||
of deep learning methods. The success in for example image
|
||||
classifications have made them a central tool for most machine
|
||||
learning practitioners.
|
||||
|
||||
@@ -1807,470 +1985,3 @@ the course
|
||||
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/"
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user