我想在 R 中训练一个 SVM 分类器,并能够通过导出相关参数在其他软件中使用它。为此,我首先希望能够重现predict.svm()
R 中的行为(使用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
我希望对遇到同样问题的人有所帮助。