Let's first define a few variables that we will need to use:
a) L= total number of layers in the network
b)
c) K= number of output units/classes
Recall that in neural networks, we may have many output nodes. We denote
Our cost function for neural networks is going to be a generalization of the one we used for logistic regression.
Recall that the cost function for regularized logistic regression was:
For neural networks, it is going to be slightly more complicated:
We have added a few nested summations to account for our multiple output nodes. In the first part of the equation, between the square brackets, we have an additional nested summation that loops through the number of output nodes.
In the regularization part, after the square brackets, we must account for multiple theta matrices. The number of columns in our current theta matrix is equal to the number of nodes in our current layer (including the bias unit). The number of rows in our current theta matrix is equal to the number of nodes in the next layer (excluding the bias unit). As before with logistic regression, we square every term.
Note:
"Backpropagation" is neural-network terminology for minimizing our cost function, just like what we were doing with gradient descent in logistic and linear regression.
Our goal is to compute:
That is, we want to minimize our cost function J using an optimal set of parameters in theta.
In this section we'll look at the equations we use to compute the partial derivative of J(Θ):
In back propagation we're going to compute for every node:
Recall that
For the last layer, we can compute the vector of delta values with:
Where L is our total number of layers and
To get the delta values of the layers before the last layer, we can use an equation that steps us back from right to left:
The delta values of layer l are calculated by multiplying the delta values in the next layer with the theta matrix of layer l. We then element-wise multiply that with a function called g', or g-prime, which is the derivative of the activation function g evaluated with the input values given by z(l).
The g-prime derivative terms can also be written out as:
This can be shown and proved in calculus.
The full back propagation equation for the inner nodes is then:
A. Ng states that the derivation and proofs are complicated and involved, but you can still implement the above equations to do back propagation without knowing the details.
We can compute our partial derivative terms by multiplying our activation values and our error values for each training example t:
This however ignores regularization, which we'll deal with later.
Note:
We can now take all these equations and put them together into a backpropagation algorithm:
Back propagation Algorithm
Given training set
For training example t =1 to m:
The capital-delta matrix is used as an "accumulator" to add up our values as we go along and eventually compute our partial derivative.
The actual proof is quite involved, but, the
The cost function is:
If we consider simple non-multiclass classification (k = 1) and disregard regularization, the cost is computed with:
More intuitively you can think of that equation roughly as:
Intuitively,
More formally, the delta values are actually the derivative of the cost function:
Recall that our derivative is the slope of a line tangent to the cost function, so the steeper the slope the more incorrect we are.
Note: In lecture, sometimes i is used to index a training example. Sometimes it is used to index a unit in a layer. In the Back Propagation Algorithm described here, t is used to index a training example rather than overloading the use of i.
With neural networks, we are working with sets of matrices:
In order to use optimizing functions such as "fminunc()", we will want to "unroll" all the elements and put them into one long vector:
12thetaVector = [ Theta1(:); Theta2(:); Theta3(:); ]deltaVector = [ D1(:); D2(:); D3(:) ]
If the dimensions of Theta1 is 10x11, Theta2 is 10x11 and Theta3 is 1x11, then we can get back our original matrices from the "unrolled" versions as follows:
1234Theta1 = reshape(thetaVector(1:110),10,11)Theta2 = reshape(thetaVector(111:220),10,11)Theta3 = reshape(thetaVector(221:231),1,11)
NOTE: The lecture slides show an example neural network with 3 layers. However, 3 theta matrices are defined: Theta1, Theta2, Theta3. There should be only 2 theta matrices: Theta1 (10 x 11), Theta2 (1 x 11).
Gradient checking will assure that our backpropagation works as intended.
We can approximate the derivative of our cost function with:
With multiple theta matrices, we can approximate the derivative with respect to
A good small value for
We are only adding or subtracting epsilon to the
123456789epsilon = 1e-4;for i = 1:n,thetaPlus = theta;thetaPlus(i) += epsilon;thetaMinus = theta;thetaMinus(i) -= epsilon;gradApprox(i) = (J(thetaPlus) - J(thetaMinus))/(2*epsilon)end;
We then want to check that gradApprox ≈ deltaVector.
Once you've verified once that your backpropagation algorithm is correct, then you don't need to compute gradApprox again. The code to compute gradApprox is very slow.
Initializing all theta weights to zero does not work with neural networks. When we backpropagate, all nodes will update to the same value repeatedly.
Instead we can randomly initialize our weights:
Initialize each
123456If the dimensions of Theta1 is 10x11, Theta2 is 10x11 and Theta3 is 1x11.Theta1 = rand(10,11) * (2 * INIT_EPSILON) - INIT_EPSILON;Theta2 = rand(10,11) * (2 * INIT_EPSILON) - INIT_EPSILON;Theta3 = rand(1,11) * (2 * INIT_EPSILON) - INIT_EPSILON;
rand(x,y) will initialize a matrix of random real numbers between 0 and 1. (Note: this epsilon is unrelated to the epsilon from Gradient Checking)
Why use this method? This paper may be useful: https://web.stanford.edu/class/ee373b/nninitialization.pdf
First, pick a network architecture; choose the layout of your neural network, including how many hidden units in each layer and how many layers total.
Training a Neural Network
When we perform forward and back propagation, we loop on every training example:
123for i = 1:m,Perform forward propagation and backpropagation using example (x(i),y(i))(Get activations a(l) and delta terms d(l) for l = 2,...,L
This tutorial will guide you on how to use the classifier provided in exercise 3 to classify you own images like this:
The classifier provided expects 20 x 20 pixels black and white images converted in a row vector of 400 real numbers like this
1[ 0.14532, 0.12876, ...]
Each pixel is represented by a real number between -1.0 to 1.0, meaning -1.0 equal black and 1.0 equal white (any number in between is a shade of gray, and number 0.0 is exactly the middle gray).
.jpg and color RGB images
The most common image format that can be read by Octave is .jpg using function that outputs a three-dimensional matrix of integer numbers from 0 to 255, representing the height x width x 3 integers as indexes of a color map for each pixel (explaining color maps is beyond scope).
1Image3DmatrixRGB = imread("myOwnPhoto.jpg");
A common way to convert color images to black & white, is to convert them to a YIQ standard and keep only the Y component that represents the luma information (black & white). I and Q represent the chrominance information (color).Octave has a function rgb2ntsc() that outputs a similar three-dimensional matrix but of real numbers from -1.0 to 1.0, representing the height x width x 3 (Y luma, I in-phase, Q quadrature) intensity for each pixel.
1Image3DmatrixYIQ = rgb2ntsc(MyImageRGB);
To obtain the Black & White component just discard the I and Q matrices. This leaves a two-dimensional matrix of real numbers from -1.0 to 1.0 representing the height x width pixels black & white values.
1Image2DmatrixBW = Image3DmatrixYIQ(:,:,1);
It is useful to crop the original image to be as square as possible. The way to crop a matrix is by selecting an area inside the original B&W image and copy it to a new matrix. This is done by selecting the rows and columns that define the area. In other words, it is copying a rectangular subset of the matrix like this:
12croppedImage = Image2DmatrixBW(origen1:size1, origin2:size2);
Cropping does not have to be all the way to a square.It could be cropping just a percentage of the way to a squareso you can leave more of the image intact. The next step of scaling will take care of streaching the image to fit a square.
The classifier provided was trained with 20 x 20 pixels images so we need to scale our photos to meet. It may cause distortion depending on the height and width ratio of the cropped original photo. There are many ways to scale a photo but we are going to use the simplest one. We lay a scaled grid of 20 x 20 over the original photo and take a sample pixel on the center of each grid. To lay a scaled grid, we compute two vectors of 20 indexes each evenly spaced on the original size of the image. One for the height and one for the width of the image. For example, in an image of 320 x 200 pixels will produce to vectors like
1[9 25 41 57 73 ... 313] % 20 indexes
1[6 16 26 36 46 ... 196] % 20 indexes
Copy the value of each pixel located by the grid of these indexes to a new matrix. Ending up with a matrix of 20 x 20 real numbers.
The classifier provided was trained with images of white digits over gray background. Specifically, the 20 x 20 matrix of real numbers ONLY range from 0.0 to 1.0 instead of the complete black & white range of -1.0 to 1.0, this means that we have to normalize our photos to a range 0.0 to 1.0 for this classifier to work. But also, we invert the black and white colors because is easier to "draw" black over white on our photos and we need to get white digits. So in short, we invert black and white and stretch black to gray.
Some times our photos are automatically rotated like in our celular phones. The classifier provided can not recognize rotated images so we may need to rotate it back sometimes. This can be done with an Octave function rot90() like this.
1ImageAligned = rot90(Image, rotationStep);
Where rotationStep is an integer: -1 mean rotate 90 degrees CCW and 1 mean rotate 90 degrees CW.
Define the function name, the output variable and three parameters, one for the filename of our photo, one optional cropping percentage (if not provided will default to zero, meaning no cropping) and the last optional rotation of the image (if not provided will default to cero, meaning no rotation).
12function vectorImage = imageTo20x20Gray(fileName, cropPercentage=0, rotStep=0)
Read the file as a RGB image and convert it to Black & White 2D matrix (see the introduction).
12345678% Read as RGB imageImage3DmatrixRGB = imread(fileName);% Convert to NTSC image (YIQ)Image3DmatrixYIQ = rgb2ntsc(Image3DmatrixRGB );% Convert to grays keeping only luminance (Y)% ...and discard chrominance (IQ)Image2DmatrixBW = Image3DmatrixYIQ(:,:,1);
Establish the final size of the cropped image.
1234567891011% Get the size of your imageoldSize = size(Image2DmatrixBW);% Obtain crop size toward centered square (cropDelta)% ...will be zero for the already minimum dimension% ...and if the cropPercentage is zero,% ...both dimensions are zero% ...meaning that the original image will go intact to croppedImagecropDelta = floor((oldSize - min(oldSize)) .* (cropPercentage/100));% Compute the desired final pixel size for the original imagefinalSize = oldSize - cropDelta;
Obtain the origin and amount of the columns and rows to be copied to the cropped image.
12345678% Compute each dimension origin for cropingcropOrigin = floor(cropDelta / 2) + 1;% Compute each dimension copying sizecopySize = cropOrigin + finalSize - 1;% Copy just the desired cropped image from the original B&W imagecroppedImage = Image2DmatrixBW( ...cropOrigin(1):copySize(1), cropOrigin(2):copySize(2));
Compute the scale and compute back the new size. This last step is extra. It is computed back so the code keeps general for future modification of the classifier size. For example: if changed from 20 x 20 pixels to 30 x 30. Then the we only need to change the line of code where the scale is computed.
12345% Resolution scale factors: [rows cols]scale = [20 20] ./ finalSize;% Compute back the new image size (extra step to keep code general)newSize = max(floor(scale .* finalSize),1);
Compute two sets of 20 indexes evenly spaced. One over the original height and one over the original width of the image.
1234% Compute a re-sampled set of indices:rowIndex = min(round(((1:newSize(1))-0.5)./scale(1)+0.5), finalSize(1));colIndex = min(round(((1:newSize(2))-0.5)./scale(2)+0.5), finalSize(2));
Copy just the indexed values from old image to get new image of 20 x 20 real numbers. This is called "sampling" because it copies just a sample pixel indexed by a grid. All the sample pixels make the new image.
123% Copy just the indexed values from old image to get new imagenewImage = croppedImage(rowIndex,colIndex,:);
Rotate the matrix using the rot90() function with the rotStep parameter: -1 is CCW, 0 is no rotate, 1 is CW.
123% Rotate if needed: -1 is CCW, 0 is no rotate, 1 is CWnewAlignedImage = rot90(newImage, rotStep);
Invert black and white because it is easier to draw black digits over white background in our photos but the classifier needs white digits.
123% Invert black and whiteinvertedImage = - newAlignedImage;
Find the min and max gray values in the image and compute the total value range in preparation for normalization.
123456% Find min and max grays values in the imagemaxValue = max(invertedImage(:));minValue = min(invertedImage(:));% Compute the value range of actual graysdelta = maxValue - minValue;
Do normalization so all values end up between 0.0 and 1.0 because this particular classifier do not perform well with negative numbers.
12% Normalize grays between 0 and 1normImage = (invertedImage - minValue) / delta;
Add some contrast to the image. The multiplication factor is the contrast control, you can increase it if desired to obtain sharper contrast (contrast only between gray and white, black was already removed in normalization).
123% Add contrast. Multiplication factor is contrast control.contrastedImage = sigmoid((normImage -0.5) * 5);
Show the image specifying the black & white range [-1 1] to avoid automatic ranging using the image range values of gray to white. Showing the photo with different range, does not affect the values in the output matrix, so do not affect the classifier. It is only as a visual feedback for the user.
12% Show image as seen by the classifierimshow(contrastedImage, [-1, 1] );
Finally, output the matrix as a unrolled vector to be compatible with the classifier.
12% Output the matrix as a unrolled vectorvectorImage = reshape(normImage, 1, newSize(1) * newSize(2));
End function.
1end;
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172function vectorImage = imageTo20x20Gray(fileName, cropPercentage=0, rotStep=0)%IMAGETO20X20GRAY display reduced image and converts for digit classification%% Sample usage:% imageTo20x20Gray('myDigit.jpg', 100, -1);%% First parameter: Image file name% Could be bigger than 20 x 20 px, it will% be resized to 20 x 20. Better if used with% square images but not required.%% Second parameter: cropPercentage (any number between 0 and 100)% 0 0% will be cropped (optional, no needed for square images)% 50 50% of available croping will be cropped% 100 crop all the way to square image (for rectangular images)%% Third parameter: rotStep% -1 rotate image 90 degrees CCW% 0 do not rotate (optional)% 1 rotate image 90 degrees CW%% (Thanks to Edwin Frühwirth for parts of this code)% Read as RGB imageImage3DmatrixRGB = imread(fileName);% Convert to NTSC image (YIQ)Image3DmatrixYIQ = rgb2ntsc(Image3DmatrixRGB );% Convert to grays keeping only luminance (Y) and discard chrominance (IQ)Image2DmatrixBW = Image3DmatrixYIQ(:,:,1);% Get the size of your imageoldSize = size(Image2DmatrixBW);% Obtain crop size toward centered square (cropDelta)% ...will be zero for the already minimum dimension% ...and if the cropPercentage is zero,% ...both dimensions are zero% ...meaning that the original image will go intact to croppedImagecropDelta = floor((oldSize - min(oldSize)) .* (cropPercentage/100));% Compute the desired final pixel size for the original imagefinalSize = oldSize - cropDelta;% Compute each dimension origin for cropingcropOrigin = floor(cropDelta / 2) + 1;% Compute each dimension copying sizecopySize = cropOrigin + finalSize - 1;% Copy just the desired cropped image from the original B&W imagecroppedImage = Image2DmatrixBW( ...cropOrigin(1):copySize(1), cropOrigin(2):copySize(2));% Resolution scale factors: [rows cols]scale = [20 20] ./ finalSize;% Compute back the new image size (extra step to keep code general)newSize = max(floor(scale .* finalSize),1);% Compute a re-sampled set of indices:rowIndex = min(round(((1:newSize(1))-0.5)./scale(1)+0.5), finalSize(1));colIndex = min(round(((1:newSize(2))-0.5)./scale(2)+0.5), finalSize(2));% Copy just the indexed values from old image to get new imagenewImage = croppedImage(rowIndex,colIndex,:);% Rotate if needed: -1 is CCW, 0 is no rotate, 1 is CWnewAlignedImage = rot90(newImage, rotStep);% Invert black and whiteinvertedImage = - newAlignedImage;% Find min and max grays values in the imagemaxValue = max(invertedImage(:));minValue = min(invertedImage(:));% Compute the value range of actual graysdelta = maxValue - minValue;% Normalize grays between 0 and 1normImage = (invertedImage - minValue) / delta;% Add contrast. Multiplication factor is contrast control.contrastedImage = sigmoid((normImage -0.5) * 5);% Show image as seen by the classifierimshow(contrastedImage, [-1, 1] );% Output the matrix as a unrolled vectorvectorImage = reshape(contrastedImage, 1, newSize(1)*newSize(2));end
The NN we created for classification can easily be modified to have a linear output. First solve the 4th programming exercise. You can create a new function script, nnCostFunctionLinear.m, with the following characteristics
You still need to randomly initialize the Theta values, just as with any NN. You will want to experiment with different epsilon values. You will also need to create a predictLinear() function, using the tanh() function in the hidden layer, and a linear output.
Here is a test case for your nnCostFunctionLinear()
12345678910111213141516171819202122232425262728% inputsnn_params = [31 16 15 -29 -13 -8 -7 13 54 -17 -11 -9 16]'/ 10;il = 1;hl = 4;X = [1; 2; 3];y = [1; 4; 9];lambda = 0.01;% command[j g] = nnCostFunctionLinear(nn_params, il, hl, X, y, lambda)% resultsj = 0.020815g =-0.0131002-0.0110085-0.00705690.0189212-0.0189639-0.0192539-0.01022910.03447320.00249470.00806240.00219640.0031675-0.0064244
Now create a script that uses the 'ex5data1.mat' from ex5, but without creating the polynomial terms. With 8 units in the hidden layer and MaxIter set to 200, you should be able to get a final cost value of 0.3 to 0.4. The results will vary a bit due to the random Theta initialization. If you plot the training set and the predicted values for the training set (using your predictLinear() function), you should have a good match.