Path: blob/master/Week 3/Programming Assignment - 2/machine-learning-ex2/ex2/costFunctionReg.m
863 views
function [J, grad] = costFunctionReg(theta, X, y, lambda)1%COSTFUNCTIONREG Compute cost and gradient for logistic regression with regularization2% J = COSTFUNCTIONREG(theta, X, y, lambda) computes the cost of using3% theta as the parameter for regularized logistic regression and the4% gradient of the cost w.r.t. to the parameters.56% Initialize some useful values7m = length(y); % number of training examples89% You need to return the following variables correctly10J = 0;11grad = zeros(size(theta));1213% ====================== YOUR CODE HERE ======================14% Instructions: Compute the cost of a particular choice of theta.15% You should set J to the cost.16% Compute the partial derivatives and set grad to the partial17% derivatives of the cost w.r.t. each parameter in theta1819thetaReg = theta;20thetaReg(1) = 0;21J = (-1/m) * sum ( (y.*log (sigmoid(X * theta))) + ((1-y).*log (1-sigmoid(X * theta)))) + ((lambda/(2*m)) * sum((thetaReg).^2));22grad = (1/m) * (X'*((sigmoid(X * theta)) - y)) + ((lambda/m) * (thetaReg));23% =============================================================2425end262728