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