【发布时间】:2017-02-23 04:53:44
【问题描述】:
我正在cafe 数据集上构建线性回归,我想通过计算留一法交叉验证来验证结果。
我为此编写了自己的函数,如果我在所有数据上拟合 lm(),则该函数有效,但是当我使用列的子集(来自逐步回归)时,我收到错误消息。考虑以下代码:
cafe <- read.table("C:/.../cafedata.txt", header=T)
cafe$Date <- as.Date(cafe$Date, format="%d/%m/%Y")
#Delete row 34
cafe <- cafe[-c(34), ]
#wont need date
cafe <- cafe[,-1]
library(DAAG)
#center the data
cafe.c <- data.frame(lapply(cafe[,2:15], function(x) scale(x, center = FALSE, scale = max(x, na.rm = TRUE))))
cafe.c$Day.of.Week <- cafe$Day.of.Week
cafe.c$Sales <- cafe$Sales
#Leave-One-Out CrossValidation function
LOOCV <- function(fit, dataset){
# Attributes:
#------------------------------
# fit: Fit of the model
# dataset: Dataset to be used
# -----------------------------
# Returns mean of squared errors for each fold - MSE
MSEP_=c()
for (idx in 1:nrow(dataset)){
train <- dataset[-c(idx),]
test <- dataset[idx,]
MSEP_[idx]<-(predict(fit, newdata = test) - dataset[idx,]$Sales)^2
}
return(mean(MSEP_))
}
然后当我拟合简单的线性模型并调用该函数时,它就起作用了:
#----------------Simple Linear regression with all attributes-----------------
fit.all.c <- lm(cafe.c$Sales ~., data=cafe.c)
#MSE:258
LOOCV(fit.all.c, cafe.c)
但是,当我仅将相同的 lm() 与列的子集匹配时,会出现错误:
#-------------------------Linear Stepwise regression--------------------------
step <- stepAIC(fit.all.c, direction="both")
fit.step <- lm(cafe.c$Sales ~ cafe.c$Bread.Sand.Sold + cafe.c$Bread.Sand.Waste
+ cafe.c$Wraps.Waste + cafe.c$Muffins.Sold
+ cafe.c$Muffins.Waste + cafe.c$Fruit.Cup.Sold
+ cafe.c$Chips + cafe.c$Sodas + cafe.c$Coffees
+ cafe.c$Day.of.Week,data=cafe.c)
LOOCV(fit.step, cafe.c)
5495.069
有 50 个或更多警告(使用 warnings() 查看前 50 个)
如果我仔细观察:
idx <- 1
train <- cafe.c[-c(idx)]
test <- cafe.c[idx]
(predict(fit.step, newdata = test) -cafe.c[idx]$Sales)^2
我得到所有行的 MSE 和一个错误:
警告信息: 'newdata' 有 1 行,但找到的变量有 47 行
编辑
我发现了this关于错误的问题,它说当我为列指定不同的名称时会发生此错误,但事实并非如此。
【问题讨论】:
-
并没有想太多,但我首先想到的是 LOOCV 调用 predict.lm 并且它不能基于数据集 cafe.c 进行预测,因为变量名称lm 中使用的你是通过 cafe.c$some_variable 传递的。试试同样的公式,只写 some_variable 而不是 cafe.c$some_variable,也许它可以工作......!
标签: r machine-learning cross-validation