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

2 ビュー (過去 30 日間)
Seyed Navid Shoaiby
Seyed Navid Shoaiby 2022 年 10 月 12 日
コメント済み: Seyed Navid Shoaiby 2022 年 10 月 12 日
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
  1 件のコメント
Seyed Navid Shoaiby
Seyed Navid Shoaiby 2022 年 10 月 12 日
This code works, but I want to keep track of "J" in each iteration. I need a "for loop" to do that.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeMathematics についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by