You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

linearRegCostFunction.m 1.2 kB

8 years ago
1234567891011121314151617181920212223242526272829303132
  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. hx = X * theta;
  19. J = 1 / (2 * m) * sum((hx - y) .^ 2) + lambda / (2 * m) * theta(2:end)' * theta(2:end);
  20. grad(1) = 1 / m * X(:,1)' * (hx - y);
  21. grad(2:end) = 1 / m * X(:, 2 : end)' * (hx - y) + lambda / m * theta(2:end);
  22. % =========================================================================
  23. grad = grad(:);
  24. end

机器学习

Contributors (1)