Ex 3
Ex 3
Ex 3
Introduction
In this exercise, you will implement one-vs-all logistic regression and neural
networks to recognize hand-written digits. Before starting the programming
exercise, we strongly recommend watching the video lectures and completing
the review questions for the associated topics.
To get started with the exercise, you will need to download the starter
code and unzip its contents to the directory where you wish to complete the
exercise. If needed, use the cd command in Octave/MATLAB to change to
this directory before starting this exercise.
You can also find instructions for installing Octave/MATLAB in the Environment Setup Instructions of the course website.
Throughout the exercise, you will be using the scripts ex3.m and ex3 nn.m.
These scripts set up the dataset for the problems and make calls to functions
that you will write. You do not need to modify these scripts. You are only
required to modify functions in other files, by following the instructions in
this assignment.
Multi-class Classification
For this exercise, you will use logistic regression and neural networks to
recognize handwritten digits (from 0 to 9). Automated handwritten digit
recognition is widely used today - from recognizing zip codes (postal codes)
on mail envelopes to recognizing amounts written on bank checks. This
exercise will show you how the methods youve learned can be used for this
classification task.
In the first part of the exercise, you will extend your previous implemention of logistic regression and apply it to one-vs-all classification.
1
Octave is a free alternative to MATLAB. For the programming exercises, you are free
to use either Octave or MATLAB.
1.1
Dataset
You are given a data set in ex3data1.mat that contains 5000 training examples of handwritten digits.2 The .mat format means that that the data has
been saved in a native Octave/MATLAB matrix format, instead of a text
(ASCII) format like a csv-file. These matrices can be read directly into your
program by using the load command. After loading, matrices of the correct
dimensions and values will appear in your programs memory. The matrix
will already be named, so you do not need to assign names to them.
% Load saved matrices from file
load('ex3data1.mat');
% The matrices X and y will now be in your Octave environment
(x(1) )T
(x(2) )T
X=
..
.
(m) T
(x )
The second part of the training set is a 5000-dimensional vector y that
contains labels for the training set. To make things more compatible with
Octave/MATLAB indexing, where there is no zero index, we have mapped
the digit zero to the value ten. Therefore, a 0 digit is labeled as 10, while
the digits 1 to 9 are labeled as 1 to 9 in their natural order.
1.2
You will begin by visualizing a subset of the training set. In Part 1 of ex3.m,
the code randomly selects selects 100 rows from X and passes those rows
to the displayData function. This function maps each row to a 20 pixel by
20 pixel grayscale image and displays the images together. We have provided
2
This is a subset of the MNIST handwritten digit dataset (http://yann.lecun.com/
exdb/mnist/).
the displayData function, and you are encouraged to examine the code to
see how it works. After you run this step, you should see an image like Figure
1.
1.3
sigmoid function. It turns out that we can compute this quickly for all our
examples by using matrix multiplication. Let us define X and as
(x(1) )T
0
(x(2) )T
1
X=
and
.. .
..
.
.
(m) T
n
(x )
Then, by computing the matrix product X, we have
(x(1) )T
T (x(1) )
(x(2) )T T (x(2) )
X =
=
..
..
.
.
(m) T
T
(x )
(x(m) )
In the last equality, we used the fact that aT b = bT a if a and b are vectors.
This allows us to compute the products T x(i) for all our examples i in one
line of code.
Your job is to write the unregularized cost function in the file lrCostFunction.m
Your implementation should use the strategy we presented above to calculate T x(i) . You should also use a vectorized approach for the rest of the
cost function. A fully vectorized version of lrCostFunction.m should not
contain any loops.
(Hint: You might want to use the element-wise multiplication operation
(.*) and the sum operation sum when writing this function)
1.3.2
1 X
J
(i)
(i) (i)
(h (x ) y )xj .
=
j
m i=1
To vectorize this operation over the dataset, we start by writing out all
y
)x
0
i=1
0
J
Pm (h (x(i) ) y (i) )x(i)
1
1
i=1
J
1
Pm
2 =
(i)
(i) (i)
(h
(x
)
y
)x
2
i=1
..
..
J
Pm
(i)
(i) (i)
n
i=1 (h (x ) y )xn
where
1 X
(h (x(i) ) y (i) )x(i)
m i=1
1 T
X (h (x) y).
m
h (x) y =
h (x(1) ) y (1)
h (x(2) ) y (2)
..
.
h (x(1) ) y (m)
(1)
Note that x(i) is a vector, while (h (x(i) )y (i) ) is a scalar (single number).
To understand the last step of the derivation, let i = (h (x(i) ) y (i) ) and
observe that:
|
|
|
2
X
(i)
(1)
(2)
(m)
i x = x
x
... x
.. = X T ,
.
i
|
|
|
m
where the values i = (h (x(i) ) y (i) ).
The expression above allows us to compute all the partial derivatives
without any loops. If you are comfortable with linear algebra, we encourage
you to work through the matrix multiplications above to convince yourself
that the vectorized version does the same computations. You should now
implement Equation 1 to compute the correct vectorized gradient. Once you
are done, complete the function lrCostFunction.m by implementing the
gradient.
Debugging Tip: Vectorizing code can sometimes be tricky. One common strategy for debugging is to print out the sizes of the matrices you
are working with using the size function. For example, given a data matrix X of size 100 20 (100 examples, 20 features) and , a vector with
dimensions 20 1, you can observe that X is a valid multiplication operation, while X is not. Furthermore, if you have a non-vectorized version
of your code, you can compare the output of your vectorized code and
non-vectorized code to make sure that they produce the same outputs.
1.3.3
After you have implemented vectorization for logistic regression, you will now
add regularization to the cost function. Recall that for regularized logistic
regression, the cost function is defined as
m
n
X 2
1 X (i)
(i)
(i)
(i)
y log(h (x )) (1 y ) log(1 h (x )) +
.
J() =
m i=1
2m j=1 j
Note that you should not be regularizing 0 which is used for the bias
term.
Correspondingly, the partial derivative of regularized logistic regression
cost for j is defined as
m
1 X
J()
(i)
=
(h (x(i) ) y (i) )xj
0
m i=1
J()
=
j
1 X
(i)
(h (x(i) ) y (i) )xj
m i=1
for j = 0
!
+
j
m
for j 1
Octave/MATLAB Tip: When implementing the vectorization for regularized logistic regression, you might often want to only sum and update
certain elements of . In Octave/MATLAB, you can index into the matrices to access and update only certain elements. For example, A(:, 3:5)
= B(:, 1:3) will replaces the columns 3 to 5 of A with the columns 1 to
3 from B. One special keyword you can use in indexing is the end keyword
in indexing. This allows us to select columns (or rows) until the end of the
matrix. For example, A(:, 2:end) will only return elements from the 2nd
to last column of A. Thus, you could use this together with the sum and
.^ operations to compute the sum of only the elements you are interested
in (e.g., sum(z(2:end).^2)). In the starter code, lrCostFunction.m, we
have also provided hints on yet another possible method computing the
regularized gradient.
You should now submit your solutions.
1.4
One-vs-all Classification
One-vs-all Prediction
After training your one-vs-all classifier, you can now use it to predict the
digit contained in a given image. For each input, you should compute the
probability that it belongs to each class using the trained logistic regression
classifiers. Your one-vs-all prediction function will pick the class for which the
corresponding logistic regression classifier outputs the highest probability and
return the class label (1, 2,..., or K) as the prediction for the input example.
You should now complete the code in predictOneVsAll.m to use the
one-vs-all classifier to make predictions.
Once you are done, ex3.m will call your predictOneVsAll function using
the learned value of . You should see that the training set accuracy is about
94.9% (i.e., it classifies 94.9% of the examples in the training set correctly).
You should now submit your solutions.
Neural Networks
In the previous part of this exercise, you implemented multi-class logistic regression to recognize handwritten digits. However, logistic regression cannot
form more complex hypotheses as it is only a linear classifier.3
In this part of the exercise, you will implement a neural network to recognize handwritten digits using the same training set as before. The neural
network will be able to represent complex models that form non-linear hypotheses. For this week, you will be using parameters from a neural network
that we have already trained. Your goal is to implement the feedforward
propagation algorithm to use our weights for prediction. In next weeks exercise, you will write the backpropagation algorithm for learning the neural
network parameters.
The provided script, ex3 nn.m, will help you step through this exercise.
2.1
Model representation
You could add more features (such as polynomial features) to logistic regression, but
that can be very expensive to train.
10
2.2
Now you will implement feedforward propagation for the neural network. You
will need to complete the code in predict.m to return the neural networks
prediction.
You should implement the feedforward computation that computes h (x(i) )
for every example i and returns the associated predictions. Similar to the
one-vs-all classification strategy, the prediction from the neural network will
be the label that has the largest output (h (x))k .
Implementation Note: The matrix X contains the examples in rows.
When you complete the code in predict.m, you will need to add the
column of 1s to the matrix. The matrices Theta1 and Theta2 contain
the parameters for each unit in rows. Specifically, the first row of Theta1
corresponds to the first hidden unit in the second layer. In Octave/MATLAB, when you compute z (2) = (1) a(1) , be sure that you index (and if
necessary, transpose) X correctly so that you get a(l) as a column vector.
Once you are done, ex3 nn.m will call your predict function using the
loaded set of parameters for Theta1 and Theta2. You should see that the
11
accuracy is about 97.5%. After that, an interactive sequence will launch displaying images from the training set one at a time, while the console prints
out the predicted label for the displayed image. To stop the image sequence,
press Ctrl-C.
You should now submit your solutions.
Submitted File
lrCostFunction.m
oneVsAll.m
predictOneVsAll.m
predict.m
Points
30 points
20 points
20 points
30 points
100 points
You are allowed to submit your solutions multiple times, and we will take
only the highest score into consideration.
12