我正在尝试计算多个特征的梯度下降。以下是我使用的代码:
data = load('ex1data2.txt');
X = data(:, 1:2);
y = data(:, 3);
m = length(y);
[X mu sigma] = featureNormalize(X);
alpha = 0.01;
num_iters = 400;
theta = zeros(3, 1);
[theta, J_history] = gradientDescentMulti(X, y, theta, alpha, num_iters);
function [theta, J_history] = gradientDescentMulti(X, y, theta, alpha, num_iters)
m = length(y);
J_history = zeros(num_iters, 1);
for iter = 1:num_iters
h = X*theta;
for i = 1:size(X,2)
temp(i) = theta(i,1) - (alpha/m) * sum((h-y).*X(:,i));
theta (i,1) = temp(i);
end
J_history(iter) = computeCostMulti(X, y, theta);
end
end
我为单特征回归设置了相同的线,并且效果很好。但是当我尝试使用多个变量时,theta值很奇怪。
有人可以帮我解决这个问题吗?
谢谢。