diff --git a/doc/pub/week41/html/._week41-bs000.html b/doc/pub/week41/html/._week41-bs000.html index 112def37d..63ba71fc4 100644 --- a/doc/pub/week41/html/._week41-bs000.html +++ b/doc/pub/week41/html/._week41-bs000.html @@ -83,56 +83,35 @@ Automatically generated HTML file from DocOnce source ('Using TensorFlow backend', 2, None, '___sec29'), ('Optimizing and using gradient descent', 2, None, '___sec30'), ('Using Keras', 2, None, '___sec31'), - ('Which activation function should I use?', 2, None, '___sec32'), + ('The Breast Cancer Data, now with Keras', 2, None, '___sec32'), + ('Which activation function should I use?', 2, None, '___sec33'), ('Is the Logistic activation function (Sigmoid) our choice?', 2, None, - '___sec33'), - ('The derivative of the Logistic funtion', 2, None, '___sec34'), - ('The RELU function family', 2, None, '___sec35'), - ('Which activation function should we use?', 2, None, '___sec36'), + '___sec34'), + ('The derivative of the Logistic funtion', 2, None, '___sec35'), + ('The RELU function family', 2, None, '___sec36'), + ('Which activation function should we use?', 2, None, '___sec37'), ('A top-down perspective on Neural networks', 2, None, - '___sec37'), + '___sec38'), ('Limitations of supervised learning with deep networks', 2, None, - '___sec38'), + '___sec39'), ('Convolutional Neural Networks (recognizing images)', 2, None, - '___sec39'), + '___sec40'), ('Regular NNs don’t scale well to full images', 2, None, - '___sec40'), - ('3D volumes of neurons', 2, None, '___sec41'), - ('Layers used to build CNNs', 2, None, '___sec42'), - ('Transforming images', 2, None, '___sec43'), - ('CNNs in brief', 2, None, '___sec44'), - ('CNNs in more detail, building convolutional neural networks in ' - 'Tensorflow and Keras', - 2, - None, - '___sec45'), - ('Setting it up', 2, None, '___sec46'), - ('The MNIST dataset again', 2, None, '___sec47'), - ('Strong correlations', 2, None, '___sec48'), - ('Layers of a CNN', 2, None, '___sec49'), - ('Systematic reduction', 2, None, '___sec50'), - ('Prerequisites: Collect and pre-process data', - 2, - None, - '___sec51'), - ('Importing Keras and Tensorflow', 2, None, '___sec52'), - ('Using TensorFlow backend', 2, None, '___sec53'), - ('Train the model', 2, None, '___sec54'), - ('Visualizing the results', 2, None, '___sec55'), - ('Running with Keras', 2, None, '___sec56'), - ('Final part', 2, None, '___sec57'), - ('Final visualization', 2, None, '___sec58'), - ('Fun links', 2, None, '___sec59')]} + '___sec41'), + ('3D volumes of neurons', 2, None, '___sec42'), + ('Layers used to build CNNs', 2, None, '___sec43'), + ('Transforming images', 2, None, '___sec44'), + ('CNNs in brief', 2, None, '___sec45')]} end of tocinfo -->
@@ -202,34 +181,20 @@ MathJax.Hub.Config({-
@@ -288,7 +253,7 @@ MathJax.Hub.Config({
-
pip3 install keras
+pip install keras
or look up the instructions here.
@@ -271,18 +236,21 @@ or look up the instructions here.
-
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
@@ -367,7 +335,7 @@ plt.show()
41
42
...
- 61
+ 47
»
diff --git a/doc/pub/week41/html/._week41-bs033.html b/doc/pub/week41/html/._week41-bs033.html
index 98b197fec..fdb6f0693 100644
--- a/doc/pub/week41/html/._week41-bs033.html
+++ b/doc/pub/week41/html/._week41-bs033.html
@@ -83,56 +83,35 @@ Automatically generated HTML file from DocOnce source
('Using TensorFlow backend', 2, None, '___sec29'),
('Optimizing and using gradient descent', 2, None, '___sec30'),
('Using Keras', 2, None, '___sec31'),
- ('Which activation function should I use?', 2, None, '___sec32'),
+ ('The Breast Cancer Data, now with Keras', 2, None, '___sec32'),
+ ('Which activation function should I use?', 2, None, '___sec33'),
('Is the Logistic activation function (Sigmoid) our choice?',
2,
None,
- '___sec33'),
- ('The derivative of the Logistic funtion', 2, None, '___sec34'),
- ('The RELU function family', 2, None, '___sec35'),
- ('Which activation function should we use?', 2, None, '___sec36'),
+ '___sec34'),
+ ('The derivative of the Logistic funtion', 2, None, '___sec35'),
+ ('The RELU function family', 2, None, '___sec36'),
+ ('Which activation function should we use?', 2, None, '___sec37'),
('A top-down perspective on Neural networks',
2,
None,
- '___sec37'),
+ '___sec38'),
('Limitations of supervised learning with deep networks',
2,
None,
- '___sec38'),
+ '___sec39'),
('Convolutional Neural Networks (recognizing images)',
2,
None,
- '___sec39'),
+ '___sec40'),
('Regular NNs don’t scale well to full images',
2,
None,
- '___sec40'),
- ('3D volumes of neurons', 2, None, '___sec41'),
- ('Layers used to build CNNs', 2, None, '___sec42'),
- ('Transforming images', 2, None, '___sec43'),
- ('CNNs in brief', 2, None, '___sec44'),
- ('CNNs in more detail, building convolutional neural networks in '
- 'Tensorflow and Keras',
- 2,
- None,
- '___sec45'),
- ('Setting it up', 2, None, '___sec46'),
- ('The MNIST dataset again', 2, None, '___sec47'),
- ('Strong correlations', 2, None, '___sec48'),
- ('Layers of a CNN', 2, None, '___sec49'),
- ('Systematic reduction', 2, None, '___sec50'),
- ('Prerequisites: Collect and pre-process data',
- 2,
- None,
- '___sec51'),
- ('Importing Keras and Tensorflow', 2, None, '___sec52'),
- ('Using TensorFlow backend', 2, None, '___sec53'),
- ('Train the model', 2, None, '___sec54'),
- ('Visualizing the results', 2, None, '___sec55'),
- ('Running with Keras', 2, None, '___sec56'),
- ('Final part', 2, None, '___sec57'),
- ('Final visualization', 2, None, '___sec58'),
- ('Fun links', 2, None, '___sec59')]}
+ '___sec41'),
+ ('3D volumes of neurons', 2, None, '___sec42'),
+ ('Layers used to build CNNs', 2, None, '___sec43'),
+ ('Transforming images', 2, None, '___sec44'),
+ ('CNNs in brief', 2, None, '___sec45')]}
end of tocinfo -->
@@ -202,34 +181,20 @@ MathJax.Hub.Config({
Using TensorFlow backend
Optimizing and using gradient descent
Using Keras
- Which activation function should I use?
- Is the Logistic activation function (Sigmoid) our choice?
- The derivative of the Logistic funtion
- The RELU function family
- Which activation function should we use?
- A top-down perspective on Neural networks
- Limitations of supervised learning with deep networks
- Convolutional Neural Networks (recognizing images)
- Regular NNs don’t scale well to full images
- 3D volumes of neurons
- Layers used to build CNNs
- Transforming images
- CNNs in brief
- CNNs in more detail, building convolutional neural networks in Tensorflow and Keras
- Setting it up
- The MNIST dataset again
- Strong correlations
- Layers of a CNN
- Systematic reduction
- Prerequisites: Collect and pre-process data
- Importing Keras and Tensorflow
- Using TensorFlow backend
- Train the model
- Visualizing the results
- Running with Keras
- Final part
- Final visualization
- Fun links
+ The Breast Cancer Data, now with Keras
+ Which activation function should I use?
+ Is the Logistic activation function (Sigmoid) our choice?
+ The derivative of the Logistic funtion
+ The RELU function family
+ Which activation function should we use?
+ A top-down perspective on Neural networks
+ Limitations of supervised learning with deep networks
+ Convolutional Neural Networks (recognizing images)
+ Regular NNs don’t scale well to full images
+ 3D volumes of neurons
+ Layers used to build CNNs
+ Transforming images
+ CNNs in brief
@@ -243,34 +208,179 @@ MathJax.Hub.Config({
-
+
-Which activation function should I use?
+The Breast Cancer Data, now with Keras
-The Back propagation algorithm we derived above works by going from
-the output layer to the input layer, propagating the error gradient on
-the way. Once the algorithm has computed the gradient of the cost
-function with regards to each parameter in the network, it uses these
-gradients to update each parameter with a Gradient Descent (GD) step.
-
-Unfortunately for us, the gradients often get smaller and smaller as the
-algorithm progresses down to the first hidden layers. As a result, the
-GD update leaves the lower layer connection weights
-virtually unchanged, and training never converges to a good
-solution. This is known in the literature as
-the vanishing gradients problem.
+
+
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
-
-In other cases, the opposite can happen, namely the the gradients can grow bigger and
-bigger. The result is that many of the layers get large updates of the
-weights the
-algorithm diverges. This is the exploding gradients problem, which is
-mostly encountered in recurrent neural networks. More generally, deep
-neural networks suffer from unstable gradients, different layers may
-learn at widely different speeds
+"""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')
+
@@ -297,7 +407,7 @@ learn at widely different speeds
42
43
...
- 61
+ 47
»
diff --git a/doc/pub/week41/html/._week41-bs034.html b/doc/pub/week41/html/._week41-bs034.html
index be0274908..c1bf94a05 100644
--- a/doc/pub/week41/html/._week41-bs034.html
+++ b/doc/pub/week41/html/._week41-bs034.html
@@ -83,56 +83,35 @@ Automatically generated HTML file from DocOnce source
('Using TensorFlow backend', 2, None, '___sec29'),
('Optimizing and using gradient descent', 2, None, '___sec30'),
('Using Keras', 2, None, '___sec31'),
- ('Which activation function should I use?', 2, None, '___sec32'),
+ ('The Breast Cancer Data, now with Keras', 2, None, '___sec32'),
+ ('Which activation function should I use?', 2, None, '___sec33'),
('Is the Logistic activation function (Sigmoid) our choice?',
2,
None,
- '___sec33'),
- ('The derivative of the Logistic funtion', 2, None, '___sec34'),
- ('The RELU function family', 2, None, '___sec35'),
- ('Which activation function should we use?', 2, None, '___sec36'),
+ '___sec34'),
+ ('The derivative of the Logistic funtion', 2, None, '___sec35'),
+ ('The RELU function family', 2, None, '___sec36'),
+ ('Which activation function should we use?', 2, None, '___sec37'),
('A top-down perspective on Neural networks',
2,
None,
- '___sec37'),
+ '___sec38'),
('Limitations of supervised learning with deep networks',
2,
None,
- '___sec38'),
+ '___sec39'),
('Convolutional Neural Networks (recognizing images)',
2,
None,
- '___sec39'),
+ '___sec40'),
('Regular NNs don’t scale well to full images',
2,
None,
- '___sec40'),
- ('3D volumes of neurons', 2, None, '___sec41'),
- ('Layers used to build CNNs', 2, None, '___sec42'),
- ('Transforming images', 2, None, '___sec43'),
- ('CNNs in brief', 2, None, '___sec44'),
- ('CNNs in more detail, building convolutional neural networks in '
- 'Tensorflow and Keras',
- 2,
- None,
- '___sec45'),
- ('Setting it up', 2, None, '___sec46'),
- ('The MNIST dataset again', 2, None, '___sec47'),
- ('Strong correlations', 2, None, '___sec48'),
- ('Layers of a CNN', 2, None, '___sec49'),
- ('Systematic reduction', 2, None, '___sec50'),
- ('Prerequisites: Collect and pre-process data',
- 2,
- None,
- '___sec51'),
- ('Importing Keras and Tensorflow', 2, None, '___sec52'),
- ('Using TensorFlow backend', 2, None, '___sec53'),
- ('Train the model', 2, None, '___sec54'),
- ('Visualizing the results', 2, None, '___sec55'),
- ('Running with Keras', 2, None, '___sec56'),
- ('Final part', 2, None, '___sec57'),
- ('Final visualization', 2, None, '___sec58'),
- ('Fun links', 2, None, '___sec59')]}
+ '___sec41'),
+ ('3D volumes of neurons', 2, None, '___sec42'),
+ ('Layers used to build CNNs', 2, None, '___sec43'),
+ ('Transforming images', 2, None, '___sec44'),
+ ('CNNs in brief', 2, None, '___sec45')]}
end of tocinfo -->
@@ -202,34 +181,20 @@ MathJax.Hub.Config({
Using TensorFlow backend
Optimizing and using gradient descent
Using Keras
- Which activation function should I use?
- Is the Logistic activation function (Sigmoid) our choice?
- The derivative of the Logistic funtion
- The RELU function family
- Which activation function should we use?
- A top-down perspective on Neural networks
- Limitations of supervised learning with deep networks
- Convolutional Neural Networks (recognizing images)
- Regular NNs don’t scale well to full images
- 3D volumes of neurons
- Layers used to build CNNs
- Transforming images
- CNNs in brief
- CNNs in more detail, building convolutional neural networks in Tensorflow and Keras
- Setting it up
- The MNIST dataset again
- Strong correlations
- Layers of a CNN
- Systematic reduction
- Prerequisites: Collect and pre-process data
- Importing Keras and Tensorflow
- Using TensorFlow backend
- Train the model
- Visualizing the results
- Running with Keras
- Final part
- Final visualization
- Fun links
+ The Breast Cancer Data, now with Keras
+ Which activation function should I use?
+ Is the Logistic activation function (Sigmoid) our choice?
+ The derivative of the Logistic funtion
+ The RELU function family
+ Which activation function should we use?
+ A top-down perspective on Neural networks
+ Limitations of supervised learning with deep networks
+ Convolutional Neural Networks (recognizing images)
+ Regular NNs don’t scale well to full images
+ 3D volumes of neurons
+ Layers used to build CNNs
+ Transforming images
+ CNNs in brief
@@ -245,32 +210,31 @@ MathJax.Hub.Config({
-Is the Logistic activation function (Sigmoid) our choice?
+Which activation function should I use?
-Although this unfortunate behavior has been empirically observed for
-quite a while (it was one of the reasons why deep neural networks were
-mostly abandoned for a long time), it is only around 2010 that
-significant progress was made in understanding it.
+The Back propagation algorithm we derived above works by going from
+the output layer to the input layer, propagating the error gradient on
+the way. Once the algorithm has computed the gradient of the cost
+function with regards to each parameter in the network, it uses these
+gradients to update each parameter with a Gradient Descent (GD) step.
-A paper titled Understanding the Difficulty of Training Deep
-Feedforward Neural Networks by Xavier Glorot and Yoshua Bengio found that
-the problems with the popular logistic
-sigmoid activation function and the weight initialization technique
-that was most popular at the time, namely random initialization using
-a normal distribution with a mean of 0 and a standard deviation of
-1.
+Unfortunately for us, the gradients often get smaller and smaller as the
+algorithm progresses down to the first hidden layers. As a result, the
+GD update leaves the lower layer connection weights
+virtually unchanged, and training never converges to a good
+solution. This is known in the literature as
+the vanishing gradients problem.
-They showed that with this activation function and this
-initialization scheme, the variance of the outputs of each layer is
-much greater than the variance of its inputs. Going forward in the
-network, the variance keeps increasing after each layer until the
-activation function saturates at the top layers. This is actually made
-worse by the fact that the logistic function has a mean of 0.5, not 0
-(the hyperbolic tangent function has a mean of 0 and behaves slightly
-better than the logistic function in deep networks).
+In other cases, the opposite can happen, namely the the gradients can grow bigger and
+bigger. The result is that many of the layers get large updates of the
+weights the
+algorithm diverges. This is the exploding gradients problem, which is
+mostly encountered in recurrent neural networks. More generally, deep
+neural networks suffer from unstable gradients, different layers may
+learn at widely different speeds
@@ -298,7 +262,7 @@ better than the logistic function in deep networks).
43
44
...
- 61
+ 47
»
diff --git a/doc/pub/week41/html/._week41-bs035.html b/doc/pub/week41/html/._week41-bs035.html
index 10d501a47..aa0b1c558 100644
--- a/doc/pub/week41/html/._week41-bs035.html
+++ b/doc/pub/week41/html/._week41-bs035.html
@@ -83,56 +83,35 @@ Automatically generated HTML file from DocOnce source
('Using TensorFlow backend', 2, None, '___sec29'),
('Optimizing and using gradient descent', 2, None, '___sec30'),
('Using Keras', 2, None, '___sec31'),
- ('Which activation function should I use?', 2, None, '___sec32'),
+ ('The Breast Cancer Data, now with Keras', 2, None, '___sec32'),
+ ('Which activation function should I use?', 2, None, '___sec33'),
('Is the Logistic activation function (Sigmoid) our choice?',
2,
None,
- '___sec33'),
- ('The derivative of the Logistic funtion', 2, None, '___sec34'),
- ('The RELU function family', 2, None, '___sec35'),
- ('Which activation function should we use?', 2, None, '___sec36'),
+ '___sec34'),
+ ('The derivative of the Logistic funtion', 2, None, '___sec35'),
+ ('The RELU function family', 2, None, '___sec36'),
+ ('Which activation function should we use?', 2, None, '___sec37'),
('A top-down perspective on Neural networks',
2,
None,
- '___sec37'),
+ '___sec38'),
('Limitations of supervised learning with deep networks',
2,
None,
- '___sec38'),
+ '___sec39'),
('Convolutional Neural Networks (recognizing images)',
2,
None,
- '___sec39'),
+ '___sec40'),
('Regular NNs don’t scale well to full images',
2,
None,
- '___sec40'),
- ('3D volumes of neurons', 2, None, '___sec41'),
- ('Layers used to build CNNs', 2, None, '___sec42'),
- ('Transforming images', 2, None, '___sec43'),
- ('CNNs in brief', 2, None, '___sec44'),
- ('CNNs in more detail, building convolutional neural networks in '
- 'Tensorflow and Keras',
- 2,
- None,
- '___sec45'),
- ('Setting it up', 2, None, '___sec46'),
- ('The MNIST dataset again', 2, None, '___sec47'),
- ('Strong correlations', 2, None, '___sec48'),
- ('Layers of a CNN', 2, None, '___sec49'),
- ('Systematic reduction', 2, None, '___sec50'),
- ('Prerequisites: Collect and pre-process data',
- 2,
- None,
- '___sec51'),
- ('Importing Keras and Tensorflow', 2, None, '___sec52'),
- ('Using TensorFlow backend', 2, None, '___sec53'),
- ('Train the model', 2, None, '___sec54'),
- ('Visualizing the results', 2, None, '___sec55'),
- ('Running with Keras', 2, None, '___sec56'),
- ('Final part', 2, None, '___sec57'),
- ('Final visualization', 2, None, '___sec58'),
- ('Fun links', 2, None, '___sec59')]}
+ '___sec41'),
+ ('3D volumes of neurons', 2, None, '___sec42'),
+ ('Layers used to build CNNs', 2, None, '___sec43'),
+ ('Transforming images', 2, None, '___sec44'),
+ ('CNNs in brief', 2, None, '___sec45')]}
end of tocinfo -->
@@ -202,34 +181,20 @@ MathJax.Hub.Config({
Using TensorFlow backend
Optimizing and using gradient descent
Using Keras
- Which activation function should I use?
- Is the Logistic activation function (Sigmoid) our choice?
- The derivative of the Logistic funtion
- The RELU function family
- Which activation function should we use?
- A top-down perspective on Neural networks
- Limitations of supervised learning with deep networks
- Convolutional Neural Networks (recognizing images)
- Regular NNs don’t scale well to full images
- 3D volumes of neurons
- Layers used to build CNNs
- Transforming images
- CNNs in brief
- CNNs in more detail, building convolutional neural networks in Tensorflow and Keras
- Setting it up
- The MNIST dataset again
- Strong correlations
- Layers of a CNN
- Systematic reduction
- Prerequisites: Collect and pre-process data
- Importing Keras and Tensorflow
- Using TensorFlow backend
- Train the model
- Visualizing the results
- Running with Keras
- Final part
- Final visualization
- Fun links
+ The Breast Cancer Data, now with Keras
+ Which activation function should I use?
+ Is the Logistic activation function (Sigmoid) our choice?
+ The derivative of the Logistic funtion
+ The RELU function family
+ Which activation function should we use?
+ A top-down perspective on Neural networks
+ Limitations of supervised learning with deep networks
+ Convolutional Neural Networks (recognizing images)
+ Regular NNs don’t scale well to full images
+ 3D volumes of neurons
+ Layers used to build CNNs
+ Transforming images
+ CNNs in brief
@@ -243,40 +208,34 @@ MathJax.Hub.Config({
-
+
-The derivative of the Logistic funtion
+Is the Logistic activation function (Sigmoid) our choice?
-Looking at the logistic activation function, when inputs become large
-(negative or positive), the function saturates at 0 or 1, with a
-derivative extremely close to 0. Thus when backpropagation kicks in,
-it has virtually no gradient to propagate back through the network,
-and what little gradient exists keeps getting diluted as
-backpropagation progresses down through the top layers, so there is
-really nothing left for the lower layers.
+Although this unfortunate behavior has been empirically observed for
+quite a while (it was one of the reasons why deep neural networks were
+mostly abandoned for a long time), it is only around 2010 that
+significant progress was made in understanding it.
-In their paper, Glorot and Bengio propose a way to significantly
-alleviate this problem. We need the signal to flow properly in both
-directions: in the forward direction when making predictions, and in
-the reverse direction when backpropagating gradients. We don’t want
-the signal to die out, nor do we want it to explode and saturate. For
-the signal to flow properly, the authors argue that we need the
-variance of the outputs of each layer to be equal to the variance of
-its inputs, and we also need the gradients to have equal variance
-before and after flowing through a layer in the reverse direction.
+A paper titled Understanding the Difficulty of Training Deep
+Feedforward Neural Networks by Xavier Glorot and Yoshua Bengio found that
+the problems with the popular logistic
+sigmoid activation function and the weight initialization technique
+that was most popular at the time, namely random initialization using
+a normal distribution with a mean of 0 and a standard deviation of
+1.
-One of the insights in the 2010 paper by Glorot and Bengio was that
-the vanishing/exploding gradients problems were in part due to a poor
-choice of activation function. Until then most people had assumed that
-if Nature had chosen to use roughly sigmoid activation functions in
-biological neurons, they must be an excellent choice. But it turns out
-that other activation functions behave much better in deep neural
-networks, in particular the ReLU activation function, mostly because
-it does not saturate for positive values (and also because it is quite
-fast to compute).
+They showed that with this activation function and this
+initialization scheme, the variance of the outputs of each layer is
+much greater than the variance of its inputs. Going forward in the
+network, the variance keeps increasing after each layer until the
+activation function saturates at the top layers. This is actually made
+worse by the fact that the logistic function has a mean of 0.5, not 0
+(the hyperbolic tangent function has a mean of 0 and behaves slightly
+better than the logistic function in deep networks).
@@ -304,7 +263,7 @@ fast to compute).
44
45
...
- 61
+ 47
»
diff --git a/doc/pub/week41/html/._week41-bs036.html b/doc/pub/week41/html/._week41-bs036.html
index 86ea16e34..8435b22c6 100644
--- a/doc/pub/week41/html/._week41-bs036.html
+++ b/doc/pub/week41/html/._week41-bs036.html
@@ -83,56 +83,35 @@ Automatically generated HTML file from DocOnce source
('Using TensorFlow backend', 2, None, '___sec29'),
('Optimizing and using gradient descent', 2, None, '___sec30'),
('Using Keras', 2, None, '___sec31'),
- ('Which activation function should I use?', 2, None, '___sec32'),
+ ('The Breast Cancer Data, now with Keras', 2, None, '___sec32'),
+ ('Which activation function should I use?', 2, None, '___sec33'),
('Is the Logistic activation function (Sigmoid) our choice?',
2,
None,
- '___sec33'),
- ('The derivative of the Logistic funtion', 2, None, '___sec34'),
- ('The RELU function family', 2, None, '___sec35'),
- ('Which activation function should we use?', 2, None, '___sec36'),
+ '___sec34'),
+ ('The derivative of the Logistic funtion', 2, None, '___sec35'),
+ ('The RELU function family', 2, None, '___sec36'),
+ ('Which activation function should we use?', 2, None, '___sec37'),
('A top-down perspective on Neural networks',
2,
None,
- '___sec37'),
+ '___sec38'),
('Limitations of supervised learning with deep networks',
2,
None,
- '___sec38'),
+ '___sec39'),
('Convolutional Neural Networks (recognizing images)',
2,
None,
- '___sec39'),
+ '___sec40'),
('Regular NNs don’t scale well to full images',
2,
None,
- '___sec40'),
- ('3D volumes of neurons', 2, None, '___sec41'),
- ('Layers used to build CNNs', 2, None, '___sec42'),
- ('Transforming images', 2, None, '___sec43'),
- ('CNNs in brief', 2, None, '___sec44'),
- ('CNNs in more detail, building convolutional neural networks in '
- 'Tensorflow and Keras',
- 2,
- None,
- '___sec45'),
- ('Setting it up', 2, None, '___sec46'),
- ('The MNIST dataset again', 2, None, '___sec47'),
- ('Strong correlations', 2, None, '___sec48'),
- ('Layers of a CNN', 2, None, '___sec49'),
- ('Systematic reduction', 2, None, '___sec50'),
- ('Prerequisites: Collect and pre-process data',
- 2,
- None,
- '___sec51'),
- ('Importing Keras and Tensorflow', 2, None, '___sec52'),
- ('Using TensorFlow backend', 2, None, '___sec53'),
- ('Train the model', 2, None, '___sec54'),
- ('Visualizing the results', 2, None, '___sec55'),
- ('Running with Keras', 2, None, '___sec56'),
- ('Final part', 2, None, '___sec57'),
- ('Final visualization', 2, None, '___sec58'),
- ('Fun links', 2, None, '___sec59')]}
+ '___sec41'),
+ ('3D volumes of neurons', 2, None, '___sec42'),
+ ('Layers used to build CNNs', 2, None, '___sec43'),
+ ('Transforming images', 2, None, '___sec44'),
+ ('CNNs in brief', 2, None, '___sec45')]}
end of tocinfo -->
@@ -202,34 +181,20 @@ MathJax.Hub.Config({
Using TensorFlow backend
Optimizing and using gradient descent
Using Keras
- Which activation function should I use?
- Is the Logistic activation function (Sigmoid) our choice?
- The derivative of the Logistic funtion
- The RELU function family
- Which activation function should we use?
- A top-down perspective on Neural networks
- Limitations of supervised learning with deep networks
- Convolutional Neural Networks (recognizing images)
- Regular NNs don’t scale well to full images
- 3D volumes of neurons
- Layers used to build CNNs
- Transforming images
- CNNs in brief
- CNNs in more detail, building convolutional neural networks in Tensorflow and Keras
- Setting it up
- The MNIST dataset again
- Strong correlations
- Layers of a CNN
- Systematic reduction
- Prerequisites: Collect and pre-process data
- Importing Keras and Tensorflow
- Using TensorFlow backend
- Train the model
- Visualizing the results
- Running with Keras
- Final part
- Final visualization
- Fun links
+ The Breast Cancer Data, now with Keras
+ Which activation function should I use?
+ Is the Logistic activation function (Sigmoid) our choice?
+ The derivative of the Logistic funtion
+ The RELU function family
+ Which activation function should we use?
+ A top-down perspective on Neural networks
+ Limitations of supervised learning with deep networks
+ Convolutional Neural Networks (recognizing images)
+ Regular NNs don’t scale well to full images
+ 3D volumes of neurons
+ Layers used to build CNNs
+ Transforming images
+ CNNs in brief
@@ -245,29 +210,38 @@ MathJax.Hub.Config({
-The RELU function family
+The derivative of the Logistic funtion
-The ReLU activation function suffers from a problem known as the dying
-ReLUs: during training, some neurons effectively die, meaning they
-stop outputting anything other than 0.
+Looking at the logistic activation function, when inputs become large
+(negative or positive), the function saturates at 0 or 1, with a
+derivative extremely close to 0. Thus when backpropagation kicks in,
+it has virtually no gradient to propagate back through the network,
+and what little gradient exists keeps getting diluted as
+backpropagation progresses down through the top layers, so there is
+really nothing left for the lower layers.
-In some cases, you may find that half of your network’s neurons are
-dead, especially if you used a large learning rate. During training,
-if a neuron’s weights get updated such that the weighted sum of the
-neuron’s inputs is negative, it will start outputting 0. When this
-happen, the neuron is unlikely to come back to life since the gradient
-of the ReLU function is 0 when its input is negative.
+In their paper, Glorot and Bengio propose a way to significantly
+alleviate this problem. We need the signal to flow properly in both
+directions: in the forward direction when making predictions, and in
+the reverse direction when backpropagating gradients. We don’t want
+the signal to die out, nor do we want it to explode and saturate. For
+the signal to flow properly, the authors argue that we need the
+variance of the outputs of each layer to be equal to the variance of
+its inputs, and we also need the gradients to have equal variance
+before and after flowing through a layer in the reverse direction.
-To solve this problem, nowadays practitioners use a variant of the ReLU
-function, such as the leaky ReLU discussed above or the so-called
-exponential linear unit (ELU) function
-
-$$
-ELU(z) = \left\{\begin{array}{cc} \alpha\left( \exp{(z)}-1\right) & z < 0,\\ z & z \ge 0.\end{array}\right.
-$$
+One of the insights in the 2010 paper by Glorot and Bengio was that
+the vanishing/exploding gradients problems were in part due to a poor
+choice of activation function. Until then most people had assumed that
+if Nature had chosen to use roughly sigmoid activation functions in
+biological neurons, they must be an excellent choice. But it turns out
+that other activation functions behave much better in deep neural
+networks, in particular the ReLU activation function, mostly because
+it does not saturate for positive values (and also because it is quite
+fast to compute).
@@ -295,7 +269,7 @@ $$
45
46
...
- 61
+ 47
»
diff --git a/doc/pub/week41/html/._week41-bs037.html b/doc/pub/week41/html/._week41-bs037.html
index eb8f8573b..1659fc38a 100644
--- a/doc/pub/week41/html/._week41-bs037.html
+++ b/doc/pub/week41/html/._week41-bs037.html
@@ -83,56 +83,35 @@ Automatically generated HTML file from DocOnce source
('Using TensorFlow backend', 2, None, '___sec29'),
('Optimizing and using gradient descent', 2, None, '___sec30'),
('Using Keras', 2, None, '___sec31'),
- ('Which activation function should I use?', 2, None, '___sec32'),
+ ('The Breast Cancer Data, now with Keras', 2, None, '___sec32'),
+ ('Which activation function should I use?', 2, None, '___sec33'),
('Is the Logistic activation function (Sigmoid) our choice?',
2,
None,
- '___sec33'),
- ('The derivative of the Logistic funtion', 2, None, '___sec34'),
- ('The RELU function family', 2, None, '___sec35'),
- ('Which activation function should we use?', 2, None, '___sec36'),
+ '___sec34'),
+ ('The derivative of the Logistic funtion', 2, None, '___sec35'),
+ ('The RELU function family', 2, None, '___sec36'),
+ ('Which activation function should we use?', 2, None, '___sec37'),
('A top-down perspective on Neural networks',
2,
None,
- '___sec37'),
+ '___sec38'),
('Limitations of supervised learning with deep networks',
2,
None,
- '___sec38'),
+ '___sec39'),
('Convolutional Neural Networks (recognizing images)',
2,
None,
- '___sec39'),
+ '___sec40'),
('Regular NNs don’t scale well to full images',
2,
None,
- '___sec40'),
- ('3D volumes of neurons', 2, None, '___sec41'),
- ('Layers used to build CNNs', 2, None, '___sec42'),
- ('Transforming images', 2, None, '___sec43'),
- ('CNNs in brief', 2, None, '___sec44'),
- ('CNNs in more detail, building convolutional neural networks in '
- 'Tensorflow and Keras',
- 2,
- None,
- '___sec45'),
- ('Setting it up', 2, None, '___sec46'),
- ('The MNIST dataset again', 2, None, '___sec47'),
- ('Strong correlations', 2, None, '___sec48'),
- ('Layers of a CNN', 2, None, '___sec49'),
- ('Systematic reduction', 2, None, '___sec50'),
- ('Prerequisites: Collect and pre-process data',
- 2,
- None,
- '___sec51'),
- ('Importing Keras and Tensorflow', 2, None, '___sec52'),
- ('Using TensorFlow backend', 2, None, '___sec53'),
- ('Train the model', 2, None, '___sec54'),
- ('Visualizing the results', 2, None, '___sec55'),
- ('Running with Keras', 2, None, '___sec56'),
- ('Final part', 2, None, '___sec57'),
- ('Final visualization', 2, None, '___sec58'),
- ('Fun links', 2, None, '___sec59')]}
+ '___sec41'),
+ ('3D volumes of neurons', 2, None, '___sec42'),
+ ('Layers used to build CNNs', 2, None, '___sec43'),
+ ('Transforming images', 2, None, '___sec44'),
+ ('CNNs in brief', 2, None, '___sec45')]}
end of tocinfo -->
@@ -202,34 +181,20 @@ MathJax.Hub.Config({
Using TensorFlow backend
Optimizing and using gradient descent
Using Keras
- Which activation function should I use?
- Is the Logistic activation function (Sigmoid) our choice?
- The derivative of the Logistic funtion
- The RELU function family
- Which activation function should we use?
- A top-down perspective on Neural networks
- Limitations of supervised learning with deep networks
- Convolutional Neural Networks (recognizing images)
- Regular NNs don’t scale well to full images
- 3D volumes of neurons
- Layers used to build CNNs
- Transforming images
- CNNs in brief
- CNNs in more detail, building convolutional neural networks in Tensorflow and Keras
- Setting it up
- The MNIST dataset again
- Strong correlations
- Layers of a CNN
- Systematic reduction
- Prerequisites: Collect and pre-process data
- Importing Keras and Tensorflow
- Using TensorFlow backend
- Train the model
- Visualizing the results
- Running with Keras
- Final part
- Final visualization
- Fun links
+ The Breast Cancer Data, now with Keras
+ Which activation function should I use?
+ Is the Logistic activation function (Sigmoid) our choice?
+ The derivative of the Logistic funtion
+ The RELU function family
+ Which activation function should we use?
+ A top-down perspective on Neural networks
+ Limitations of supervised learning with deep networks
+ Convolutional Neural Networks (recognizing images)
+ Regular NNs don’t scale well to full images
+ 3D volumes of neurons
+ Layers used to build CNNs
+ Transforming images
+ CNNs in brief
@@ -245,22 +210,29 @@ MathJax.Hub.Config({
-Which activation function should we use?
+The RELU function family
-In general it seems that the ELU activation function is better than
-the leaky ReLU function (and its variants), which is better than
-ReLU. ReLU performs better than \( \tanh \) which in turn performs better
-than the logistic function.
+The ReLU activation function suffers from a problem known as the dying
+ReLUs: during training, some neurons effectively die, meaning they
+stop outputting anything other than 0.
-If runtime
-performance is an issue, then you may opt for the leaky ReLU function over the
-ELU function If you don’t
-want to tweak yet another hyperparameter, you may just use the default
-\( \alpha \) of \( 0.01 \) for the leaky ReLU, and \( 1 \) for ELU. If you have
-spare time and computing power, you can use cross-validation or
-bootstrap to evaluate other activation functions.
+In some cases, you may find that half of your network’s neurons are
+dead, especially if you used a large learning rate. During training,
+if a neuron’s weights get updated such that the weighted sum of the
+neuron’s inputs is negative, it will start outputting 0. When this
+happen, the neuron is unlikely to come back to life since the gradient
+of the ReLU function is 0 when its input is negative.
+
+
+To solve this problem, nowadays practitioners use a variant of the ReLU
+function, such as the leaky ReLU discussed above or the so-called
+exponential linear unit (ELU) function
+
+$$
+ELU(z) = \left\{\begin{array}{cc} \alpha\left( \exp{(z)}-1\right) & z < 0,\\ z & z \ge 0.\end{array}\right.
+$$
@@ -287,8 +259,6 @@ bootstrap to evaluate other activation functions.
45
46
47
- ...
- 61
»
diff --git a/doc/pub/week41/html/._week41-bs038.html b/doc/pub/week41/html/._week41-bs038.html
index 90e4d2f50..94e1a6cc1 100644
--- a/doc/pub/week41/html/._week41-bs038.html
+++ b/doc/pub/week41/html/._week41-bs038.html
@@ -83,56 +83,35 @@ Automatically generated HTML file from DocOnce source
('Using TensorFlow backend', 2, None, '___sec29'),
('Optimizing and using gradient descent', 2, None, '___sec30'),
('Using Keras', 2, None, '___sec31'),
- ('Which activation function should I use?', 2, None, '___sec32'),
+ ('The Breast Cancer Data, now with Keras', 2, None, '___sec32'),
+ ('Which activation function should I use?', 2, None, '___sec33'),
('Is the Logistic activation function (Sigmoid) our choice?',
2,
None,
- '___sec33'),
- ('The derivative of the Logistic funtion', 2, None, '___sec34'),
- ('The RELU function family', 2, None, '___sec35'),
- ('Which activation function should we use?', 2, None, '___sec36'),
+ '___sec34'),
+ ('The derivative of the Logistic funtion', 2, None, '___sec35'),
+ ('The RELU function family', 2, None, '___sec36'),
+ ('Which activation function should we use?', 2, None, '___sec37'),
('A top-down perspective on Neural networks',
2,
None,
- '___sec37'),
+ '___sec38'),
('Limitations of supervised learning with deep networks',
2,
None,
- '___sec38'),
+ '___sec39'),
('Convolutional Neural Networks (recognizing images)',
2,
None,
- '___sec39'),
+ '___sec40'),
('Regular NNs don’t scale well to full images',
2,
None,
- '___sec40'),
- ('3D volumes of neurons', 2, None, '___sec41'),
- ('Layers used to build CNNs', 2, None, '___sec42'),
- ('Transforming images', 2, None, '___sec43'),
- ('CNNs in brief', 2, None, '___sec44'),
- ('CNNs in more detail, building convolutional neural networks in '
- 'Tensorflow and Keras',
- 2,
- None,
- '___sec45'),
- ('Setting it up', 2, None, '___sec46'),
- ('The MNIST dataset again', 2, None, '___sec47'),
- ('Strong correlations', 2, None, '___sec48'),
- ('Layers of a CNN', 2, None, '___sec49'),
- ('Systematic reduction', 2, None, '___sec50'),
- ('Prerequisites: Collect and pre-process data',
- 2,
- None,
- '___sec51'),
- ('Importing Keras and Tensorflow', 2, None, '___sec52'),
- ('Using TensorFlow backend', 2, None, '___sec53'),
- ('Train the model', 2, None, '___sec54'),
- ('Visualizing the results', 2, None, '___sec55'),
- ('Running with Keras', 2, None, '___sec56'),
- ('Final part', 2, None, '___sec57'),
- ('Final visualization', 2, None, '___sec58'),
- ('Fun links', 2, None, '___sec59')]}
+ '___sec41'),
+ ('3D volumes of neurons', 2, None, '___sec42'),
+ ('Layers used to build CNNs', 2, None, '___sec43'),
+ ('Transforming images', 2, None, '___sec44'),
+ ('CNNs in brief', 2, None, '___sec45')]}
end of tocinfo -->
@@ -202,34 +181,20 @@ MathJax.Hub.Config({
Using TensorFlow backend
Optimizing and using gradient descent
Using Keras
- Which activation function should I use?
- Is the Logistic activation function (Sigmoid) our choice?
- The derivative of the Logistic funtion
- The RELU function family
- Which activation function should we use?
- A top-down perspective on Neural networks
- Limitations of supervised learning with deep networks
- Convolutional Neural Networks (recognizing images)
- Regular NNs don’t scale well to full images
- 3D volumes of neurons
- Layers used to build CNNs
- Transforming images
- CNNs in brief
- CNNs in more detail, building convolutional neural networks in Tensorflow and Keras
- Setting it up
- The MNIST dataset again
- Strong correlations
- Layers of a CNN
- Systematic reduction
- Prerequisites: Collect and pre-process data
- Importing Keras and Tensorflow
- Using TensorFlow backend
- Train the model
- Visualizing the results
- Running with Keras
- Final part
- Final visualization
- Fun links
+ The Breast Cancer Data, now with Keras
+ Which activation function should I use?
+ Is the Logistic activation function (Sigmoid) our choice?
+ The derivative of the Logistic funtion
+ The RELU function family
+ Which activation function should we use?
+ A top-down perspective on Neural networks
+ Limitations of supervised learning with deep networks
+ Convolutional Neural Networks (recognizing images)
+ Regular NNs don’t scale well to full images
+ 3D volumes of neurons
+ Layers used to build CNNs
+ Transforming images
+ CNNs in brief
@@ -243,46 +208,24 @@ MathJax.Hub.Config({
-
+
-A top-down perspective on Neural networks
+Which activation function should we use?
-The first thing we would like to do is divide the data into two or three
-parts. A training set, a validation or dev (development) set, and a
-test set. The test set is the data on which we want to make
-predictions. The dev set is a subset of the training data we use to
-check how well we are doing out-of-sample, after training the model on
-the training dataset. We use the validation error as a proxy for the
-test error in order to make tweaks to our model. It is crucial that we
-do not use any of the test data to train the algorithm. This is a
-cardinal sin in ML. Then:
-
-
-- Estimate optimal error rate
-- Minimize underfitting (bias) on training data set.
-- Make sure you are not overfitting.
-
-
-If the validation and test sets are drawn from the same distributions,
-then a good performance on the validation set should lead to similarly
-good performance on the test set.
+In general it seems that the ELU activation function is better than
+the leaky ReLU function (and its variants), which is better than
+ReLU. ReLU performs better than \( \tanh \) which in turn performs better
+than the logistic function.
-However, sometimes
-the training data and test data differ in subtle ways because, for
-example, they are collected using slightly different methods, or
-because it is cheaper to collect data in one way versus another. In
-this case, there can be a mismatch between the training and test
-data. This can lead to the neural network overfitting these small
-differences between the test and training sets, and a poor performance
-on the test set despite having a good performance on the validation
-set. To rectify this, Andrew Ng suggests making two validation or dev
-sets, one constructed from the training data and one constructed from
-the test data. The difference between the performance of the algorithm
-on these two validation sets quantifies the train-test mismatch. This
-can serve as another important diagnostic when using DNNs for
-supervised learning.
+If runtime
+performance is an issue, then you may opt for the leaky ReLU function over the
+ELU function If you don’t
+want to tweak yet another hyperparameter, you may just use the default
+\( \alpha \) of \( 0.01 \) for the leaky ReLU, and \( 1 \) for ELU. If you have
+spare time and computing power, you can use cross-validation or
+bootstrap to evaluate other activation functions.
@@ -308,9 +251,6 @@ supervised learning.
45
46
47
- 48
- ...
- 61
»
diff --git a/doc/pub/week41/html/._week41-bs039.html b/doc/pub/week41/html/._week41-bs039.html
index 9b2a919e6..6a515a03b 100644
--- a/doc/pub/week41/html/._week41-bs039.html
+++ b/doc/pub/week41/html/._week41-bs039.html
@@ -83,56 +83,35 @@ Automatically generated HTML file from DocOnce source
('Using TensorFlow backend', 2, None, '___sec29'),
('Optimizing and using gradient descent', 2, None, '___sec30'),
('Using Keras', 2, None, '___sec31'),
- ('Which activation function should I use?', 2, None, '___sec32'),
+ ('The Breast Cancer Data, now with Keras', 2, None, '___sec32'),
+ ('Which activation function should I use?', 2, None, '___sec33'),
('Is the Logistic activation function (Sigmoid) our choice?',
2,
None,
- '___sec33'),
- ('The derivative of the Logistic funtion', 2, None, '___sec34'),
- ('The RELU function family', 2, None, '___sec35'),
- ('Which activation function should we use?', 2, None, '___sec36'),
+ '___sec34'),
+ ('The derivative of the Logistic funtion', 2, None, '___sec35'),
+ ('The RELU function family', 2, None, '___sec36'),
+ ('Which activation function should we use?', 2, None, '___sec37'),
('A top-down perspective on Neural networks',
2,
None,
- '___sec37'),
+ '___sec38'),
('Limitations of supervised learning with deep networks',
2,
None,
- '___sec38'),
+ '___sec39'),
('Convolutional Neural Networks (recognizing images)',
2,
None,
- '___sec39'),
+ '___sec40'),
('Regular NNs don’t scale well to full images',
2,
None,
- '___sec40'),
- ('3D volumes of neurons', 2, None, '___sec41'),
- ('Layers used to build CNNs', 2, None, '___sec42'),
- ('Transforming images', 2, None, '___sec43'),
- ('CNNs in brief', 2, None, '___sec44'),
- ('CNNs in more detail, building convolutional neural networks in '
- 'Tensorflow and Keras',
- 2,
- None,
- '___sec45'),
- ('Setting it up', 2, None, '___sec46'),
- ('The MNIST dataset again', 2, None, '___sec47'),
- ('Strong correlations', 2, None, '___sec48'),
- ('Layers of a CNN', 2, None, '___sec49'),
- ('Systematic reduction', 2, None, '___sec50'),
- ('Prerequisites: Collect and pre-process data',
- 2,
- None,
- '___sec51'),
- ('Importing Keras and Tensorflow', 2, None, '___sec52'),
- ('Using TensorFlow backend', 2, None, '___sec53'),
- ('Train the model', 2, None, '___sec54'),
- ('Visualizing the results', 2, None, '___sec55'),
- ('Running with Keras', 2, None, '___sec56'),
- ('Final part', 2, None, '___sec57'),
- ('Final visualization', 2, None, '___sec58'),
- ('Fun links', 2, None, '___sec59')]}
+ '___sec41'),
+ ('3D volumes of neurons', 2, None, '___sec42'),
+ ('Layers used to build CNNs', 2, None, '___sec43'),
+ ('Transforming images', 2, None, '___sec44'),
+ ('CNNs in brief', 2, None, '___sec45')]}
end of tocinfo -->
@@ -202,34 +181,20 @@ MathJax.Hub.Config({
Using TensorFlow backend
Optimizing and using gradient descent
Using Keras
- Which activation function should I use?
- Is the Logistic activation function (Sigmoid) our choice?
- The derivative of the Logistic funtion
- The RELU function family
- Which activation function should we use?
- A top-down perspective on Neural networks
- Limitations of supervised learning with deep networks
- Convolutional Neural Networks (recognizing images)
- Regular NNs don’t scale well to full images
- 3D volumes of neurons
- Layers used to build CNNs
- Transforming images
- CNNs in brief
- CNNs in more detail, building convolutional neural networks in Tensorflow and Keras
- Setting it up
- The MNIST dataset again
- Strong correlations
- Layers of a CNN
- Systematic reduction
- Prerequisites: Collect and pre-process data
- Importing Keras and Tensorflow
- Using TensorFlow backend
- Train the model
- Visualizing the results
- Running with Keras
- Final part
- Final visualization
- Fun links
+ The Breast Cancer Data, now with Keras
+ Which activation function should I use?
+ Is the Logistic activation function (Sigmoid) our choice?
+ The derivative of the Logistic funtion
+ The RELU function family
+ Which activation function should we use?
+ A top-down perspective on Neural networks
+ Limitations of supervised learning with deep networks
+ Convolutional Neural Networks (recognizing images)
+ Regular NNs don’t scale well to full images
+ 3D volumes of neurons
+ Layers used to build CNNs
+ Transforming images
+ CNNs in brief
@@ -243,30 +208,46 @@ MathJax.Hub.Config({
-
+
-Limitations of supervised learning with deep networks
+A top-down perspective on Neural networks
-Like all statistical methods, supervised learning using neural
-networks has important limitations. This is especially important when
-one seeks to apply these methods, especially to physics problems. Like
-all tools, DNNs are not a universal solution. Often, the same or
-better performance on a task can be achieved by using a few
-hand-engineered features (or even a collection of random
-features).
-
-
-Here we list some of the important limitations of supervised neural network based models.
+The first thing we would like to do is divide the data into two or three
+parts. A training set, a validation or dev (development) set, and a
+test set. The test set is the data on which we want to make
+predictions. The dev set is a subset of the training data we use to
+check how well we are doing out-of-sample, after training the model on
+the training dataset. We use the validation error as a proxy for the
+test error in order to make tweaks to our model. It is crucial that we
+do not use any of the test data to train the algorithm. This is a
+cardinal sin in ML. Then:
-- Need labeled data. All supervised learning methods, DNNs for supervised learning require labeled data. Often, labeled data is harder to acquire than unlabeled data (e.g. one must pay for human experts to label images).
-- Supervised neural networks are extremely data intensive. DNNs are data hungry. They perform best when data is plentiful. This is doubly so for supervised methods where the data must also be labeled. The utility of DNNs is extremely limited if data is hard to acquire or the datasets are small (hundreds to a few thousand samples). In this case, the performance of other methods that utilize hand-engineered features can exceed that of DNNs.
-- Homogeneous data. Almost all DNNs deal with homogeneous data of one type. It is very hard to design architectures that mix and match data types (i.e. some continuous variables, some discrete variables, some time series). In applications beyond images, video, and language, this is often what is required. In contrast, ensemble models like random forests or gradient-boosted trees have no difficulty handling mixed data types.
-- Many problems are not about prediction. In natural science we are often interested in learning something about the underlying distribution that generates the data. In this case, it is often difficult to cast these ideas in a supervised learning setting. While the problems are related, it is possible to make good predictions with a wrong model. The model might or might not be useful for understanding the underlying science.
+- Estimate optimal error rate
+- Minimize underfitting (bias) on training data set.
+- Make sure you are not overfitting.
-Some of these remarks are particular to DNNs, others are shared by all supervised learning methods. This motivates the use of unsupervised methods which in part circumvent these problems.
+If the validation and test sets are drawn from the same distributions,
+then a good performance on the validation set should lead to similarly
+good performance on the test set.
+
+
+However, sometimes
+the training data and test data differ in subtle ways because, for
+example, they are collected using slightly different methods, or
+because it is cheaper to collect data in one way versus another. In
+this case, there can be a mismatch between the training and test
+data. This can lead to the neural network overfitting these small
+differences between the test and training sets, and a poor performance
+on the test set despite having a good performance on the validation
+set. To rectify this, Andrew Ng suggests making two validation or dev
+sets, one constructed from the training data and one constructed from
+the test data. The difference between the performance of the algorithm
+on these two validation sets quantifies the train-test mismatch. This
+can serve as another important diagnostic when using DNNs for
+supervised learning.
@@ -291,10 +272,6 @@ Some of these remarks are particular to DNNs, others are shared by all supervise
45
46
47
- 48
- 49
- ...
- 61
»
diff --git a/doc/pub/week41/html/._week41-bs040.html b/doc/pub/week41/html/._week41-bs040.html
index d5b969b56..983038dc1 100644
--- a/doc/pub/week41/html/._week41-bs040.html
+++ b/doc/pub/week41/html/._week41-bs040.html
@@ -83,56 +83,35 @@ Automatically generated HTML file from DocOnce source
('Using TensorFlow backend', 2, None, '___sec29'),
('Optimizing and using gradient descent', 2, None, '___sec30'),
('Using Keras', 2, None, '___sec31'),
- ('Which activation function should I use?', 2, None, '___sec32'),
+ ('The Breast Cancer Data, now with Keras', 2, None, '___sec32'),
+ ('Which activation function should I use?', 2, None, '___sec33'),
('Is the Logistic activation function (Sigmoid) our choice?',
2,
None,
- '___sec33'),
- ('The derivative of the Logistic funtion', 2, None, '___sec34'),
- ('The RELU function family', 2, None, '___sec35'),
- ('Which activation function should we use?', 2, None, '___sec36'),
+ '___sec34'),
+ ('The derivative of the Logistic funtion', 2, None, '___sec35'),
+ ('The RELU function family', 2, None, '___sec36'),
+ ('Which activation function should we use?', 2, None, '___sec37'),
('A top-down perspective on Neural networks',
2,
None,
- '___sec37'),
+ '___sec38'),
('Limitations of supervised learning with deep networks',
2,
None,
- '___sec38'),
+ '___sec39'),
('Convolutional Neural Networks (recognizing images)',
2,
None,
- '___sec39'),
+ '___sec40'),
('Regular NNs don’t scale well to full images',
2,
None,
- '___sec40'),
- ('3D volumes of neurons', 2, None, '___sec41'),
- ('Layers used to build CNNs', 2, None, '___sec42'),
- ('Transforming images', 2, None, '___sec43'),
- ('CNNs in brief', 2, None, '___sec44'),
- ('CNNs in more detail, building convolutional neural networks in '
- 'Tensorflow and Keras',
- 2,
- None,
- '___sec45'),
- ('Setting it up', 2, None, '___sec46'),
- ('The MNIST dataset again', 2, None, '___sec47'),
- ('Strong correlations', 2, None, '___sec48'),
- ('Layers of a CNN', 2, None, '___sec49'),
- ('Systematic reduction', 2, None, '___sec50'),
- ('Prerequisites: Collect and pre-process data',
- 2,
- None,
- '___sec51'),
- ('Importing Keras and Tensorflow', 2, None, '___sec52'),
- ('Using TensorFlow backend', 2, None, '___sec53'),
- ('Train the model', 2, None, '___sec54'),
- ('Visualizing the results', 2, None, '___sec55'),
- ('Running with Keras', 2, None, '___sec56'),
- ('Final part', 2, None, '___sec57'),
- ('Final visualization', 2, None, '___sec58'),
- ('Fun links', 2, None, '___sec59')]}
+ '___sec41'),
+ ('3D volumes of neurons', 2, None, '___sec42'),
+ ('Layers used to build CNNs', 2, None, '___sec43'),
+ ('Transforming images', 2, None, '___sec44'),
+ ('CNNs in brief', 2, None, '___sec45')]}
end of tocinfo -->
@@ -202,34 +181,20 @@ MathJax.Hub.Config({
Using TensorFlow backend
Optimizing and using gradient descent
Using Keras
- Which activation function should I use?
- Is the Logistic activation function (Sigmoid) our choice?
- The derivative of the Logistic funtion
- The RELU function family
- Which activation function should we use?
- A top-down perspective on Neural networks
- Limitations of supervised learning with deep networks
- Convolutional Neural Networks (recognizing images)
- Regular NNs don’t scale well to full images
- 3D volumes of neurons
- Layers used to build CNNs
- Transforming images
- CNNs in brief
- CNNs in more detail, building convolutional neural networks in Tensorflow and Keras
- Setting it up
- The MNIST dataset again
- Strong correlations
- Layers of a CNN
- Systematic reduction
- Prerequisites: Collect and pre-process data
- Importing Keras and Tensorflow
- Using TensorFlow backend
- Train the model
- Visualizing the results
- Running with Keras
- Final part
- Final visualization
- Fun links
+ The Breast Cancer Data, now with Keras
+ Which activation function should I use?
+ Is the Logistic activation function (Sigmoid) our choice?
+ The derivative of the Logistic funtion
+ The RELU function family
+ Which activation function should we use?
+ A top-down perspective on Neural networks
+ Limitations of supervised learning with deep networks
+ Convolutional Neural Networks (recognizing images)
+ Regular NNs don’t scale well to full images
+ 3D volumes of neurons
+ Layers used to build CNNs
+ Transforming images
+ CNNs in brief
@@ -245,41 +210,28 @@ MathJax.Hub.Config({
-Convolutional Neural Networks (recognizing images)
+Limitations of supervised learning with deep networks
-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.
+Like all statistical methods, supervised learning using neural
+networks has important limitations. This is especially important when
+one seeks to apply these methods, especially to physics problems. Like
+all tools, DNNs are not a universal solution. Often, the same or
+better performance on a task can be achieved by using a few
+hand-engineered features (or even a collection of random
+features).
-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).
+Here we list some of the important limitations of supervised neural network based models.
-
-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.
+
+- Need labeled data. All supervised learning methods, DNNs for supervised learning require labeled data. Often, labeled data is harder to acquire than unlabeled data (e.g. one must pay for human experts to label images).
+- Supervised neural networks are extremely data intensive. DNNs are data hungry. They perform best when data is plentiful. This is doubly so for supervised methods where the data must also be labeled. The utility of DNNs is extremely limited if data is hard to acquire or the datasets are small (hundreds to a few thousand samples). In this case, the performance of other methods that utilize hand-engineered features can exceed that of DNNs.
+- Homogeneous data. Almost all DNNs deal with homogeneous data of one type. It is very hard to design architectures that mix and match data types (i.e. some continuous variables, some discrete variables, some time series). In applications beyond images, video, and language, this is often what is required. In contrast, ensemble models like random forests or gradient-boosted trees have no difficulty handling mixed data types.
+- Many problems are not about prediction. In natural science we are often interested in learning something about the underlying distribution that generates the data. In this case, it is often difficult to cast these ideas in a supervised learning setting. While the problems are related, it is possible to make good predictions with a wrong model. The model might or might not be useful for understanding the underlying science.
+
-
-Here we provide only a superficial overview, for the more interested, we recommend highly the course
-IN5400 – Machine Learning for Image Analysis
-and the slides of CS231.
-
-
-Another good read is the article here https://arxiv.org/pdf/1603.07285.pdf.
+Some of these remarks are particular to DNNs, others are shared by all supervised learning methods. This motivates the use of unsupervised methods which in part circumvent these problems.
@@ -303,11 +255,6 @@ Another good read is the article here 45
46
47
- 48
- 49
- 50
- ...
- 61
»
diff --git a/doc/pub/week41/html/._week41-bs041.html b/doc/pub/week41/html/._week41-bs041.html
index af0311d0e..aa478ca4a 100644
--- a/doc/pub/week41/html/._week41-bs041.html
+++ b/doc/pub/week41/html/._week41-bs041.html
@@ -83,56 +83,35 @@ Automatically generated HTML file from DocOnce source
('Using TensorFlow backend', 2, None, '___sec29'),
('Optimizing and using gradient descent', 2, None, '___sec30'),
('Using Keras', 2, None, '___sec31'),
- ('Which activation function should I use?', 2, None, '___sec32'),
+ ('The Breast Cancer Data, now with Keras', 2, None, '___sec32'),
+ ('Which activation function should I use?', 2, None, '___sec33'),
('Is the Logistic activation function (Sigmoid) our choice?',
2,
None,
- '___sec33'),
- ('The derivative of the Logistic funtion', 2, None, '___sec34'),
- ('The RELU function family', 2, None, '___sec35'),
- ('Which activation function should we use?', 2, None, '___sec36'),
+ '___sec34'),
+ ('The derivative of the Logistic funtion', 2, None, '___sec35'),
+ ('The RELU function family', 2, None, '___sec36'),
+ ('Which activation function should we use?', 2, None, '___sec37'),
('A top-down perspective on Neural networks',
2,
None,
- '___sec37'),
+ '___sec38'),
('Limitations of supervised learning with deep networks',
2,
None,
- '___sec38'),
+ '___sec39'),
('Convolutional Neural Networks (recognizing images)',
2,
None,
- '___sec39'),
+ '___sec40'),
('Regular NNs don’t scale well to full images',
2,
None,
- '___sec40'),
- ('3D volumes of neurons', 2, None, '___sec41'),
- ('Layers used to build CNNs', 2, None, '___sec42'),
- ('Transforming images', 2, None, '___sec43'),
- ('CNNs in brief', 2, None, '___sec44'),
- ('CNNs in more detail, building convolutional neural networks in '
- 'Tensorflow and Keras',
- 2,
- None,
- '___sec45'),
- ('Setting it up', 2, None, '___sec46'),
- ('The MNIST dataset again', 2, None, '___sec47'),
- ('Strong correlations', 2, None, '___sec48'),
- ('Layers of a CNN', 2, None, '___sec49'),
- ('Systematic reduction', 2, None, '___sec50'),
- ('Prerequisites: Collect and pre-process data',
- 2,
- None,
- '___sec51'),
- ('Importing Keras and Tensorflow', 2, None, '___sec52'),
- ('Using TensorFlow backend', 2, None, '___sec53'),
- ('Train the model', 2, None, '___sec54'),
- ('Visualizing the results', 2, None, '___sec55'),
- ('Running with Keras', 2, None, '___sec56'),
- ('Final part', 2, None, '___sec57'),
- ('Final visualization', 2, None, '___sec58'),
- ('Fun links', 2, None, '___sec59')]}
+ '___sec41'),
+ ('3D volumes of neurons', 2, None, '___sec42'),
+ ('Layers used to build CNNs', 2, None, '___sec43'),
+ ('Transforming images', 2, None, '___sec44'),
+ ('CNNs in brief', 2, None, '___sec45')]}
end of tocinfo -->
@@ -202,34 +181,20 @@ MathJax.Hub.Config({
Using TensorFlow backend
Optimizing and using gradient descent
Using Keras
- Which activation function should I use?
- Is the Logistic activation function (Sigmoid) our choice?
- The derivative of the Logistic funtion
- The RELU function family
- Which activation function should we use?
- A top-down perspective on Neural networks
- Limitations of supervised learning with deep networks
- Convolutional Neural Networks (recognizing images)
- Regular NNs don’t scale well to full images
- 3D volumes of neurons
- Layers used to build CNNs
- Transforming images
- CNNs in brief
- CNNs in more detail, building convolutional neural networks in Tensorflow and Keras
- Setting it up
- The MNIST dataset again
- Strong correlations
- Layers of a CNN
- Systematic reduction
- Prerequisites: Collect and pre-process data
- Importing Keras and Tensorflow
- Using TensorFlow backend
- Train the model
- Visualizing the results
- Running with Keras
- Final part
- Final visualization
- Fun links
+ The Breast Cancer Data, now with Keras
+ Which activation function should I use?
+ Is the Logistic activation function (Sigmoid) our choice?
+ The derivative of the Logistic funtion
+ The RELU function family
+ Which activation function should we use?
+ A top-down perspective on Neural networks
+ Limitations of supervised learning with deep networks
+ Convolutional Neural Networks (recognizing images)
+ Regular NNs don’t scale well to full images
+ 3D volumes of neurons
+ Layers used to build CNNs
+ Transforming images
+ CNNs in brief
@@ -245,30 +210,41 @@ MathJax.Hub.Config({
-Regular NNs don’t scale well to full images
+Convolutional Neural Networks (recognizing 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.
+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 deep learning methods. The success in for example image
+classifications have made them a central tool for most machine
+learning practitioners.
-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.
+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).
-
-
-Figure 1: A regular 3-layer Neural Network.
-
-
+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
+and the slides of CS231.
+
+
+Another good read is the article here https://arxiv.org/pdf/1603.07285.pdf.
@@ -291,12 +267,6 @@ would quickly lead to possible overfitting.
45
46
47
- 48
- 49
- 50
- 51
- ...
- 61
»
diff --git a/doc/pub/week41/html/._week41-bs042.html b/doc/pub/week41/html/._week41-bs042.html
index 0d312e831..072eeb2c1 100644
--- a/doc/pub/week41/html/._week41-bs042.html
+++ b/doc/pub/week41/html/._week41-bs042.html
@@ -83,56 +83,35 @@ Automatically generated HTML file from DocOnce source
('Using TensorFlow backend', 2, None, '___sec29'),
('Optimizing and using gradient descent', 2, None, '___sec30'),
('Using Keras', 2, None, '___sec31'),
- ('Which activation function should I use?', 2, None, '___sec32'),
+ ('The Breast Cancer Data, now with Keras', 2, None, '___sec32'),
+ ('Which activation function should I use?', 2, None, '___sec33'),
('Is the Logistic activation function (Sigmoid) our choice?',
2,
None,
- '___sec33'),
- ('The derivative of the Logistic funtion', 2, None, '___sec34'),
- ('The RELU function family', 2, None, '___sec35'),
- ('Which activation function should we use?', 2, None, '___sec36'),
+ '___sec34'),
+ ('The derivative of the Logistic funtion', 2, None, '___sec35'),
+ ('The RELU function family', 2, None, '___sec36'),
+ ('Which activation function should we use?', 2, None, '___sec37'),
('A top-down perspective on Neural networks',
2,
None,
- '___sec37'),
+ '___sec38'),
('Limitations of supervised learning with deep networks',
2,
None,
- '___sec38'),
+ '___sec39'),
('Convolutional Neural Networks (recognizing images)',
2,
None,
- '___sec39'),
+ '___sec40'),
('Regular NNs don’t scale well to full images',
2,
None,
- '___sec40'),
- ('3D volumes of neurons', 2, None, '___sec41'),
- ('Layers used to build CNNs', 2, None, '___sec42'),
- ('Transforming images', 2, None, '___sec43'),
- ('CNNs in brief', 2, None, '___sec44'),
- ('CNNs in more detail, building convolutional neural networks in '
- 'Tensorflow and Keras',
- 2,
- None,
- '___sec45'),
- ('Setting it up', 2, None, '___sec46'),
- ('The MNIST dataset again', 2, None, '___sec47'),
- ('Strong correlations', 2, None, '___sec48'),
- ('Layers of a CNN', 2, None, '___sec49'),
- ('Systematic reduction', 2, None, '___sec50'),
- ('Prerequisites: Collect and pre-process data',
- 2,
- None,
- '___sec51'),
- ('Importing Keras and Tensorflow', 2, None, '___sec52'),
- ('Using TensorFlow backend', 2, None, '___sec53'),
- ('Train the model', 2, None, '___sec54'),
- ('Visualizing the results', 2, None, '___sec55'),
- ('Running with Keras', 2, None, '___sec56'),
- ('Final part', 2, None, '___sec57'),
- ('Final visualization', 2, None, '___sec58'),
- ('Fun links', 2, None, '___sec59')]}
+ '___sec41'),
+ ('3D volumes of neurons', 2, None, '___sec42'),
+ ('Layers used to build CNNs', 2, None, '___sec43'),
+ ('Transforming images', 2, None, '___sec44'),
+ ('CNNs in brief', 2, None, '___sec45')]}
end of tocinfo -->
@@ -202,34 +181,20 @@ MathJax.Hub.Config({
Using TensorFlow backend
Optimizing and using gradient descent
Using Keras
- Which activation function should I use?
- Is the Logistic activation function (Sigmoid) our choice?
- The derivative of the Logistic funtion
- The RELU function family
- Which activation function should we use?
- A top-down perspective on Neural networks
- Limitations of supervised learning with deep networks
- Convolutional Neural Networks (recognizing images)
- Regular NNs don’t scale well to full images
- 3D volumes of neurons
- Layers used to build CNNs
- Transforming images
- CNNs in brief
- CNNs in more detail, building convolutional neural networks in Tensorflow and Keras
- Setting it up
- The MNIST dataset again
- Strong correlations
- Layers of a CNN
- Systematic reduction
- Prerequisites: Collect and pre-process data
- Importing Keras and Tensorflow
- Using TensorFlow backend
- Train the model
- Visualizing the results
- Running with Keras
- Final part
- Final visualization
- Fun links
+ The Breast Cancer Data, now with Keras
+ Which activation function should I use?
+ Is the Logistic activation function (Sigmoid) our choice?
+ The derivative of the Logistic funtion
+ The RELU function family
+ Which activation function should we use?
+ A top-down perspective on Neural networks
+ Limitations of supervised learning with deep networks
+ Convolutional Neural Networks (recognizing images)
+ Regular NNs don’t scale well to full images
+ 3D volumes of neurons
+ Layers used to build CNNs
+ Transforming images
+ CNNs in brief
@@ -245,41 +210,29 @@ MathJax.Hub.Config({
-3D volumes of neurons
+Regular NNs don’t scale well to full images
-Convolutional Neural Networks take advantage of the fact that the
-input consists of images and they constrain the architecture in a more
-sensible way.
+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.
-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.
+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 2: 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).
-
+Figure 1: A regular 3-layer Neural Network.
+
@@ -302,13 +255,6 @@ dimension.
45
46
47
- 48
- 49
- 50
- 51
- 52
- ...
- 61
»
diff --git a/doc/pub/week41/html/._week41-bs043.html b/doc/pub/week41/html/._week41-bs043.html
index 0e5474312..306316700 100644
--- a/doc/pub/week41/html/._week41-bs043.html
+++ b/doc/pub/week41/html/._week41-bs043.html
@@ -83,56 +83,35 @@ Automatically generated HTML file from DocOnce source
('Using TensorFlow backend', 2, None, '___sec29'),
('Optimizing and using gradient descent', 2, None, '___sec30'),
('Using Keras', 2, None, '___sec31'),
- ('Which activation function should I use?', 2, None, '___sec32'),
+ ('The Breast Cancer Data, now with Keras', 2, None, '___sec32'),
+ ('Which activation function should I use?', 2, None, '___sec33'),
('Is the Logistic activation function (Sigmoid) our choice?',
2,
None,
- '___sec33'),
- ('The derivative of the Logistic funtion', 2, None, '___sec34'),
- ('The RELU function family', 2, None, '___sec35'),
- ('Which activation function should we use?', 2, None, '___sec36'),
+ '___sec34'),
+ ('The derivative of the Logistic funtion', 2, None, '___sec35'),
+ ('The RELU function family', 2, None, '___sec36'),
+ ('Which activation function should we use?', 2, None, '___sec37'),
('A top-down perspective on Neural networks',
2,
None,
- '___sec37'),
+ '___sec38'),
('Limitations of supervised learning with deep networks',
2,
None,
- '___sec38'),
+ '___sec39'),
('Convolutional Neural Networks (recognizing images)',
2,
None,
- '___sec39'),
+ '___sec40'),
('Regular NNs don’t scale well to full images',
2,
None,
- '___sec40'),
- ('3D volumes of neurons', 2, None, '___sec41'),
- ('Layers used to build CNNs', 2, None, '___sec42'),
- ('Transforming images', 2, None, '___sec43'),
- ('CNNs in brief', 2, None, '___sec44'),
- ('CNNs in more detail, building convolutional neural networks in '
- 'Tensorflow and Keras',
- 2,
- None,
- '___sec45'),
- ('Setting it up', 2, None, '___sec46'),
- ('The MNIST dataset again', 2, None, '___sec47'),
- ('Strong correlations', 2, None, '___sec48'),
- ('Layers of a CNN', 2, None, '___sec49'),
- ('Systematic reduction', 2, None, '___sec50'),
- ('Prerequisites: Collect and pre-process data',
- 2,
- None,
- '___sec51'),
- ('Importing Keras and Tensorflow', 2, None, '___sec52'),
- ('Using TensorFlow backend', 2, None, '___sec53'),
- ('Train the model', 2, None, '___sec54'),
- ('Visualizing the results', 2, None, '___sec55'),
- ('Running with Keras', 2, None, '___sec56'),
- ('Final part', 2, None, '___sec57'),
- ('Final visualization', 2, None, '___sec58'),
- ('Fun links', 2, None, '___sec59')]}
+ '___sec41'),
+ ('3D volumes of neurons', 2, None, '___sec42'),
+ ('Layers used to build CNNs', 2, None, '___sec43'),
+ ('Transforming images', 2, None, '___sec44'),
+ ('CNNs in brief', 2, None, '___sec45')]}
end of tocinfo -->
@@ -202,34 +181,20 @@ MathJax.Hub.Config({
Using TensorFlow backend
Optimizing and using gradient descent
Using Keras
- Which activation function should I use?
- Is the Logistic activation function (Sigmoid) our choice?
- The derivative of the Logistic funtion
- The RELU function family
- Which activation function should we use?
- A top-down perspective on Neural networks
- Limitations of supervised learning with deep networks
- Convolutional Neural Networks (recognizing images)
- Regular NNs don’t scale well to full images
- 3D volumes of neurons
- Layers used to build CNNs
- Transforming images
- CNNs in brief
- CNNs in more detail, building convolutional neural networks in Tensorflow and Keras
- Setting it up
- The MNIST dataset again
- Strong correlations
- Layers of a CNN
- Systematic reduction
- Prerequisites: Collect and pre-process data
- Importing Keras and Tensorflow
- Using TensorFlow backend
- Train the model
- Visualizing the results
- Running with Keras
- Final part
- Final visualization
- Fun links
+ The Breast Cancer Data, now with Keras
+ Which activation function should I use?
+ Is the Logistic activation function (Sigmoid) our choice?
+ The derivative of the Logistic funtion
+ The RELU function family
+ Which activation function should we use?
+ A top-down perspective on Neural networks
+ Limitations of supervised learning with deep networks
+ Convolutional Neural Networks (recognizing images)
+ Regular NNs don’t scale well to full images
+ 3D volumes of neurons
+ Layers used to build CNNs
+ Transforming images
+ CNNs in brief
@@ -243,29 +208,46 @@ MathJax.Hub.Config({
-
+
-Layers used to build CNNs
+3D volumes of neurons
-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.
+Convolutional Neural Networks take advantage of the fact that the
+input consists of images and they constrain the architecture in a more
+sensible way.
-A simple CNN for image classification could have the architecture:
+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.)
-
-- 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.
-
+
+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 2: 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).
+
+
+
+
@@ -284,14 +266,6 @@ A simple CNN for image classification could have the architecture:
- 45
- 46
- 47
- - 48
- - 49
- - 50
- - 51
- - 52
- - 53
- - ...
- - 61
- »
diff --git a/doc/pub/week41/html/._week41-bs044.html b/doc/pub/week41/html/._week41-bs044.html
index c1f341580..3522fc992 100644
--- a/doc/pub/week41/html/._week41-bs044.html
+++ b/doc/pub/week41/html/._week41-bs044.html
@@ -83,56 +83,35 @@ Automatically generated HTML file from DocOnce source
('Using TensorFlow backend', 2, None, '___sec29'),
('Optimizing and using gradient descent', 2, None, '___sec30'),
('Using Keras', 2, None, '___sec31'),
- ('Which activation function should I use?', 2, None, '___sec32'),
+ ('The Breast Cancer Data, now with Keras', 2, None, '___sec32'),
+ ('Which activation function should I use?', 2, None, '___sec33'),
('Is the Logistic activation function (Sigmoid) our choice?',
2,
None,
- '___sec33'),
- ('The derivative of the Logistic funtion', 2, None, '___sec34'),
- ('The RELU function family', 2, None, '___sec35'),
- ('Which activation function should we use?', 2, None, '___sec36'),
+ '___sec34'),
+ ('The derivative of the Logistic funtion', 2, None, '___sec35'),
+ ('The RELU function family', 2, None, '___sec36'),
+ ('Which activation function should we use?', 2, None, '___sec37'),
('A top-down perspective on Neural networks',
2,
None,
- '___sec37'),
+ '___sec38'),
('Limitations of supervised learning with deep networks',
2,
None,
- '___sec38'),
+ '___sec39'),
('Convolutional Neural Networks (recognizing images)',
2,
None,
- '___sec39'),
+ '___sec40'),
('Regular NNs don’t scale well to full images',
2,
None,
- '___sec40'),
- ('3D volumes of neurons', 2, None, '___sec41'),
- ('Layers used to build CNNs', 2, None, '___sec42'),
- ('Transforming images', 2, None, '___sec43'),
- ('CNNs in brief', 2, None, '___sec44'),
- ('CNNs in more detail, building convolutional neural networks in '
- 'Tensorflow and Keras',
- 2,
- None,
- '___sec45'),
- ('Setting it up', 2, None, '___sec46'),
- ('The MNIST dataset again', 2, None, '___sec47'),
- ('Strong correlations', 2, None, '___sec48'),
- ('Layers of a CNN', 2, None, '___sec49'),
- ('Systematic reduction', 2, None, '___sec50'),
- ('Prerequisites: Collect and pre-process data',
- 2,
- None,
- '___sec51'),
- ('Importing Keras and Tensorflow', 2, None, '___sec52'),
- ('Using TensorFlow backend', 2, None, '___sec53'),
- ('Train the model', 2, None, '___sec54'),
- ('Visualizing the results', 2, None, '___sec55'),
- ('Running with Keras', 2, None, '___sec56'),
- ('Final part', 2, None, '___sec57'),
- ('Final visualization', 2, None, '___sec58'),
- ('Fun links', 2, None, '___sec59')]}
+ '___sec41'),
+ ('3D volumes of neurons', 2, None, '___sec42'),
+ ('Layers used to build CNNs', 2, None, '___sec43'),
+ ('Transforming images', 2, None, '___sec44'),
+ ('CNNs in brief', 2, None, '___sec45')]}
end of tocinfo -->
@@ -202,34 +181,20 @@ MathJax.Hub.Config({
Using TensorFlow backend
Optimizing and using gradient descent
Using Keras
- Which activation function should I use?
- Is the Logistic activation function (Sigmoid) our choice?
- The derivative of the Logistic funtion
- The RELU function family
- Which activation function should we use?
- A top-down perspective on Neural networks
- Limitations of supervised learning with deep networks
- Convolutional Neural Networks (recognizing images)
- Regular NNs don’t scale well to full images
- 3D volumes of neurons
- Layers used to build CNNs
- Transforming images
- CNNs in brief
- CNNs in more detail, building convolutional neural networks in Tensorflow and Keras
- Setting it up
- The MNIST dataset again
- Strong correlations
- Layers of a CNN
- Systematic reduction
- Prerequisites: Collect and pre-process data
- Importing Keras and Tensorflow
- Using TensorFlow backend
- Train the model
- Visualizing the results
- Running with Keras
- Final part
- Final visualization
- Fun links
+ The Breast Cancer Data, now with Keras
+ Which activation function should I use?
+ Is the Logistic activation function (Sigmoid) our choice?
+ The derivative of the Logistic funtion
+ The RELU function family
+ Which activation function should we use?
+ A top-down perspective on Neural networks
+ Limitations of supervised learning with deep networks
+ Convolutional Neural Networks (recognizing images)
+ Regular NNs don’t scale well to full images
+ 3D volumes of neurons
+ Layers used to build CNNs
+ Transforming images
+ CNNs in brief
@@ -243,25 +208,29 @@ MathJax.Hub.Config({
-
+
-Transforming images
+Layers used to build CNNs
-CNNs transform the original image layer by layer from the original
-pixel values to the final class scores.
+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.
-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.
+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.
+
-
@@ -279,15 +248,6 @@ are consistent with the labels in the training set for each image.
- 45
- 46
- 47
- - 48
- - 49
- - 50
- - 51
- - 52
- - 53
- - 54
- - ...
- - 61
- »
diff --git a/doc/pub/week41/html/._week41-bs045.html b/doc/pub/week41/html/._week41-bs045.html
index 2462722fa..d742ead94 100644
--- a/doc/pub/week41/html/._week41-bs045.html
+++ b/doc/pub/week41/html/._week41-bs045.html
@@ -83,56 +83,35 @@ Automatically generated HTML file from DocOnce source
('Using TensorFlow backend', 2, None, '___sec29'),
('Optimizing and using gradient descent', 2, None, '___sec30'),
('Using Keras', 2, None, '___sec31'),
- ('Which activation function should I use?', 2, None, '___sec32'),
+ ('The Breast Cancer Data, now with Keras', 2, None, '___sec32'),
+ ('Which activation function should I use?', 2, None, '___sec33'),
('Is the Logistic activation function (Sigmoid) our choice?',
2,
None,
- '___sec33'),
- ('The derivative of the Logistic funtion', 2, None, '___sec34'),
- ('The RELU function family', 2, None, '___sec35'),
- ('Which activation function should we use?', 2, None, '___sec36'),
+ '___sec34'),
+ ('The derivative of the Logistic funtion', 2, None, '___sec35'),
+ ('The RELU function family', 2, None, '___sec36'),
+ ('Which activation function should we use?', 2, None, '___sec37'),
('A top-down perspective on Neural networks',
2,
None,
- '___sec37'),
+ '___sec38'),
('Limitations of supervised learning with deep networks',
2,
None,
- '___sec38'),
+ '___sec39'),
('Convolutional Neural Networks (recognizing images)',
2,
None,
- '___sec39'),
+ '___sec40'),
('Regular NNs don’t scale well to full images',
2,
None,
- '___sec40'),
- ('3D volumes of neurons', 2, None, '___sec41'),
- ('Layers used to build CNNs', 2, None, '___sec42'),
- ('Transforming images', 2, None, '___sec43'),
- ('CNNs in brief', 2, None, '___sec44'),
- ('CNNs in more detail, building convolutional neural networks in '
- 'Tensorflow and Keras',
- 2,
- None,
- '___sec45'),
- ('Setting it up', 2, None, '___sec46'),
- ('The MNIST dataset again', 2, None, '___sec47'),
- ('Strong correlations', 2, None, '___sec48'),
- ('Layers of a CNN', 2, None, '___sec49'),
- ('Systematic reduction', 2, None, '___sec50'),
- ('Prerequisites: Collect and pre-process data',
- 2,
- None,
- '___sec51'),
- ('Importing Keras and Tensorflow', 2, None, '___sec52'),
- ('Using TensorFlow backend', 2, None, '___sec53'),
- ('Train the model', 2, None, '___sec54'),
- ('Visualizing the results', 2, None, '___sec55'),
- ('Running with Keras', 2, None, '___sec56'),
- ('Final part', 2, None, '___sec57'),
- ('Final visualization', 2, None, '___sec58'),
- ('Fun links', 2, None, '___sec59')]}
+ '___sec41'),
+ ('3D volumes of neurons', 2, None, '___sec42'),
+ ('Layers used to build CNNs', 2, None, '___sec43'),
+ ('Transforming images', 2, None, '___sec44'),
+ ('CNNs in brief', 2, None, '___sec45')]}
end of tocinfo -->
@@ -202,34 +181,20 @@ MathJax.Hub.Config({
Using TensorFlow backend
Optimizing and using gradient descent
Using Keras
- Which activation function should I use?
- Is the Logistic activation function (Sigmoid) our choice?
- The derivative of the Logistic funtion
- The RELU function family
- Which activation function should we use?
- A top-down perspective on Neural networks
- Limitations of supervised learning with deep networks
- Convolutional Neural Networks (recognizing images)
- Regular NNs don’t scale well to full images
- 3D volumes of neurons
- Layers used to build CNNs
- Transforming images
- CNNs in brief
- CNNs in more detail, building convolutional neural networks in Tensorflow and Keras
- Setting it up
- The MNIST dataset again
- Strong correlations
- Layers of a CNN
- Systematic reduction
- Prerequisites: Collect and pre-process data
- Importing Keras and Tensorflow
- Using TensorFlow backend
- Train the model
- Visualizing the results
- Running with Keras
- Final part
- Final visualization
- Fun links
+ The Breast Cancer Data, now with Keras
+ Which activation function should I use?
+ Is the Logistic activation function (Sigmoid) our choice?
+ The derivative of the Logistic funtion
+ The RELU function family
+ Which activation function should we use?
+ A top-down perspective on Neural networks
+ Limitations of supervised learning with deep networks
+ Convolutional Neural Networks (recognizing images)
+ Regular NNs don’t scale well to full images
+ 3D volumes of neurons
+ Layers used to build CNNs
+ Transforming images
+ CNNs in brief
@@ -245,23 +210,21 @@ MathJax.Hub.Config({
-CNNs in brief
+Transforming images
-In summary:
+CNNs transform the original image layer by layer from the original
+pixel values to the final class scores.
-
-- 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
-and the slides of CS231 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.
+
+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.
@@ -280,16 +243,6 @@ and the slides of 45
46
47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- ...
- 61
»
diff --git a/doc/pub/week41/html/._week41-bs046.html b/doc/pub/week41/html/._week41-bs046.html
index 9d30f7f12..a7a4d3d8d 100644
--- a/doc/pub/week41/html/._week41-bs046.html
+++ b/doc/pub/week41/html/._week41-bs046.html
@@ -83,56 +83,35 @@ Automatically generated HTML file from DocOnce source
('Using TensorFlow backend', 2, None, '___sec29'),
('Optimizing and using gradient descent', 2, None, '___sec30'),
('Using Keras', 2, None, '___sec31'),
- ('Which activation function should I use?', 2, None, '___sec32'),
+ ('The Breast Cancer Data, now with Keras', 2, None, '___sec32'),
+ ('Which activation function should I use?', 2, None, '___sec33'),
('Is the Logistic activation function (Sigmoid) our choice?',
2,
None,
- '___sec33'),
- ('The derivative of the Logistic funtion', 2, None, '___sec34'),
- ('The RELU function family', 2, None, '___sec35'),
- ('Which activation function should we use?', 2, None, '___sec36'),
+ '___sec34'),
+ ('The derivative of the Logistic funtion', 2, None, '___sec35'),
+ ('The RELU function family', 2, None, '___sec36'),
+ ('Which activation function should we use?', 2, None, '___sec37'),
('A top-down perspective on Neural networks',
2,
None,
- '___sec37'),
+ '___sec38'),
('Limitations of supervised learning with deep networks',
2,
None,
- '___sec38'),
+ '___sec39'),
('Convolutional Neural Networks (recognizing images)',
2,
None,
- '___sec39'),
+ '___sec40'),
('Regular NNs don’t scale well to full images',
2,
None,
- '___sec40'),
- ('3D volumes of neurons', 2, None, '___sec41'),
- ('Layers used to build CNNs', 2, None, '___sec42'),
- ('Transforming images', 2, None, '___sec43'),
- ('CNNs in brief', 2, None, '___sec44'),
- ('CNNs in more detail, building convolutional neural networks in '
- 'Tensorflow and Keras',
- 2,
- None,
- '___sec45'),
- ('Setting it up', 2, None, '___sec46'),
- ('The MNIST dataset again', 2, None, '___sec47'),
- ('Strong correlations', 2, None, '___sec48'),
- ('Layers of a CNN', 2, None, '___sec49'),
- ('Systematic reduction', 2, None, '___sec50'),
- ('Prerequisites: Collect and pre-process data',
- 2,
- None,
- '___sec51'),
- ('Importing Keras and Tensorflow', 2, None, '___sec52'),
- ('Using TensorFlow backend', 2, None, '___sec53'),
- ('Train the model', 2, None, '___sec54'),
- ('Visualizing the results', 2, None, '___sec55'),
- ('Running with Keras', 2, None, '___sec56'),
- ('Final part', 2, None, '___sec57'),
- ('Final visualization', 2, None, '___sec58'),
- ('Fun links', 2, None, '___sec59')]}
+ '___sec41'),
+ ('3D volumes of neurons', 2, None, '___sec42'),
+ ('Layers used to build CNNs', 2, None, '___sec43'),
+ ('Transforming images', 2, None, '___sec44'),
+ ('CNNs in brief', 2, None, '___sec45')]}
end of tocinfo -->
@@ -202,34 +181,20 @@ MathJax.Hub.Config({
Using TensorFlow backend
Optimizing and using gradient descent
Using Keras
- Which activation function should I use?
- Is the Logistic activation function (Sigmoid) our choice?
- The derivative of the Logistic funtion
- The RELU function family
- Which activation function should we use?
- A top-down perspective on Neural networks
- Limitations of supervised learning with deep networks
- Convolutional Neural Networks (recognizing images)
- Regular NNs don’t scale well to full images
- 3D volumes of neurons
- Layers used to build CNNs
- Transforming images
- CNNs in brief
- CNNs in more detail, building convolutional neural networks in Tensorflow and Keras
- Setting it up
- The MNIST dataset again
- Strong correlations
- Layers of a CNN
- Systematic reduction
- Prerequisites: Collect and pre-process data
- Importing Keras and Tensorflow
- Using TensorFlow backend
- Train the model
- Visualizing the results
- Running with Keras
- Final part
- Final visualization
- Fun links
+ The Breast Cancer Data, now with Keras
+ Which activation function should I use?
+ Is the Logistic activation function (Sigmoid) our choice?
+ The derivative of the Logistic funtion
+ The RELU function family
+ Which activation function should we use?
+ A top-down perspective on Neural networks
+ Limitations of supervised learning with deep networks
+ Convolutional Neural Networks (recognizing images)
+ Regular NNs don’t scale well to full images
+ 3D volumes of neurons
+ Layers used to build CNNs
+ Transforming images
+ CNNs in brief
@@ -245,20 +210,26 @@ MathJax.Hub.Config({
-CNNs in more detail, building convolutional neural networks in Tensorflow and Keras
+CNNs in brief
-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.
+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
+and the slides of CS231 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.
-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).
-
@@ -274,18 +245,6 @@ matrices, typically 1 for each color dimension (Red, Green, Blue).
- 45
- 46
- 47
- - 48
- - 49
- - 50
- - 51
- - 52
- - 53
- - 54
- - 55
- - 56
- - ...
- - 61
- - »
diff --git a/doc/pub/week41/html/week41-bs.html b/doc/pub/week41/html/week41-bs.html
index 112def37d..63ba71fc4 100644
--- a/doc/pub/week41/html/week41-bs.html
+++ b/doc/pub/week41/html/week41-bs.html
@@ -83,56 +83,35 @@ Automatically generated HTML file from DocOnce source
('Using TensorFlow backend', 2, None, '___sec29'),
('Optimizing and using gradient descent', 2, None, '___sec30'),
('Using Keras', 2, None, '___sec31'),
- ('Which activation function should I use?', 2, None, '___sec32'),
+ ('The Breast Cancer Data, now with Keras', 2, None, '___sec32'),
+ ('Which activation function should I use?', 2, None, '___sec33'),
('Is the Logistic activation function (Sigmoid) our choice?',
2,
None,
- '___sec33'),
- ('The derivative of the Logistic funtion', 2, None, '___sec34'),
- ('The RELU function family', 2, None, '___sec35'),
- ('Which activation function should we use?', 2, None, '___sec36'),
+ '___sec34'),
+ ('The derivative of the Logistic funtion', 2, None, '___sec35'),
+ ('The RELU function family', 2, None, '___sec36'),
+ ('Which activation function should we use?', 2, None, '___sec37'),
('A top-down perspective on Neural networks',
2,
None,
- '___sec37'),
+ '___sec38'),
('Limitations of supervised learning with deep networks',
2,
None,
- '___sec38'),
+ '___sec39'),
('Convolutional Neural Networks (recognizing images)',
2,
None,
- '___sec39'),
+ '___sec40'),
('Regular NNs don’t scale well to full images',
2,
None,
- '___sec40'),
- ('3D volumes of neurons', 2, None, '___sec41'),
- ('Layers used to build CNNs', 2, None, '___sec42'),
- ('Transforming images', 2, None, '___sec43'),
- ('CNNs in brief', 2, None, '___sec44'),
- ('CNNs in more detail, building convolutional neural networks in '
- 'Tensorflow and Keras',
- 2,
- None,
- '___sec45'),
- ('Setting it up', 2, None, '___sec46'),
- ('The MNIST dataset again', 2, None, '___sec47'),
- ('Strong correlations', 2, None, '___sec48'),
- ('Layers of a CNN', 2, None, '___sec49'),
- ('Systematic reduction', 2, None, '___sec50'),
- ('Prerequisites: Collect and pre-process data',
- 2,
- None,
- '___sec51'),
- ('Importing Keras and Tensorflow', 2, None, '___sec52'),
- ('Using TensorFlow backend', 2, None, '___sec53'),
- ('Train the model', 2, None, '___sec54'),
- ('Visualizing the results', 2, None, '___sec55'),
- ('Running with Keras', 2, None, '___sec56'),
- ('Final part', 2, None, '___sec57'),
- ('Final visualization', 2, None, '___sec58'),
- ('Fun links', 2, None, '___sec59')]}
+ '___sec41'),
+ ('3D volumes of neurons', 2, None, '___sec42'),
+ ('Layers used to build CNNs', 2, None, '___sec43'),
+ ('Transforming images', 2, None, '___sec44'),
+ ('CNNs in brief', 2, None, '___sec45')]}
end of tocinfo -->
@@ -202,34 +181,20 @@ MathJax.Hub.Config({
Using TensorFlow backend
Optimizing and using gradient descent
Using Keras
- Which activation function should I use?
- Is the Logistic activation function (Sigmoid) our choice?
- The derivative of the Logistic funtion
- The RELU function family
- Which activation function should we use?
- A top-down perspective on Neural networks
- Limitations of supervised learning with deep networks
- Convolutional Neural Networks (recognizing images)
- Regular NNs don’t scale well to full images
- 3D volumes of neurons
- Layers used to build CNNs
- Transforming images
- CNNs in brief
- CNNs in more detail, building convolutional neural networks in Tensorflow and Keras
- Setting it up
- The MNIST dataset again
- Strong correlations
- Layers of a CNN
- Systematic reduction
- Prerequisites: Collect and pre-process data
- Importing Keras and Tensorflow
- Using TensorFlow backend
- Train the model
- Visualizing the results
- Running with Keras
- Final part
- Final visualization
- Fun links
+ The Breast Cancer Data, now with Keras
+ Which activation function should I use?
+ Is the Logistic activation function (Sigmoid) our choice?
+ The derivative of the Logistic funtion
+ The RELU function family
+ Which activation function should we use?
+ A top-down perspective on Neural networks
+ Limitations of supervised learning with deep networks
+ Convolutional Neural Networks (recognizing images)
+ Regular NNs don’t scale well to full images
+ 3D volumes of neurons
+ Layers used to build CNNs
+ Transforming images
+ CNNs in brief
@@ -264,7 +229,7 @@ MathJax.Hub.Config({
[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
-
Oct 5, 2020
+Oct 6, 2020
@@ -288,7 +253,7 @@ MathJax.Hub.Config({
9
10
...
- 61
+ 47
»
diff --git a/doc/pub/week41/html/week41-reveal.html b/doc/pub/week41/html/week41-reveal.html
index 8f9ad9417..da63c4200 100644
--- a/doc/pub/week41/html/week41-reveal.html
+++ b/doc/pub/week41/html/week41-reveal.html
@@ -148,7 +148,7 @@ MathJax.Hub.Config({
[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
-
Oct 5, 2020
+Oct 6, 2020
@@ -163,7 +163,7 @@ MathJax.Hub.Config({
- 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).
@@ -1836,7 +1836,7 @@ Alternatively, if you have Tensorflow or one of the other supported backends ins
-
pip3 install keras
+pip install keras
or look up the instructions here.
@@ -1844,18 +1844,21 @@ or look up the instructions here
-
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
@@ -1918,7 +1921,182 @@ plt.show()
-Which activation function should I use?
+The Breast Cancer Data, now with Keras
+
+
+
+
+
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')
+
+
+
+
+
+Which activation function should I use?
The Back propagation algorithm we derived above works by going from
@@ -1947,7 +2125,7 @@ learn at widely different speeds
-Is the Logistic activation function (Sigmoid) our choice?
+Is the Logistic activation function (Sigmoid) our choice?
Although this unfortunate behavior has been empirically observed for
@@ -1977,7 +2155,7 @@ better than the logistic function in deep networks).
-The derivative of the Logistic funtion
+The derivative of the Logistic funtion
Looking at the logistic activation function, when inputs become large
@@ -2013,7 +2191,7 @@ fast to compute).
-The RELU function family
+The RELU function family
The ReLU activation function suffers from a problem known as the dying
@@ -2042,7 +2220,7 @@ $$
-Which activation function should we use?
+Which activation function should we use?
In general it seems that the ELU activation function is better than
@@ -2062,7 +2240,7 @@ bootstrap to evaluate other activation functions.
-A top-down perspective on Neural networks
+A top-down perspective on Neural networks
The first thing we would like to do is divide the data into two or three
@@ -2105,7 +2283,7 @@ supervised learning.
-Limitations of supervised learning with deep networks
+Limitations of supervised learning with deep networks
Like all statistical methods, supervised learning using neural
@@ -2132,13 +2310,13 @@ Some of these remarks are particular to DNNs, others are shared by all supervise
-Convolutional Neural Networks (recognizing images)
+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
+of deep learning methods. The success in for example image
classifications have made them a central tool for most machine
learning practitioners.
@@ -2171,7 +2349,7 @@ Another good read is the article here Regular NNs don’t scale well to full images
+Regular NNs don’t scale well to full images
As an example, consider
@@ -2199,7 +2377,7 @@ would quickly lead to possible overfitting.
-3D volumes of neurons
+3D volumes of neurons
Convolutional Neural Networks take advantage of the fact that the
@@ -2239,7 +2417,7 @@ dimension.
-Layers used to build CNNs
+Layers used to build CNNs
A simple CNN is a sequence of layers, and every layer of a CNN
@@ -2263,7 +2441,7 @@ A simple CNN for image classification could have the architecture:
-Transforming images
+Transforming images
CNNs transform the original image layer by layer from the original
@@ -2282,7 +2460,7 @@ are consistent with the labels in the training set for each image.
-CNNs in brief
+CNNs in brief
In summary:
@@ -2303,523 +2481,6 @@ and the slides of
-
-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).
-
-
-
-
-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:
-
-
-$$
-(n_{inputs},\, n_{pixels, width},\, n_{pixels, height},\, depth) .
-$$
-
-
-
-
-
-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.
-
-
-
-
-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.
-
-
-
-
-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.
-
-
-
-
-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.
-
-
-
-
-Prerequisites: Collect and pre-process data
-
-
-
-
# 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()
-
-
-
-
-
-Importing Keras and Tensorflow
-
-
-
-
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)
-
-
-
-
-
-Using TensorFlow backend
-
-
-We need to define model and architecture and choose cost function and optmizer.
-
-
-
-
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})
-
-
-
-
-
-Train the model
-
-
-We need now to train the model, evaluate it and test its performance on test data, and eventually include hyperparameters.
-
-
-
-
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
-
-
-
-
-
-Visualizing the results
-
-
-
-
-
# 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()
-
-
-
-
-
-Running with Keras
-
-
-
-
-
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)
-
-
-
-
-
-Final part
-
-
-
-
-
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()
-
-
-
-
-
-Final visualization
-
-
-
-
-
# 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()
-
-
-
-
-
-Fun links
-
-
-
-
-
diff --git a/doc/pub/week41/html/week41-solarized.html b/doc/pub/week41/html/week41-solarized.html
index 164fa7351..d6cb93791 100644
--- a/doc/pub/week41/html/week41-solarized.html
+++ b/doc/pub/week41/html/week41-solarized.html
@@ -103,56 +103,35 @@ div { text-align: justify; text-justify: inter-word; }
('Using TensorFlow backend', 2, None, '___sec29'),
('Optimizing and using gradient descent', 2, None, '___sec30'),
('Using Keras', 2, None, '___sec31'),
- ('Which activation function should I use?', 2, None, '___sec32'),
+ ('The Breast Cancer Data, now with Keras', 2, None, '___sec32'),
+ ('Which activation function should I use?', 2, None, '___sec33'),
('Is the Logistic activation function (Sigmoid) our choice?',
2,
None,
- '___sec33'),
- ('The derivative of the Logistic funtion', 2, None, '___sec34'),
- ('The RELU function family', 2, None, '___sec35'),
- ('Which activation function should we use?', 2, None, '___sec36'),
+ '___sec34'),
+ ('The derivative of the Logistic funtion', 2, None, '___sec35'),
+ ('The RELU function family', 2, None, '___sec36'),
+ ('Which activation function should we use?', 2, None, '___sec37'),
('A top-down perspective on Neural networks',
2,
None,
- '___sec37'),
+ '___sec38'),
('Limitations of supervised learning with deep networks',
2,
None,
- '___sec38'),
+ '___sec39'),
('Convolutional Neural Networks (recognizing images)',
2,
None,
- '___sec39'),
+ '___sec40'),
('Regular NNs don’t scale well to full images',
2,
None,
- '___sec40'),
- ('3D volumes of neurons', 2, None, '___sec41'),
- ('Layers used to build CNNs', 2, None, '___sec42'),
- ('Transforming images', 2, None, '___sec43'),
- ('CNNs in brief', 2, None, '___sec44'),
- ('CNNs in more detail, building convolutional neural networks in '
- 'Tensorflow and Keras',
- 2,
- None,
- '___sec45'),
- ('Setting it up', 2, None, '___sec46'),
- ('The MNIST dataset again', 2, None, '___sec47'),
- ('Strong correlations', 2, None, '___sec48'),
- ('Layers of a CNN', 2, None, '___sec49'),
- ('Systematic reduction', 2, None, '___sec50'),
- ('Prerequisites: Collect and pre-process data',
- 2,
- None,
- '___sec51'),
- ('Importing Keras and Tensorflow', 2, None, '___sec52'),
- ('Using TensorFlow backend', 2, None, '___sec53'),
- ('Train the model', 2, None, '___sec54'),
- ('Visualizing the results', 2, None, '___sec55'),
- ('Running with Keras', 2, None, '___sec56'),
- ('Final part', 2, None, '___sec57'),
- ('Final visualization', 2, None, '___sec58'),
- ('Fun links', 2, None, '___sec59')]}
+ '___sec41'),
+ ('3D volumes of neurons', 2, None, '___sec42'),
+ ('Layers used to build CNNs', 2, None, '___sec43'),
+ ('Transforming images', 2, None, '___sec44'),
+ ('CNNs in brief', 2, None, '___sec45')]}
end of tocinfo -->
@@ -194,7 +173,7 @@ MathJax.Hub.Config({
[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
-
Oct 5, 2020
+Oct 6, 2020
@@ -203,7 +182,7 @@ MathJax.Hub.Config({
- 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:
-pip3 install keras
+pip install keras
or look up the instructions here.
@@ -1764,18 +1743,21 @@ or look up the instructions here
-
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
@@ -1835,9 +1817,183 @@ ax.set_xlabel("$\lambda$")
plt.show()
+
+
+
The Breast Cancer Data, now with Keras
+
+
+
+
+
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')
+
+
-
Which activation function should I use?
+Which activation function should I use?
The Back propagation algorithm we derived above works by going from
@@ -1866,7 +2022,7 @@ learn at widely different speeds
-
Is the Logistic activation function (Sigmoid) our choice?
+Is the Logistic activation function (Sigmoid) our choice?
Although this unfortunate behavior has been empirically observed for
@@ -1896,7 +2052,7 @@ better than the logistic function in deep networks).
-
The derivative of the Logistic funtion
+The derivative of the Logistic funtion
Looking at the logistic activation function, when inputs become large
@@ -1932,7 +2088,7 @@ fast to compute).
-
The RELU function family
+The RELU function family
The ReLU activation function suffers from a problem known as the dying
@@ -1959,7 +2115,7 @@ $$
-
Which activation function should we use?
+Which activation function should we use?
In general it seems that the ELU activation function is better than
@@ -1979,7 +2135,7 @@ bootstrap to evaluate other activation functions.
-
A top-down perspective on Neural networks
+A top-down perspective on Neural networks
The first thing we would like to do is divide the data into two or three
@@ -2021,7 +2177,7 @@ supervised learning.
-
Limitations of supervised learning with deep networks
+Limitations of supervised learning with deep networks
Like all statistical methods, supervised learning using neural
@@ -2047,13 +2203,13 @@ Some of these remarks are particular to DNNs, others are shared by all supervise
-
Convolutional Neural Networks (recognizing images)
+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
+of deep learning methods. The success in for example image
classifications have made them a central tool for most machine
learning practitioners.
@@ -2086,7 +2242,7 @@ Another good read is the article here Regular NNs don’t scale well to full images
+Regular NNs don’t scale well to full images
As an example, consider
@@ -2114,7 +2270,7 @@ would quickly lead to possible overfitting.
-
3D volumes of neurons
+3D volumes of neurons
Convolutional Neural Networks take advantage of the fact that the
@@ -2154,7 +2310,7 @@ dimension.
-
Layers used to build CNNs
+Layers used to build CNNs
A simple CNN is a sequence of layers, and every layer of a CNN
@@ -2177,7 +2333,7 @@ A simple CNN for image classification could have the architecture:
-
Transforming images
+Transforming images
CNNs transform the original image layer by layer from the original
@@ -2196,7 +2352,7 @@ are consistent with the labels in the training set for each image.
-
CNNs in brief
+CNNs in brief
In summary:
@@ -2215,511 +2371,6 @@ the course
and the slides of CS231 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.
-
-
-
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).
-
-
-
-
-
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:
-$$
-(n_{inputs},\, n_{pixels, width},\, n_{pixels, height},\, depth) .
-$$
-
-
-
-
-
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.
-
-
-
-
-
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.
-
-
-
-
-
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.
-
-
-
-
-
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.
-
-
-
-
-
Prerequisites: Collect and pre-process data
-
-
-
-
# 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()
-
-
-
-
-
Importing Keras and Tensorflow
-
-
-
-
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)
-
-
-
-
-
Using TensorFlow backend
-
-
-We need to define model and architecture and choose cost function and optmizer.
-
-
-
-
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})
-
-
-
-
-
Train the model
-
-
-We need now to train the model, evaluate it and test its performance on test data, and eventually include hyperparameters.
-
-
-
-
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
-
-
-
-
-
Visualizing the results
-
-
-
-
-
# 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()
-
-
-
-
-
Running with Keras
-
-
-
-
-
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)
-
-
-
-
-
Final part
-
-
-
-
-
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()
-
-
-
-
-
Final visualization
-
-
-
-
-
# 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()
-
-
-
-
-
Fun links
-
-
-- Self-Driving cars using a convolutional neural network
-- Abstract art using convolutional neural networks
-
-
diff --git a/doc/pub/week41/html/week41.html b/doc/pub/week41/html/week41.html
index 13a71098e..8f8139ad9 100644
--- a/doc/pub/week41/html/week41.html
+++ b/doc/pub/week41/html/week41.html
@@ -108,56 +108,35 @@ div { text-align: justify; text-justify: inter-word; }
('Using TensorFlow backend', 2, None, '___sec29'),
('Optimizing and using gradient descent', 2, None, '___sec30'),
('Using Keras', 2, None, '___sec31'),
- ('Which activation function should I use?', 2, None, '___sec32'),
+ ('The Breast Cancer Data, now with Keras', 2, None, '___sec32'),
+ ('Which activation function should I use?', 2, None, '___sec33'),
('Is the Logistic activation function (Sigmoid) our choice?',
2,
None,
- '___sec33'),
- ('The derivative of the Logistic funtion', 2, None, '___sec34'),
- ('The RELU function family', 2, None, '___sec35'),
- ('Which activation function should we use?', 2, None, '___sec36'),
+ '___sec34'),
+ ('The derivative of the Logistic funtion', 2, None, '___sec35'),
+ ('The RELU function family', 2, None, '___sec36'),
+ ('Which activation function should we use?', 2, None, '___sec37'),
('A top-down perspective on Neural networks',
2,
None,
- '___sec37'),
+ '___sec38'),
('Limitations of supervised learning with deep networks',
2,
None,
- '___sec38'),
+ '___sec39'),
('Convolutional Neural Networks (recognizing images)',
2,
None,
- '___sec39'),
+ '___sec40'),
('Regular NNs don’t scale well to full images',
2,
None,
- '___sec40'),
- ('3D volumes of neurons', 2, None, '___sec41'),
- ('Layers used to build CNNs', 2, None, '___sec42'),
- ('Transforming images', 2, None, '___sec43'),
- ('CNNs in brief', 2, None, '___sec44'),
- ('CNNs in more detail, building convolutional neural networks in '
- 'Tensorflow and Keras',
- 2,
- None,
- '___sec45'),
- ('Setting it up', 2, None, '___sec46'),
- ('The MNIST dataset again', 2, None, '___sec47'),
- ('Strong correlations', 2, None, '___sec48'),
- ('Layers of a CNN', 2, None, '___sec49'),
- ('Systematic reduction', 2, None, '___sec50'),
- ('Prerequisites: Collect and pre-process data',
- 2,
- None,
- '___sec51'),
- ('Importing Keras and Tensorflow', 2, None, '___sec52'),
- ('Using TensorFlow backend', 2, None, '___sec53'),
- ('Train the model', 2, None, '___sec54'),
- ('Visualizing the results', 2, None, '___sec55'),
- ('Running with Keras', 2, None, '___sec56'),
- ('Final part', 2, None, '___sec57'),
- ('Final visualization', 2, None, '___sec58'),
- ('Fun links', 2, None, '___sec59')]}
+ '___sec41'),
+ ('3D volumes of neurons', 2, None, '___sec42'),
+ ('Layers used to build CNNs', 2, None, '___sec43'),
+ ('Transforming images', 2, None, '___sec44'),
+ ('CNNs in brief', 2, None, '___sec45')]}
end of tocinfo -->
@@ -199,7 +178,7 @@ MathJax.Hub.Config({
[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
-
Oct 5, 2020
+Oct 6, 2020
@@ -208,7 +187,7 @@ MathJax.Hub.Config({
- 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:
-pip3 install keras
+pip install keras
or look up the instructions here.
@@ -1769,18 +1748,21 @@ or look up the instructions here
-
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
@@ -1840,9 +1822,183 @@ ax.set_xlabel(&
plt.show()
+
+
+
The Breast Cancer Data, now with Keras
+
+
+
+
+
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')
+
+
-
Which activation function should I use?
+Which activation function should I use?
The Back propagation algorithm we derived above works by going from
@@ -1871,7 +2027,7 @@ learn at widely different speeds
-
Is the Logistic activation function (Sigmoid) our choice?
+Is the Logistic activation function (Sigmoid) our choice?
Although this unfortunate behavior has been empirically observed for
@@ -1901,7 +2057,7 @@ better than the logistic function in deep networks).
-
The derivative of the Logistic funtion
+The derivative of the Logistic funtion
Looking at the logistic activation function, when inputs become large
@@ -1937,7 +2093,7 @@ fast to compute).
-
The RELU function family
+The RELU function family
The ReLU activation function suffers from a problem known as the dying
@@ -1964,7 +2120,7 @@ $$
-
Which activation function should we use?
+Which activation function should we use?
In general it seems that the ELU activation function is better than
@@ -1984,7 +2140,7 @@ bootstrap to evaluate other activation functions.
-
A top-down perspective on Neural networks
+A top-down perspective on Neural networks
The first thing we would like to do is divide the data into two or three
@@ -2026,7 +2182,7 @@ supervised learning.
-
Limitations of supervised learning with deep networks
+Limitations of supervised learning with deep networks
Like all statistical methods, supervised learning using neural
@@ -2052,13 +2208,13 @@ Some of these remarks are particular to DNNs, others are shared by all supervise
-
Convolutional Neural Networks (recognizing images)
+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
+of deep learning methods. The success in for example image
classifications have made them a central tool for most machine
learning practitioners.
@@ -2091,7 +2247,7 @@ Another good read is the article here Regular NNs don’t scale well to full images
+Regular NNs don’t scale well to full images
As an example, consider
@@ -2119,7 +2275,7 @@ would quickly lead to possible overfitting.
-
3D volumes of neurons
+3D volumes of neurons
Convolutional Neural Networks take advantage of the fact that the
@@ -2159,7 +2315,7 @@ dimension.
-
Layers used to build CNNs
+Layers used to build CNNs
A simple CNN is a sequence of layers, and every layer of a CNN
@@ -2182,7 +2338,7 @@ A simple CNN for image classification could have the architecture:
-
Transforming images
+Transforming images
CNNs transform the original image layer by layer from the original
@@ -2201,7 +2357,7 @@ are consistent with the labels in the training set for each image.
-
CNNs in brief
+CNNs in brief
In summary:
@@ -2220,511 +2376,6 @@ the course
and the slides of CS231 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.
-
-
-
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).
-
-
-
-
-
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:
-$$
-(n_{inputs},\, n_{pixels, width},\, n_{pixels, height},\, depth) .
-$$
-
-
-
-
-
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.
-
-
-
-
-
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.
-
-
-
-
-
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.
-
-
-
-
-
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.
-
-
-
-
-
Prerequisites: Collect and pre-process data
-
-
-
-
# 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()
-
-
-
-
-
Importing Keras and Tensorflow
-
-
-
-
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)
-
-
-
-
-
Using TensorFlow backend
-
-
-We need to define model and architecture and choose cost function and optmizer.
-
-
-
-
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})
-
-
-
-
-
Train the model
-
-
-We need now to train the model, evaluate it and test its performance on test data, and eventually include hyperparameters.
-
-
-
-
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
-
-
-
-
-
Visualizing the results
-
-
-
-
-
# 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()
-
-
-
-
-
Running with Keras
-
-
-
-
-
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)
-
-
-
-
-
Final part
-
-
-
-
-
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()
-
-
-
-
-
Final visualization
-
-
-
-
-
# 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()
-
-
-
-
-
Fun links
-
-
-
diff --git a/doc/pub/week41/ipynb/ipynb-week41-src.tar.gz b/doc/pub/week41/ipynb/ipynb-week41-src.tar.gz
index 6b1ffac99..a380d35a8 100644
Binary files a/doc/pub/week41/ipynb/ipynb-week41-src.tar.gz and b/doc/pub/week41/ipynb/ipynb-week41-src.tar.gz differ
diff --git a/doc/pub/week41/ipynb/week41.ipynb b/doc/pub/week41/ipynb/week41.ipynb
index 335842002..9cd8d691b 100644
--- a/doc/pub/week41/ipynb/week41.ipynb
+++ b/doc/pub/week41/ipynb/week41.ipynb
@@ -10,7 +10,7 @@
" \n",
"**Morten Hjorth-Jensen**, Department of Physics, University of Oslo and Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University\n",
"\n",
- "Date: **Oct 5, 2020**\n",
+ "Date: **Oct 6, 2020**\n",
"\n",
"Copyright 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license\n",
"\n",
@@ -21,7 +21,7 @@
"\n",
"* Thursday: Building our own Feed-forward Neural Network\n",
"\n",
- "* Friday: Playing around with our own Feed-forward Neural Network and introduction to TensorFlow. Start convolutional Neural Networks.\n",
+ "* Friday: Playing around with our own Feed-forward Neural Network and introduction to TensorFlow. Start convolutional Neural Networks (CNN).\n",
"\n",
"Reading suggestions for both days: [Aurelien Geron's chapters 10-11](https://github.com/CompPhysics/MachineLearning/blob/master/doc/T\\\n",
"extbooks/TensorflowML.pdf) and Hastie et al chapter 11.\n",
@@ -1814,7 +1814,7 @@
},
"outputs": [],
"source": [
- "pip3 install keras"
+ "pip install keras"
]
},
{
@@ -1832,18 +1832,21 @@
},
"outputs": [],
"source": [
- "from keras.models import Sequential\n",
- "from keras.layers import Dense\n",
- "from keras.regularizers import l2\n",
- "from keras.optimizers import SGD\n",
+ "import tensorflow as tf\n",
+ "from tensorflow.keras.layers import Input\n",
+ "from tensorflow.keras.models import Sequential #This allows appending layers to existing models\n",
+ "from tensorflow.keras.layers import Dense #This allows defining the characteristics of a particular layer\n",
+ "from tensorflow.keras import optimizers #This allows using whichever optimiser we want (sgd,adam,RMSprop)\n",
+ "from tensorflow.keras import regularizers #This allows using whichever regularizer we want (l1,l2,l1_l2)\n",
+ "from tensorflow.keras.utils import to_categorical #This allows using categorical cross entropy as the cost function\n",
"\n",
"def create_neural_network_keras(n_neurons_layer1, n_neurons_layer2, n_categories, eta, lmbd):\n",
" model = Sequential()\n",
- " model.add(Dense(n_neurons_layer1, activation='sigmoid', kernel_regularizer=l2(lmbd)))\n",
- " model.add(Dense(n_neurons_layer2, activation='sigmoid', kernel_regularizer=l2(lmbd)))\n",
+ " model.add(Dense(n_neurons_layer1, activation='sigmoid', kernel_regularizer=regularizers.l2(lmbd)))\n",
+ " model.add(Dense(n_neurons_layer2, activation='sigmoid', kernel_regularizer=regularizers.l2(lmbd)))\n",
" model.add(Dense(n_categories, activation='softmax'))\n",
" \n",
- " sgd = SGD(lr=eta)\n",
+ " sgd = optimizers.SGD(lr=eta)\n",
" model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])\n",
" \n",
" return model"
@@ -1915,6 +1918,189 @@
"plt.show()"
]
},
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## The Breast Cancer Data, now with Keras"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 26,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "\n",
+ "import tensorflow as tf\n",
+ "from tensorflow.keras.layers import Input\n",
+ "from tensorflow.keras.models import Sequential #This allows appending layers to existing models\n",
+ "from tensorflow.keras.layers import Dense #This allows defining the characteristics of a particular layer\n",
+ "from tensorflow.keras import optimizers #This allows using whichever optimiser we want (sgd,adam,RMSprop)\n",
+ "from tensorflow.keras import regularizers #This allows using whichever regularizer we want (l1,l2,l1_l2)\n",
+ "from tensorflow.keras.utils import to_categorical #This allows using categorical cross entropy as the cost function\n",
+ "import numpy as np\n",
+ "import matplotlib.pyplot as plt\n",
+ "import seaborn as sns\n",
+ "from sklearn.model_selection import train_test_split as splitter\n",
+ "from sklearn.datasets import load_breast_cancer\n",
+ "import pickle\n",
+ "import os \n",
+ "\n",
+ "\n",
+ "\"\"\"Load breast cancer dataset\"\"\"\n",
+ "\n",
+ "np.random.seed(0) #create same seed for random number every time\n",
+ "\n",
+ "cancer=load_breast_cancer() #Download breast cancer dataset\n",
+ "\n",
+ "inputs=cancer.data #Feature matrix of 569 rows (samples) and 30 columns (parameters)\n",
+ "outputs=cancer.target #Label array of 569 rows (0 for benign and 1 for malignant)\n",
+ "labels=cancer.feature_names[0:30]\n",
+ "\n",
+ "print('The content of the breast cancer dataset is:') #Print information about the datasets\n",
+ "print(labels)\n",
+ "print('-------------------------')\n",
+ "print(\"inputs = \" + str(inputs.shape))\n",
+ "print(\"outputs = \" + str(outputs.shape))\n",
+ "print(\"labels = \"+ str(labels.shape))\n",
+ "\n",
+ "x=inputs #Reassign the Feature and Label matrices to other variables\n",
+ "y=outputs\n",
+ "\n",
+ "#%% \n",
+ "\n",
+ "# Visualisation of dataset (for correlation analysis)\n",
+ "\n",
+ "plt.figure()\n",
+ "plt.scatter(x[:,0],x[:,2],s=40,c=y,cmap=plt.cm.Spectral)\n",
+ "plt.xlabel('Mean radius',fontweight='bold')\n",
+ "plt.ylabel('Mean perimeter',fontweight='bold')\n",
+ "plt.show()\n",
+ "\n",
+ "plt.figure()\n",
+ "plt.scatter(x[:,5],x[:,6],s=40,c=y, cmap=plt.cm.Spectral)\n",
+ "plt.xlabel('Mean compactness',fontweight='bold')\n",
+ "plt.ylabel('Mean concavity',fontweight='bold')\n",
+ "plt.show()\n",
+ "\n",
+ "\n",
+ "plt.figure()\n",
+ "plt.scatter(x[:,0],x[:,1],s=40,c=y,cmap=plt.cm.Spectral)\n",
+ "plt.xlabel('Mean radius',fontweight='bold')\n",
+ "plt.ylabel('Mean texture',fontweight='bold')\n",
+ "plt.show()\n",
+ "\n",
+ "plt.figure()\n",
+ "plt.scatter(x[:,2],x[:,1],s=40,c=y,cmap=plt.cm.Spectral)\n",
+ "plt.xlabel('Mean perimeter',fontweight='bold')\n",
+ "plt.ylabel('Mean compactness',fontweight='bold')\n",
+ "plt.show()\n",
+ "\n",
+ "\n",
+ "# Generate training and testing datasets\n",
+ "\n",
+ "#Select features relevant to classification (texture,perimeter,compactness and symmetery) \n",
+ "#and add to input matrix\n",
+ "\n",
+ "temp1=np.reshape(x[:,1],(len(x[:,1]),1))\n",
+ "temp2=np.reshape(x[:,2],(len(x[:,2]),1))\n",
+ "X=np.hstack((temp1,temp2)) \n",
+ "temp=np.reshape(x[:,5],(len(x[:,5]),1))\n",
+ "X=np.hstack((X,temp)) \n",
+ "temp=np.reshape(x[:,8],(len(x[:,8]),1))\n",
+ "X=np.hstack((X,temp)) \n",
+ "\n",
+ "X_train,X_test,y_train,y_test=splitter(X,y,test_size=0.1) #Split datasets into training and testing\n",
+ "\n",
+ "y_train=to_categorical(y_train) #Convert labels to categorical when using categorical cross entropy\n",
+ "y_test=to_categorical(y_test)\n",
+ "\n",
+ "del temp1,temp2,temp\n",
+ "\n",
+ "# %%\n",
+ "\n",
+ "# Define tunable parameters\"\n",
+ "\n",
+ "eta=np.logspace(-3,-1,3) #Define vector of learning rates (parameter to SGD optimiser)\n",
+ "lamda=0.01 #Define hyperparameter\n",
+ "n_layers=2 #Define number of hidden layers in the model\n",
+ "n_neuron=np.logspace(0,3,4,dtype=int) #Define number of neurons per layer\n",
+ "epochs=100 #Number of reiterations over the input data\n",
+ "batch_size=100 #Number of samples per gradient update\n",
+ "\n",
+ "# %%\n",
+ "\n",
+ "\"\"\"Define function to return Deep Neural Network model\"\"\"\n",
+ "\n",
+ "def NN_model(inputsize,n_layers,n_neuron,eta,lamda):\n",
+ " model=Sequential() \n",
+ " for i in range(n_layers): #Run loop to add hidden layers to the model\n",
+ " if (i==0): #First layer requires input dimensions\n",
+ " model.add(Dense(n_neuron,activation='relu',kernel_regularizer=regularizers.l2(lamda),input_dim=inputsize))\n",
+ " else: #Subsequent layers are capable of automatic shape inferencing\n",
+ " model.add(Dense(n_neuron,activation='relu',kernel_regularizer=regularizers.l2(lamda)))\n",
+ " model.add(Dense(2,activation='softmax')) #2 outputs - ordered and disordered (softmax for prob)\n",
+ " sgd=optimizers.SGD(lr=eta)\n",
+ " model.compile(loss='categorical_crossentropy',optimizer=sgd,metrics=['accuracy'])\n",
+ " return model\n",
+ "\n",
+ " \n",
+ "Train_accuracy=np.zeros((len(n_neuron),len(eta))) #Define matrices to store accuracy scores as a function\n",
+ "Test_accuracy=np.zeros((len(n_neuron),len(eta))) #of learning rate and number of hidden neurons for \n",
+ "\n",
+ "for i in range(len(n_neuron)): #run loops over hidden neurons and learning rates to calculate \n",
+ " for j in range(len(eta)): #accuracy scores \n",
+ " DNN_model=NN_model(X_train.shape[1],n_layers,n_neuron[i],eta[j],lamda)\n",
+ " DNN_model.fit(X_train,y_train,epochs=epochs,batch_size=batch_size,verbose=1)\n",
+ " Train_accuracy[i,j]=DNN_model.evaluate(X_train,y_train)[1]\n",
+ " Test_accuracy[i,j]=DNN_model.evaluate(X_test,y_test)[1]\n",
+ " \n",
+ "\n",
+ "def plot_data(x,y,data,title=None):\n",
+ "\n",
+ " # plot results\n",
+ " fontsize=16\n",
+ "\n",
+ "\n",
+ " fig = plt.figure()\n",
+ " ax = fig.add_subplot(111)\n",
+ " cax = ax.matshow(data, interpolation='nearest', vmin=0, vmax=1)\n",
+ " \n",
+ " cbar=fig.colorbar(cax)\n",
+ " cbar.ax.set_ylabel('accuracy (%)',rotation=90,fontsize=fontsize)\n",
+ " cbar.set_ticks([0,.2,.4,0.6,0.8,1.0])\n",
+ " cbar.set_ticklabels(['0%','20%','40%','60%','80%','100%'])\n",
+ "\n",
+ " # put text on matrix elements\n",
+ " for i, x_val in enumerate(np.arange(len(x))):\n",
+ " for j, y_val in enumerate(np.arange(len(y))):\n",
+ " c = \"${0:.1f}\\\\%$\".format( 100*data[j,i]) \n",
+ " ax.text(x_val, y_val, c, va='center', ha='center')\n",
+ "\n",
+ " # convert axis vaues to to string labels\n",
+ " x=[str(i) for i in x]\n",
+ " y=[str(i) for i in y]\n",
+ "\n",
+ "\n",
+ " ax.set_xticklabels(['']+x)\n",
+ " ax.set_yticklabels(['']+y)\n",
+ "\n",
+ " ax.set_xlabel('$\\\\mathrm{learning\\\\ rate}$',fontsize=fontsize)\n",
+ " ax.set_ylabel('$\\\\mathrm{hidden\\\\ neurons}$',fontsize=fontsize)\n",
+ " if title is not None:\n",
+ " ax.set_title(title)\n",
+ "\n",
+ " plt.tight_layout()\n",
+ "\n",
+ " plt.show()\n",
+ " \n",
+ "plot_data(eta,n_neuron,Train_accuracy, 'training')\n",
+ "plot_data(eta,n_neuron,Test_accuracy, 'testing')"
+ ]
+ },
{
"cell_type": "markdown",
"metadata": {},
@@ -2125,7 +2311,7 @@
"Convolutional neural networks (CNNs) were developed during the last\n",
"decade of the previous century, with a focus on character recognition\n",
"tasks. Nowadays, CNNs are a central element in the spectacular success\n",
- "of dee learning methods. The success in for example image\n",
+ "of deep learning methods. The success in for example image\n",
"classifications have made them a central tool for most machine\n",
"learning practitioners.\n",
"\n",
@@ -2268,566 +2454,7 @@
"For more material on convolutional networks, we strongly recommend\n",
"the course\n",
"[IN5400 – Machine Learning for Image Analysis](https://www.uio.no/studier/emner/matnat/ifi/IN5400/index-eng.html)\n",
- "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).\n",
- "\n",
- "\n",
- "## CNNs in more detail, building convolutional neural networks in Tensorflow and Keras\n",
- "\n",
- "\n",
- "As discussed above, CNNs are neural networks built from the assumption that the inputs\n",
- "to the network are 2D images. This is important because the number of features or pixels in images\n",
- "grows very fast with the image size, and an enormous number of weights and biases are needed in order to build an accurate network. \n",
- "\n",
- "As before, we still have our input, a hidden layer and an output. What's novel about convolutional networks\n",
- "are the **convolutional** and **pooling** layers stacked in pairs between the input and the hidden layer.\n",
- "In addition, the data is no longer represented as a 2D feature matrix, instead each input is a number of 2D\n",
- "matrices, typically 1 for each color dimension (Red, Green, Blue). \n",
- "\n",
- "\n",
- "## Setting it up\n",
- "\n",
- "It means that to represent the entire\n",
- "dataset of images, we require a 4D matrix or **tensor**. This tensor has the dimensions:"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "$$\n",
- "(n_{inputs},\\, n_{pixels, width},\\, n_{pixels, height},\\, depth) .\n",
- "$$"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## The MNIST dataset again\n",
- "\n",
- "The MNIST dataset consists of grayscale images with a pixel size of\n",
- "$28\\times 28$, meaning we require $28 \\times 28 = 724$ weights to each\n",
- "neuron in the first hidden layer.\n",
- "\n",
- "If we were to analyze images of size $128\\times 128$ we would require\n",
- "$128 \\times 128 = 16384$ weights to each neuron. Even worse if we were\n",
- "dealing with color images, as most images are, we have an image matrix\n",
- "of size $128\\times 128$ for each color dimension (Red, Green, Blue),\n",
- "meaning 3 times the number of weights $= 49152$ are required for every\n",
- "single neuron in the first hidden layer.\n",
- "\n",
- "\n",
- "## Strong correlations\n",
- "Images typically have strong local correlations, meaning that a small\n",
- "part of the image varies little from its neighboring regions. If for\n",
- "example we have an image of a blue car, we can roughly assume that a\n",
- "small blue part of the image is surrounded by other blue regions.\n",
- "\n",
- "Therefore, instead of connecting every single pixel to a neuron in the\n",
- "first hidden layer, as we have previously done with deep neural\n",
- "networks, we can instead connect each neuron to a small part of the\n",
- "image (in all 3 RGB depth dimensions). The size of each small area is\n",
- "fixed, and known as a [receptive](https://en.wikipedia.org/wiki/Receptive_field).\n",
- "\n",
- "\n",
- "\n",
- "## Layers of a CNN\n",
- "The layers of a convolutional neural network arrange neurons in 3D: width, height and depth. \n",
- "The input image is typically a square matrix of depth 3. \n",
- "\n",
- "A **convolution** is performed on the image which outputs\n",
- "a 3D volume of neurons. The weights to the input are arranged in a number of 2D matrices, known as **filters**.\n",
- "\n",
- "\n",
- "Each filter slides along the input image, taking the dot product\n",
- "between each small part of the image and the filter, in all depth\n",
- "dimensions. This is then passed through a non-linear function,\n",
- "typically the **Rectified Linear (ReLu)** function, which serves as the\n",
- "activation of the neurons in the first convolutional layer. This is\n",
- "further passed through a **pooling layer**, which reduces the size of the\n",
- "convolutional layer, e.g. by taking the maximum or average across some\n",
- "small regions, and this serves as input to the next convolutional\n",
- "layer.\n",
- "\n",
- "\n",
- "## Systematic reduction\n",
- "\n",
- "By systematically reducing the size of the input volume, through\n",
- "convolution and pooling, the network should create representations of\n",
- "small parts of the input, and then from them assemble representations\n",
- "of larger areas. The final pooling layer is flattened to serve as\n",
- "input to a hidden layer, such that each neuron in the final pooling\n",
- "layer is connected to every single neuron in the hidden layer. This\n",
- "then serves as input to the output layer, e.g. a softmax output for\n",
- "classification.\n",
- "\n",
- "\n",
- "## Prerequisites: Collect and pre-process data"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 26,
- "metadata": {
- "collapsed": false
- },
- "outputs": [],
- "source": [
- "# import necessary packages\n",
- "import numpy as np\n",
- "import matplotlib.pyplot as plt\n",
- "from sklearn import datasets\n",
- "\n",
- "\n",
- "# ensure the same random numbers appear every time\n",
- "np.random.seed(0)\n",
- "\n",
- "# display images in notebook\n",
- "%matplotlib inline\n",
- "plt.rcParams['figure.figsize'] = (12,12)\n",
- "\n",
- "\n",
- "# download MNIST dataset\n",
- "digits = datasets.load_digits()\n",
- "\n",
- "# define inputs and labels\n",
- "inputs = digits.images\n",
- "labels = digits.target\n",
- "\n",
- "# RGB images have a depth of 3\n",
- "# our images are grayscale so they should have a depth of 1\n",
- "inputs = inputs[:,:,:,np.newaxis]\n",
- "\n",
- "print(\"inputs = (n_inputs, pixel_width, pixel_height, depth) = \" + str(inputs.shape))\n",
- "print(\"labels = (n_inputs) = \" + str(labels.shape))\n",
- "\n",
- "\n",
- "# choose some random images to display\n",
- "n_inputs = len(inputs)\n",
- "indices = np.arange(n_inputs)\n",
- "random_indices = np.random.choice(indices, size=5)\n",
- "\n",
- "for i, image in enumerate(digits.images[random_indices]):\n",
- " plt.subplot(1, 5, i+1)\n",
- " plt.axis('off')\n",
- " plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')\n",
- " plt.title(\"Label: %d\" % digits.target[random_indices[i]])\n",
- "plt.show()"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Importing Keras and Tensorflow"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 27,
- "metadata": {
- "collapsed": false
- },
- "outputs": [],
- "source": [
- "from keras.utils import to_categorical\n",
- "from sklearn.model_selection import train_test_split\n",
- "\n",
- "# representation of labels\n",
- "labels = to_categorical(labels)\n",
- "\n",
- "# split into train and test data\n",
- "# one-liner from scikit-learn library\n",
- "train_size = 0.8\n",
- "test_size = 1 - train_size\n",
- "X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,\n",
- " test_size=test_size)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Using TensorFlow backend\n",
- "\n",
- "We need to define model and architecture and choose cost function and optmizer."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 28,
- "metadata": {
- "collapsed": false
- },
- "outputs": [],
- "source": [
- "\n",
- "import tensorflow as tf\n",
- "\n",
- "class ConvolutionalNeuralNetworkTensorflow:\n",
- " def __init__(\n",
- " self,\n",
- " X_train,\n",
- " Y_train,\n",
- " X_test,\n",
- " Y_test,\n",
- " n_filters=10,\n",
- " n_neurons_connected=50,\n",
- " n_categories=10,\n",
- " receptive_field=3,\n",
- " stride=1,\n",
- " padding=1,\n",
- " epochs=10,\n",
- " batch_size=100,\n",
- " eta=0.1,\n",
- " lmbd=0.0):\n",
- " \n",
- " self.global_step = tf.Variable(0, dtype=tf.int32, trainable=False, name='global_step')\n",
- " \n",
- " self.X_train = X_train\n",
- " self.Y_train = Y_train\n",
- " self.X_test = X_test\n",
- " self.Y_test = Y_test\n",
- " \n",
- " self.n_inputs, self.input_width, self.input_height, self.depth = X_train.shape\n",
- " \n",
- " self.n_filters = n_filters\n",
- " self.n_downsampled = int(self.input_width*self.input_height*n_filters / 4)\n",
- " self.n_neurons_connected = n_neurons_connected\n",
- " self.n_categories = n_categories\n",
- " \n",
- " self.receptive_field = receptive_field\n",
- " self.stride = stride\n",
- " self.strides = [stride, stride, stride, stride]\n",
- " self.padding = padding\n",
- " \n",
- " self.epochs = epochs\n",
- " self.batch_size = batch_size\n",
- " self.iterations = self.n_inputs // self.batch_size\n",
- " self.eta = eta\n",
- " self.lmbd = lmbd\n",
- " \n",
- " self.create_placeholders()\n",
- " self.create_CNN()\n",
- " self.create_loss()\n",
- " self.create_optimiser()\n",
- " self.create_accuracy()\n",
- " \n",
- " def create_placeholders(self):\n",
- " with tf.name_scope('data'):\n",
- " self.X = tf.placeholder(tf.float32, shape=(None, self.input_width, self.input_height, self.depth), name='X_data')\n",
- " self.Y = tf.placeholder(tf.float32, shape=(None, self.n_categories), name='Y_data')\n",
- " \n",
- " def create_CNN(self):\n",
- " with tf.name_scope('CNN'):\n",
- " \n",
- " # Convolutional layer\n",
- " self.W_conv = self.weight_variable([self.receptive_field, self.receptive_field, self.depth, self.n_filters], name='conv', dtype=tf.float32)\n",
- " b_conv = self.weight_variable([self.n_filters], name='conv', dtype=tf.float32)\n",
- " z_conv = tf.nn.conv2d(self.X, self.W_conv, self.strides, padding='SAME', name='conv') + b_conv\n",
- " a_conv = tf.nn.relu(z_conv)\n",
- " \n",
- " # 2x2 max pooling\n",
- " a_pool = tf.nn.max_pool(a_conv, [1, 2, 2, 1], [1, 2, 2, 1], padding='SAME', name='pool')\n",
- " \n",
- " # Fully connected layer\n",
- " a_pool_flat = tf.reshape(a_pool, [-1, self.n_downsampled])\n",
- " self.W_fc = self.weight_variable([self.n_downsampled, self.n_neurons_connected], name='fc', dtype=tf.float32)\n",
- " b_fc = self.bias_variable([self.n_neurons_connected], name='fc', dtype=tf.float32)\n",
- " a_fc = tf.nn.relu(tf.matmul(a_pool_flat, self.W_fc) + b_fc)\n",
- " \n",
- " # Output layer\n",
- " self.W_out = self.weight_variable([self.n_neurons_connected, self.n_categories], name='out', dtype=tf.float32)\n",
- " b_out = self.bias_variable([self.n_categories], name='out', dtype=tf.float32)\n",
- " self.z_out = tf.matmul(a_fc, self.W_out) + b_out\n",
- " \n",
- " def create_loss(self):\n",
- " with tf.name_scope('loss'):\n",
- " softmax_loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=self.Y, logits=self.z_out))\n",
- " \n",
- " regularizer_loss_conv = tf.nn.l2_loss(self.W_conv)\n",
- " regularizer_loss_fc = tf.nn.l2_loss(self.W_fc)\n",
- " regularizer_loss_out = tf.nn.l2_loss(self.W_out)\n",
- " regularizer_loss = self.lmbd*(regularizer_loss_conv + regularizer_loss_fc + regularizer_loss_out)\n",
- " \n",
- " self.loss = softmax_loss + regularizer_loss\n",
- "\n",
- " def create_accuracy(self):\n",
- " with tf.name_scope('accuracy'):\n",
- " probabilities = tf.nn.softmax(self.z_out)\n",
- " predictions = tf.argmax(probabilities, 1)\n",
- " labels = tf.argmax(self.Y, 1)\n",
- " \n",
- " correct_predictions = tf.equal(predictions, labels)\n",
- " correct_predictions = tf.cast(correct_predictions, tf.float32)\n",
- " self.accuracy = tf.reduce_mean(correct_predictions)\n",
- " \n",
- " def create_optimiser(self):\n",
- " with tf.name_scope('optimizer'):\n",
- " self.optimizer = tf.train.GradientDescentOptimizer(learning_rate=self.eta).minimize(self.loss, global_step=self.global_step)\n",
- " \n",
- " def weight_variable(self, shape, name='', dtype=tf.float32):\n",
- " initial = tf.truncated_normal(shape, stddev=0.1)\n",
- " return tf.Variable(initial, name=name, dtype=dtype)\n",
- " \n",
- " def bias_variable(self, shape, name='', dtype=tf.float32):\n",
- " initial = tf.constant(0.1, shape=shape)\n",
- " return tf.Variable(initial, name=name, dtype=dtype)\n",
- "\n",
- " def fit(self):\n",
- " data_indices = np.arange(self.n_inputs)\n",
- "\n",
- " with tf.Session() as sess:\n",
- " sess.run(tf.global_variables_initializer())\n",
- " for i in range(self.epochs):\n",
- " for j in range(self.iterations):\n",
- " chosen_datapoints = np.random.choice(data_indices, size=self.batch_size, replace=False)\n",
- " batch_X, batch_Y = self.X_train[chosen_datapoints], self.Y_train[chosen_datapoints]\n",
- " \n",
- " sess.run([CNN.loss, CNN.optimizer],\n",
- " feed_dict={CNN.X: batch_X,\n",
- " CNN.Y: batch_Y})\n",
- " accuracy = sess.run(CNN.accuracy,\n",
- " feed_dict={CNN.X: batch_X,\n",
- " CNN.Y: batch_Y})\n",
- " step = sess.run(CNN.global_step)\n",
- " \n",
- " self.train_loss, self.train_accuracy = sess.run([CNN.loss, CNN.accuracy],\n",
- " feed_dict={CNN.X: self.X_train,\n",
- " CNN.Y: self.Y_train})\n",
- " \n",
- " self.test_loss, self.test_accuracy = sess.run([CNN.loss, CNN.accuracy],\n",
- " feed_dict={CNN.X: self.X_test,\n",
- " CNN.Y: self.Y_test})"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Train the model\n",
- "\n",
- "We need now to train the model, evaluate it and test its performance on test data, and eventually include hyperparameters."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 29,
- "metadata": {
- "collapsed": false
- },
- "outputs": [],
- "source": [
- "epochs = 100\n",
- "batch_size = 100\n",
- "n_filters = 10\n",
- "n_neurons_connected = 50\n",
- "n_categories = 10\n",
- "\n",
- "eta_vals = np.logspace(-5, 1, 7)\n",
- "lmbd_vals = np.logspace(-5, 1, 7)\n",
- "CNN_tf = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)\n",
- " \n",
- "for i, eta in enumerate(eta_vals):\n",
- " for j, lmbd in enumerate(lmbd_vals):\n",
- " CNN = ConvolutionalNeuralNetworkTensorflow(X_train, Y_train, X_test, Y_test,\n",
- " n_filters=n_filters, n_neurons_connected=n_neurons_connected,\n",
- " n_categories=n_categories, epochs=epochs, batch_size=batch_size,\n",
- " eta=eta, lmbd=lmbd)\n",
- " CNN.fit()\n",
- " \n",
- " print(\"Learning rate = \", eta)\n",
- " print(\"Lambda = \", lmbd)\n",
- " print(\"Test accuracy: %.3f\" % CNN.test_accuracy)\n",
- " print()\n",
- " \n",
- " CNN_tf[i][j] = CNN"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Visualizing the results"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 30,
- "metadata": {
- "collapsed": false
- },
- "outputs": [],
- "source": [
- "# visual representation of grid search\n",
- "# uses seaborn heatmap, could probably do this in matplotlib\n",
- "import seaborn as sns\n",
- "\n",
- "sns.set()\n",
- "\n",
- "train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n",
- "test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n",
- "\n",
- "for i in range(len(eta_vals)):\n",
- " for j in range(len(lmbd_vals)):\n",
- " CNN = CNN_tf[i][j]\n",
- "\n",
- " train_accuracy[i][j] = CNN.train_accuracy\n",
- " test_accuracy[i][j] = CNN.test_accuracy\n",
- "\n",
- " \n",
- "fig, ax = plt.subplots(figsize = (10, 10))\n",
- "sns.heatmap(train_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n",
- "ax.set_title(\"Training Accuracy\")\n",
- "ax.set_ylabel(\"$\\eta$\")\n",
- "ax.set_xlabel(\"$\\lambda$\")\n",
- "plt.show()\n",
- "\n",
- "fig, ax = plt.subplots(figsize = (10, 10))\n",
- "sns.heatmap(test_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n",
- "ax.set_title(\"Test Accuracy\")\n",
- "ax.set_ylabel(\"$\\eta$\")\n",
- "ax.set_xlabel(\"$\\lambda$\")\n",
- "plt.show()"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "\n",
- "## Running with Keras"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 31,
- "metadata": {
- "collapsed": false
- },
- "outputs": [],
- "source": [
- "from keras.models import Sequential\n",
- "from keras.layers.convolutional import Conv2D\n",
- "from keras.layers.convolutional import MaxPooling2D\n",
- "from keras.layers import Flatten\n",
- "from keras.layers import Dense\n",
- "from keras.regularizers import l2\n",
- "from keras.optimizers import SGD\n",
- "\n",
- "def create_convolutional_neural_network_keras(input_shape, receptive_field,\n",
- " n_filters, n_neurons_connected, n_categories,\n",
- " eta, lmbd):\n",
- " model = Sequential()\n",
- " model.add(Conv2D(n_filters, (receptive_field, receptive_field), input_shape=input_shape, padding='same',\n",
- " activation='relu', kernel_regularizer=l2(lmbd)))\n",
- " model.add(MaxPooling2D(pool_size=(2, 2)))\n",
- " model.add(Flatten())\n",
- " model.add(Dense(n_neurons_connected, activation='relu', kernel_regularizer=l2(lmbd)))\n",
- " model.add(Dense(n_categories, activation='softmax', kernel_regularizer=l2(lmbd)))\n",
- " \n",
- " sgd = SGD(lr=eta)\n",
- " model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])\n",
- " \n",
- " return model\n",
- "\n",
- "epochs = 100\n",
- "batch_size = 100\n",
- "input_shape = X_train.shape[1:4]\n",
- "receptive_field = 3\n",
- "n_filters = 10\n",
- "n_neurons_connected = 50\n",
- "n_categories = 10\n",
- "\n",
- "eta_vals = np.logspace(-5, 1, 7)\n",
- "lmbd_vals = np.logspace(-5, 1, 7)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Final part"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 32,
- "metadata": {
- "collapsed": false
- },
- "outputs": [],
- "source": [
- "CNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)\n",
- " \n",
- "for i, eta in enumerate(eta_vals):\n",
- " for j, lmbd in enumerate(lmbd_vals):\n",
- " CNN = create_convolutional_neural_network_keras(input_shape, receptive_field,\n",
- " n_filters, n_neurons_connected, n_categories,\n",
- " eta, lmbd)\n",
- " CNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0)\n",
- " scores = CNN.evaluate(X_test, Y_test)\n",
- " \n",
- " CNN_keras[i][j] = CNN\n",
- " \n",
- " print(\"Learning rate = \", eta)\n",
- " print(\"Lambda = \", lmbd)\n",
- " print(\"Test accuracy: %.3f\" % scores[1])\n",
- " print()"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Final visualization"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- " # visual representation of grid search\n",
- " # uses seaborn heatmap, could probably do this in matplotlib\n",
- " import seaborn as sns\n",
- " \n",
- " sns.set()\n",
- " \n",
- " train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n",
- " test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n",
- " \n",
- " for i in range(len(eta_vals)):\n",
- " for j in range(len(lmbd_vals)):\n",
- " CNN = CNN_keras[i][j]\n",
- " \n",
- " train_accuracy[i][j] = CNN.evaluate(X_train, Y_train)[1]\n",
- " test_accuracy[i][j] = CNN.evaluate(X_test, Y_test)[1]\n",
- " \n",
- " \n",
- " fig, ax = plt.subplots(figsize = (10, 10))\n",
- " sns.heatmap(train_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n",
- " ax.set_title(\"Training Accuracy\")\n",
- " ax.set_ylabel(\"$\\eta$\")\n",
- " ax.set_xlabel(\"$\\lambda$\")\n",
- " plt.show()\n",
- " \n",
- " fig, ax = plt.subplots(figsize = (10, 10))\n",
- " sns.heatmap(test_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n",
- " ax.set_title(\"Test Accuracy\")\n",
- " ax.set_ylabel(\"$\\eta$\")\n",
- " ax.set_xlabel(\"$\\lambda$\")\n",
- " plt.show()\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## Fun links\n",
- "\n",
- "1. [Self-Driving cars using a convolutional neural network](https://arxiv.org/abs/1604.07316)\n",
- "\n",
- "2. [Abstract art using convolutional neural networks](https://deepdreamgenerator.com/)"
+ "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)."
]
}
],
diff --git a/doc/src/week41/week41.do.txt b/doc/src/week41/week41.do.txt
index ff44ae165..92a4a5db9 100644
--- a/doc/src/week41/week41.do.txt
+++ b/doc/src/week41/week41.do.txt
@@ -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/"
-
-