【问题标题】:Linear regression from scratch in rr中从零开始的线性回归
【发布时间】:2019-02-25 20:37:39
【问题描述】:

我正在尝试使用梯度下降法编写简单线性回归的基本代码。 这是我的代码。

linear = function(x,y,lr)
{
theta0 = 0

theta1 = 0

m=length(x)

hypo = theta0 +theta1*x

costt = cost(hypo , y)
prev_cost = 1000000

while (prev_cost > cost)
{

prev_cost = cost

theta0 = theta0 - (lr/m)*(hypo - y)

theta1 = theta1 - (lr/m)*(hypo - y)*x

hypo = theta0 + theta1*x

New_cost = cost(hypo , y)

if(New_cost < cost)
{
cost = New_cost
}
}
theta = c(theta0 , theta1)
return( theta )
}  

cost = function(hypo , y)
{
interm = (hypo - y)^2

interm1 = sum(interm)

interm2 = interm1/(2 * m)

return(interm2)  
}

但是当我用数据对其进行测试时,它会生成一条警告消息。

There were 50 or more warnings (use warnings() to see the first 50)

并停止终止。 代码有什么问题? 当我使用警告时,我得到了

Warning messages:
1: In while (prev_cost > cost) { ... :
the condition has length > 1 and only the first element will be used 

lr = 0.01 这是学习率。 这是数据 x 和 y 的快照

【问题讨论】:

  • 请使用warnings() 并编辑您的问题。我们需要查看实际的错误消息。通常所有的警告都是一样的
  • 但并非所有警告都是平等创建的。
  • 我在上面的代码中使用的逻辑是对的吗? @mischva11
  • 条件的长度 > 1 并且只会使用第一个元素——这是我使用警告时得到的结果
  • costt = cost(hypo , y) - 不应该是cost = cost(hypo , y) 吗?另外,如果代码停止运行,是否有错误?请粘贴warnings()的输出

标签: r algorithm machine-learning linear-regression


【解决方案1】:

这适合我。它生成的向量长度是 length(x) 的两倍 - 这就是你想要的吗?

linear = function(x,y,lr)
{
    theta0 = 0

    theta1 = 0

    m=length(x)

    hypo = theta0 +theta1*x

    costt = cost(hypo , y, m)
    prev_cost = 1000000

    while (prev_cost > costt)
    {

        prev_cost = costt

        theta0 = theta0 - (lr/m)*(hypo - y)

        theta1 = theta1 - (lr/m)*(hypo - y)*x

        hypo = theta0 + theta1*x

        New_cost = cost(hypo , y, m)

        if(New_cost < costt)
        {
            costt = New_cost
        }
    }
    theta = c(theta0 , theta1)
    return( theta )
}  

cost = function(hypo , y, m)
{
    interm = (hypo - y)^2

    interm1 = sum(interm)

    interm2 = interm1/(2 * m)

    return(interm2)  
}

x <- rnorm(80)
y <- rnorm(80)
lr <- 0.01
linear(x, y, lr)

【讨论】:

  • thankq 先生现在它的工作,但不幸的是我写了一个错误的梯度体面代码
猜你喜欢
  • 1970-01-01
  • 2023-04-03
  • 2021-01-20
  • 2021-04-22
  • 1970-01-01
  • 2020-06-12
  • 2020-04-08
  • 1970-01-01
  • 2020-07-13
相关资源
最近更新 更多