How can I use fitcsvm and pass parameters to a custom kernel?

15 views (last 30 days)
How can I use fitcsvm and pass parameters to a custom kernel?
I currently use svmtrain and svmclassify with custom kernels that take parameters. However, I need to use fitcsvm for some of the new functionality it offers.
The fitcsvm example with a custom kernel hard codes the parameter, rather than passing it. This is insufficient for my requirements.
KernelParameters is a read-only structure that is output from fitcsvm, it is not an input.
The only parameter that can be passed into a kernel, is PolynomialOrder, which is only allowed for the polynomial kernel (otherwise fitcsvm returns an error).

Accepted Answer

Zhaodong Wang
Zhaodong Wang on 29 Jul 2015
Edited: Zhaodong Wang on 29 Jul 2015
As a workaround, you can pass global variables to the kernel functions.
  3 Comments
Zhaodong Wang
Zhaodong Wang on 30 Jul 2015
Thank you Andre! Actually after giving my previous answer, I found the same issue as yours. I would appreciate your detailed explanation and the new option. Besides, I solved this problem by using a third-party library, libsvm (probably you have already heard about that). This library provides much more flexibilities on defining the kernel function, since you can directly provide the kernel matrix. Also the solver in libsvm seems to be running faster than svmtrain in Matlab. You can have a try if you like. :)
Volker Osterholt
Volker Osterholt on 30 Mar 2016
Edited: Volker Osterholt on 30 Mar 2016
Thanks Andre! It took me a while to work out what you mean so I will share it for the benefit of others.
The function myKernelProxy is saved as myKernelProxy.m and referenced in the call of fitcsvm() or fitrsvm().
The main script has to look something like this:
global khandle
% define the function handle as required
khandle = @(U,V) myCustomKernel(U,V,gamma);
mdl = fitrsvm(X,y,'KernelFunction','myKernelProxy');
function K = myCustomKernel(u,v,gamma)
% here goes the kernel matrix code with all parameters
D=myDistFcn(u,v);
G=exp(-gamma*D.^2);
end
What I am not yet sure about is how save the global function handle is. I am using this in the context of optimising hyper-parameters and want to use parallel processing. So I need to find out if any handle version could get accessed by the wrong worker.
Any suggestions?

Sign in to comment.

More Answers (0)

Tags

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!