Filter löschen
Filter löschen

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

1 Ansicht (letzte 30 Tage)
Seyed Navid Shoaiby
Seyed Navid Shoaiby am 12 Okt. 2022
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

Antworten (2)

Torsten
Torsten am 12 Okt. 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.

David Hill
David Hill am 12 Okt. 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
  1 Kommentar
Seyed Navid Shoaiby
Seyed Navid Shoaiby am 12 Okt. 2022
This code works, but I want to keep track of "J" in each iteration. I need a "for loop" to do that.

Melden Sie sich an, um zu kommentieren.

Community Treasure Hunt

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

Start Hunting!

Translated by