【发布时间】:2013-01-17 08:41:33
【问题描述】:
我想在 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
希望对遇到同样问题的人有所帮助。
【问题讨论】:
-
ir data.frame 何时缩放?应用了哪种缩放比例?
-
svm函数对每个训练属性应用缩放,使得均值为零,方差为 1。在预测期间,它使用相同的因子缩放输入属性 - 这样用户就不必知道缩放。我会在问题中举一个m$x.scale的例子。 -
我真的没有看到任何错误。我的猜测是函数 f 是错误的。其余的似乎还可以。我曾经遇到过同样的问题,但不记得我是如何解决的。你可以看看 svm 的 predict 函数,看看有什么区别。
-
没关系,问题出在
x在my.predict的下标中。修复了它,它现在可以工作了。我应该删除这个问题还是把它留在这里,因为它显然确实为在 R 中使用svm的人提供了有用的代码? -
@roelandvanbeek 将您的评论作为结束问题的答案。