我正在尝试计算
其中h(x) = X*theta, theta is nx1 matrix and X is an mxn and y is also m x 1
矩阵。 alpha,m,theta(j) and x(j)(i)
是标量值。我正在尝试通过以下方式对此向量化
theta0 =(X*theta - y)
theta1 = (X*theta - y).*X(:,2)
theta0 = sum(theta0);
theta1 = sum(theta1);
theta0 = theta(1) - theta0*alpha/m;
theta1 = theta(2) - theta1*alpha/m;
theta = [theta0;theta1];
其中num_iter=1500
和m=length(y)
,但是我的代码进入了无限循环。我的等效循环解决方案如下
theta0 =0;
theta1= 0;
for i = 1:m,
theta0 = theta0 + (sum(X(i,:)*theta) - y(i));
theta1 = theta1 + (sum(X(i,:)*theta) - y(i))*X(i,2);
end
theta(1) = theta(1) - theta0*alpha/m;
theta(2) = theta(2) - theta1*alpha/m;
请告诉我我哪里出问题了
答案 0 :(得分:0)
公式可以以矢量化方式编写为:
theta = theta - alpha/m * ((X*theta - y).' *X).';