2014-04-25 1 views
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) 
} 

고마워요!

+0

이것이 문제를 해결할 수 있는지 확실하지 않지만 : 여기에 'seq_along'을 정말로 사용해야합니까? '1 : 10'만으로 충분합니다. – Shambho

+0

'seq_along (1:10)'의 값은 1:10이므로 seq_along은 중복됩니다. 자신의 롤링보다는'cvTools' 패키지 사용을 고려하십시오. –

+0

여기에 귀하의 질문은 무엇입니까? 분명하지 않아. –

답변

0

이것은 범위 지정 문제 일 수 있습니다. 시도하지 않았지만 다음을 시도해보십시오.

lapply(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) 
}) 

여기서 유일한 변경 사항은 assignment operator입니다.

또한 문제가 해결 될지 확실하지 않지만 실제로 여기에 seq_along을 사용해야합니까? 그냥 1:10이면 충분합니다.