Bây giờ tôi có một R
khung dữ liệu (đào tạo), bất cứ ai cũng có thể cho tôi biết làm thế nào để phân chia ngẫu nhiên bộ dữ liệu này để xác thực chéo 10 lần?
Bây giờ tôi có một R
khung dữ liệu (đào tạo), bất cứ ai cũng có thể cho tôi biết làm thế nào để phân chia ngẫu nhiên bộ dữ liệu này để xác thực chéo 10 lần?
Câu trả lời:
caret
có chức năng này:
require(caret)
flds <- createFolds(y, k = 10, list = TRUE, returnTrain = FALSE)
names(flds)[1] <- "train"
Sau đó, mỗi phần tử flds
là một danh sách các chỉ mục cho mỗi tập dữ liệu. Nếu tập dữ liệu của bạn được gọi dat
, sau đó dat[flds$train,]
sẽ đưa bạn tập huấn luyện, dat[ flds[[2]], ]
giúp bạn tập lần thứ hai, v.v.
Đây là một cách đơn giản để thực hiện 10 lần mà không cần gói:
#Randomly shuffle the data
yourData<-yourData[sample(nrow(yourData)),]
#Create 10 equally size folds
folds <- cut(seq(1,nrow(yourData)),breaks=10,labels=FALSE)
#Perform 10 fold cross validation
for(i in 1:10){
#Segement your data by fold using the which() function
testIndexes <- which(folds==i,arr.ind=TRUE)
testData <- yourData[testIndexes, ]
trainData <- yourData[-testIndexes, ]
#Use the test and train data partitions however you desire...
}
Có lẽ không phải là cách tốt nhất, nhưng đây là một cách để làm điều đó. Tôi khá chắc chắn khi tôi viết mã này, tôi đã mượn một mẹo từ một câu trả lời khác ở đây, nhưng tôi không thể tìm thấy nó để liên kết đến.
# Generate some test data
x <- runif(100)*10 #Random values between 0 and 10
y <- x+rnorm(100)*.1 #y~x+error
dataset <- data.frame(x,y) #Create data frame
plot(dataset$x,dataset$y) #Plot the data
#install.packages("cvTools")
library(cvTools) #run the above line if you don't have this library
k <- 10 #the number of folds
folds <- cvFolds(NROW(dataset), K=k)
dataset$holdoutpred <- rep(0,nrow(dataset))
for(i in 1:k){
train <- dataset[folds$subsets[folds$which != i], ] #Set the training set
validation <- dataset[folds$subsets[folds$which == i], ] #Set the validation set
newlm <- lm(y~x,data=train) #Get your new linear model (just fit on the train data)
newpred <- predict(newlm,newdata=validation) #Get the predicitons for the validation set (from the model just fit on the train data)
dataset[folds$subsets[folds$which == i], ]$holdoutpred <- newpred #Put the hold out prediction in the data set for later use
}
dataset$holdoutpred #do whatever you want with these predictions
vui lòng tìm bên dưới một số mã khác mà tôi sử dụng (mượn và điều chỉnh từ nguồn khác). Sao chép nó trực tiếp từ một kịch bản mà tôi chỉ sử dụng bản thân mình, còn lại trong thói quen rpart. Phần có lẽ được quan tâm nhất là các dòng về việc tạo ra các nếp gấp. Ngoài ra - bạn có thể sử dụng chức năng chéo từ gói bootstrap.
#define error matrix
err <- matrix(NA,nrow=1,ncol=10)
errcv=err
#creation of folds
for(c in 1:10){
n=nrow(df);K=10; sizeblock= n%/%K;alea=runif(n);rang=rank(alea);bloc=(rang-1)%/%sizeblock+1;bloc[bloc==K+1]=K;bloc=factor(bloc); bloc=as.factor(bloc);print(summary(bloc))
for(k in 1:10){
#rpart
fit=rpart(type~., data=df[bloc!=k,],xval=0) ; (predict(fit,df[bloc==k,]))
answers=(predict(fit,df[bloc==k,],type="class")==resp[bloc==k])
err[1,k]=1-(sum(answers)/length(answers))
}
err
errcv[,c]=rowMeans(err, na.rm = FALSE, dims = 1)
}
errcv
# Evaluate models uses k-fold cross-validation
install.packages("DAAG")
library("DAAG")
cv.lm(data=dat, form.lm=mod1, m= 10, plotit = F)
Tất cả mọi thứ được thực hiện cho bạn trong một dòng mã!
?cv.lm for information on input and output
Vì tôi không tiếp cận trong danh sách này, tôi nghĩ rằng tôi có thể chia sẻ tùy chọn khác cho những người không muốn cài đặt gói để xác thực chéo nhanh
# get the data from somewhere and specify number of folds
data <- read.csv('my_data.csv')
nrFolds <- 10
# generate array containing fold-number for each sample (row)
folds <- rep_len(1:nrFolds, nrow(data))
# actual cross validation
for(k in 1:nrFolds) {
# actual split of the data
fold <- which(folds == k)
data.train <- data[-fold,]
data.test <- data[fold,]
# train and test your model with data.train and data.test
}
Lưu ý rằng mã ở trên giả định rằng dữ liệu đã được xáo trộn. Nếu đây không phải là trường hợp, bạn có thể xem xét thêm một cái gì đó như
folds <- sample(folds, nrow(data))