使用我自己的内核函数时的SVM分类错误 - Matlab

时间:2014-06-25 09:08:19

标签: matlab matrix machine-learning svm

我正在尝试实现svmtrain功能。它在训练中起作用,并且在对与训练矩阵相同数量的样本的样本矩阵进行分类时起作用。我做错了什么?

主要功能

function [ output_args ] = RBFTest( xtrain, ytrain)
output_args=svmtrain(xtrain,ytrain,'Kernel_Function',@mine,...
'boxconstraint',1);
end

KERNEL FUNCTION(假设是和RBF内核,我试图加速使用GPU)

function [ output ] = mine( U,V )
sig=1;
n=size(U,1);
K=U*V'/sig^2;
d=diag(K);
K=K-ones(n,1)*d'/2;
K=K-d*ones(1,n)/2;
output=exp(K);
end

我训练......

>> R2=RBFTest(X(1:3000,:),Y(1:3000,:))

R2 = 

          SupportVectors: [3000x57 double]
                   Alpha: [3000x1 double]
                    Bias: -0.0219
          KernelFunction: @mine
      KernelFunctionArgs: {}
              GroupNames: [3000x1 double]
    SupportVectorIndices: [3000x1 double]
               ScaleData: [1x1 struct]
           FigureHandles: []

我尝试对一小部分样本进行分类......但它不起作用

>> mean(svmclassify(R2,X(1:2000,:))==Y(1:2000))
Error using svmclassify (line 114)
An error was encountered during classification.
Matrix dimensions must agree.

我尝试对用于训练......工作的相同数据进行分类!

>> mean(svmclassify(R2,X(1:3000,:))==Y(1:3000))

ans =

    0.9990

我用较小的样本重新训练....

>> R2=RBFTest(X(1:1000,:),Y(1:1000,:))

R2 = 

          SupportVectors: [1000x57 double]
                   Alpha: [1000x1 double]
                    Bias: -0.0549
          KernelFunction: @mine
      KernelFunctionArgs: {}
              GroupNames: [1000x1 double]
    SupportVectorIndices: [1000x1 double]
               ScaleData: [1x1 struct]
           FigureHandles: []

我对不同的样本进行分类,但使用相同的矩阵和向量大小...并且它可以正常工作

>> mean(svmclassify(R2,X(1001:2000,:))==Y(1001:2000))

ans =

    0.4610

为什么在使用不同规模的培训和分类矩阵时它不起作用?

1 个答案:

答案 0 :(得分:0)

我不认为您的RBF内核功能是正确的(diag的部分看起来不正确)...

请尝试使用以下向量化实现(请参阅来源herehere):

function K = rbf(U, V, sigma)
    if nargin < 3, sigma = 1; end
    %K = pdist2(U, V, 'euclidean').^2;
    K = bsxfun(@plus, sum(U.^2,2), sum(V.^2,2).') - 2*(U*V');
    K = exp(-K ./ (2*sigma^2));
end

并将其用作:

c = 1; gamma = 1;
model = svmtrain(Xtrain, Ytrain, 'Kernel_Function',@(u,v) rbf(u,v,gamma), ...
    'BoxConstraint',c);
Ytest_hat = svmclassify(model, Xtest);

事实上,如果你看一下MATLAB自己的RBF内核私有实现(which -all rbf_kernel),你会发现它正在使用类似的技巧(只有repmat代替效率更高bsxfun