【问题标题】:Getting NaN while implementing Linear regression在实现线性回归时获得 NaN
【发布时间】:2024-01-12 00:38:01
【问题描述】:

我正在尝试在 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。

【问题讨论】:

  • 原因是temp1temp2 在循环中的某个点变得无限,这会在后续迭代中创建NaN

标签: r linear-regression


【解决方案1】:

如果我们将print 用于其中一个“temp”,则值会在某个点变得无限,然后在下一次迭代中变为 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

【讨论】:

  • 从第一个值开始,我得到了 NaN,这不应该是一种情况,因为我是手动计算的,它大约是。 6
  • 我也用你的代码重试了,输出是一样的。 [1] NaN [1] NaN [1] NaN [1] NaN [1] NaN [1] NaN [1] NaN [1] NaN [1] NaN [1] NaN [1] NaN
  • @NeerajSharma 原因是你没有更新theta&lt;-c(0,0) 如果theta一开始就已经是NaN,它总是会给出那个值
  • 感谢您指出我的错误。我正在获取值,但它们似乎不是正确的 theta 值。需要进一步研究梯度下降的实现。再次感谢您。