Path: blob/master/Week 4/Programming Assignment - 3/machine-learning-ex3/ex3/lrCostFunction.m
864 views
function [J, grad] = lrCostFunction(theta, X, y, lambda)1%LRCOSTFUNCTION Compute cost and gradient for logistic regression with2%regularization3% J = LRCOSTFUNCTION(theta, X, y, lambda) computes the cost of using4% theta as the parameter for regularized logistic regression and the5% gradient of the cost w.r.t. to the parameters.67% Initialize some useful values8m = length(y); % number of training examples910% You need to return the following variables correctly11J = 0;12grad = zeros(size(theta));1314% ====================== 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 partial18% derivatives of the cost w.r.t. each parameter in theta19%20% Hint: The computation of the cost function and gradients can be21% efficiently vectorized. For example, consider the computation22%23% sigmoid(X * theta)24%25% Each row of the resulting matrix will contain the value of the26% prediction for that example. You can make use of this to vectorize27% the cost function and gradient computations.28%29% Hint: When computing the gradient of the regularized cost function,30% there're many possible vectorized solutions, but one solution31% looks like:32% grad = (unregularized gradient for logistic regression)33% temp = theta;34% temp(1) = 0; % because we don't add anything for j = 035% grad = grad + YOUR_CODE_HERE (using the temp variable)36%3738thetaReg = theta;39thetaReg(1) = 0;40J = (-1/m) * sum ( (y.*log (sigmoid(X * theta))) + ((1-y).*log (1-sigmoid(X * theta)))) + ((lambda/(2*m)) * sum(thetaReg.^2));41grad = (1/m) * (X'*((sigmoid(X * theta)) - y)) + ((lambda/m) * thetaReg);42% =============================================================4344grad = grad(:);4546end474849