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

2 visualizzazioni (ultimi 30 giorni)
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

Risposte (2)

Torsten
Torsten il 12 Ott 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 il 12 Ott 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 Commento
Seyed Navid Shoaiby
Seyed Navid Shoaiby il 12 Ott 2022
This code works, but I want to keep track of "J" in each iteration. I need a "for loop" to do that.

Accedi per commentare.

Categorie

Scopri di più su Mathematics in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by