【问题标题】:Gradient descent does not converge for linear regression梯度下降不会收敛于线性回归
【发布时间】:2020-10-10 11:56:02
【问题描述】:

我在 Octave 中编写了一个简单的线性回归算法,但无论我选择什么样的学习率和迭代次数,甚至在纸上画出矩阵,theta 的值都不会收敛。任何人都可以看到我的代码中的任何错误吗?

data = load('ex1data2.txt');
X = data(:,1:2);
y = data(:,3);          
m = rows(X);        
X = [ones(m,1), data(:,1:2)];   

alpha = 0.01;

iterations = 5000;          

n = columns(X);                 

theta = zeros(n,1);

for count = 1:iterations

    hypo = zeros(1,m);
    hypo = theta'*X';
    sqr_err = (hypo-y').*(hypo-y');
    sum_sqr_err = sum(sqr_err);
    J = 1/(2*m)*sum_sqr_err;

    for i = 1:n
        theta(i) = theta(i)-(alpha/m)*((hypo-y')*X(:,i));
    end

end

J
theta

谢谢。

【问题讨论】:

  • 您需要提供一组输入数据。您的代码应该有 cmets,以便我们了解您想要做什么。
  • 附带说明,使用ordinary least square method 或标准化方程将更容易编码。

标签: machine-learning octave linear-regression gradient-descent


【解决方案1】:

在 Matlab online 中,我在 47 次迭代中收敛:

data = load('ex1data2.txt');
X = data(:,1:2);
y = data(:,3);

mu = mean(X); % Mean.
s = max(X) - min(X); % Range.
X = X - mu;
X = X ./ s; 

m = size(X, 1); % Number of rows.
n = size(X, 2); % Number of columns.
X = [ones(m, 1) X]; % Add columns of ones to add biasing.
theta = zeros(n+1,1); % Initializing theta.

J = costFunction(X,y,theta);

alpha = 2.02;
iterations = 100;          

j_hist = zeros(iterations,1); % Initializing j_hist.
m = size(X, 1);
n = size(theta,1);

for i=1 : iterations
    hypo = X*theta;
    for j = 1 : n
        theta(j) = theta(j) - alpha*(1/m)*sum((hypo - y).*X(:,j));
    end
    j_hist(i) = costFunction(X,y,theta);
end

function J = costFunction(X,y,theta)
    prediction = X*theta;
    m = size(X, 1);
    sqError = (prediction - y).^2; % ignore negative vals.
    J = (1/(2*m))*sum(sqError); % derivative of sqroot cancels.
end

%J
%j_hist
%theta

然后,运行后,您可以取消注释,一次单独检查 J、j_hist 和 theta。

【讨论】:

    【解决方案2】:

    sqr_err = (hypo-y').*(hypo-y')

    尝试删除“。”

    【讨论】:

    • 我想对各个条款进行平方,不会删除“。”对整个矩阵求平方?此外,由于尺寸的原因,您不能对这个特定的矩阵进行平方。谢谢。
    猜你喜欢
    • 2018-07-05
    • 2017-08-09
    • 1970-01-01
    • 2017-07-17
    • 1970-01-01
    • 2015-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多