这些天我只是在Libsvm中使用chi2内核。我将代码粘贴在这里,希望它有用。
function [chi2_ans]=chi2_kernel(x,y)
f=@(x,y) 1-sum(((x'-y').*(x'-y'))./(x'+y'+eps)*2);
[m, ~]=size(x);
chi2_ans=zeros(size(x,1),size(y,1));
for i=1:size(x,1)
veci=x(i,:);
for j=1:size(y,1)
vecj=y(j,:);
chi2_ans(i,j)=f(veci,vecj);
end
end
end
并使用它。
function [ acc ] = singleChi2Kernel( trainData,testData,trainLabel,testLabel )
numTrain = size(trainData,1);
numTest = size(testData,1);
%# compute kernel matrices between every pairs of (train,train) and
%# (test,train) instances and include sample serial number as first column
K = [ (1:numTrain)' , chi2_kernel(trainData,trainData) ];
KK = [ (1:numTest)' , chi2_kernel(testData,trainData) ];
%# train and test
model = svmtrain(trainLabel, K, '-t 4 ');
[predClass, acc, decVals] = svmpredict(testLabel, KK, model);
%# confusion matrix
%C = confusionmat(testClass,predClass)
end
链接中的代码