R語言基於支援向量機訓練模型實現類預測
阿新 • • 發佈:2019-01-04
前面介紹了基於訓練集訓練SVM的方法。通過訓練,演算法能找到使間隔區間最大化的最優平面來分割訓練資料集,得到SVM模型能夠被用來預測新到樣例的類別。
準備
使用之前構建的churn構建的model.
操作
利用已構建的SVM模型和測試資料集的屬性預測它的模型
svm.pred = predict(model,testset[,!names(testset) %in% c("churn")])
svm.table = table(svm.pred,testset$churn)
svm.table
svm.pred yes no
yes 70 12
no 71 865
呼叫classAgreement計算分類一致性
classAgreement(svm.table)
$diag
[1] 0.9184676
$kappa
[1] 0.5855903
$rand
[1] 0.850083
$crand
[1] 0.5260472
呼叫confusionMatrix基於分類表評測預測效能
library(lattice)
library(ggplot2)
library(caret)
confusionMatrix(svm.table)
Confusion Matrix and Statistics
svm.pred yes no
yes 70 12
no 71 865
Accuracy : 0.9185
95% CI : (0.8999, 0.9345)
No Information Rate : 0.8615
P-Value [Acc > NIR] : 1.251e-08
Kappa : 0.5856
Mcnemar's Test P-Value : 1.936e-10
Sensitivity : 0.49645
Specificity : 0.98632
Pos Pred Value : 0.85366
Neg Pred Value : 0.92415
Prevalence : 0.13851
Detection Rate : 0.06876
Detection Prevalence : 0.08055
Balanced Accuracy : 0.74139
'Positive' Class : yes
說明
本節首先呼叫predict函式獲得測試資料集的預測模型,然後用table函式產生測試資料集的分類表,接下來的效能評測過程與前述章節其他方法其他分類方法的評測類似。
引入了一個新的函式classAgreement用來計算一個二維列聯錶行列之間多種一致性關係數。
diag係數為分類表主對角性上資料點的百分比,kappa係數是對diag係數隨機一致性的修正,rand代表聚類評價指標(rand index),主要用來橫量兩個聚簇之間的相似性,crand係數是出現元素隨機分類情況對Rand index 修正結果。
SVM迴歸分析
還可以使用SVM預測連續變數,也就是使用SVM實現迴歸分析。在接下來的樣例中,我們使用名為eps-regression模型說明如何使用SVM執行迴歸分析。
使用Quartet資料集來訓練一個支援向量機:
library(car)
data(Quartet)
model.regression = svm(Quartet$y1~Quartet$x,type = "eps-regression")
使用predict函式得到預測結果
predict.y = predict(model.regression,Quartet$x)
predict.y
呼叫plot繪圖函式,預測值用正方形,訓練資料用圓形:
plot(Quartet$x,Quartet$y1,pch = 19)
points(Quartet$x,predict.y,pch = 15,col = "red")