Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
hackassin
GitHub Repository: hackassin/Coursera-Machine-Learning
Path: blob/master/Week 5/Programming Assignment - 4/machine-learning-ex4/ex4/ex4.m
864 views
1
%% Machine Learning Online Class - Exercise 4 Neural Network Learning
2
3
% Instructions
4
% ------------
5
%
6
% This file contains code that helps you get started on the
7
% linear exercise. You will need to complete the following functions
8
% in this exericse:
9
%
10
% sigmoidGradient.m
11
% randInitializeWeights.m
12
% nnCostFunction.m
13
%
14
% For this exercise, you will not need to change any code in this file,
15
% or any other files other than those mentioned above.
16
%
17
18
%% Initialization
19
clear ; close all; clc
20
21
%% Setup the parameters you will use for this exercise
22
input_layer_size = 400; % 20x20 Input Images of Digits
23
hidden_layer_size = 25; % 25 hidden units
24
num_labels = 10; % 10 labels, from 1 to 10
25
% (note that we have mapped "0" to label 10)
26
27
%% =========== Part 1: Loading and Visualizing Data =============
28
% We start the exercise by first loading and visualizing the dataset.
29
% You will be working with a dataset that contains handwritten digits.
30
%
31
32
% Load Training Data
33
fprintf('Loading and Visualizing Data ...\n')
34
35
load('ex4data1.mat');
36
m = size(X, 1);
37
38
% Randomly select 100 data points to display
39
sel = randperm(size(X, 1));
40
sel = sel(1:100);
41
42
displayData(X(sel, :));
43
44
fprintf('Program paused. Press enter to continue.\n');
45
pause;
46
47
48
%% ================ Part 2: Loading Parameters ================
49
% In this part of the exercise, we load some pre-initialized
50
% neural network parameters.
51
52
fprintf('\nLoading Saved Neural Network Parameters ...\n')
53
54
% Load the weights into variables Theta1 and Theta2
55
load('ex4weights.mat');
56
57
% Unroll parameters
58
nn_params = [Theta1(:) ; Theta2(:)];
59
60
%% ================ Part 3: Compute Cost (Feedforward) ================
61
% To the neural network, you should first start by implementing the
62
% feedforward part of the neural network that returns the cost only. You
63
% should complete the code in nnCostFunction.m to return cost. After
64
% implementing the feedforward to compute the cost, you can verify that
65
% your implementation is correct by verifying that you get the same cost
66
% as us for the fixed debugging parameters.
67
%
68
% We suggest implementing the feedforward cost *without* regularization
69
% first so that it will be easier for you to debug. Later, in part 4, you
70
% will get to implement the regularized cost.
71
%
72
fprintf('\nFeedforward Using Neural Network ...\n')
73
74
% Weight regularization parameter (we set this to 0 here).
75
lambda = 0;
76
77
J = nnCostFunction(nn_params, input_layer_size, hidden_layer_size, ...
78
num_labels, X, y, lambda);
79
80
fprintf(['Cost at parameters (loaded from ex4weights): %f '...
81
'\n(this value should be about 0.287629)\n'], J);
82
83
fprintf('\nProgram paused. Press enter to continue.\n');
84
pause;
85
86
%% =============== Part 4: Implement Regularization ===============
87
% Once your cost function implementation is correct, you should now
88
% continue to implement the regularization with the cost.
89
%
90
91
fprintf('\nChecking Cost Function (w/ Regularization) ... \n')
92
93
% Weight regularization parameter (we set this to 1 here).
94
lambda = 1;
95
96
J = nnCostFunction(nn_params, input_layer_size, hidden_layer_size, ...
97
num_labels, X, y, lambda);
98
99
fprintf(['Cost at parameters (loaded from ex4weights): %f '...
100
'\n(this value should be about 0.383770)\n'], J);
101
102
fprintf('Program paused. Press enter to continue.\n');
103
pause;
104
105
106
%% ================ Part 5: Sigmoid Gradient ================
107
% Before you start implementing the neural network, you will first
108
% implement the gradient for the sigmoid function. You should complete the
109
% code in the sigmoidGradient.m file.
110
%
111
112
fprintf('\nEvaluating sigmoid gradient...\n')
113
114
g = sigmoidGradient([-1 -0.5 0 0.5 1]);
115
fprintf('Sigmoid gradient evaluated at [-1 -0.5 0 0.5 1]:\n ');
116
fprintf('%f ', g);
117
fprintf('\n\n');
118
119
fprintf('Program paused. Press enter to continue.\n');
120
pause;
121
122
123
%% ================ Part 6: Initializing Pameters ================
124
% In this part of the exercise, you will be starting to implment a two
125
% layer neural network that classifies digits. You will start by
126
% implementing a function to initialize the weights of the neural network
127
% (randInitializeWeights.m)
128
129
fprintf('\nInitializing Neural Network Parameters ...\n')
130
131
initial_Theta1 = randInitializeWeights(input_layer_size, hidden_layer_size);
132
initial_Theta2 = randInitializeWeights(hidden_layer_size, num_labels);
133
134
% Unroll parameters
135
initial_nn_params = [initial_Theta1(:) ; initial_Theta2(:)];
136
137
138
%% =============== Part 7: Implement Backpropagation ===============
139
% Once your cost matches up with ours, you should proceed to implement the
140
% backpropagation algorithm for the neural network. You should add to the
141
% code you've written in nnCostFunction.m to return the partial
142
% derivatives of the parameters.
143
%
144
fprintf('\nChecking Backpropagation... \n');
145
146
% Check gradients by running checkNNGradients
147
checkNNGradients;
148
149
fprintf('\nProgram paused. Press enter to continue.\n');
150
pause;
151
152
153
%% =============== Part 8: Implement Regularization ===============
154
% Once your backpropagation implementation is correct, you should now
155
% continue to implement the regularization with the cost and gradient.
156
%
157
158
fprintf('\nChecking Backpropagation (w/ Regularization) ... \n')
159
160
% Check gradients by running checkNNGradients
161
lambda = 3;
162
checkNNGradients(lambda);
163
164
% Also output the costFunction debugging values
165
debug_J = nnCostFunction(nn_params, input_layer_size, ...
166
hidden_layer_size, num_labels, X, y, lambda);
167
168
fprintf(['\n\nCost at (fixed) debugging parameters (w/ lambda = %f): %f ' ...
169
'\n(for lambda = 3, this value should be about 0.576051)\n\n'], lambda, debug_J);
170
171
fprintf('Program paused. Press enter to continue.\n');
172
pause;
173
174
175
%% =================== Part 8: Training NN ===================
176
% You have now implemented all the code necessary to train a neural
177
% network. To train your neural network, we will now use "fmincg", which
178
% is a function which works similarly to "fminunc". Recall that these
179
% advanced optimizers are able to train our cost functions efficiently as
180
% long as we provide them with the gradient computations.
181
%
182
fprintf('\nTraining Neural Network... \n')
183
184
% After you have completed the assignment, change the MaxIter to a larger
185
% value to see how more training helps.
186
options = optimset('MaxIter', 50);
187
188
% You should also try different values of lambda
189
lambda = 1;
190
191
% Create "short hand" for the cost function to be minimized
192
costFunction = @(p) nnCostFunction(p, ...
193
input_layer_size, ...
194
hidden_layer_size, ...
195
num_labels, X, y, lambda);
196
197
% Now, costFunction is a function that takes in only one argument (the
198
% neural network parameters)
199
[nn_params, cost] = fmincg(costFunction, initial_nn_params, options);
200
201
% Obtain Theta1 and Theta2 back from nn_params
202
Theta1 = reshape(nn_params(1:hidden_layer_size * (input_layer_size + 1)), ...
203
hidden_layer_size, (input_layer_size + 1));
204
205
Theta2 = reshape(nn_params((1 + (hidden_layer_size * (input_layer_size + 1))):end), ...
206
num_labels, (hidden_layer_size + 1));
207
208
fprintf('Program paused. Press enter to continue.\n');
209
pause;
210
211
212
%% ================= Part 9: Visualize Weights =================
213
% You can now "visualize" what the neural network is learning by
214
% displaying the hidden units to see what features they are capturing in
215
% the data.
216
217
fprintf('\nVisualizing Neural Network... \n')
218
219
displayData(Theta1(:, 2:end));
220
221
fprintf('\nProgram paused. Press enter to continue.\n');
222
pause;
223
224
%% ================= Part 10: Implement Predict =================
225
% After training the neural network, we would like to use it to predict
226
% the labels. You will now implement the "predict" function to use the
227
% neural network to predict the labels of the training set. This lets
228
% you compute the training set accuracy.
229
230
pred = predict(Theta1, Theta2, X);
231
232
fprintf('\nTraining Set Accuracy: %f\n', mean(double(pred == y)) * 100);
233
234
235
236