myex5.m 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. %% Machine Learning Online Class
  2. % Exercise 5 | Regularized Linear Regression and Bias-Variance
  3. %
  4. % Instructions
  5. % ------------
  6. %
  7. % This file contains code that helps you get started on the
  8. % exercise. You will need to complete the following functions:
  9. %
  10. % linearRegCostFunction.m
  11. % learningCurve.m
  12. % validationCurve.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. %% Initialization
  18. clear ; close all; clc
  19. %% =========== Part 1: Loading and Visualizing Data =============
  20. % We start the exercise by first loading and visualizing the dataset.
  21. % The following code will load the dataset into your environment and plot
  22. % the data.
  23. %
  24. % Load Training Data
  25. fprintf('Loading and Visualizing Data ...\n')
  26. % Load from ex5data1:
  27. % You will have X, y, Xval, yval, Xtest, ytest in your environment
  28. load ('ex5data1.mat');
  29. % m = Number of examples
  30. m = size(X, 1);
  31. % Plot training data
  32. plot(X, y, 'rx', 'MarkerSize', 10, 'LineWidth', 1.5);
  33. xlabel('Change in water level (x)');
  34. ylabel('Water flowing out of the dam (y)');
  35. fprintf('Program paused. Press enter to continue.\n');
  36. %% =========== Part 2: Regularized Linear Regression Cost =============
  37. % You should now implement the cost function for regularized linear
  38. % regression.
  39. %
  40. theta = [1 ; 1];
  41. J = linearRegCostFunction([ones(m, 1) X], y, theta, 1);
  42. fprintf(['Cost at theta = [1 ; 1]: %f '...
  43. '\n(this value should be about 303.993192)\n'], J);
  44. fprintf('Program paused. Press enter to continue.\n');
  45. %% =========== Part 3: Regularized Linear Regression Gradient =============
  46. % You should now implement the gradient for regularized linear
  47. % regression.
  48. %
  49. theta = [1 ; 1];
  50. [J, grad] = linearRegCostFunction([ones(m, 1) X], y, theta, 1);
  51. fprintf(['Gradient at theta = [1 ; 1]: [%f; %f] '...
  52. '\n(this value should be about [-15.303016; 598.250744])\n'], ...
  53. grad(1), grad(2));
  54. fprintf('Program paused. Press enter to continue.\n');
  55. %% =========== Part 4: Train Linear Regression =============
  56. % Once you have implemented the cost and gradient correctly, the
  57. % trainLinearReg function will use your cost function to train
  58. % regularized linear regression.
  59. %
  60. % Write Up Note: The data is non-linear, so this will not give a great
  61. % fit.
  62. %
  63. % Train linear regression with lambda = 0
  64. lambda = 0;
  65. [theta] = trainLinearReg([ones(m, 1) X], y, lambda);
  66. % Plot fit over the data
  67. plot(X, y, 'rx', 'MarkerSize', 10, 'LineWidth', 1.5);
  68. xlabel('Change in water level (x)');
  69. ylabel('Water flowing out of the dam (y)');
  70. hold on;
  71. plot(X, [ones(m, 1) X]*theta, '--', 'LineWidth', 2)
  72. hold off;
  73. fprintf('Program paused. Press enter to continue.\n');
  74. %% =========== Part 5: Learning Curve for Linear Regression =============
  75. % Next, you should implement the learningCurve function.
  76. %
  77. % Write Up Note: Since the model is underfitting the data, we expect to
  78. % see a graph with "high bias" -- Figure 3 in ex5.pdf
  79. %
  80. lambda = 0;
  81. [error_train, error_val] = ...
  82. learningCurve([ones(m, 1) X], y, ...
  83. [ones(size(Xval, 1), 1) Xval], yval, ...
  84. lambda);
  85. plot(1:m, error_train, 1:m, error_val);
  86. title('Learning curve for linear regression')
  87. legend('Train', 'Cross Validation')
  88. xlabel('Number of training examples')
  89. ylabel('Error')
  90. axis([0 13 0 150])
  91. fprintf('# Training Examples\tTrain Error\tCross Validation Error\n');
  92. for i = 1:m
  93. fprintf(' \t%d\t\t%f\t%f\n', i, error_train(i), error_val(i));
  94. end
  95. fprintf('Program paused. Press enter to continue.\n');
  96. %% =========== Part 6: Feature Mapping for Polynomial Regression =============
  97. % One solution to this is to use polynomial regression. You should now
  98. % complete polyFeatures to map each example into its powers
  99. %
  100. p = 8;
  101. % Map X onto Polynomial Features and Normalize
  102. X_poly = polyFeatures(X, p);
  103. [X_poly, mu, sigma] = featureNormalize(X_poly); % Normalize
  104. X_poly = [ones(m, 1), X_poly]; % Add Ones
  105. % Map X_poly_test and normalize (using mu and sigma)
  106. X_poly_test = polyFeatures(Xtest, p);
  107. X_poly_test = bsxfun(@minus, X_poly_test, mu);
  108. X_poly_test = bsxfun(@rdivide, X_poly_test, sigma);
  109. X_poly_test = [ones(size(X_poly_test, 1), 1), X_poly_test]; % Add Ones
  110. % Map X_poly_val and normalize (using mu and sigma)
  111. X_poly_val = polyFeatures(Xval, p);
  112. X_poly_val = bsxfun(@minus, X_poly_val, mu);
  113. X_poly_val = bsxfun(@rdivide, X_poly_val, sigma);
  114. X_poly_val = [ones(size(X_poly_val, 1), 1), X_poly_val]; % Add Ones
  115. fprintf('Normalized Training Example 1:\n');
  116. fprintf(' %f \n', X_poly(1, :));
  117. fprintf('\nProgram paused. Press enter to continue.\n');
  118. pause;
  119. %% =========== Part 7: Learning Curve for Polynomial Regression =============
  120. % Now, you will get to experiment with polynomial regression with multiple
  121. % values of lambda. The code below runs polynomial regression with
  122. % lambda = 0. You should try running the code with different values of
  123. % lambda to see how the fit and learning curve change.
  124. %
  125. lambda = 0;
  126. [theta] = trainLinearReg(X_poly, y, lambda);
  127. % Plot training data and fit
  128. figure(1);
  129. plot(X, y, 'rx', 'MarkerSize', 10, 'LineWidth', 1.5);
  130. plotFit(min(X), max(X), mu, sigma, theta, p);
  131. xlabel('Change in water level (x)');
  132. ylabel('Water flowing out of the dam (y)');
  133. title (sprintf('Polynomial Regression Fit (lambda = %f)', lambda));
  134. figure(2);
  135. [error_train, error_val] = ...
  136. learningCurve(X_poly, y, X_poly_val, yval, lambda);
  137. plot(1:m, error_train, 1:m, error_val);
  138. title(sprintf('Polynomial Regression Learning Curve (lambda = %f)', lambda));
  139. xlabel('Number of training examples')
  140. ylabel('Error')
  141. axis([0 13 0 100])
  142. legend('Train', 'Cross Validation')
  143. fprintf('Polynomial Regression (lambda = %f)\n\n', lambda);
  144. fprintf('# Training Examples\tTrain Error\tCross Validation Error\n');
  145. for i = 1:m
  146. fprintf(' \t%d\t\t%f\t%f\n', i, error_train(i), error_val(i));
  147. end
  148. fprintf('Program paused. Press enter to continue.\n');
  149. pause;
  150. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  151. % lambda = 1100
  152. lambda = 1100;
  153. [theta] = trainLinearReg(X_poly, y, lambda);
  154. % Plot training data and fit
  155. figure(1);
  156. plot(X, y, 'rx', 'MarkerSize', 10, 'LineWidth', 1.5);
  157. plotFit(min(X), max(X), mu, sigma, theta, p);
  158. xlabel('Change in water level (x)');
  159. ylabel('Water flowing out of the dam (y)');
  160. title (sprintf('Polynomial Regression Fit (lambda = %f)', lambda));
  161. figure(2);
  162. [error_train, error_val] = ...
  163. learningCurve(X_poly, y, X_poly_val, yval, lambda);
  164. plot(1:m, error_train, 1:m, error_val);
  165. title(sprintf('Polynomial Regression Learning Curve (lambda = %f)', lambda));
  166. xlabel('Number of training examples')
  167. ylabel('Error')
  168. axis([0 13 0 100])
  169. legend('Train', 'Cross Validation')
  170. fprintf('Polynomial Regression (lambda = %f)\n\n', lambda);
  171. fprintf('# Training Examples\tTrain Error\tCross Validation Error\n');
  172. for i = 1:m
  173. fprintf(' \t%d\t\t%f\t%f\n', i, error_train(i), error_val(i));
  174. end
  175. fprintf('Program paused. Press enter to continue.\n');
  176. pause;
  177. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  178. % lambda = 1
  179. lambda = 1;
  180. [theta] = trainLinearReg(X_poly, y, lambda);
  181. % Plot training data and fit
  182. figure(1);
  183. plot(X, y, 'rx', 'MarkerSize', 10, 'LineWidth', 1.5);
  184. plotFit(min(X), max(X), mu, sigma, theta, p);
  185. xlabel('Change in water level (x)');
  186. ylabel('Water flowing out of the dam (y)');
  187. title (sprintf('Polynomial Regression Fit (lambda = %f)', lambda));
  188. figure(2);
  189. [error_train, error_val] = ...
  190. learningCurve(X_poly, y, X_poly_val, yval, lambda);
  191. plot(1:m, error_train, 1:m, error_val);
  192. title(sprintf('Polynomial Regression Learning Curve (lambda = %f)', lambda));
  193. xlabel('Number of training examples')
  194. ylabel('Error')
  195. axis([0 13 0 100])
  196. legend('Train', 'Cross Validation')
  197. fprintf('Polynomial Regression (lambda = %f)\n\n', lambda);
  198. fprintf('# Training Examples\tTrain Error\tCross Validation Error\n');
  199. for i = 1:m
  200. fprintf(' \t%d\t\t%f\t%f\n', i, error_train(i), error_val(i));
  201. end
  202. fprintf('Program paused. Press enter to continue.\n');
  203. pause;
  204. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  205. % lambda = 100
  206. lambda = 100;
  207. [theta] = trainLinearReg(X_poly, y, lambda);
  208. % Plot training data and fit
  209. figure(1);
  210. plot(X, y, 'rx', 'MarkerSize', 10, 'LineWidth', 1.5);
  211. plotFit(min(X), max(X), mu, sigma, theta, p);
  212. xlabel('Change in water level (x)');
  213. ylabel('Water flowing out of the dam (y)');
  214. title (sprintf('Polynomial Regression Fit (lambda = %f)', lambda));
  215. figure(2);
  216. [error_train, error_val] = ...
  217. learningCurve(X_poly, y, X_poly_val, yval, lambda);
  218. plot(1:m, error_train, 1:m, error_val);
  219. title(sprintf('Polynomial Regression Learning Curve (lambda = %f)', lambda));
  220. xlabel('Number of training examples')
  221. ylabel('Error')
  222. axis([0 13 0 100])
  223. legend('Train', 'Cross Validation')
  224. fprintf('Polynomial Regression (lambda = %f)\n\n', lambda);
  225. fprintf('# Training Examples\tTrain Error\tCross Validation Error\n');
  226. for i = 1:m
  227. fprintf(' \t%d\t\t%f\t%f\n', i, error_train(i), error_val(i));
  228. end
  229. fprintf('Program paused. Press enter to continue.\n');
  230. pause;
  231. %% =========== Part 8: Validation for Selecting Lambda =============
  232. % You will now implement validationCurve to test various values of
  233. % lambda on a validation set. You will then use this to select the
  234. % "best" lambda value.
  235. %
  236. [lambda_vec, error_train, error_val] = ...
  237. validationCurve(X_poly, y, X_poly_val, yval);
  238. close all;
  239. plot(lambda_vec, error_train, lambda_vec, error_val);
  240. legend('Train', 'Cross Validation');
  241. xlabel('lambda');
  242. ylabel('Error');
  243. fprintf('lambda\t\tTrain Error\tValidation Error\n');
  244. for i = 1:length(lambda_vec)
  245. fprintf(' %f\t%f\t%f\n', ...
  246. lambda_vec(i), error_train(i), error_val(i));
  247. end
  248. fprintf('Program paused. Press enter to continue.\n');
  249. pause;
  250. validateFinal(X_poly, y, X_poly_test, ytest, 3);