Skip to content

Instantly share code, notes, and snippets.

@sheki
Created October 27, 2011 07:03
Show Gist options
  • Select an option

  • Save sheki/1318950 to your computer and use it in GitHub Desktop.

Select an option

Save sheki/1318950 to your computer and use it in GitHub Desktop.
function [J, grad] = costFunction(theta, X, y)
%COSTFUNCTION Compute cost and gradient for logistic regression
% J = COSTFUNCTION(theta, X, y) computes the cost of using theta as the
% parameter for logistic regression and the gradient of the cost
% w.r.t. to the parameters.
% Initialize some useful values
m = length(y); % number of training examples
% You need to return the following variables correctly
J = 0;
grad = zeros(size(theta));
% ====================== YOUR CODE HERE ======================
% Instructions: Compute the cost of a particular choice of theta.
% You should set J to the cost.
% Compute the partial derivatives and set grad to the partial
% derivatives of the cost w.r.t. each parameter in theta
%
% Note: grad should have the same dimensions as theta
%
#disp(X)
#disp (theta)
disp(size(X))
disp(size(theta))
t = (theta' * X')';
h = sigmoid(t);
J = 0
% How to vectorize this?
for i = 1:length(h)
th = h(i,1)
ty = y(i,1)
c = -ty * log(th ) - (1-ty) * log (1-th)
J=J+c
endfor
J = J/m
% =============================================================
end
@ethaniel0

Copy link
Copy Markdown

h = sigmoid((theta' * X')');

J = sum((-y.*log(h)) - (1-y).*log(1-h)) / m;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment