我正在尝试使用单个变量实现线性回归以进行线性回归(来自standford's course的练习1关于机器学习的课程)。
现在,我的代码实现将是这样的:
for iter = 1:num_iters
temp1 = theta(1) - alpha * sum(X * theta - y) / m;
temp2 = theta(2) - alpha * sum( (X * theta - y) .* X(2) ) / m;
theta(1) = temp1;
theta(2) = temp2;
,其中
我尝试用一个小例子(m = 4)手动执行此操作,我认为我的代码是正确的...但显然不是,或者我不会在这里写。当我运行算法时,根据我传递给函数的初始theta,我得到一个不同的theta作为回报,如果我绘制成本函数,它显然不适合theta的某些值(不是全部):
这可能意味着我并不真正理解数学(这可以解释为什么stackoverflow上的其他人都在使用'transpose'而我没有),问题是我不知道哪个是我的'我遇到了麻烦。
我真的很感激一些见解,但我想自己完成练习。基本上我正在寻求帮助,但不是寻求完整的解决方案
编辑:显然这不是逻辑错误,而是语义错误。在分配temp2时,我应该写(X * theta - y) .* X(:,2)
而不是(X * theta - y) .* X(2)
;基本上,我没有选择X的第二列(这是一个mX2矩阵),而是一个标量(由于octave的语法)。
答案 0 :(得分:2)
我只是简单地看了一下课程,看起来你大部分都在正确的轨道上,但这里有一些有用的提示:
以下是您可以开始工作的起点:
for iter = 1:num_iters
theta(1) = theta(1) - alpha * sum( (theta(1)+theta(2).*X) - y) / m;
theta(2) = theta(2) - alpha * sum( ((theta(1)+theta(2).*X) - y) .* X ) / m;
答案 1 :(得分:2)
根据梯度下降算法,您必须同时更新theta(1)
和theta(2)
的值。您无法先更新theta(1)
的值,然后再使用更新后的theta(2)
值来计算theta(1)
的值。
检查此代码以更好地理解:
m = length(y); % number of training examples
J_history = zeros(num_iters, 1);
for iter = 1:num_iters
x = X(:,2);
h = theta(1) + (theta(2)*x);
theta_zero = theta(1) - alpha * (1/m) * sum(h-y);
theta_one = theta(2) - alpha * (1/m) * sum((h - y) .* x);
theta = [theta_zero; theta_one];
J_history(iter) = computeCost(X, y, theta);
end
在这里,我同时更新了theta(1)
和theta(2)
的值。梯度下降算法的定义是重复直到收敛并同时更新theta的值。
答案 2 :(得分:0)
请尝试以下操作(带有一个变量的线性回归):
m = length(y);
J_history = zeros(num_iters, 1);
for iter = 1:num_iters
% Normal Equation
% theta = pinv(X'*X)*X'*y;
predictions = X * theta;
delta = (1/m) * X' * (predictions - y);
theta = theta - alpha * delta;
% Save the cost J in every iteration
J_history(iter) = computeCost(X, y, theta);
end