【发布时间】: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。
【问题讨论】:
-
原因是
temp1和temp2在循环中的某个点变得无限,这会在后续迭代中创建NaN
标签: r linear-regression