从头开始在R中实现线性回归

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

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 

lr = 0.01,这是学习率。这是x和y数据的截图enter image description here


回答:

对我来说这个运行得很好。它产生了一个长度是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)

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注