1. 程式人生 > >R語言中的SVM

R語言中的SVM

轉載自:http://www.klshu.com/1667.html

通過本文,你將瞭解到如下的內容:
1、如何在R語言中通過kernlab包來使用SVM
2、觀察C引數和和核函式的變化的影響
3、使用SVM分類來測試一個基因實驗資料的癌症診斷

一、線性SVM

     在這裡我們生成了二維的玩具資料,並且學習如何訓練和測試SVM

1.1 生成玩具資料

首先從2高斯(2 Gaussians)產生正樣本和負樣本的樣例資料。
n <- 150 # number of data points
p <- 2 # dimension
sigma <- 1 # variance of the distribution
meanpos <- 0 # centre of the distribution of positive examples
meanneg <- 3 # center of the distribution of negative examples
npos <- round(n/2) # number of positive examples
nneg <- n-npos # number of negative examples
#Generate the positive and negative examples
xpos <- matrix(rnorm(npos*p,mean=meanpos,sd=sigma),npos,p)
xneg <- matrix(rnorm(nneg*p,mean=meanneg,sd=sigma),npos,p)
x <- rbind(xpos,xneg)
#Generatethelabels
y<-matrix(c(rep(1,npos),rep(-1,nneg)))
#Visualize the data
plot(x,col=ifelse(y>0,1,2))
legend("topleft",c('Positive','Negative'),col=seq(2),pch=1,text.col=seq(2))

a 下面將資料劃分為80%的訓練集和20%的測試集

##Prepare a training and a test set##
ntrain <- round(n*0.8) # number of training examples
tindex <- sample(n,ntrain) # indices of training samples
xtrain<-x[tindex,]
xtest<-x[-tindex,]
ytrain<-y[tindex]
ytest<-y[-tindex]
istrain=rep(0,n)
istrain[tindex]=1
#Visualize
plot(x,col=ifelse(y>0,1,2),pch=ifelse(istrain==1,1,2))
legend("topleft",c('PositiveTrain','PositiveTest','NegativeTrain','NegativeTest'), col=c(1,1,2,2),pch=c(1,2,1,2),text.col=c(1,1,2,2))

b

1.2 訓練SVM

現在我們在訓練集上使用引數C=0.08來訓練線性SVM

#load the kernlab package
library(kernlab)
#traintheSVM
svp<-ksvm(xtrain,ytrain,type="C-svc",kernel='vanilladot',C=100,scaled=c())

下面來了解和看看svp包含了什麼

#Generalsummary
svp
#Attributes that you can access
attributes(svp)
#For example,the support vectors
alpha(svp)
alphaindex(svp)
b(svp)
#Use the built-in function to pretty-plot the classifier
plot(svp,data=xtrain)

c

1.3 使用SVM預測

現在我們可以使用訓練過的SVM來預測測試集中的點的型別。然後我們來使用指標變數來分析結果。

#Predict labels on test
ypred = predict(svp,xtest)
table(ytest,ypred)
#Compute accuracy
sum(ypred==ytest)/length(ytest)
#Compute at the prediction scores
ypredscore=predict(svp,xtest,type="decision”)
#Check that the predicted labels are the signs of the scores
table(ypredscore>0,ypred)
#Package to compute ROC curve,precision-recall etc...
library(ROCR)
pred<-prediction(ypredscore,ytest)
#Plot ROC curve
perf<-performance(pred,measure="tpr",x.measure="fpr")
plot(perf)
#Plot precision/recall curve
perf<-performance(pred,measure="prec",x.measure="rec")
plot(perf)
#Plot accuracy as function of threshold
perf<-performance(pred,measure="acc")
plot(perf)

d

1.4 交叉驗證(Cross-validation)

cv.folds <- function(n,folds=3)
 ##randomly split the n samples into folds
 {
 split(sample(n),rep(1:folds,length=length(y)))
 }
svp<-ksvm(x,y,type="C-svc",kernel=’vanilladot’,C=1,scaled=c(),cross=5)
print(cross(svp))
#[1] -1

1.5 引數C的影響

C平衡了大量的邊際和沒法識別的點
如何選擇好它是非常重要的。

二、非線性SVM

有時候線性的SVM是不夠的,比如產生的玩具的資料的正樣本和負樣本是混合在一起的,沒法使用線性分類。
比如下圖使用線性SVM是沒法分類的。

e

為了解決這個問題,我們使用非線性SVM。我們改變了kernerl引數,如使用高斯RBF的核函式,並且σ=1,C=1

#Train a nonlinear SVM
svp<-ksvm(x,y,type="C-svc",kernel=’rbf’,kpar=list(sigma=1),C=1)

#Visualizeit
plot(svp,data=x)

f