线性SVM并提取权重

Jac*_*ong 1 r svm r-caret

我正在使用虹膜数据集在R中练习SVM,并且我想从模型中获取特征权重/系数,但是鉴于我的输出为我提供了32个支持向量,因此我认为我可能会误解某些东西。假设我要分析四个变量,我将得到四个。我知道使用该svm()函数时有一种方法,但是我尝试使用train()插入符号中的函数来生成我的SVM。

library(caret)

# Define fitControl
fitControl <- trainControl(## 5-fold CV
              method = "cv",
              number = 5,
              classProbs = TRUE,
              summaryFunction = twoClassSummary )

# Define Tune
grid<-expand.grid(C=c(2^-5,2^-3,2^-1))

########## 
df<-iris head(df)
df<-df[df$Species!='setosa',]
df$Species<-as.character(df$Species)
df$Species<-as.factor(df$Species)

# set random seed and run the model
set.seed(321)
svmFit1 <- train(x = df[-5],
                 y=df$Species,
                 method = "svmLinear", 
                 trControl = fitControl,
                 preProc = c("center","scale"),
                 metric="ROC",
                 tuneGrid=grid )
svmFit1
Run Code Online (Sandbox Code Playgroud)

我以为这很简单,svmFit1$finalModel@coef但是当我相信我应该得到4时,我得到了32个向量。为什么呢?

tma*_*tny 6

所以,coef是不是重W了支持向量。这是docs中ksvm该类的相关部分:

coef 相应的系数乘以训练标签。

要获得所需的内容,您需要执行以下操作:

coefs <- svmFit1$finalModel@coef[[1]]
mat <- svmFit1$finalModel@xmatrix[[1]]

coefs %*% mat
Run Code Online (Sandbox Code Playgroud)

请参见下面的可复制示例。

library(caret)
#> Loading required package: lattice
#> Loading required package: ggplot2
#> Warning: package 'ggplot2' was built under R version 3.5.2

# Define fitControl
fitControl <- trainControl(
  method = "cv",
  number = 5,
  classProbs = TRUE,
  summaryFunction = twoClassSummary
)

# Define Tune
grid <- expand.grid(C = c(2^-5, 2^-3, 2^-1))

########## 
df <- iris 

df<-df[df$Species != 'setosa', ]
df$Species <- as.character(df$Species)
df$Species <- as.factor(df$Species)

# set random seed and run the model
set.seed(321)
svmFit1 <- train(x = df[-5],
                 y=df$Species,
                 method = "svmLinear", 
                 trControl = fitControl,
                 preProc = c("center","scale"),
                 metric="ROC",
                 tuneGrid=grid )

coefs <- svmFit1$finalModel@coef[[1]]
mat <- svmFit1$finalModel@xmatrix[[1]]

coefs %*% mat
#>      Sepal.Length Sepal.Width Petal.Length Petal.Width
#> [1,]   -0.1338791  -0.2726322    0.9497457    1.027411
Run Code Online (Sandbox Code Playgroud)

reprex软件包(v0.2.1.9000)创建于2019-06-11

资料来源

  1. https://www.researchgate.net/post/How_can_I_find_the_w_coefficients_of_SVM

  2. http://r.789695.n4.nabble.com/SVM-coefficients-td903591.html

  3. /sf/answers/133084031/