linearRegCostFunction.m 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  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.5 * ( sum((hypothesis(theta, X) - y) .^ 2) + lambda * sum(theta(2:end) .^ 2)) / m;
  11. grad = (X' * (hypothesis(theta, X) - y) + theta * lambda) / m;
  12. grad(1) = grad(1) - lambda * theta(1) / m;
  13. % ====================== YOUR CODE HERE ======================
  14. % Instructions: Compute the cost and gradient of regularized linear
  15. % regression for a particular choice of theta.
  16. %
  17. % You should set J to the cost and grad to the gradient.
  18. %
  19. % =========================================================================
  20. grad = grad(:);
  21. end