楼主: 痴迷花花
6847 2

[问答] 求助 “变数长度不一致” [推广有奖]

  • 0关注
  • 0粉丝

初中生

85%

还不是VIP/贵宾

-

威望
0
论坛币
6 个
通用积分
0
学术水平
0 点
热心指数
0 点
信用等级
0 点
经验
334 点
帖子
12
精华
0
在线时间
18 小时
注册时间
2017-10-6
最后登录
2021-9-16

楼主
痴迷花花 发表于 2017-11-11 04:47:00 |AI写论文

+2 论坛币
k人 参与回答

经管之家送您一份

应届毕业生专属福利!

求职就业群
赵安豆老师微信:zhaoandou666

经管之家联合CDA

送您一个全额奖学金名额~ !

感谢您参与论坛问题回答

经管之家送您两个论坛币!

+2 论坛币


数据载入Boston,求cross-validation

我的代码是
library(ggplot2)  
library(MASS)
#利用函数poly进行高次拟合,该函数可以将自变量自动进行高次变化,degree参数控制着最高次项的次数如下:
fit3=lm(nox~poly(dis,4),data=Boston)
yy3 = predict(fit3)
df <- transform(Boston,yy3 = predict(fit3))  

ggplot(data=Boston,aes(x=dis,y=nox)) + geom_point()+geom_line(aes(x=dis,y=yy3),data=Boston,col='blue')  

rmse <- function(nox,rnox)  

{  

   return(sqrt(sum((nox-rnox)^ 2))/length(rnox))  

}

split <- function(Boston,rate)  

{  

   n <- length(Boston[,1])  

   index <- sample(1:n,round(rate * n))  

   train <- Boston[index,]  

   test <- Boston[-index,]  

  df <- list(train=train,test=test,data=Boston)  

   return(df)  

}  



performance_Gen <- function(Boston,n){

   performance <- data.frame()  

   for(index in 1:n){  


     fit <- lm(y ~ poly(dis,degree=index),data = Boston$train)  

     performance <- rbind(performance,data.frame(degree =index,type='train',rmse=rmse(Boston$train['nox'],predict(fit))))  

     performance <- rbind(performance,data.frame(degree = index,type='test',rmse=rmse(Boston$test['nox'],predict(fit,newdata=Boston$test))))  

   }  

   return(performance)  

}

df_split <- split(df,0.5)  
performance<- performance_Gen(df_split,10)

ggplot(performance,aes(x=degree,y=rmse,linetype=type))+geom_point()+geom_line()


在运行到performance<- performance_Gen(df_split,10) 时报错变数的长度不一样('poly(dis, degree = index)')
完全看不懂什么意思,都运行到就差一步了,内心十分崩溃~求高人指点,万分感谢
二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

关键词:Validation Library predict ggplot2 Boston R语言 数据可视化

沙发
GOD.M.W 学生认证  发表于 2017-11-12 11:36:13 来自手机
痴迷花花 发表于 2017-11-11 04:47
数据载入Boston,求cross-validation

我的代码是
这个函数里用lm拟合的y没有指定变量。换成nox试试。

藤椅
痴迷花花 发表于 2017-11-13 21:19:02
GOD.M.W 发表于 2017-11-12 11:36
这个函数里用lm拟合的y没有指定变量。换成nox试试。
是说 fit <- lm(y ~ poly(dis,degree=index),data = Boston$train)
改成fit <- lm(y ~ nox,data = Boston$train)   吗?可是还是报错啊
【 Error in model.frame.default(formula = y ~ nox, data = Boston$train, drop.unused.levels = TRUE) :
  变数的长度不一样('nox') 】

您需要登录后才可以回帖 登录 | 我要注册

本版微信群
加好友,备注cda
拉您进交流群
GMT+8, 2025-12-9 14:19