I get an error when I try to run my logistic regression.
2 views (last 30 days)
Show older comments
This is my gradient function for logistic regression, but when I try to run it, I get an error that says "the left and right sides have a different number of elements". It refers to line 8. Any suggestions?
function [theta,J] = gradient(X_training, Y_training, alpha, theta, iterations)
J = 0; % Initial cost
m = length(Y_training);
for j = 1:iterations
h = sigmoid(X_training * theta);
error = h - Y_training;
for i = 1:length(theta)
line 8 -----> theta(i) = theta(i) - (alpha/m) * sum(error .* X_training(:,i)); % Updating thetas
end
J(j) = cost_function(X_training,Y_training,theta); % Cost of each iteration
end
end
0 Comments
Answers (2)
Torsten
on 12 Oct 2022
theta is not initialized - thus the theta(i) at the right-hand side of the assignment
theta(i) = theta(i) - (alpha/m) * sum(error .* X_training(:,i)); % Updating thetas
will throw an error.
Further,
sum(error .* X_training(:,i))
doesn't seem to be a scalar value, but a vector.
Maybe
sum((error.') .* X_training(:,i))
has to be used instead.
0 Comments
David Hill
on 12 Oct 2022
function [J, grad] = costFunction(theta, X, y)
m = length(y);
h=sigmoid(X*theta);
J=sum((-y.*log(h)-(1-y).*log(1-h)))/m;
grad=X'*(h-y)/m;
end
function g = sigmoid(z)
g=1./(1+exp(-z));
end
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!