我在 MATLAB 中使用 libsvm,并正在训练和测试具有预计算非线性内核的 1-vs-all SVM。我对 SVM 有点陌生,我正在尝试计算决策函数。我知道对于线性 SVM,我们可以通过(根据 libsvm 文档)获得 w:
w = model.sv_coef'*model.SVs;
然后我们可以根据以下条件计算决策值:
w'*x
然后,根据 sign(w'*x+b)
预测标签,其中 b 是某个阈值。
我特别感兴趣的是从我的非线性内核中获取分类分数。我该怎么做?
我想了解您所说的分类分数是什么意思。实际上你可以比较每个模型的概率,然后选择最大的一个,就像我在你的previous post中所做的那样。 .
如果您使用的是决策函数,那也很好。假设您正在使用 RBF 内核,并且 model.Label(1) = 1
,那么您有 (if model.Label(1) = -1
, then w = -w; b = -b;
)
[m,n] = size(model.SVs); % m is the number of support vectors,...
and n is the number of features
w = model.sv_coef; % m*1 weight vector
b = -model.rho; % scalar
现在给你 v
进行测试。你还有 [1,n] = size(v);
然后对于支持向量中的每一行 i
,计算欧氏距离(你可以向量化下面的代码) :
for i = 1:m
d(i) = norm(model.SVs(i,:) - v);
t(i) = exp(-gamma* d(i) .^2); % RBF model, t is 1*m vector
end
决策函数(或决策函数的分数)是:
s = t * w + b;
您可以像其他非线性内核一样获得决策函数。
编辑
有了自己写的预计算核,我们以RBF核为例:
% RBF kernel: exp(-gamma*|u-v|^2)
rbf = @(X,Y) exp(-gamma .* pdist2(X,Y,'euclidean').^2);
% Kernel matrices with sample serial number as first column as required
K_train = [(1:numTrain)' , rbf(trainData,trainData)];
K_test = [(1:numTest)' , rbf(testData,trainData)];
%# train and test
model = svmtrain(trainLabel, K_train, '-t 4');
[predLabel, ~, ~] = svmpredict(testLabel, K_test, model);
%# confusion matrix
C = confusionmat(testLabel,predLabel);
我是一名优秀的程序员,十分优秀!