Skip to content

Instantly share code, notes, and snippets.

@Leon-Ray
Leon-Ray / lrCostFunction
Last active January 31, 2022 22:40
Vectorized logistic regression with regularization using gradient descent for the Coursera course Machine Learning. Cost function (J) and partial derivatives of the cost w.r.t. each parameter in theta (grad).
len = size(theta);
J = 1/m*(-y'*log(sigmoid(X*theta))-(1-y)'*log(1-sigmoid(X*theta))) + lambda/(2*m)*sum(theta(2:len).^2);
grad = 1./m*((sigmoid(X*theta)-y)'*X);
temp = theta;
temp(1) = 0;
grad = grad + (lambda/m.*temp)';