黑箱方法 支持向量机②

支持向量机

1. R中svm介绍

  • R的函数包e1071提供了libsvm的接口。使用e1071包中svm函数可以得到与libsvm相同的结果。write.svm()更是可以把R训练得到的结果写为标准的Libsvm格式,以供其他环境下libsvm的使用。下面我们来看看svm()函数的用法。有两种格式都可以。
> # svm函数的基本语法及参数解释
> svm(formula, data = NULL, ..., subset, na.action =na.omit, scale = TRUE)
# formula:指定参与分析的变量公式
# subset:为索引向量,指定分析的样本数据
# na.action:针对缺失值的处理方法,默认会删除缺失值所在的行
# scale:逻辑参数,是否标准化变量,默认标准化处理
> svm(x, y = NULL, scale = TRUE, type = NULL, kernel ="radial", degree = 3,
+ gamma = if (is.vector(x)) 1 else 1 / ncol(x),coef0 = 0, cost = 1, nu = 0.5,
+ class.weights = NULL, cachesize = 40, tolerance = 0.001, epsilon = 0.1,
+ shrinking = TRUE, cross = 0, probability = FALSE, fitted = TRUE,...,subset,
+ na.action = na.omit)
# x:可以是矩阵,可以是向量,也可以是稀疏矩阵
# y:分类变量
# type:指定建模的类别,支持向量机通常用于分类、回归和异常值检测,默认情况下,svm模型根据因变量y是否为因子,type选择C-classification或eps-regression
# kernel:指定建模过程中使用的核函数,目的在于解决支持向量机线性不可分问题。函数中有四类核函数可选,即线性核函数、多项式核函数、高斯核函数和神经网络核函数
# degree:用于多项式核函数的参数,默认为3
# gamma:用于除线性核函数之外的所有核函数参数,默认为1
# coef0:用于多项式核函数和神经网络核函数的参数,默认为0
# nu:用于nu-classification、nu-regression和one-classification回归类型中的参数
# class.weights:指定类权重
# cachesize:默认缓存大小为40M
# cross:可为训练集数据指定k重交叉验证
# probability:逻辑参数,指定模型是否生成各类的概率预测,默认不产生概率值
# fitted:逻辑参数,是否将分类结果包含在模型中,默认生成拟合值

degree:多项式核的次数,默认为3

gamma:除去线性核外,其他核的参数,默认为1/数据维数

coef0:多项式核与sigmoid核的参数,默认为0.

cost:C分类中惩罚项c的取值

nu:Nu分类,单一分类中nu的值

cross:做k折交叉验证,计算分类正确性。

首先,对于分类问题而言,svm()han函数中的'type'参数有C-classification、nu-classification和one-classification三种选项,  

核函数'kernel'参数有linear、polynomial、radial和sigmoid四种选项,  
2. 一个具体的小例子。

我们依然使用iris数据集(R中自带的关于三类植物的数据集)来做svm分类。如下

data(iris)

ir<-iris

set.seed(124)

count.test<-round(runif(50,1,150))

test<-ir[count.test,]

library(e1071)

sv<-svm(Species~.,data=ir,cross=5,type='C-classification',kernel='sigmoid')

summary(sv) #查看支持向量机sv的具体信息,发现做5倍交叉验证的正确率为92%

pre<-predict(sv,test)#对测试样本作预测。pre是一个类别向量。

dim(test[test$Species!=pre,])[1]/dim(test)[1]#计算错误率

[1] 0.06

我们发现错误率为6%

3.实例操作

#=========================================================

#--------load file and divide the data to train and test

#========================================================
setwd("E:\\Rwork")
library(e1071)
svm_data <- read.csv("BLCA.mRNA.for.rf.csv",header = T)
svm_data <- svm_data[,-1]
set.seed(1234)
index <- sample(nrow(svm_data),0.7*nrow(svm_data))
svm_train <- svm_data[index,]
svm_test <- svm_data[-index,]
svm_train$subtype <- as.character(svm_train$subtype)
svm_train$subtype <- as.factor(svm_train$subtype)
svm_test$subtype <- as.character(svm_test$subtype)
svm_test$subtype <- as.factor(svm_test$subtype)
#================================================

#----------establish the mdel

#================================================


x <- svm_train[,-1]

y <- svm_train[,1]

library(e1071)

SVM <- function(x,y){
  
  type <- c('C-classification','nu-classification','one-classification')
  
  kernel <- c('linear','polynomial','radial','sigmoid')
  
  #用于存放12种组合的预测结果
  
  pred <- array(0, dim=c(nrow(x),3,4))
  
  #用于存放预测错误数
  
  errors <- matrix(0,3,4)
  
  dimnames(errors) <- list(type, kernel)
  
  for(i in 1:3){
    
    for(j in 1:4){
      
      pred[,i,j] <- predict(object = svm(x, y, type = type[i], kernel = kernel[j]), newdata = x)
      
      if(i > 2) errors[i,j] <- sum(pred[,i,j] != 1)
      
      else errors[i,j] <- sum(pred[,i,j] != as.integer(y))
      
    }
    
  }
  
  return(errors)
  
}

SVM(x = x, y = y)


classifier <- svm(x = x, y = y, type = 'C-classification', 
             kernel = 'radial')


> SVM(x = x, y = y)
                   linear polynomial radial sigmoid
C-classification        0          0      0       1
nu-classification       7          0      4       9
one-classification    145        187    142     152

发现type为C-classification和radial 及 linear等时error最低

  • 交叉验证
#================================================

#----------K-fold corss validation

#================================================
library(caret)
folds <- createFolds(svm_train$subtype, k=10)
cv <- lapply(folds, function(x) {
  training_fold = svm_train[-x,]
  test_fold = svm_train[x,]
  classifier = svm(formula = subtype ~.,
                   data =training_fold,
                   type = "C-classification",
                   kernal = "radial")
  confusion=table(test_fold$subtype,predict(classifier,test_fold,type="class"))
  accuracy=sum(diag(confusion))/sum(confusion)
  return(accuracy)
})

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值