0
배 교차 검증 방법을 사용하여 포워드 선택을 사용하여 장착 된 잔여 모델 19 개를 비교합니다. 나는 마지막 단계에 갇혔다. 코드는 다음과 같습니다.lapply에 seq_along을 사용합니다.
library(ISLR)
summary(Hitters) # Use the dataset of Hitters
Hitters = na.omit(Hitters)
library(leaps)
set.seed(11)
folds = sample(rep(1:10,length=nrow(Hitters))) # used for cross validation later
table(folds)
cv.errors = matrix(NA,10,19)
# store the errors from 10 validations, each contains an error for a model
# write a prediction function
predict.regsubsets = function(object,newdata,id,...){
form = as.formula(object$call[[2]]) # extract the formula
mat = model.matrix(form,newdata) # extract the exploratory data
coefi = coef(object,id=id) # coefficients for the ith model
return(mat[,names(coefi)]%*%coefi) # manually get the predicted value
}
# write a function to extract the Mean of squared root of residuals
error = function(object,newdata,origin,num,...){
pred = lapply(seq_along(1:num),function(x){predict.regsubsets(object,newdata,id=x)})
sapply(pred,function(x){mean((x-origin)^2)})
}
# this gives error: $ operator is invalid for atomic vectors
lapply(seq_along(1:10),function(X){
best.fit = regsubsets(Salary~.,data=Hitters[folds!=X,],nvmax=19,method="forward")
cv.errors[X,]=error(best.fit,newdata=Hitters[folds==X,],origin=Hitters$Salary[folds==X],num=19)
})
# this works well, except for being slow...
for(X in 1:10){
best.fit = regsubsets(Salary~.,data=Hitters[folds!=X,],nvmax=19,method="forward")
cv.errors[X,]=error(best.fit,newdata=Hitters[folds==X,],origin=Hitters$Salary[folds==X],num=19)
}
고마워요!
이것이 문제를 해결할 수 있는지 확실하지 않지만 : 여기에 'seq_along'을 정말로 사용해야합니까? '1 : 10'만으로 충분합니다. – Shambho
'seq_along (1:10)'의 값은 1:10이므로 seq_along은 중복됩니다. 자신의 롤링보다는'cvTools' 패키지 사용을 고려하십시오. –
여기에 귀하의 질문은 무엇입니까? 분명하지 않아. –