如何在R中重现predict.svm?

时间:2013-01-17 08:41:34

标签: r svm predict

我想在R中训练SVM分类器,并能够通过导出相关参数在其他软件中使用它。为此,我首先希望能够重现R中predict.svm()的行为(使用e1071包)。

我根据虹膜数据训练了模型。

data(iris)

# simplify the data by removing the third label
ir <- iris[1:100,]
ir$Species <- as.factor(as.integer(ir$Species))

# train the model
m <- svm(Species ~ ., data=ir, cost=8)

# the model internally uses a scaled version of the data, example:
m$x.scale
# # # # # 
# $`scaled:center`
# Sepal.Length  Sepal.Width Petal.Length  Petal.Width 
#        5.471        3.099        2.861        0.786 
#
# $`scaled:scale`
# Sepal.Length  Sepal.Width Petal.Length  Petal.Width 
#    0.6416983    0.4787389    1.4495485    0.5651531 
# # # # #

# because the model uses scaled data, make a scaled data frame
irs<-ir;
sc<-data.frame(m$x.scale);
for(col in row.names(sc)){
      irs[[col]]<-(ir[[col]]-sc[[col,1]])/sc[[col,2]]
}

# a radial kernel function
k<-function(x,x1,gamma){
    return(exp(-gamma*sum((x-x1)^2)))
}

根据Hastie,Tibshirani,Friedman(2001),等式12.24,x的预测函数可以写成系数的支持向量乘以SV和x的核函数,它对应于矩阵产品,加上拦截。

$ \ hat {f}(x)= \ sum ^ N_ {i = 1} \ hat {\ alpha} _i y_i K(x,x_i)+ \ hat {\ beta} _0 $,其中$ y_i $已包含在m$coefs

# m$coefs contains the coefficients of the support vectors, m$SV 
# the support vectors, and m$rho the *negative* intercept
f<-function(x,m){
    return(t(m$coefs) %*% as.matrix(apply(m$SV,1,k,x,m$gamma)) - m$rho)
}

# a prediction function based on the sign of the prediction function
my.predict<-function(m,x){
    apply(x,1,function(y) sign(f(y,m)))
}

# applying my prediction function to the scaled data frame should
# yield the same result as applying predict.svm() to the original data
# example, thus the table should show one-to-one correspondence:
table(my.predict(m,irs[,1:4]),predict(m,ir[,1:4]))

# the unexpected result:    
# # # # #
#      1  2
#  -1  4 24
#  1  46 26
# # # # #

谁能解释这出错的地方?

编辑:我的代码中出现了一个小错误,它现在提供了以下预期结果:

      1  2
  -1  0 50
  1  50  0

我希望能够帮助任何面临同样问题的人。

1 个答案:

答案 0 :(得分:1)

我的某个功能出现了轻微错误。编辑后的版本有效。