Support Vector Machine

Machine Learning

R code using Various Kernel Function for Support Vector Machine

Yeongeun Jeon , Jeongwook Lee , Jung In Seo
09-28-2020

서포트 벡터 머신을 사용할 수 있는 대표적인 패키지는 "e1071""kernlab"이다. "kernlab""e1071"의 확장된 형태이며, 다양한 커널 함수를 사용할 수 있다.
예제 데이터는 “Universal Bank_Main”로 유니버셜 은행의 고객들에 대한 데이터(출처 : Data Mining for Business Intelligence, Shmueli et al. 2010)이다. 데이터는 총 2500개이며, 변수의 갯수는 13개이다. 여기서 TargetPerson.Loan이다.



1. 데이터 불러오기

pacman::p_load("data.table", "dplyr") 

UB <- fread(paste(getwd(),"Universal Bank_Main.csv", sep="/")) %>%  # 데이터 불러오기
  data.frame()                                                      # Data Frame 변환cols <- c("Family", "Education", "Personal.Loan",          
          "Securities.Account", "CD.Account", "Online", "CreditCard")

UB <- UB %>%
  select(-1) %>%                                                    # 1열 제거mutate_at(cols, factor)                                           # 범주형 변수 변환

glimpse(UB)                                                         # 데이터 구조
Rows: 2,500
Columns: 13
$ Age                <int> 25, 45, 39, 35, 35, 37, 53, 50, 35, 34, 6~
$ Experience         <int> 1, 19, 15, 9, 8, 13, 27, 24, 10, 9, 39, 5~
$ Income             <int> 49, 34, 11, 100, 45, 29, 72, 22, 81, 180,~
$ ZIP.Code           <int> 91107, 90089, 94720, 94112, 91330, 92121,~
$ Family             <fct> 4, 3, 1, 1, 4, 4, 2, 1, 3, 1, 4, 3, 2, 4,~
$ CCAvg              <dbl> 1.6, 1.5, 1.0, 2.7, 1.0, 0.4, 1.5, 0.3, 0~
$ Education          <fct> 1, 1, 1, 2, 2, 2, 2, 3, 2, 3, 3, 2, 3, 2,~
$ Mortgage           <int> 0, 0, 0, 0, 0, 155, 0, 0, 104, 0, 0, 0, 0~
$ Personal.Loan      <fct> 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0,~
$ Securities.Account <fct> 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0,~
$ CD.Account         <fct> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,~
$ Online             <fct> 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1,~
$ CreditCard         <fct> 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0,~

2. 데이터 분할

pacman::p_load("caret")
# Partition (Traning Data : Test Data = 7:3)
y      <- UB$Personal.Loan                       # Target

set.seed(200)
ind    <- createDataPartition(y, p=0.7, list=F)  # Training Data를 70% 추출
UB.trd <- UB[ind,]                               # Traning Data

UB.ted <- UB[-ind,]                              # Test Data

detach(package:caret)

3. R Package “e1071”

Package "e1071""svm" 함수로 서포트 벡터 머신을 사용할 수 있다. 자세한 옵션은 여기를 참조한다.

svm(formula, data, kernel , cost, cross, probability, ...)

3-1. Linear Kernel

3-1-1. 모형 적합

pacman::p_load("e1071") 


set.seed(200)
svm.model.li <- svm(Personal.Loan~.,     
                    data=UB.trd,  
                    cost=1,              
                    cross=10,           
                    kernel="linear",     # kernel = "linear" (Linear Kernel)
                    probability = T)     


summary(svm.model.li)

Call:
svm(formula = Personal.Loan ~ ., data = UB.trd, cost = 1, 
    cross = 10, kernel = "linear", probability = T)


Parameters:
   SVM-Type:  C-classification 
 SVM-Kernel:  linear 
       cost:  1 

Number of Support Vectors:  199

 ( 101 98 )


Number of Classes:  2 

Levels: 
 0 1

10-fold cross-validation on training data:

Total Accuracy: 95.77384 
Single Accuracies:
 97.14286 96 93.71429 95.42857 95.42857 93.14286 98.85714 96 94.28571 97.72727 
svm.model.li$index   # Support Vector
  [1]    9   48   68  108  109  123  147  156  157  203  205  221  228
 [14]  230  294  299  311  323  352  366  373  384  413  430  433  452
 [27]  476  525  532  560  582  614  626  643  645  760  767  781  784
 [40]  845  846  853  863  870  876  880  883  890  899  904  920  936
 [53]  953  960  996 1036 1056 1061 1083 1095 1113 1121 1130 1190 1193
 [66] 1197 1201 1202 1226 1252 1254 1259 1274 1309 1318 1324 1327 1336
 [79] 1340 1359 1365 1384 1387 1395 1400 1408 1421 1430 1436 1476 1530
 [92] 1588 1600 1619 1621 1637 1666 1669 1706 1714 1715   14   24   34
[105]   46   69  110  115  128  210  219  220  224  225  226  246  268
[118]  277  293  305  308  359  375  380  436  455  458  472  493  517
[131]  539  541  547  567  583  622  664  670  672  679  708  715  720
[144]  727  742  782  783  794  796  809  816  829  861  887  909  916
[157]  951  952  978  979 1045 1059 1090 1100 1103 1107 1110 1122 1131
[170] 1154 1170 1172 1175 1213 1241 1253 1257 1260 1262 1281 1284 1308
[183] 1317 1326 1342 1403 1429 1504 1505 1585 1586 1622 1630 1654 1674
[196] 1680 1689 1709 1713

3-1-2. 최적 모수 찾기

함수 "svm"은 cross validation을 통해 최적의 모수를 찾을 수 있으며 "tune" 함수를 이용한다.

tune(method, train.x, train.y, data, ranges , ...) # Version 1
tune(method, formula, data, ranges , ...)          # Version 2
set.seed(200)
tn.control  <- tune.control(cross=10)        # Number of Partitions For Cross Validation 
tune.svm.li <- tune(svm, Personal.Loan~., data=UB.trd, kernel="linear",
                    ranges=list(cost=c(0.1,1,10)), tunecontrol=tn.control) 

summary(tune.svm.li)

Parameter tuning of 'svm':

- sampling method: 10-fold cross validation 

- best parameters:
 cost
    1

- best performance: 0.03825974 

- Detailed performance results:
  cost      error dispersion
1  0.1 0.04225974 0.01479686
2  1.0 0.03825974 0.01204431
3 10.0 0.03883117 0.01564838
plot(tune.svm.li)

# 최적의 모수를 이용한 최종 모형 NAset.seed(200)
svm.li.best <- svm(Personal.Loan~., 
                   data=UB.trd, 
                   cost=1, 
                   cross=10,
                   kernel="linear", 
                   probability=T)


summary(svm.li.best)     

Call:
svm(formula = Personal.Loan ~ ., data = UB.trd, cost = 1, 
    cross = 10, kernel = "linear", probability = T)


Parameters:
   SVM-Type:  C-classification 
 SVM-Kernel:  linear 
       cost:  1 

Number of Support Vectors:  199

 ( 101 98 )


Number of Classes:  2 

Levels: 
 0 1

10-fold cross-validation on training data:

Total Accuracy: 95.77384 
Single Accuracies:
 97.14286 96 93.71429 95.42857 95.42857 93.14286 98.85714 96 94.28571 97.72727 

3-1-3. 모형 평가

# 적합된 모형에 대하여 Test Data 예측NAsvm.li.best.pred <- predict(svm.li.best, newdata=UB.ted, probability=T)        # predict(svm모형, Test Data)    

ConfusionMatrix

pacman::p_load("caret")


confusionMatrix(svm.li.best.pred, UB.ted$Personal.Loan, positive="1")  # confusionMatrix(예측 클래스, 실제 클래스, positive = "관심 클래스") 클래스")
Confusion Matrix and Statistics

          Reference
Prediction   0   1
         0 666  28
         1   7  48
                                          
               Accuracy : 0.9533          
                 95% CI : (0.9356, 0.9672)
    No Information Rate : 0.8985          
    P-Value [Acc > NIR] : 3.36e-08        
                                          
                  Kappa : 0.7079          
                                          
 Mcnemar's Test P-Value : 0.0007232       
                                          
            Sensitivity : 0.63158         
            Specificity : 0.98960         
         Pos Pred Value : 0.87273         
         Neg Pred Value : 0.95965         
             Prevalence : 0.10147         
         Detection Rate : 0.06409         
   Detection Prevalence : 0.07343         
      Balanced Accuracy : 0.81059         
                                          
       'Positive' Class : 1               
                                          
detach(package:caret)


ROC 곡선

1) Package “pROC”
pacman::p_load("pROC")                          

ac <- UB.ted$Personal.Loan                                   # 실제 클래스래스
pp <- attr(svm.li.best.pred, "probabilities")[,2]            # "1"에 대한 예측 확률


svm.li.roc <- roc(ac, pp, plot=T, col="red")                 # roc(실제 클래스, 예측 확률)률)

auc <- round(auc(svm.li.roc), 3)                             # AUC 
legend("bottomright",legend=auc, bty="n")
detach(package:pROC)


2) Package “Epi”
# install.packages("Epi")
pacman::p_load("Epi")                        
# install_version("etm", version = "1.1", repos = "http://cran.us.r-project.org")

ROC(pp,ac, plot="ROC")       # ROC(예측 확률 , 실제 클래스)                                  
detach(package:Epi)


3) Package “ROCR”
pacman::p_load("ROCR")                      

svm.li.pred <- prediction(pp, ac)                        # prediction(예측 확률, 실제 클래스)스)

svm.li.perf <- performance(svm.li.pred, "tpr", "fpr")    # performance(, "민감도", "1-특이도")                        
plot(svm.li.perf, col="red")                             # ROC Curve
abline(0,1, col="black")


perf.auc <- performance(svm.li.pred, "auc")              # AUC        

auc <- attributes(perf.auc)$y.values                  
legend("bottomright",legend=auc,bty="n") 


향상 차트

1) Package “ROCR”
li.lift <- performance(svm.li.pred,"lift", "rpp")       # Lift chart
plot(li.lift, colorize=T, lwd=2)      
detach(package:ROCR)


2) Package “lift”
# install.packages("lift")
pacman::p_load("lift")
 
plotLift(pp, ac, cumulative = T, n.buckets =24)      # plotLift(예측 확률, 실제 클래스)스)
TopDecileLift(pp, ac)                                # Top 10% 향상도 출력
[1] 7.359
detach(package:lift)

3-2. Radial Basis Kernel

3-2-1. 모형 적합

set.seed(200)
svm.model.nl <- svm(Personal.Loan~.,     
                    data=UB.trd,        
                    gamma=1,             # gamma : 가우시안 커널의 모수로써, 가우시안 커널의 폭을 제어하는 매개 변수
                    cost=1,              
                    cross=10,            
                    kernel="radial",     # 비선형 옵션 “radial” (가우시안 커널)커널)
                    probability = T)     


summary(svm.model.nl)

Call:
svm(formula = Personal.Loan ~ ., data = UB.trd, gamma = 1, 
    cost = 1, cross = 10, kernel = "radial", probability = T)


Parameters:
   SVM-Type:  C-classification 
 SVM-Kernel:  radial 
       cost:  1 

Number of Support Vectors:  1397

 ( 1217 180 )


Number of Classes:  2 

Levels: 
 0 1

10-fold cross-validation on training data:

Total Accuracy: 89.77727 
Single Accuracies:
 91.42857 89.14286 90.28571 90.28571 93.14286 87.42857 89.71429 88.57143 85.71429 92.04545 
svm.model.nl$index   # Support Vector
   [1]    1    2    3    4    7    9   10   11   13   15   17   18
  [13]   19   20   21   22   23   26   27   28   29   30   31   35
  [25]   36   37   39   40   41   42   44   45   47   48   49   50
  [37]   51   52   53   55   56   57   58   59   60   61   62   63
  [49]   65   66   68   72   73   74   76   77   79   80   82   84
  [61]   85   86   88   89   90   91   92   93   94   95   97   99
  [73]  101  102  103  104  105  106  107  108  109  111  114  117
  [85]  119  120  121  122  123  124  125  126  127  131  132  133
  [97]  134  135  137  139  140  141  144  146  147  148  149  151
 [109]  152  154  156  157  158  160  161  163  164  165  166  167
 [121]  171  173  174  175  176  177  178  179  180  181  182  184
 [133]  185  188  189  190  191  192  194  195  196  197  198  201
 [145]  202  203  206  208  209  211  212  213  214  215  216  217
 [157]  218  221  222  223  227  228  230  233  235  240  241  242
 [169]  243  244  247  249  251  254  255  257  258  259  260  261
 [181]  264  269  272  273  278  279  280  281  282  283  284  285
 [193]  286  289  290  292  294  296  297  298  299  300  301  303
 [205]  304  307  310  312  313  314  315  316  317  318  320  321
 [217]  322  323  324  325  328  329  330  331  332  333  335  337
 [229]  338  339  340  341  343  344  345  346  350  351  352  356
 [241]  357  358  362  363  364  365  366  367  368  369  371  372
 [253]  373  374  377  378  379  381  382  384  387  388  389  390
 [265]  391  392  395  396  397  400  401  404  406  407  408  409
 [277]  410  411  412  413  414  415  416  417  419  420  421  422
 [289]  423  424  425  426  427  428  429  430  432  433  435  437
 [301]  438  439  440  443  444  445  446  447  449  450  451  452
 [313]  453  457  459  460  461  462  465  466  467  468  469  470
 [325]  471  473  474  475  476  477  478  479  480  481  483  484
 [337]  486  487  488  489  491  494  495  497  498  499  500  501
 [349]  502  503  504  505  506  512  514  515  520  522  523  524
 [361]  525  526  527  528  530  531  532  533  536  537  538  540
 [373]  542  544  546  548  549  552  553  556  557  558  559  560
 [385]  565  566  568  570  572  573  574  575  576  577  578  579
 [397]  582  584  585  586  587  589  591  594  595  596  598  599
 [409]  600  601  602  605  608  609  610  611  614  615  618  620
 [421]  623  625  626  627  630  631  632  633  634  635  636  637
 [433]  638  639  640  643  644  645  646  647  648  649  650  651
 [445]  653  654  655  656  657  658  659  660  661  662  665  666
 [457]  668  669  671  673  676  677  680  681  682  683  685  686
 [469]  687  688  690  692  693  694  695  696  697  698  699  701
 [481]  702  704  705  706  707  709  710  713  714  716  717  718
 [493]  719  721  722  723  724  725  726  729  730  731  734  735
 [505]  736  737  738  739  740  743  746  747  748  752  753  754
 [517]  755  756  757  758  759  760  762  763  765  766  767  768
 [529]  769  771  772  774  775  776  777  778  779  780  781  784
 [541]  785  786  787  788  789  791  793  797  798  799  800  801
 [553]  803  804  806  807  808  811  812  813  814  817  818  820
 [565]  821  822  824  825  832  835  836  837  838  840  841  842
 [577]  844  845  846  847  848  850  851  852  853  854  855  856
 [589]  858  860  862  863  864  865  866  867  868  871  872  873
 [601]  874  875  876  878  879  880  881  882  883  885  886  888
 [613]  889  890  891  892  893  894  895  896  899  900  902  903
 [625]  904  907  908  910  911  912  914  915  917  918  919  920
 [637]  921  923  925  927  929  933  934  935  936  937  939  940
 [649]  941  943  944  946  947  949  950  953  954  955  956  959
 [661]  960  961  962  963  964  965  966  968  970  971  974  977
 [673]  980  981  983  984  985  986  987  988  989  990  991  992
 [685]  993  994  995  996  997  998  999 1000 1001 1002 1004 1006
 [697] 1008 1009 1011 1012 1014 1015 1017 1018 1019 1021 1022 1023
 [709] 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035
 [721] 1036 1037 1038 1039 1040 1041 1044 1047 1050 1052 1053 1054
 [733] 1056 1057 1060 1061 1062 1063 1065 1067 1068 1069 1070 1071
 [745] 1072 1074 1075 1076 1077 1078 1079 1080 1081 1083 1084 1085
 [757] 1086 1087 1089 1091 1092 1094 1095 1097 1098 1099 1101 1104
 [769] 1105 1106 1108 1111 1113 1114 1115 1116 1117 1118 1119 1120
 [781] 1121 1123 1124 1125 1126 1127 1129 1130 1132 1135 1136 1137
 [793] 1139 1140 1141 1143 1144 1145 1147 1148 1150 1151 1156 1157
 [805] 1160 1162 1163 1164 1167 1168 1169 1171 1173 1177 1180 1181
 [817] 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193
 [829] 1194 1197 1198 1199 1200 1201 1202 1203 1205 1206 1208 1210
 [841] 1211 1212 1214 1215 1217 1218 1220 1222 1223 1224 1225 1226
 [853] 1227 1229 1231 1233 1236 1237 1239 1240 1243 1245 1246 1247
 [865] 1248 1250 1251 1252 1254 1255 1256 1258 1259 1261 1263 1264
 [877] 1266 1267 1268 1269 1271 1272 1273 1274 1275 1276 1277 1278
 [889] 1279 1280 1282 1285 1286 1287 1288 1289 1291 1292 1294 1295
 [901] 1296 1297 1298 1299 1300 1301 1302 1304 1305 1306 1307 1309
 [913] 1310 1312 1313 1314 1315 1316 1318 1319 1320 1321 1322 1324
 [925] 1325 1327 1330 1331 1332 1335 1336 1337 1338 1340 1341 1344
 [937] 1346 1348 1350 1351 1352 1354 1355 1357 1359 1362 1363 1364
 [949] 1365 1366 1368 1370 1372 1373 1374 1375 1377 1378 1379 1380
 [961] 1381 1382 1384 1386 1387 1388 1389 1391 1392 1393 1394 1395
 [973] 1396 1399 1400 1405 1406 1407 1408 1409 1410 1411 1413 1414
 [985] 1415 1416 1417 1418 1420 1421 1422 1423 1424 1427 1428 1431
 [997] 1432 1433 1434 1435 1436 1437 1439 1441 1442 1443 1444 1445
[1009] 1446 1447 1448 1449 1451 1453 1456 1457 1459 1460 1461 1462
[1021] 1463 1465 1466 1467 1468 1469 1470 1473 1476 1477 1478 1479
[1033] 1480 1481 1482 1485 1486 1487 1488 1489 1490 1491 1492 1493
[1045] 1498 1499 1500 1501 1502 1503 1506 1508 1509 1510 1512 1513
[1057] 1515 1517 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530
[1069] 1531 1532 1534 1535 1537 1538 1539 1541 1543 1544 1546 1548
[1081] 1550 1551 1554 1555 1556 1557 1558 1559 1560 1563 1564 1565
[1093] 1567 1568 1569 1570 1571 1572 1574 1575 1576 1577 1578 1580
[1105] 1581 1583 1584 1587 1588 1589 1591 1592 1593 1594 1596 1597
[1117] 1599 1600 1602 1604 1605 1606 1607 1608 1609 1611 1612 1613
[1129] 1614 1618 1619 1620 1621 1623 1625 1627 1628 1629 1632 1633
[1141] 1634 1635 1636 1637 1638 1640 1641 1642 1643 1644 1645 1646
[1153] 1647 1649 1652 1653 1657 1658 1659 1660 1661 1663 1664 1666
[1165] 1668 1669 1670 1672 1673 1676 1677 1678 1679 1681 1682 1683
[1177] 1684 1685 1686 1687 1688 1691 1692 1693 1695 1698 1700 1702
[1189] 1704 1706 1710 1714 1715 1716 1717 1718 1721 1722 1724 1725
[1201] 1727 1729 1730 1731 1733 1735 1736 1737 1739 1740 1741 1743
[1213] 1744 1745 1748 1749 1751    8   14   16   24   32   34   38
[1225]   43   46   69   96  110  115  128  130  143  168  172  200
[1237]  207  210  219  220  224  225  226  245  246  248  268  277
[1249]  293  305  308  326  327  334  336  359  375  380  398  402
[1261]  436  442  455  458  463  472  493  509  517  539  541  543
[1273]  547  550  551  563  567  583  619  622  629  642  663  664
[1285]  670  672  679  684  691  708  712  715  720  727  742  744
[1297]  745  751  770  782  783  790  794  796  809  816  829  834
[1309]  861  877  887  909  916  924  932  951  952  969  973  976
[1321]  978  979  982 1007 1042 1045 1049 1059 1064 1090 1100 1103
[1333] 1107 1110 1112 1122 1131 1138 1142 1146 1154 1155 1161 1166
[1345] 1170 1172 1175 1213 1228 1241 1253 1257 1260 1262 1281 1283
[1357] 1284 1290 1308 1317 1326 1342 1345 1358 1360 1403 1412 1425
[1369] 1429 1438 1450 1458 1464 1471 1495 1504 1505 1533 1540 1547
[1381] 1549 1573 1585 1586 1622 1630 1651 1654 1655 1665 1674 1680
[1393] 1689 1709 1713 1719 1728

3-2-2. 최적 모수 찾기

set.seed(200)
tn.control  <- tune.control(cross=10)          # Number of Partitions For Cross Validation 
tune.svm.nl <- tune(svm, Personal.Loan~., data=UB.ted, kernel="radial",
                    ranges=list(gamma=c(0.1,1,10), cost=c(0.1,1,10)), tunecontrol=tn.control)

summary(tune.svm.nl)

Parameter tuning of 'svm':

- sampling method: 10-fold cross validation 

- best parameters:
 gamma cost
   0.1   10

- best performance: 0.03736937 

- Detailed performance results:
  gamma cost      error dispersion
1   0.1  0.1 0.10149550 0.03944150
2   1.0  0.1 0.10149550 0.03944150
3  10.0  0.1 0.10149550 0.03944150
4   0.1  1.0 0.05340541 0.02084754
5   1.0  1.0 0.10149550 0.03944150
6  10.0  1.0 0.10149550 0.03944150
7   0.1 10.0 0.03736937 0.01510942
8   1.0 10.0 0.09882883 0.03577778
9  10.0 10.0 0.10149550 0.03944150
plot(tune.svm.nl)

# 최적의 모수를 이용한 최종 모형NAset.seed(200)            
svm.nl.best <- svm(Personal.Loan~., 
                   data=UB.trd, 
                   gamma=0.1, 
                   cost=10,
                   cross=10,
                   kernel="radial", 
                   probability=T)                 


summary(svm.nl.best)

Call:
svm(formula = Personal.Loan ~ ., data = UB.trd, gamma = 0.1, 
    cost = 10, cross = 10, kernel = "radial", probability = T)


Parameters:
   SVM-Type:  C-classification 
 SVM-Kernel:  radial 
       cost:  10 

Number of Support Vectors:  235

 ( 143 92 )


Number of Classes:  2 

Levels: 
 0 1

10-fold cross-validation on training data:

Total Accuracy: 97.2016 
Single Accuracies:
 98.85714 97.14286 96.57143 98.85714 97.71429 96 97.14286 96.57143 94.28571 98.86364 

3-2-3. 모형 평가

# 적합된 모형에 대하여 Test Data 예측NAsvm.nl.best.pred <- predict(svm.nl.best, newdata=UB.ted, probability=T)  # predict(svm모형, Test Data)    

ConfusionMatrix

pacman::p_load("caret")


confusionMatrix(svm.nl.best.pred, UB.ted$Personal.Loan, positive="1")    # confusionMatrix(예측 클래스, 실제 클래스, positive = "관심 클래스") 클래스")
Confusion Matrix and Statistics

          Reference
Prediction   0   1
         0 668  17
         1   5  59
                                          
               Accuracy : 0.9706          
                 95% CI : (0.9559, 0.9815)
    No Information Rate : 0.8985          
    P-Value [Acc > NIR] : 3.493e-14       
                                          
                  Kappa : 0.8268          
                                          
 Mcnemar's Test P-Value : 0.01902         
                                          
            Sensitivity : 0.77632         
            Specificity : 0.99257         
         Pos Pred Value : 0.92188         
         Neg Pred Value : 0.97518         
             Prevalence : 0.10147         
         Detection Rate : 0.07877         
   Detection Prevalence : 0.08545         
      Balanced Accuracy : 0.88444         
                                          
       'Positive' Class : 1               
                                          
detach(package:caret)


ROC 곡선

1) Package “pROC”
pacman::p_load("pROC")                          

ac <- UB.ted$Personal.Loan                                   # 실제 클래스래스
pp <- attr(svm.nl.best.pred, "probabilities")[,2]            # "1"에 대한 예측 확률


svm.nl.roc <- roc(ac, pp, plot=T, col="red")                 # roc(실제 클래스, 예측 확률)률)

auc <- round(auc(svm.nl.roc), 3)                             # AUC 
legend("bottomright",legend=auc, bty="n")
detach(package:pROC)


2) Package “Epi”
# install.packages("Epi")
pacman::p_load("Epi")                        
# install_version("etm", version = "1.1", repos = "http://cran.us.r-project.org")

ROC(pp,ac, plot="ROC")       # ROC(예측 확률 , 실제 클래스)                                  
detach(package:Epi)


3) Package “ROCR”
pacman::p_load("ROCR")                      

svm.nl.pred <- prediction(pp, ac)                        # prediction(예측 확률, 실제 클래스)스)

svm.nl.perf <- performance(svm.nl.pred, "tpr", "fpr")    # performance(, "민감도", "1-특이도")                        
plot(svm.nl.perf, col="red")                             # ROC Curve
abline(0,1, col="black")


perf.auc <- performance(svm.nl.pred, "auc")              # AUC        

auc <- attributes(perf.auc)$y.values                  
legend("bottomright",legend=auc,bty="n") 


향상 차트

1) Package “ROCR”
nl.lift <- performance(svm.nl.pred,"lift", "rpp")       # Lift chart
plot(nl.lift, colorize=T, lwd=2)      
detach(package:ROCR)


2) Package “lift”
# install.packages("lift")
pacman::p_load("lift")

plotLift(pp, ac, cumulative = T, n.buckets =24)      # plotLift(예측 확률, 실제 클래스)스)
TopDecileLift(pp, ac)                                # Top 10% 향상도 출력
[1] 8.41
detach(package:lift)

3-3. 모형 비교

plot(svm.li.perf, col="blue")         # ROC Curve
par(new=TRUE)
plot(svm.nl.perf, col="red")          # ROC Curve

legend("bottomright", legend=c("Linear", "RB"), col=c("blue", "red"), lty=c(1,1))


4. R Package “kernlab”

Package "kernlab""ksvm" 함수로 서포트 벡터 머신을 사용할 수 있다. "ksvm"의 장점은 Kernel 함수가 "rbfdot"인 경우 자동적으로 최적의 gamma값을 찾아준다. 자세한 옵션은 여기를 참조한다.

ksvm(x, data, y, kernel , C, cross, prob.model, ...)      # Version 1
ksvm(formula, data, kernel , C, cross, prob.model, ...)   # Version 2

4-1. Linear Kernel

4-1-1. 모형 적합

pacman::p_load("kernlab")  

set.seed(200)
ksvm.li <- ksvm(Personal.Loan ~.,         
                data=UB.trd,          
                C=1,                     
                cross=10,                 
                kernel="vanilladot",      # vanilladot :  Linear Kernel
                prob.model=TRUE)          
 Setting default kernel parameters  
ksvm.li
Support Vector Machine object of class "ksvm" 

SV type: C-svc  (classification) 
 parameter : cost C = 1 

Linear (vanilla) kernel function. 

Number of Support Vectors : 199 

Objective Function Value : -183.6871 
Training error : 0.034266 
Cross validation error : 0.04226 
Probability model included. 

4-1-2. 모형 평가

# 적합된 모형에 대하여 Test Data 예측NAksvm.li.pred <- predict(ksvm.li, UB.ted)       # predict(svm모형, Test Data)    

ConfusionMatrix

pacman::p_load("caret")


confusionMatrix(ksvm.li.pred, UB.ted$Personal.Loan, positive="1")    # confusionMatrix(예측 클래스, 실제 클래스, positive = "관심 클래스") 클래스")
Confusion Matrix and Statistics

          Reference
Prediction   0   1
         0 669  31
         1   4  45
                                          
               Accuracy : 0.9533          
                 95% CI : (0.9356, 0.9672)
    No Information Rate : 0.8985          
    P-Value [Acc > NIR] : 3.360e-08       
                                          
                  Kappa : 0.6958          
                                          
 Mcnemar's Test P-Value : 1.109e-05       
                                          
            Sensitivity : 0.59211         
            Specificity : 0.99406         
         Pos Pred Value : 0.91837         
         Neg Pred Value : 0.95571         
             Prevalence : 0.10147         
         Detection Rate : 0.06008         
   Detection Prevalence : 0.06542         
      Balanced Accuracy : 0.79308         
                                          
       'Positive' Class : 1               
                                          
detach(package:caret)


ROC 곡선

1) Package “pROC”
pacman::p_load("pROC")                          

ac <- UB.ted$Personal.Loan                                    # 실제 클래스래스
pp <- predict(ksvm.li, UB.ted, type="prob")[,2]               # "1"에 대한 예측 확률


ksvm.li.roc <- roc(ac, pp, plot=T, col="red")                 # roc(실제 클래스, 예측 확률)률)

auc <- round(auc(ksvm.li.roc), 3)                             # AUC 
legend("bottomright",legend=auc, bty="n")
detach(package:pROC)


2) Package “Epi”
# install.packages("Epi")
pacman::p_load("Epi")                        
# install_version("etm", version = "1.1", repos = "http://cran.us.r-project.org")

ROC(pp,ac, plot="ROC")       # ROC(예측 확률 , 실제 클래스)                                  
detach(package:Epi)


3) Package “ROCR”
pacman::p_load("ROCR")                      

ksvm.li.pred <- prediction(pp, ac)                         # prediction(예측 확률, 실제 클래스)스)

ksvm.li.perf <- performance(ksvm.li.pred, "tpr", "fpr")    # performance(, "민감도", "1-특이도")                        
plot(ksvm.li.perf, col="red")                              # ROC Curve
abline(0,1, col="black")


perf.auc <- performance(ksvm.li.pred, "auc")               # AUC        

auc <- attributes(perf.auc)$y.values                  
legend("bottomright",legend=auc,bty="n") 


향상 차트

1) Package “ROCR”
li.lift <- performance(ksvm.li.pred,"lift", "rpp")        # Lift chart
plot(li.lift, colorize=T, lwd=2)  
detach(package:ROCR)


2) Package “lift”
# install.packages("lift")
pacman::p_load("lift")

plotLift(pp, ac, cumulative = T, n.buckets =24)      # plotLift(예측 확률, 실제 클래스)스)
TopDecileLift(pp, ac)                                # Top 10% 향상도 출력
[1] 7.359
detach(package:lift)

4-2. Radial Basis Kernel

4-2-1. 모형 적합

set.seed(200)
ksvm.nl <- ksvm(Personal.Loan ~.,         
                data=UB.trd, 
                C=10,                      
                cross=10,                 
                kernel="rbfdot",          # knernel = "rbfdot" (Radial Basis kernel "Gaussian") /  자동적으로 최적의 gamma값을 찾음NA=TRUE)        


ksvm.nl
Support Vector Machine object of class "ksvm" 

SV type: C-svc  (classification) 
 parameter : cost C = 10 

Gaussian Radial Basis kernel function. 
 Hyperparameter : sigma =  0.0987038664607438 

Number of Support Vectors : 236 

Objective Function Value : -628.1175 
Training error : 0.006282 
Cross validation error : 0.029695 
Probability model included. 

4-2-2. 모형 평가

# 적합된 모형에 대하여 Test Data 예측NAksvm.nl.pred <- predict(ksvm.nl, UB.ted)  # predict(svm모형, Test Data)    

ConfusionMatrix

pacman::p_load("caret")


confusionMatrix(ksvm.nl.pred, UB.ted$Personal.Loan, positive="1")    # confusionMatrix(예측 클래스, 실제 클래스, positive = "관심 클래스") 클래스")
Confusion Matrix and Statistics

          Reference
Prediction   0   1
         0 668  17
         1   5  59
                                          
               Accuracy : 0.9706          
                 95% CI : (0.9559, 0.9815)
    No Information Rate : 0.8985          
    P-Value [Acc > NIR] : 3.493e-14       
                                          
                  Kappa : 0.8268          
                                          
 Mcnemar's Test P-Value : 0.01902         
                                          
            Sensitivity : 0.77632         
            Specificity : 0.99257         
         Pos Pred Value : 0.92188         
         Neg Pred Value : 0.97518         
             Prevalence : 0.10147         
         Detection Rate : 0.07877         
   Detection Prevalence : 0.08545         
      Balanced Accuracy : 0.88444         
                                          
       'Positive' Class : 1               
                                          
detach(package:caret)


ROC 곡선

1) Package “pROC”
pacman::p_load("pROC")                          

ac <- UB.ted$Personal.Loan                                    # 실제 클래스래스
pp <- predict(ksvm.nl, UB.ted, type="prob")[,2]               # "1"에 대한 예측 확률


ksvm.nl.roc <- roc(ac, pp, plot=T, col="red")                 # roc(실제 클래스, 예측 확률)률)

auc <- round(auc(ksvm.nl.roc), 3)                             # AUC 
legend("bottomright",legend=auc, bty="n")
detach(package:pROC)


2) Package “Epi”
# install.packages("Epi")
pacman::p_load("Epi")                        
# install_version("etm", version = "1.1", repos = "http://cran.us.r-project.org")

ROC(pp,ac, plot="ROC")       # ROC(예측 확률 , 실제 클래스)                                  
detach(package:Epi)


3) Package “ROCR”
pacman::p_load("ROCR")                      

ksvm.nl.pred <- prediction(pp, ac)                         # prediction(예측 확률, 실제 클래스)스)

ksvm.nl.perf <- performance(ksvm.nl.pred, "tpr", "fpr")    # performance(, "민감도", "1-특이도")                        
plot(ksvm.nl.perf, col="red")                              # ROC Curve
abline(0,1, col="black")


perf.auc <- performance(ksvm.nl.pred, "auc")               # AUC        

auc <- attributes(perf.auc)$y.values                  
legend("bottomright",legend=auc,bty="n") 


향상 차트

1) Package “ROCR”
nl.lift <- performance(ksvm.nl.pred,"lift", "rpp")        # Lift chart
plot(nl.lift, colorize=T, lwd=2)      
detach(package:ROCR)


2) Package “lift”
# install.packages("lift")
pacman::p_load("lift")

plotLift(pp, ac, cumulative = T, n.buckets =24)      # plotLift(예측 확률, 실제 클래스)스)
TopDecileLift(pp, ac)                                # Top 10% 향상도 출력
[1] 8.41
detach(package:lift)

4-3. 모형 비교

plot(ksvm.li.perf, col="blue")         # ROC Curve
par(new=TRUE)
plot(ksvm.nl.perf, col="red")          # ROC Curve

legend("bottomright", legend=c("Linear", "RB"), col=c("blue", "red"), lty=c(1,1))


5. svm과 ksvm 모형 비교

5-1. 예측 오차

pacman::p_load("tidyverse")

# 예측 클래스래스
svm.li.best.pred <- predict(svm.li.best, newdata=UB.ted, probability=T) 
svm.nl.best.pred <- predict(svm.nl.best, newdata=UB.ted, probability=T)
ksvm.li.pred <- predict(ksvm.li, UB.ted)
ksvm.nl.pred <- predict(ksvm.nl, UB.ted)


prev.class <- data.frame(svm.li= svm.li.best.pred, svm.rbf=svm.nl.best.pred,
                         ksvm.li=ksvm.li.pred, ksvm.rbf=ksvm.nl.pred,obs=UB.ted$Personal.Loan)


prev.class %>% 
  summarise_all(funs(err=mean(obs!=.))) %>% 
  select(-obs_err) %>% 
  round(3)
  svm.li_err svm.rbf_err ksvm.li_err ksvm.rbf_err
1      0.047       0.029       0.047        0.029

5-2. ROC 곡선

pacman::p_load("plotROC")


plot(svm.li.perf, col="blue")         # ROC Curve
par(new=TRUE)
plot(svm.nl.perf, col="red")          # ROC Curve
par(new=TRUE)
plot(ksvm.li.perf, col="green")       # ROC Curve
par(new=TRUE)
plot(ksvm.nl.perf, col="orange")      # ROC Curve

legend("bottomright", legend=c("svm (Linear)", "svm (RB)", "ksvm (Linear)", "ksvm (RB)" ),
       col=c("blue", "red", "green", "orange"), lty=c(1,1,1,1))

Reuse

Text and figures are licensed under Creative Commons Attribution CC BY 4.0. The figures that have been reused from other sources don't fall under this license and can be recognized by a note in their caption: "Figure from ...".