diff --git a/doc/pub/week41/html/week41-bs.html b/doc/pub/week41/html/week41-bs.html index 54e48bba2..abd36d462 100644 --- a/doc/pub/week41/html/week41-bs.html +++ b/doc/pub/week41/html/week41-bs.html @@ -1,15 +1,15 @@
- + - + -@@ -274,7 +328,7 @@ MathJax.Hub.Config({
-
@@ -310,13 +364,13 @@ MathJax.Hub.Config({
@@ -148,32 +148,33 @@ MathJax.Hub.Config({
-
Reading suggestions for both days: Aurelien Geron's chapters 10-11 and Hastie et al chapter 11. +extbooks/TensorflowML.pdf" target="_blank">Aurelien Geron's chapters 10-11. +For amore in depth discussion on neural networks we recommend Goodfellow et al chapters 6 and 7. For CNNs, see Goodfellow et al chapter 9. chapter 11 and 12 on practicalities and applications
The four equations derived last week provide us with a way of computing the gradient of the cost function. Let us write this out in the form of an algorithm.
@@ -246,7 +247,7 @@ Here it is convenient to use stochastic gradient descent (see the examples below
We are now gong to develop an example based on the MNIST data
@@ -288,7 +289,7 @@ of our network.
Our cost function is given as (see the Logistic regression lectures)
@@ -356,7 +357,7 @@ The back propagation equations need now only a small change, namely the definiti
As an example of the above, relevant for project 2 as well, let us consider a binary class. As discussed in our logistic regression lectures, we defined a cost function in terms of the parameters \( \beta \) as
@@ -418,7 +419,7 @@ In case we use another activation function than the logistic one, we need to eva
One can identify a set of key steps when using neural networks to solve supervised learning problems:
@@ -468,7 +469,7 @@ One can identify a set of key steps when using neural networks to solve supervis
Here we will be using the MNIST dataset, which is readily available through the scikit-learn
@@ -521,7 +522,7 @@ images.
-
Performing analysis before partitioning the dataset is a major error, that can lead to incorrect conclusions.
@@ -586,7 +587,7 @@ collected from 12.00 to 24.00.
-
Our simple feed-forward neural network will consist of an input layer, a single hidden layer and an output layer. The activation \( y \) of each neuron is a weighted sum of inputs, passed through an activation function. In case of the simple perceptron model we have
@@ -672,7 +673,7 @@ which is inspired by probability theory (see logistic regression) and was most c
Typically weights are initialized with small values distributed around zero, drawn from a uniform
@@ -743,7 +744,7 @@ The bias weights \( \hat{b} \) are often initialized to zero, but a small value
-
Denote \( F \) the number of features, \( H \) the number of hidden neurons and \( C \) the number of categories.
@@ -798,7 +799,7 @@ $$ a_{j}^{L} = \frac{\exp{(z_j^{L})}}
Since our data has the dimensions \( X = (n_{inputs}, n_{features}) \) and our weights to the hidden
@@ -844,7 +845,7 @@ $$ output = softmax (\hat{z}^{L}) = (n_{inputs}, n_{categories}) .$$
-
To measure how well our neural network is doing we need to introduce a cost function.
@@ -919,7 +920,7 @@ you got the correct label. The probability of category \( c \) is given by the s
The network is trained by finding the weights and biases that minimize the cost function. One of the most widely used classes of methods is gradient descent and its generalizations. The idea behind gradient descent
@@ -965,7 +966,7 @@ The various optmization methods, with codes and algorithms, are discussed in o
It is common to add an extra term to the cost function, proportional
@@ -1000,7 +1001,7 @@ calculate the gradient efficently.
To more efficently train our network these equations are implemented using matrix operations.
@@ -1054,7 +1055,7 @@ $$ \nabla b_{h} = \sum_{i=1}^{n_{inputs}} \delta_h = (n_{hidden}) .$$
-
As we can see the network does not seem to be learning at all. It seems to be just guessing the label for each image.
@@ -1147,7 +1148,7 @@ Andrew Ng goes through some of these considerations in this Full object-oriented implementation
+
It is very natural to think of the network as an object, with specific instances of the network
@@ -1156,7 +1157,7 @@ being realizations of this object with different hyperparameters. An implementat
-
To measure the performance of our network we evaluate how well it does it data it has never seen before, i.e. the test data.
@@ -1277,7 +1278,7 @@ where \( I \) is the indicator function, \( 1 \) if \( \hat{y}_i = y_i \) and \(
-
We now perform a grid search to find the optimal hyperparameters for the network.
@@ -1307,7 +1308,7 @@ Note that we are only using 1 layer with 50 neurons, and human performance is es
-
-
scikit-learn focuses more
@@ -1394,7 +1395,7 @@ performance overall.
-
-
Now we want to build on the experience gained from our neural network implementation in NumPy and scikit-learn
@@ -1473,7 +1474,7 @@ NumPy arrays.
Tensorflow is an open source library machine learning library
@@ -1506,7 +1507,7 @@ To install tensorflow on Unix/Linux systems, use pip as
-
and/or if you use anaconda, just write (or install from the graphical user interface)
@@ -1514,7 +1515,7 @@ and/or if you use anaconda, just write (or install from the graphical use
-
@@ -1522,14 +1523,14 @@ To install the current release of GPU TensorFlow
-
Keras is a high level neural network
@@ -1538,7 +1539,7 @@ If you have Anaconda installed you may run the following command
-
You can look up the instructions here for more information.
@@ -1549,7 +1550,7 @@ We will to a large extent use keras in this course.
Let us look again at the MINST data set.
@@ -1557,7 +1558,7 @@ Let us look again at the MINST data set.
-
-
-
-
The flexibility of neural networks is also one of their main
@@ -1904,7 +1905,7 @@ will only be able to explore a tiny part of the hyperparameter space.
For many problems you can start with just one or two hidden layers and it will work just fine.
@@ -1924,7 +1925,7 @@ common to reuse parts of a pretrained state-of-the-art network that performs a s
The Back propagation algorithm we derived above works by going from
@@ -1953,7 +1954,7 @@ learn at widely different speeds
Although this unfortunate behavior has been empirically observed for
@@ -1983,7 +1984,7 @@ better than the logistic function in deep networks).
Looking at the logistic activation function, when inputs become large
@@ -2019,7 +2020,7 @@ fast to compute).
The ReLU activation function suffers from a problem known as the dying
@@ -2048,7 +2049,7 @@ $$
In general it seems that the ELU activation function is better than
@@ -2068,7 +2069,7 @@ bootstrap to evaluate other activation functions.
In most cases you can use the ReLU activation function in the hidden layers (or one of its variants).
@@ -2087,7 +2088,7 @@ It is a bit faster to compute than other activation functions, and the gradient
Batch Normalization
@@ -2106,7 +2107,7 @@ mini-batch, from this the name batch normalization.
It is a fairly simple algorithm: at every training step, every neuron (including the input neurons but
@@ -2121,7 +2122,7 @@ hyperparameter \( p \) is called the dropout rate, and it is typically set to 50
A popular technique to lessen the exploding gradients problem is to simply clip the gradients during
@@ -2138,7 +2139,7 @@ Normalization is preferred.
You may find this website very useful. Thx a million to Ghadi for sharing.
@@ -2146,7 +2147,7 @@ You may find this A top-down perspective on Neural networks
+
The first thing we would like to do is divide the data into two or three
@@ -2189,7 +2190,7 @@ supervised learning.
Like all statistical methods, supervised learning using neural
@@ -2216,7 +2217,7 @@ Some of these remarks are particular to DNNs, others are shared by all supervise
Convolutional neural networks (CNNs) were developed during the last
@@ -2255,7 +2256,7 @@ Another good read is the article here Regular NNs don’t scale well to full images
+
As an example, consider
@@ -2283,7 +2284,7 @@ would quickly lead to possible overfitting.
Convolutional Neural Networks take advantage of the fact that the
@@ -2323,7 +2324,7 @@ dimension.
A simple CNN is a sequence of layers, and every layer of a CNN
@@ -2347,7 +2348,7 @@ A simple CNN for image classification could have the architecture:
CNNs transform the original image layer by layer from the original
@@ -2366,7 +2367,7 @@ are consistent with the labels in the training set for each image.
In summary:
@@ -2388,7 +2389,7 @@ and the slides of
-
As discussed above, CNNs are neural networks built from the assumption that the inputs
@@ -2404,7 +2405,7 @@ matrices, typically 1 for each color dimension (Red, Green, Blue).
It means that to represent the entire
@@ -2419,7 +2420,7 @@ $$
The MNIST dataset consists of grayscale images with a pixel size of
@@ -2437,7 +2438,7 @@ single neuron in the first hidden layer.
Images typically have strong local correlations, meaning that a small
@@ -2455,7 +2456,7 @@ fixed, and known as a
-
By systematically reducing the size of the input volume, through
@@ -2492,11 +2493,11 @@ classification.
-
-
-
-
-
@@ -202,25 +256,26 @@ MathJax.Hub.Config({
-
The four equations derived last week provide us with a way of computing the gradient of the cost function. Let us write this out in the form of an algorithm.
@@ -291,7 +346,7 @@ Here it is convenient to use stochastic gradient descent (see the examples below
-
We are now gong to develop an example based on the MNIST data
@@ -329,7 +384,7 @@ of our network.
Our cost function is given as (see the Logistic regression lectures)
@@ -389,7 +444,7 @@ The back propagation equations need now only a small change, namely the definiti
As an example of the above, relevant for project 2 as well, let us consider a binary class. As discussed in our logistic regression lectures, we defined a cost function in terms of the parameters \( \beta \) as
@@ -437,7 +492,7 @@ In case we use another activation function than the logistic one, we need to eva
-
One can identify a set of key steps when using neural networks to solve supervised learning problems:
@@ -475,7 +530,7 @@ One can identify a set of key steps when using neural networks to solve supervis
Here we will be using the MNIST dataset, which is readily available through the scikit-learn
@@ -524,7 +579,7 @@ images.
-
Performing analysis before partitioning the dataset is a major error, that can lead to incorrect conclusions.
@@ -588,7 +643,7 @@ collected from 12.00 to 24.00.
-
Our simple feed-forward neural network will consist of an input layer, a single hidden layer and an output layer. The activation \( y \) of each neuron is a weighted sum of inputs, passed through an activation function. In case of the simple perceptron model we have
@@ -665,7 +720,7 @@ which is inspired by probability theory (see logistic regression) and was most c
-
-
Typically weights are initialized with small values distributed around zero, drawn from a uniform
@@ -727,7 +782,7 @@ The bias weights \( \hat{b} \) are often initialized to zero, but a small value
-
Denote \( F \) the number of features, \( H \) the number of hidden neurons and \( C \) the number of categories.
@@ -773,7 +828,7 @@ $$ a_{j}^{L} = \frac{\exp{(z_j^{L})}}
-
Since our data has the dimensions \( X = (n_{inputs}, n_{features}) \) and our weights to the hidden
@@ -809,7 +864,7 @@ $$ output = softmax (\hat{z}^{L}) = (n_{inputs}, n_{categories}) .$$
-
To measure how well our neural network is doing we need to introduce a cost function.
@@ -879,7 +934,7 @@ you got the correct label. The probability of category \( c \) is given by the s
The network is trained by finding the weights and biases that minimize the cost function. One of the most widely used classes of methods is gradient descent and its generalizations. The idea behind gradient descent
@@ -919,7 +974,7 @@ The various optmization methods, with codes and algorithms, are discussed in o
-
It is common to add an extra term to the cost function, proportional
@@ -952,7 +1007,7 @@ calculate the gradient efficently.
To more efficently train our network these equations are implemented using matrix operations.
@@ -994,7 +1049,7 @@ $$ \nabla b_{h} = \sum_{i=1}^{n_{inputs}} \delta_h = (n_{hidden}) .$$
-
Setting up a Multi-layer perceptron model for classification
+Setting up a Multi-layer perceptron model for classification
Defining the cost function
+Defining the cost function
Example: binary classification problem
+Example: binary classification problem
The Softmax function
+The Softmax function
In case we employ the more general case given by the Softmax equation, we need to evaluate the derivative of the activation function with respect to the activation \( z_i^l \), that is we need
$$
@@ -446,7 +447,7 @@ which in case of the simply binary model reduces to having \( i=j \).
Developing a code for doing neural networks with back propagation
+Developing a code for doing neural networks with back propagation
Collect and pre-process data
+Collect and pre-process data
# import necessary packages
+
# import necessary packages
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
@@ -568,7 +569,7 @@ plt.show()
Train and test datasets
+Train and test datasets
from sklearn.model_selection import train_test_split
+
from sklearn.model_selection import train_test_split
# one-liner from scikit-learn library
train_size = 0.8
@@ -618,7 +619,7 @@ X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=t
Define model and architecture
+Define model and architecture
Layers
+Layers
Weights and biases
+Weights and biases
# building our neural network
+
# building our neural network
n_inputs, n_features = X_train.shape
n_hidden_neurons = 50
@@ -763,7 +764,7 @@ output_bias = np.zeros(n_categories) + 0.01
Feed-forward pass
+Feed-forward pass
Matrix multiplications
+Matrix multiplications
# setup the feed-forward pass, subscript h = hidden layer
+
# setup the feed-forward pass, subscript h = hidden layer
def sigmoid(x):
return 1/(1 + np.exp(-x))
@@ -884,7 +885,7 @@ predictions = predict(X_train)
Choose cost function and optimizer
+Choose cost function and optimizer
Optimizing the cost function
+Optimizing the cost function
Regularization
+Regularization
Matrix multiplication
+Matrix multiplication
# to categorical turns our integer vector into a onehot representation
+
# to categorical turns our integer vector into a onehot representation
from sklearn.metrics import accuracy_score
# one-hot in numpy
@@ -1127,7 +1128,7 @@ lmbd = 0.01
Improving performance
+Improving performance
Full object-oriented implementation
class NeuralNetwork:
+
class NeuralNetwork:
def __init__(
self,
X_data,
@@ -1260,7 +1261,7 @@ being realizations of this object with different hyperparameters. An implementat
Evaluate model performance on test data
+Evaluate model performance on test data
epochs = 100
+
epochs = 100
batch_size = 100
dnn = NeuralNetwork(X_train, Y_train_onehot, eta=eta, lmbd=lmbd, epochs=epochs, batch_size=batch_size,
@@ -1298,7 +1299,7 @@ test_predict = dnn.predict(X_test)
Adjust hyperparameters
+Adjust hyperparameters
eta_vals = np.logspace(-5, 1, 7)
+
eta_vals = np.logspace(-5, 1, 7)
lmbd_vals = np.logspace(-5, 1, 7)
# store the models for later use
DNN_numpy = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
@@ -1332,12 +1333,12 @@ DNN_numpy = np.zeros((len(eta_vals),
-
Visualization
+Visualization
# visual representation of grid search
+
# visual representation of grid search
# uses seaborn heatmap, you can also do this with matplotlib imshow
import seaborn as sns
@@ -1375,7 +1376,7 @@ plt.show()
scikit-learn implementation
+scikit-learn implementation
from sklearn.neural_network import MLPClassifier
+
from sklearn.neural_network import MLPClassifier
# store models for later use
DNN_scikit = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
@@ -1415,11 +1416,11 @@ DNN_scikit = np.zeros((len(eta_vals),
-
Visualization
+Visualization
# optional
+
# optional
# visual representation of grid search
# uses seaborn heatmap, could probably do this in matplotlib
import seaborn as sns
@@ -1458,7 +1459,7 @@ plt.show()
Building neural networks in Tensorflow and Keras
+Building neural networks in Tensorflow and Keras
Tensorflow
+Tensorflow
pip3 install tensorflow
+
pip3 install tensorflow
conda create -n tf tensorflow
+
conda create -n tf tensorflow
conda activate tf
conda create -n tf-gpu tensorflow-gpu
+
conda create -n tf-gpu tensorflow-gpu
conda activate tf-gpu
Using Keras
+Using Keras
conda install keras
+
conda install keras
Collect and pre-process data
+Collect and pre-process data
# import necessary packages
+
# import necessary packages
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
@@ -1604,7 +1605,7 @@ plt.show()
from tensorflow.keras.layers import Input
+
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)
@@ -1625,7 +1626,7 @@ X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=t
epochs = 100
+
epochs = 100
batch_size = 100
n_neurons_layer1 = 100
n_neurons_layer2 = 50
@@ -1646,7 +1647,7 @@ lmbd_vals = np.logspace(-5,
-
DNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
+
DNN_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):
@@ -1665,7 +1666,7 @@ lmbd_vals = np.logspace(-5,
-
# optional
+
# optional
# visual representation of grid search
# uses seaborn heatmap, could probably do this in matplotlib
import seaborn as sns
@@ -1701,12 +1702,12 @@ plt.show()
The Breast Cancer Data, now with Keras
+The Breast Cancer Data, now with Keras
import tensorflow as tf
+
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
@@ -1876,7 +1877,7 @@ plot_data(eta,n_neuron,Test_accuracy, 'testing&
Fine-tuning neural network hyperparameters
+Fine-tuning neural network hyperparameters
Hidden layers
+Hidden layers
Which activation function should I use?
+Which activation function should I use?
Is the Logistic activation function (Sigmoid) our choice?
+Is the Logistic activation function (Sigmoid) our choice?
The derivative of the Logistic funtion
+The derivative of the Logistic funtion
The RELU function family
+The RELU function family
Which activation function should we use?
+Which activation function should we use?
More on activation functions, output layers
+More on activation functions, output layers
Batch Normalization
+Batch Normalization
Dropout
+Dropout
Gradient Clipping
+Gradient Clipping
A very nice website on Neural Networks
+A very nice website on Neural Networks
A top-down perspective on Neural networks
Limitations of supervised learning with deep networks
+Limitations of supervised learning with deep networks
Convolutional Neural Networks (recognizing images)
+Convolutional Neural Networks (recognizing images)
Regular NNs don’t scale well to full images
3D volumes of neurons
+3D volumes of neurons
Layers used to build CNNs
+Layers used to build CNNs
Transforming images
+Transforming images
CNNs in brief
+CNNs in brief
CNNs in more detail, building convolutional neural networks in Tensorflow and Keras
+CNNs in more detail, building convolutional neural networks in Tensorflow and Keras
Setting it up
+Setting it up
The MNIST dataset again
+The MNIST dataset again
Strong correlations
+Strong correlations
Layers of a CNN
+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.
@@ -2477,7 +2478,7 @@ layer.
Systematic reduction
+Systematic reduction
Prerequisites: Collect and pre-process data
+Prerequisites: Collect and pre-process data
# import necessary packages
+
# import necessary packages
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
@@ -2541,11 +2542,11 @@ plt.show()
Importing Keras and Tensorflow
+Importing Keras and Tensorflow
from tensorflow.keras import datasets, layers, models
+
from tensorflow.keras import datasets, layers, models
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
@@ -2572,12 +2573,12 @@ X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=t
Running with Keras
+Running with Keras
def create_convolutional_neural_network_keras(input_shape, receptive_field,
+
def create_convolutional_neural_network_keras(input_shape, receptive_field,
n_filters, n_neurons_connected, n_categories,
eta, lmbd):
model = Sequential()
@@ -2608,12 +2609,12 @@ lmbd_vals = np.logspace(-5, Final part
+
Final part
CNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
+
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):
@@ -2634,12 +2635,12 @@ lmbd_vals = np.logspace(-5, Final visualization
+
Final visualization
# visual representation of grid search
+
# visual representation of grid search
# uses seaborn heatmap, could probably do this in matplotlib
import seaborn as sns
@@ -2674,7 +2675,7 @@ plt.show()
Fun links
+Fun links
Week 41 Tensor flow and Deep Learning, Convolutional Neural Networks
Week 41 Constructing a Neural Network code, Tensor flow and start Convolutional Neural Networks
Oct 10, 2020
Oct 9, 2021
-Plan for week 41
+Plan for week 41
-
Reading suggestions for both days: Aurelien Geron's chapters 10-11 and Hastie et al chapter 11.
+extbooks/TensorflowML.pdf" target="_blank">Aurelien Geron's chapters 10-11.
+For amore in depth discussion on neural networks we recommend Goodfellow et al chapters 6 and 7. For CNNs, see Goodfellow et al chapter 9. chapter 11 and 12 on practicalities and applications
-Setting up the Back propagation algorithm
+Setting up the Back propagation algorithm
Setting up a Multi-layer perceptron model for classification
+Setting up a Multi-layer perceptron model for classification
-Defining the cost function
+Defining the cost function
-Example: binary classification problem
+Example: binary classification problem
-The Softmax function
+The Softmax function
In case we employ the more general case given by the Softmax equation, we need to evaluate the derivative of the activation function with respect to the activation \( z_i^l \), that is we need
$$
\frac{\partial f(z_i^l)}{\partial w_{jk}^l} =
@@ -459,7 +514,7 @@ which in case of the simply binary model reduces to having \( i=j \).
Developing a code for doing neural networks with back propagation
+Developing a code for doing neural networks with back propagation
-Collect and pre-process data
+Collect and pre-process data
# import necessary packages
+
# import necessary packages
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
@@ -570,7 +625,7 @@ plt.show()
-Train and test datasets
+Train and test datasets
from sklearn.model_selection import train_test_split
+
from sklearn.model_selection import train_test_split
# one-liner from scikit-learn library
train_size = 0.8
@@ -619,7 +674,7 @@ X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=t
-Define model and architecture
+Define model and architecture
Layers
+Layers
Weights and biases
+Weights and biases
# building our neural network
+
# building our neural network
n_inputs, n_features = X_train.shape
n_hidden_neurons = 50
@@ -746,7 +801,7 @@ output_bias = np.zeros(n_categories) + 0.01
-Feed-forward pass
+Feed-forward pass
Matrix multiplications
+Matrix multiplications
# setup the feed-forward pass, subscript h = hidden layer
+
# setup the feed-forward pass, subscript h = hidden layer
def sigmoid(x):
return 1/(1 + np.exp(-x))
@@ -848,7 +903,7 @@ predictions = predict(X_train)
-Choose cost function and optimizer
+Choose cost function and optimizer
-Optimizing the cost function
+Optimizing the cost function
Regularization
+Regularization
-Matrix multiplication
+Matrix multiplication
# to categorical turns our integer vector into a onehot representation
+
# to categorical turns our integer vector into a onehot representation
from sklearn.metrics import accuracy_score
# one-hot in numpy
@@ -1066,7 +1121,7 @@ lmbd = 0.01
-Improving performance
+Improving performance