I get an error when I try to run my logistic regression.

2 次查看(过去 30 天)
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

回答(2 个)

Torsten
Torsten 2022-10-12
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.

David Hill
David Hill 2022-10-12
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

类别

Help CenterFile Exchange 中查找有关 Mathematics 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by