linearRegCostFunction.m 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. function [J, grad] = linearRegCostFunction(X, y, theta, lambda)
  2. %LINEARREGCOSTFUNCTION Compute cost and gradient for regularized linear
  3. %regression with multiple variables
  4. % [J, grad] = LINEARREGCOSTFUNCTION(X, y, theta, lambda) computes the
  5. % cost of using theta as the parameter for linear regression to fit the
  6. % data points in X and y. Returns the cost in J and the gradient in grad
  7. % Initialize some useful values
  8. m = length(y); % number of training examples
  9. % You need to return the following variables correctly
  10. J = 0;
  11. grad = zeros(size(theta));
  12. % ====================== YOUR CODE HERE ======================
  13. % Instructions: Compute the cost and gradient of regularized linear
  14. % regression for a particular choice of theta.
  15. %
  16. % You should set J to the cost and grad to the gradient.
  17. %
  18. J = 1 / (2 * m) * sum ((X * theta - y) .^2) + lambda / (2 * m) * sum(theta(2:end) .^2);
  19. reg = lambda / m * theta .* [0; ones(rows(theta)-1, 1)];
  20. grad = 1 / m * X' * (X * theta - y) + reg;
  21. %size(grad)
  22. % =========================================================================
  23. grad = grad(:);
  24. end