ex5.m 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  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. pause;
  37. %% =========== Part 2: Regularized Linear Regression Cost =============
  38. % You should now implement the cost function for regularized linear
  39. % regression.
  40. %
  41. theta = [1 ; 1];
  42. J = linearRegCostFunction([ones(m, 1) X], y, theta, 1);
  43. fprintf(['Cost at theta = [1 ; 1]: %f '...
  44. '\n(this value should be about 303.993192)\n'], J);
  45. fprintf('Program paused. Press enter to continue.\n');
  46. pause;
  47. %% =========== Part 3: Regularized Linear Regression Gradient =============
  48. % You should now implement the gradient for regularized linear
  49. % regression.
  50. %
  51. theta = [1 ; 1];
  52. [J, grad] = linearRegCostFunction([ones(m, 1) X], y, theta, 1);
  53. fprintf(['Gradient at theta = [1 ; 1]: [%f; %f] '...
  54. '\n(this value should be about [-15.303016; 598.250744])\n'], ...
  55. grad(1), grad(2));
  56. fprintf('Program paused. Press enter to continue.\n');
  57. pause;
  58. %% =========== Part 4: Train Linear Regression =============
  59. % Once you have implemented the cost and gradient correctly, the
  60. % trainLinearReg function will use your cost function to train
  61. % regularized linear regression.
  62. %
  63. % Write Up Note: The data is non-linear, so this will not give a great
  64. % fit.
  65. %
  66. % Train linear regression with lambda = 0
  67. lambda = 0;
  68. [theta] = trainLinearReg([ones(m, 1) X], y, lambda);
  69. % Plot fit over the data
  70. plot(X, y, 'rx', 'MarkerSize', 10, 'LineWidth', 1.5);
  71. xlabel('Change in water level (x)');
  72. ylabel('Water flowing out of the dam (y)');
  73. hold on;
  74. plot(X, [ones(m, 1) X]*theta, '--', 'LineWidth', 2)
  75. hold off;
  76. fprintf('Program paused. Press enter to continue.\n');
  77. pause;
  78. %% =========== Part 5: Learning Curve for Linear Regression =============
  79. % Next, you should implement the learningCurve function.
  80. %
  81. % Write Up Note: Since the model is underfitting the data, we expect to
  82. % see a graph with "high bias" -- Figure 3 in ex5.pdf
  83. %
  84. lambda = 0;
  85. [error_train, error_val] = ...
  86. learningCurve([ones(m, 1) X], y, ...
  87. [ones(size(Xval, 1), 1) Xval], yval, ...
  88. lambda);
  89. plot(1:m, error_train, 1:m, error_val);
  90. title('Learning curve for linear regression')
  91. legend('Train', 'Cross Validation')
  92. xlabel('Number of training examples')
  93. ylabel('Error')
  94. axis([0 13 0 150])
  95. fprintf('# Training Examples\tTrain Error\tCross Validation Error\n');
  96. for i = 1:m
  97. fprintf(' \t%d\t\t%f\t%f\n', i, error_train(i), error_val(i));
  98. end
  99. fprintf('Program paused. Press enter to continue.\n');
  100. pause;
  101. %% =========== Part 6: Feature Mapping for Polynomial Regression =============
  102. % One solution to this is to use polynomial regression. You should now
  103. % complete polyFeatures to map each example into its powers
  104. %
  105. p = 8;
  106. % Map X onto Polynomial Features and Normalize
  107. X_poly = polyFeatures(X, p);
  108. [X_poly, mu, sigma] = featureNormalize(X_poly); % Normalize
  109. X_poly = [ones(m, 1), X_poly]; % Add Ones
  110. % Map X_poly_test and normalize (using mu and sigma)
  111. X_poly_test = polyFeatures(Xtest, p);
  112. X_poly_test = bsxfun(@minus, X_poly_test, mu);
  113. X_poly_test = bsxfun(@rdivide, X_poly_test, sigma);
  114. X_poly_test = [ones(size(X_poly_test, 1), 1), X_poly_test]; % Add Ones
  115. % Map X_poly_val and normalize (using mu and sigma)
  116. X_poly_val = polyFeatures(Xval, p);
  117. X_poly_val = bsxfun(@minus, X_poly_val, mu);
  118. X_poly_val = bsxfun(@rdivide, X_poly_val, sigma);
  119. X_poly_val = [ones(size(X_poly_val, 1), 1), X_poly_val]; % Add Ones
  120. fprintf('Normalized Training Example 1:\n');
  121. fprintf(' %f \n', X_poly(1, :));
  122. fprintf('\nProgram paused. Press enter to continue.\n');
  123. pause;
  124. %% =========== Part 7: Learning Curve for Polynomial Regression =============
  125. % Now, you will get to experiment with polynomial regression with multiple
  126. % values of lambda. The code below runs polynomial regression with
  127. % lambda = 0. You should try running the code with different values of
  128. % lambda to see how the fit and learning curve change.
  129. %
  130. lambda = 0;
  131. [theta] = trainLinearReg(X_poly, y, lambda);
  132. % Plot training data and fit
  133. figure(1);
  134. plot(X, y, 'rx', 'MarkerSize', 10, 'LineWidth', 1.5);
  135. plotFit(min(X), max(X), mu, sigma, theta, p);
  136. xlabel('Change in water level (x)');
  137. ylabel('Water flowing out of the dam (y)');
  138. title (sprintf('Polynomial Regression Fit (lambda = %f)', lambda));
  139. figure(2);
  140. [error_train, error_val] = ...
  141. learningCurve(X_poly, y, X_poly_val, yval, lambda);
  142. plot(1:m, error_train, 1:m, error_val);
  143. title(sprintf('Polynomial Regression Learning Curve (lambda = %f)', lambda));
  144. xlabel('Number of training examples')
  145. ylabel('Error')
  146. axis([0 13 0 100])
  147. legend('Train', 'Cross Validation')
  148. fprintf('Polynomial Regression (lambda = %f)\n\n', lambda);
  149. fprintf('# Training Examples\tTrain Error\tCross Validation Error\n');
  150. for i = 1:m
  151. fprintf(' \t%d\t\t%f\t%f\n', i, error_train(i), error_val(i));
  152. end
  153. fprintf('Program paused. Press enter to continue.\n');
  154. pause;
  155. %% =========== Part 8: Validation for Selecting Lambda =============
  156. % You will now implement validationCurve to test various values of
  157. % lambda on a validation set. You will then use this to select the
  158. % "best" lambda value.
  159. %
  160. [lambda_vec, error_train, error_val] = ...
  161. validationCurve(X_poly, y, X_poly_val, yval);
  162. close all;
  163. plot(lambda_vec, error_train, lambda_vec, error_val);
  164. legend('Train', 'Cross Validation');
  165. xlabel('lambda');
  166. ylabel('Error');
  167. fprintf('lambda\t\tTrain Error\tValidation Error\n');
  168. for i = 1:length(lambda_vec)
  169. fprintf(' %f\t%f\t%f\n', ...
  170. lambda_vec(i), error_train(i), error_val(i));
  171. end
  172. fprintf('Program paused. Press enter to continue.\n');
  173. pause;