Advertisement
Guest User

Untitled

a guest
Mar 10th, 2017
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Octave 1.65 KB | None | 0 0
  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.  
  7. % Initialize some useful values
  8. m = length(y); % number of training examples
  9. n = size(X, 2); % number of features
  10.  
  11. % You need to return the following variables correctly
  12. J = 0;
  13. grad = zeros(size(theta));
  14.  
  15. % ====================== YOUR CODE HERE ======================
  16. % Instructions: Compute the cost of a particular choice of theta.
  17. %               You should set J to the cost.
  18. %               Compute the partial derivatives and set grad to the partial
  19. %               derivatives of the cost w.r.t. each parameter in theta
  20.  
  21. % ==== Evaluating the cost ====
  22. %First part, without Regularization
  23. for i = 1:m
  24.     hypothesis = sigmoid(theta' * X(i, :)');
  25.     J += y(i) * log(hypothesis) + (1 - y(i)) * log(1 - hypothesis);
  26. end;
  27. J *= -1 / m;
  28.  
  29. %Regularization (penalizing the parameters)
  30. secondPart = 0;
  31. for j = 2:n
  32.     secondPart += theta(j) ^ 2;
  33. end;
  34. secondPart *= lambda / (2 * m);
  35. J += secondPart;
  36.  
  37. % ==== Evaluating the gradient ====
  38. for i = 1:m
  39.     hypothesis = sigmoid(theta' * X(i, :)');
  40.     grad(1) += (hypothesis - y(i)) * X(i, 1);
  41. end;
  42. grad(1) *= 1 / m;
  43.  
  44. for j = 2:n
  45.     for i = 1:m
  46.         hypothesis = sigmoid(theta' * X(i, :)');
  47.         grad(j) += (hypothesis - y(i)) * X(i, j);
  48.     end;
  49.     grad(j) *= 1 / m;
  50.     grad(j) += (lambda * theta(j)) / m;
  51. end;
  52.  
  53. % =============================================================
  54.  
  55. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement