Caret包(即Classification And REgression Training的縮寫),包含簡化復雜的回歸和分類問題模型訓練過程的功能。
1、導入數據并分割數據
> library(pacman)
> p_load(caret,mlbench,dplyr)
> # 使用Sonar數據集
> data("Sonar")
>
> # 拆分為訓練集和測試集
> # 默認情況下,該函數使用分層隨機分割
> set.seed(123)
> ind <- createDataPartition(y = Sonar$Class,
+ # 訓練集所占比例
+ p = 0.75,
+ list = F)
> train <- Sonar[ind,]
> test <- Sonar[-ind,]
> dim(train)
## [1] 157 61
> dim(test)
## [1] 51 61
2、模型構建與訓練
通過調整PLS組件的數量對PLSDA(partial least squares discriminant analysis)模型進行調優:
> # 修改重采樣方法
> # method控制重新取樣的類型,默認為“boot”
> # 另一個方法是“ repeatedcv” ,用于指定重復的k折交叉驗證(repeats參數控制重復的次數)
> # K由number參數控制,默認值為10
>
> # 為了選擇不同的性能指標,Summaryfunction 參數用于傳入一個函數,該函數接受觀察值和預測值,并估計性能的某種度量
> # 包中已經包含了兩個這樣的函數: defaultSummary 和 twoClassSummary。
># 后者將計算特定于兩類問題的度量,例如 ROC 曲線下的面積,靈敏度和特異度
> # 由于ROC曲線是基于預測的類別概率(不會自動計算)
> # Classprobs=TRUE 選項用于包含這些計算。
> ctrl <- trainControl(method = "repeatedcv",repeats = 3,
+ classProbs = T,
+ summaryFunction = twoClassSummary)
> set.seed(123)
> fit.pls <- train(Class ~ .,
+ data = train,
+ method = "pls",
+ preProc = c("center","scale"),
+ # train函數生成一系列候選參數值,tuneLength參數控制數量
+ tuneLength = 15,
+ trControl = ctrl,
+ # 使用ROC指標度量性能
+ metric = "ROC")
> fit.pls
## Partial Least Squares
##
## 157 samples
## 60 predictor
## 2 classes: 'M', 'R'
##
## Pre-processing: centered (60), scaled (60)
## Resampling: Cross-Validated (10 fold, repeated 3 times)
## Summary of sample sizes: 141, 141, 142, 142, 141, 142, ...
## Resampling results across tuning parameters:
##
## ncomp ROC Sens Spec
## 1 0.8060764 0.7185185 0.6785714
## 2 0.8641617 0.7569444 0.7958333
## 3 0.8516121 0.7685185 0.7702381
## 4 0.8457672 0.7444444 0.7755952
## 5 0.8350777 0.7481481 0.7517857
## 6 0.8200149 0.7435185 0.7482143
## 7 0.8125992 0.7430556 0.7339286
## 8 0.8144180 0.7712963 0.7386905
## 9 0.8095238 0.7500000 0.7380952
## 10 0.8084160 0.7578704 0.7238095
## 11 0.8086310 0.7578704 0.7279762
## 12 0.8019924 0.7509259 0.7232143
## 13 0.7945271 0.7430556 0.7333333
## 14 0.7933780 0.7629630 0.7339286
## 15 0.7904679 0.7629630 0.7339286
##
## ROC was used to select the optimal model using the largest value.
## The final value used for the model was ncomp = 2.
輸出的是性能的平均重采樣估計,最后2個PLS組件(ncomp = 2)被認為是最優的。如圖所示:
> ggplot(fit.pls)
性能平均重采樣估計
3、預測
預測新樣本使用predict函數。
> # 默認情況下是預測分類type=class
> pls.class <- predict(fit.pls, newdata = test)
> str(pls.class)
## Factor w/ 2 levels "M","R": 1 2 2 2 2 1 2 2 2 2 ...
> # 返回分類概率
> pls.prob <- predict(fit.pls, newdata = test, type = "prob")
> head(pls.prob)
## M R
## 2 0.5444070 0.4555930
## 6 0.4030138 0.5969862
## 12 0.4371093 0.5628907
## 15 0.4101486 0.5898514
## 18 0.3932332 0.6067668
## 28 0.5213515 0.4786485
4、性能計算
confusionMatrix函數用于計算模型混淆矩陣和相關統計信息。
> confusionMatrix(data = pls.class, test$Class)
## Confusion Matrix and Statistics
##
## Reference
## Prediction M R
## M 19 7
## R 8 17
##
## Accuracy : 0.7059
## 95% CI : (0.5617, 0.8251)
## No Information Rate : 0.5294
## P-Value [Acc > NIR] : 0.007812
##
## Kappa : 0.4111
##
## Mcnemar's Test P-Value : 1.000000
##
## Sensitivity : 0.7037
## Specificity : 0.7083
## Pos Pred Value : 0.7308
## Neg Pred Value : 0.6800
## Prevalence : 0.5294
## Detection Rate : 0.3725
## Detection Prevalence : 0.5098
## Balanced Accuracy : 0.7060
##
## 'Positive' Class : M
##
可以看到該模型準確度為70.59%。
5、擬合另一個模型
在數據上擬合RDA正則化鑒別模型。
> grid.rda <- data.frame(gamma = (0:4)/4, lambda = 3/4)
> set.seed(123)
> fit.rda <- train(Class ~ ., data = train,
+ method = "rda",
+ tuneGrid = grid.rda,
+ trControl = ctrl,
+ metric = "ROC")
>
> fit.rda
## Regularized Discriminant Analysis
##
## 157 samples
## 60 predictor
## 2 classes: 'M', 'R'
##
## No pre-processing
## Resampling: Cross-Validated (10 fold, repeated 3 times)
## Summary of sample sizes: 141, 141, 142, 142, 141, 142, ...
## Resampling results across tuning parameters:
##
## gamma ROC Sens Spec
## 0.00 0.8156250 0.7606481 0.7392857
## 0.25 0.8851852 0.8796296 0.7166667
## 0.50 0.8832011 0.8972222 0.6833333
## 0.75 0.8663608 0.8842593 0.6654762
## 1.00 0.7288360 0.6972222 0.6309524
##
## Tuning parameter 'lambda' was held
## constant at a value of 0.75
## ROC was used to select the optimal
## model using the largest value.
## The final values used for the model
## were gamma = 0.25 and lambda = 0.75.
最終選擇的參數為:gamma = 0.25,lambda = 0.75。
> rda.class <- predict(fit.rda, newdata = test)
> confusionMatrix(rda.class, test$Class)
## Confusion Matrix and Statistics
##
## Reference
## Prediction M R
## M 23 10
## R 4 14
##
## Accuracy : 0.7255
## 95% CI : (0.5826, 0.8411)
## No Information Rate : 0.5294
## P-Value [Acc > NIR] : 0.003347
##
## Kappa : 0.4413
##
## Mcnemar's Test P-Value : 0.181449
##
## Sensitivity : 0.8519
## Specificity : 0.5833
## Pos Pred Value : 0.6970
## Neg Pred Value : 0.7778
## Prevalence : 0.5294
## Detection Rate : 0.4510
## Detection Prevalence : 0.6471
## Balanced Accuracy : 0.7176
##
## 'Positive' Class : M
此模型的準確度為72.55%,略高于第一個模型。
6、兩個模型的對比
resamples函數可以對結果進行收集、總結和對比。
> resamps <- resamples(list(pls = fit.pls, rda = fit.rda))
> summary(resamps)
## Call:
## summary.resamples(object = resamps)
##
## Models: pls, rda
## Number of resamples: 30
##
## ROC
## Min. 1st Qu. Median Mean 3rd Qu. Max. NA's
## pls 0.6666667 0.7916667 0.8611111 0.8641617 0.9350198 1 0
## rda 0.6964286 0.8571429 0.8888889 0.8851852 0.9305556 1 0
##
## Sens
## Min. 1st Qu. Median Mean 3rd Qu. Max. NA's
## pls 0.375 0.6666667 0.7777778 0.7569444 0.8750000 1 0
## rda 0.625 0.8750000 0.8888889 0.8796296 0.8888889 1 0
##
## Spec
## Min. 1st Qu. Median Mean 3rd Qu. Max. NA's
## pls 0.4285714 0.7142857 0.8571429 0.7958333 0.8750000 1 0
## rda 0.4285714 0.6250000 0.7142857 0.7166667 0.8571429 1 0
將對比結果可視化:
> xyplot(resamps, what = "BlandAltman")
兩個模型的結果對比
結果看起來很相似。 由于每次重采樣都有成對的結果,因此可以使用配對 t 檢驗來評估 ROC 曲線下的平均重采樣面積是否存在差異。 可以使用 diff.resamples 函數來計算:
> diffs <- diff(resamps)
> summary(diffs)
## Call:
## summary.diff.resamples(object = diffs)
## p-value adjustment: bonferroni
## Upper diagonal: estimates of the difference
## Lower diagonal: p-value for H0: difference = 0
##
## ROC
## pls rda
## pls -0.02102
## rda 0.1584
##
## Sens
## pls rda
## pls -0.1227
## rda 1.922e-05
##
## Spec
## pls rda
## pls 0.07917
## rda 0.02049
rda模型的ROC和Sens性能高于pls模型,但Spec性能低于pls模型。ROC曲線差異性P值=0.1584>0.05,所以不能拒絕原假設,即兩個模型性能相同,沒有差異。