我正在尝试编写一个使用梯度下降法的简单线性回归的基本代码。这里是我的代码。
linear = function(x,y,lr){theta0 = 0theta1 = 0m=length(x)hypo = theta0 +theta1*xcostt = cost(hypo , y)prev_cost = 1000000while (prev_cost > cost){prev_cost = costtheta0 = theta0 - (lr/m)*(hypo - y)theta1 = theta1 - (lr/m)*(hypo - y)*xhypo = theta0 + theta1*xNew_cost = cost(hypo , y)if(New_cost < cost){cost = New_cost}}theta = c(theta0 , theta1)return( theta )} cost = function(hypo , y){interm = (hypo - y)^2interm1 = sum(interm)interm2 = interm1/(2 * m)return(interm2) }
但是当我用数据测试它时,会生成一个警告消息。
There were 50 or more warnings (use warnings() to see the first 50)
然后停止运行。代码哪里出了问题?当我使用warnings()时,我得到以下信息:
Warning messages:1: In while (prev_cost > cost) { ... :the condition has length > 1 and only the first element will be used
回答:
对我来说这个运行得很好。它产生了一个长度是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.01linear(x, y, lr)