Support-Vector-Machine
Support-Vector-Machine
411210002 郭玉皓
2024-12-14
set.seed(1)
library(e1071)
x=matrix(rnorm(200*2), ncol=2)
x[1:100, ]=x[1:100, ]+2
x[101:150, ]=x[101:150, ]-2
y=c(rep(1, 150), rep(2, 50))
dat=data.frame(x=x, y=as.factor(y))
plot(x, col=y)
train=sample(200, 100)
svmfit=svm(y~., data=dat[train, ], kernel="radial", gamma=1, cost=1)
plot(svmfit, dat[train, ])
summary(svmfit)
##
## Call:
## svm(formula = y ~ ., data = dat[train, ], kernel = "radial", gamma
= 1,
## cost = 1)
##
##
## Parameters:
## SVM-Type: C-classification
## SVM-Kernel: radial
## cost: 1
##
## Number of Support Vectors: 31
##
## ( 16 15 )
##
##
## Number of Classes: 2
##
## Levels:
## 1 2
##
## Parameter tuning of 'svm':
##
## - sampling method: 10-fold cross validation
##
## - best parameters:
## cost gamma
## 1 0.5
##
## - best performance: 0.07
##
## - Detailed performance results:
## cost gamma error dispersion
## 1 1e-01 0.5 0.26 0.15776213
## 2 1e+00 0.5 0.07 0.08232726
## 3 1e+01 0.5 0.07 0.08232726
## 4 1e+02 0.5 0.14 0.15055453
## 5 1e+03 0.5 0.11 0.07378648
## 6 1e-01 1.0 0.22 0.16193277
## 7 1e+00 1.0 0.07 0.08232726
## 8 1e+01 1.0 0.09 0.07378648
## 9 1e+02 1.0 0.12 0.12292726
## 10 1e+03 1.0 0.11 0.11005049
## 11 1e-01 2.0 0.27 0.15670212
## 12 1e+00 2.0 0.07 0.08232726
## 13 1e+01 2.0 0.11 0.07378648
## 14 1e+02 2.0 0.12 0.13165612
## 15 1e+03 2.0 0.16 0.13498971
## 16 1e-01 3.0 0.27 0.15670212
## 17 1e+00 3.0 0.07 0.08232726
## 18 1e+01 3.0 0.08 0.07888106
## 19 1e+02 3.0 0.13 0.14181365
## 20 1e+03 3.0 0.15 0.13540064
## 21 1e-01 4.0 0.27 0.15670212
## 22 1e+00 4.0 0.07 0.08232726
## 23 1e+01 4.0 0.09 0.07378648
## 24 1e+02 4.0 0.13 0.14181365
## 25 1e+03 4.0 0.15 0.13540064
## pred
## true 1 2
## 1 54 23
## 2 17 6
library(ROCR)
fitted=attributes(predict(svmfit.opt, dat[train, ],
decision.values=TRUE))$decision.values
par(mfrow=c(1, 2))
fitted=attributes(predict(svmfit.flex, dat[train, ],
decision.values=TRUE))$decision.values
rocplot(-fitted, dat[train, "y"], add=TRUE, col="red")
fitted=attributes(predict(svmfit.opt, dat[-train, ],
decision.values=TRUE))$decision.values
fitted=attributes(predict(svmfit.flex, dat[-
train,],decision.values=TRUE))$decision.values