【问题标题】:Linear Regression Code线性回归码
【发布时间】:2019-01-29 19:54:27
【问题描述】:

我正在参加Andrew Ng 课程关于机器学习并实施线性回归算法。

我的代码有什么问题?

function [theta, J_history] = gradientDescent(X, y, theta, alpha, num_iters)
m = length(y); 
J_history = zeros(num_iters, 1);
h = (X*theta)
for iter = 1:num_iters
    theta(1,1) = theta(1,1)-(alpha/m)*sum((h-y).*X(:,1));
    theta(2,1) = theta(2,1)-(alpha/m)*sum((h-y).*X(:,2));  
    J_history(iter) = computeCost(X, y, theta);
end
end

成本函数如下:

function J = computeCost(X, y, theta)
m = length(y); 
h = (X*theta)
J = (1/(2*m))*sum((h-y).^2)
end

J_history 的值不断增加。它给出的值非常不正常(大值),即比它应该的值高出大约 1000 倍。

【问题讨论】:

  • 如果你解释一下你是如何知道有问题的,回答这样的问题会容易得多。这意味着要么发布完整的错误消息(最好带有示例输入),要么发布输出并解释为什么它与您的预期不同。您可以编辑您的帖子以添加这些内容。
  • J_history 的值不断增加它给出了非常不正常的(大值),即比它应该多出大约 1000 倍。 .
  • 你能添加一些示例数据吗?否则很难调试数值算法
  • 你不应该在theta之后更新h吗?
  • 您在computeCost 函数中更新h,但没有将其作为输出参数,因此您的代码继续使用h 的先前值

标签: matlab linear-regression gradient-descent


【解决方案1】:

您需要在for循环中更新htheta,如下所示

function [theta, J_history] = gradientDescent(X, y, theta, alpha, num_iters)
m = length(y); 
J_history = zeros(num_iters, 1);

for iter = 1:num_iters
    h = ((X*theta)-y)'*X;
    theta = theta - alpha*(1/m)*h';
    J_history(iter) = computeCost(X, y, theta);
end
end

【讨论】:

    猜你喜欢
    • 2023-02-11
    • 2012-10-28
    • 2018-07-31
    • 2019-10-09
    • 1970-01-01
    • 2017-06-17
    • 2013-02-11
    • 2018-05-16
    • 1970-01-01
    相关资源
    最近更新 更多