2 SVM(支持向量機法)vs 線性回歸+ROC曲線

step1 線性回歸ROC與AUC的實現(xiàn)

rm(list = ls())
# BiocManager::install('ROCR')
library(ROCR)
# 載入AER包,使用包中的Affairs數(shù)據(jù)集
# BiocManager::install('AER')
library(AER)
data(Affairs,package="AER")
# 將'affaris'特征進行因子化處理,作為新增加的一列'ynaffairs'
Affairs$ynaffair[Affairs$affairs > 0] <- 1
Affairs$ynaffair[Affairs$affairs== 0] <- 0
Affairs$ynaffair <-factor(Affairs$ynaffair,levels=c(0,1),labels=c("No","Yes"))
# 構(gòu)建Logistics模型
myfit <- glm(ynaffair ~ gender + age + yearsmarried + children + religiousness + education + occupation + rating, data=Affairs,family=binomial())
pre <- predict(myfit,type='response')
pred <- prediction(pre,Affairs$ynaffair)
# 計算AUC值
performance(pred,'auc')@y.values
perf <- performance(pred,'tpr','fpr')
plot(perf)

這是計算affair的一個數(shù)據(jù)集


結(jié)果
summary(myfit) ### 得到擬合公式
擬合公式

step2 繪圖強大的一個包——pROC

雖然ROCR包可以滿足我們的需要,但在功能上還是有些單一,繪制的圖也比較粗糙。因此接下來我們學(xué)習(xí)R中更為強大的一個包——pROC,該包不僅作圖美觀,還可以在同一幅圖上繪制多條ROC曲線,方便我們比較兩個分類器的性能優(yōu)劣。

# BiocManager::install('pROC')
library(pROC)

# 同樣使用上一節(jié)中的myfit模型
pre <- predict(myfit,type='response')
modelroc <- roc(Affairs$ynaffair,pre)
modelroc

# 可視化展示,同時給出AUC的面積與最優(yōu)的臨界點
plot(modelroc, print.auc=TRUE, auc.polygon=TRUE, grid=c(0.1, 0.2), grid.col=c("green", "red"), max.auc.polygon=TRUE, auc.polygon.col="skyblue", print.thres=TRUE)
結(jié)果2

step3 支持向量機法SVM

svm命令的R包 下載

svm命令的R包
# 以下為之前的logistics模型
pre_1 <- predict(myfit,type='response')
modelroc_1 <- roc(Affairs$ynaffair,pre_1)


# 使用支持向量機算法對同樣的數(shù)據(jù)進行預(yù)測

library(e1071) ###### 這個包里面有svm
svm_model <- svm(ynaffair ~ gender + age + yearsmarried + children + religiousness + education + occupation + rating, data=Affairs)
# 提取模型預(yù)測值并進行格式處理
pred_2 <- as.factor(svm_model$decision.values)
pred_2 <- as.ordered(pred_2)
modelroc_2 <- roc(Affairs$ynaffair,pred_2)
modelroc_2


# 可視化展示,使用add=TRUE將第二個模型添加到圖形中
plot.roc(modelroc_2, add=TRUE, col="green",print.thres=TRUE) 
plot(modelroc_1, print.auc=TRUE, auc.polygon=TRUE, grid=c(0.1, 0.2), grid.col=c("green", "red"), max.auc.polygon=TRUE, auc.polygon.col="skyblue", print.thres=TRUE,col='blue')
plot.roc(modelroc_2, add=TRUE, col="green",print.thres=TRUE) 
最終的結(jié)果

SVM深度分析:區(qū)分training group和test group請參考文章

一文學(xué)會SVM——生信技能樹

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容