trainLinearReg.m 714 B

123456789101112131415161718192021
  1. function [theta] = trainLinearReg(X, y, lambda)
  2. %TRAINLINEARREG Trains linear regression given a dataset (X, y) and a
  3. %regularization parameter lambda
  4. % [theta] = TRAINLINEARREG (X, y, lambda) trains linear regression using
  5. % the dataset (X, y) and regularization parameter lambda. Returns the
  6. % trained parameters theta.
  7. %
  8. % Initialize Theta
  9. initial_theta = zeros(size(X, 2), 1);
  10. % Create "short hand" for the cost function to be minimized
  11. costFunction = @(t) linearRegCostFunction(X, y, t, lambda);
  12. % Now, costFunction is a function that takes in only one argument
  13. options = optimset('MaxIter', 200, 'GradObj', 'on');
  14. % Minimize using fmincg
  15. theta = fmincg(costFunction, initial_theta, options);
  16. end