Matlab SVM自定义内核函数

时间:2015-05-25 01:23:34

标签: matlab machine-learning classification svm

在Matlab SVM tutorial中,它说

  

您可以通过设置' KernelFunction' kernel'来设置您自己的内核功能,例如内核。 kernel必须具有以下形式:

     

函数G =内核(U,V)

     

其中:

     

U是m-by-p矩阵。   V是n-by-p矩阵。   G是U和V行的m-by-n Gram矩阵。

当我遵循自定义SVM内核example时,我在mysigmoid.m函数中设置了一个断点。然而,我发现U和V实际上是1-by-p向量而G是标量。

为什么MATLAB不通过矩阵处理内核?

我的自定义内核函数是

function G = mysigmoid(U,V)
% Sigmoid kernel function with slope gamma and intercept c
gamma = 0.5;
c = -1;
G = tanh(gamma*U*V' + c);
end

我的Matlab脚本是

%% Train SVM Classifiers Using a Custom Kernel

rng(1); % For reproducibility
n = 100; % Number of points per quadrant

r1 = sqrt(rand(2*n,1)); % Random radius
t1 = [pi/2*rand(n,1); (pi/2*rand(n,1)+pi)]; % Random angles for Q1 and Q3
X1 = [r1.*cos(t1), r1.*sin(t1)]; % Polar-to-Cartesian conversion

r2 = sqrt(rand(2*n,1));
t2 = [pi/2*rand(n,1)+pi/2; (pi/2*rand(n,1)-pi/2)]; % Random angles for Q2 and Q4
X2 = [r2.*cos(t2), r2.*sin(t2)];

X = [X1; X2]; % Predictors
Y = ones(4*n,1);
Y(2*n + 1:end) = -1; % Labels

% Plot the data
figure(1);
gscatter(X(:,1),X(:,2),Y);
title('Scatter Diagram of Simulated Data');

SVMModel1 = fitcsvm(X,Y,'KernelFunction','mysigmoid','Standardize',true);

% Compute the scores over a grid
d = 0.02; % Step size of the grid
[x1Grid,x2Grid] = meshgrid(min(X(:,1)):d:max(X(:,1)),...
min(X(:,2)):d:max(X(:,2)));
xGrid = [x1Grid(:),x2Grid(:)]; % The grid
[~,scores1] = predict(SVMModel1,xGrid); % The scores

figure(2);
h(1:2) = gscatter(X(:,1),X(:,2),Y);
hold on;
h(3) = plot(X(SVMModel1.IsSupportVector,1),X(SVMModel1.IsSupportVector,2),...
'ko','MarkerSize',10);
% Support vectors
contour(x1Grid,x2Grid,reshape(scores1(:,2),size(x1Grid)),[0,0],'k');
% Decision boundary
title('Scatter Diagram with the Decision Boundary');
legend({'-1','1','Support Vectors'},'Location','Best');
hold off;

CVSVMModel1 = crossval(SVMModel1);
misclass1 = kfoldLoss(CVSVMModel1);
disp(misclass1);

1 个答案:

答案 0 :(得分:1)

内核为要素添加尺寸。例如,如果您有一个样本x={a}的一个功能,它会将其扩展为类似x= {a_1... a_q}的内容。当您对所有数据同时执行此操作时,您将获得M x PM是训练集中的示例数量,P是要素数量)。它要求的第二个矩阵是P x N,其中N是训练/测试集中的示例数。

那就是说,你的输出应该是M x N。由于它是1,这意味着您U = 1XMV=Nx1位于N=M。要获得M x N逻辑输出,您应该简单地转置输入。