Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
hackassin
GitHub Repository: hackassin/Coursera-Machine-Learning
Path: blob/master/Week 3/Programming Assignment - 2/machine-learning-ex2/ex2/costFunctionReg.m
863 views
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
10
% You need to return the following variables correctly
11
J = 0;
12
grad = zeros(size(theta));
13
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
thetaReg = theta;
21
thetaReg(1) = 0;
22
J = (-1/m) * sum ( (y.*log (sigmoid(X * theta))) + ((1-y).*log (1-sigmoid(X * theta)))) + ((lambda/(2*m)) * sum((thetaReg).^2));
23
grad = (1/m) * (X'*((sigmoid(X * theta)) - y)) + ((lambda/m) * (thetaReg));
24
% =============================================================
25
26
end
27
28