1. 交叉驗證基本介紹
通常在建立模型后需要使用外部進(jìn)行驗證雾袱,以評估模型的外部可用性。然而俱萍,獲取外部數(shù)據(jù)并不容易立磁,這時交叉驗證(Cross Validation)則是一種較好的可替代方案。交叉驗證的方法很多晃洒,這里我們介紹最常用的k折交叉驗證慨灭。
簡單解釋一下:
假如原始數(shù)據(jù)為100例患者,建模后我們使用K折交叉驗證(K一般取3-10折)球及。
若取K=10氧骤,則:將原始數(shù)據(jù)分為10份(K值):
9份做訓(xùn)練,1份做驗證吃引,這樣循環(huán)10次(因為這樣的組合有10種)筹陵。
取10次評價指標(biāo)的平均值(如AUC值)作為模型的驗證結(jié)果刽锤。即【數(shù)據(jù)分為K個子集,1個子集做驗證朦佩,K-1個子集做訓(xùn)練并思,這樣的取法有K種,所以會產(chǎn)生K個新數(shù)據(jù)集(訓(xùn)練集+訓(xùn)練集)语稠。我們進(jìn)行K次訓(xùn)練和驗證得到的平均評價指標(biāo)可能較為準(zhǔn)確
為了保證數(shù)據(jù)分割的影響宋彼,目前的k折交叉驗證一般會進(jìn)行多次重復(fù)(200-1000次)。即進(jìn)行200次的10折交叉驗證仙畦。這樣做出的結(jié)果可能會更加準(zhǔn)確输涕。
如文獻(xiàn)所示
2.交叉驗證的原理圖
3.R Scripts
3.1數(shù)據(jù)示例
library("caret")
library(pROC)
bc<-read.csv("E:/r/test/buyunzheng.csv",sep=',',header=TRUE)
數(shù)據(jù)有8個指標(biāo),最后兩個是PSM匹配結(jié)果慨畸,我們不用理他莱坎,其余六個為:
Education:教育程度,age:年齡寸士,parity產(chǎn)次檐什,induced:人流次數(shù),case:是否不孕碉京,這是結(jié)局指標(biāo)厢汹,spontaneous:自然流產(chǎn)次數(shù)螟深。有一些變量是分類變量谐宙,我們需要把它轉(zhuǎn)換一下
bc$education<-ifelse(bc$education=="0-5yrs",0,ifelse(bc$education=="6-11yrs",1,2))
bc$spontaneous<-as.factor(bc$spontaneous)
bc$case<-as.factor(bc$case)
bc$induced<-as.factor(bc$induced)
bc$education<-as.factor(bc$education)
使用caret包的createFolds函數(shù)根據(jù)結(jié)果變量把數(shù)據(jù)分成10份,因為是隨機分配界弧,為了可重復(fù)性凡蜻,我們先設(shè)立一個種子
set.seed(666)
folds <- createFolds(y=bc$case,k=10)###分成10份
接下來我們可以根據(jù)每一份的數(shù)據(jù)建立方程,并求出AUC垢箕,95%CI和截點划栓,并且畫出ROC曲線。
我們先來做第一個數(shù)據(jù)的条获,要提取列表的數(shù)據(jù)忠荞,需要做成[[1]]這種形式
fold_test <- bc[folds[[1]],]#取fold 1數(shù)據(jù),建立測試集和驗證集
fold_train <- bc[-folds[[1]],]#
建立預(yù)測模型
fold_pre <- glm(case ~ age + parity +spontaneous,
family = binomial(link = logit), data =fold_train )###建立模型
fold_predict <- predict(fold_pre,type='response',newdata=fold_test)##生成預(yù)測值
roc1<-roc((fold_test[,5]),fold_predict)
round(auc(roc1),3)##AUC
round(ci(roc1),3)##95%CI
繪制ROC曲線
plot(roc1, print.auc=T, auc.polygon=T, grid=c(0.1, 0.2),
grid.col=c("green", "red"), max.auc.polygon=T,
auc.polygon.col="skyblue",
print.thres=T)
嫌一個一個做比較麻煩的話我們也可以做成循環(huán)帅掘,一次跑完結(jié)果
先建立一個auc的空值委煤,不然跑不了
auc_value<-as.numeric()###建立空值
for(i in 1:10){
fold_test <- bc[folds[[i]],] #取folds[[i]]作為測試集
fold_train <- bc[-folds[[i]],] # 剩下的數(shù)據(jù)作為訓(xùn)練集
fold_pre <- glm(case ~ age + parity +spontaneous,
family = binomial(link = logit), data =fold_train )
fold_predict <- predict(fold_pre,type='response',newdata=fold_test)
auc_value<- append(auc_value,as.numeric(auc(as.numeric(fold_test[,5]),fold_predict)))
}
#找到最大AUC的索引,用該索引對應(yīng)的數(shù)據(jù)作為測試集修档,其它數(shù)據(jù)作為訓(xùn)練集即可訓(xùn)練出AUC最高的模型
max.index = which(auc_value==max(auc_value),arr.ind=TRUE)
fold_test <- bc[folds[[max.index]],]
fold_train <- bc[-folds[[max.index]],]