myex5.m 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. % =========== Part 2: Regularized Linear Regression Cost =============
  2. % You should now implement the cost function for regularized linear
  3. % regression.
  4. %
  5. % Load Training Data
  6. fprintf('Loading and Visualizing Data ...\n')
  7. % Load from ex5data1:
  8. % You will have X, y, Xval, yval, Xtest, ytest in your environment
  9. load ('ex5data1.mat');
  10. % m = Number of examples
  11. m = size(X, 1);
  12. theta = [1 ; 1];
  13. J = linearRegCostFunction([ones(m, 1) X], y, theta, 1);
  14. fprintf(['Cost at theta = [1 ; 1]: %f '...
  15. '\n(this value should be about 303.993192)\n'], J);
  16. fprintf('Program paused. Press enter to continue.\n');
  17. theta = [1 ; 1];
  18. [J, grad] = linearRegCostFunction([ones(m, 1) X], y, theta, 1);
  19. fprintf(['Gradient at theta = [1 ; 1]: [%f; %f] '...
  20. '\n(this value should be about [-15.303016; 598.250744])\n'], ...
  21. grad(1), grad(2));
  22. fprintf('Program paused. Press enter to continue.\n');
  23. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  24. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  25. lambda = 0;
  26. [error_train, error_val] = ...
  27. learningCurve([ones(m, 1) X], y, ...
  28. [ones(size(Xval, 1), 1) Xval], yval, ...
  29. lambda);
  30. plot(1:m, error_train, 1:m, error_val);
  31. title('Learning curve for linear regression')
  32. legend('Train', 'Cross Validation')
  33. xlabel('Number of training examples')
  34. ylabel('Error')
  35. axis([0 13 0 150])
  36. fprintf('# Training Examples\tTrain Error\tCross Validation Error\n');
  37. for i = 1:m
  38. fprintf(' \t%d\t\t%f\t%f\n', i, error_train(i), error_val(i));
  39. end
  40. fprintf('Program paused. Press enter to continue.\n');