costFunctionReg.m 1.1 KB

123456789101112131415161718192021222324252627282930
  1. function [J, grad] = costFunctionReg(theta, X, y, lambda)
  2. %COSTFUNCTIONREG Compute cost and gradient for logistic regression with regularization
  3. % J = COSTFUNCTIONREG(theta, X, y, lambda) computes the cost of using
  4. % theta as the parameter for regularized logistic regression and the
  5. % gradient of the cost w.r.t. to the parameters.
  6. % Initialize some useful values
  7. m = length(y); % number of training examples
  8. % You need to return the following variables correctly
  9. z = hypothesis(theta, X);
  10. t = lambda*(sum(theta .^ 2)-theta(1)^2)/2/m;
  11. J = mean(- y .* log(z) + (y - 1) .* log(1 - z)) + t;
  12. grad = mean((z - y) .* X)' + lambda /m * theta;
  13. grad(1) = grad(1) - lambda /m * theta(1);
  14. % ====================== YOUR CODE HERE ======================
  15. % Instructions: Compute the cost of a particular choice of theta.
  16. % You should set J to the cost.
  17. % Compute the partial derivatives and set grad to the partial
  18. % derivatives of the cost w.r.t. each parameter in theta
  19. % =============================================================
  20. end