validationCurve.m 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. function [lambda_vec, error_train, error_val] = ...
  2. validationCurve(X, y, Xval, yval)
  3. %VALIDATIONCURVE Generate the train and validation errors needed to
  4. %plot a validation curve that we can use to select lambda
  5. % [lambda_vec, error_train, error_val] = ...
  6. % VALIDATIONCURVE(X, y, Xval, yval) returns the train
  7. % and validation errors (in error_train, error_val)
  8. % for different values of lambda. You are given the training set (X,
  9. % y) and validation set (Xval, yval).
  10. %
  11. % Selected values of lambda (you should not change this)
  12. lambda_vec = [0 0.001 0.003 0.01 0.03 0.1 0.3 1 3 10]';
  13. % You need to return these variables correctly.
  14. error_train = zeros(length(lambda_vec), 1);
  15. error_val = zeros(length(lambda_vec), 1);
  16. for i = 1:length(lambda_vec)
  17. lambda = lambda_vec(i);
  18. theta = trainLinearReg(X, y, lambda);
  19. error_train(i) = linearRegCostFunction(X, y, theta, 0);
  20. error_val(i) = linearRegCostFunction(Xval, yval, theta, 0);
  21. % Compute train / val errors when training linear
  22. % regression with regularization parameter lambda
  23. % You should store the result in error_train(i)
  24. % and error_val(i)
  25. end
  26. % ====================== YOUR CODE HERE ======================
  27. % Instructions: Fill in this function to return training errors in
  28. % error_train and the validation errors in error_val. The
  29. % vector lambda_vec contains the different lambda parameters
  30. % to use for each calculation of the errors, i.e,
  31. % error_train(i), and error_val(i) should give
  32. % you the errors obtained after training with
  33. % lambda = lambda_vec(i)
  34. %
  35. % Note: You can loop over lambda_vec with the following:
  36. %
  37. % for i = 1:length(lambda_vec)
  38. % lambda = lambda_vec(i);
  39. % % Compute train / val errors when training linear
  40. % % regression with regularization parameter lambda
  41. % % You should store the result in error_train(i)
  42. % % and error_val(i)
  43. % ....
  44. %
  45. % end
  46. %
  47. %
  48. % =========================================================================
  49. end