ex4.m 7.9 KB

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