r - 实现线性回归时得到 NaN

标签 r linear-regression

我正在尝试在 R 中实现线性回归。下面是我的代码:

library(ggplot2)
df <- data.frame()

df<-cbind(c(10000,20000,5000,5123,5345,5454,11000,23000,6000,6100,6300),
c(5600,21000,1000,2000,2300,3000,7000,21400,3200,3250,3300))

df <- as.data.frame(df)
colnames(df)<-c("Population","Profit")

plot(df,df$Population,df$Profit)

X<-df$Population
Y<-df$Profit
X<-cbind(1,X)
theta<-c(0,0)
m<-nrow(X)
cost=sum(((X %*% theta)-Y)^2)/(2*m)
alpha<-0.001
iterations<-1500

for(i in 1:iterations){
  temp1 <- theta[1] - alpha * (1/m) * sum(((X%*%theta)- Y))
  temp2 <- theta[2] <- theta[2] - alpha * (1/m) * sum(((X%*%theta)- Y)*X[,2])
  theta[1] = temp1
  theta[2] = temp2
}

但是我得到的 theta 值为 NaN。需要帮助来理解为什么得到 NaN。

最佳答案

如果我们对其中一个“temp”使用print,则这些值在某个点会变得无穷大,然后对于下一次迭代,它会变为 NaN

iterations <- 62

for(i in 1:iterations){
  temp1 <- theta[1] - alpha * (1/m) * sum(((X%*%theta)- Y))
  temp2 <- theta[2] <- theta[2] - alpha * (1/m) * sum(((X%*%theta)- Y)*X[,2])
  print(temp1)
  #print(temp2)
  theta[1] = temp1
  theta[2] = temp2
}

-打印输出

#[1] 6.640909
#[1] -981047.5
#[1] 122403140248
#[1] -1.527201e+16
#[1] 1.90546e+21
#[1] -2.377406e+26
#[1] 2.966245e+31
#[1] -3.700928e+36
#[1] 4.617578e+41
#...
#...
#[1] 1.894035e+286
#[1] -2.363151e+291
#[1] 2.948459e+296
#[1] -3.678737e+301
#[1] Inf
#[1] NaN

关于r - 实现线性回归时得到 NaN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49600778/

相关文章:

r - R 中的精确匹配和 GenMatch

r - 从批处理文件执行 Rscript - 无法正确处理 "Umlaute"(ä, ö, ü)

r - 为什么在异步代码中使用 withr::with_seed 和 R.utils::withSeed 会产生不同的结果?

python - 使用 statsmodels 线性回归拟合下降趋势(负斜率)

r - R中的线性回归而不在内存中复制数据?

R计算几年来每天的趋势

r - Rmarkdown/knitr 中的 texreg

R 不使用 For 循环对数据进行子集化

r - 线性回归并将结果存储在数据框中

matlab - matlab 中的岭回归