3
votes

This is my first Matlab program.

I'm trying to use svmtrain and svmclassify with custom kernel.

Assume my kernel is regular inner product.

How should I write it?

I did:

function [K] = mykernel(U, V)
    for i=size(U,1)
        for j=size(V,1)
            K(i,j) = dot(U(i,:),V(j,:));
        end
    end
    return 
end

and then in the command window:

x=randn(1000,10);
w=rand(1,10);
y=sign(x*w');
a=svmtrain(x,y,'kernel_function',mykernel);

and I get:

Error using mykernel (line 2)
Not enough input arguments.

Maybe one has a trick to do it without loops, something like U*V', it'll be nice to know this trick, but i need to do it in loop, since i'm going to change the inner product to some more complicated stuff.

I also didn't really understand what are those U,V, and I didn't really get what this function should return (is it the Gram matrix?)

Thanks for your help!!

--- EDIT:

I did the following:

function [K] = mink(U, V)
    for i=1:size(U,1)
        for j=1:size(V,1)
            K(i,j) = min(exp(-dot(U(i,:),U(j,:))),exp(-dot(V(i,:),V(j,:))));
        end
    end
    return 
end

>>x=randn(100,10);
>>w=rand(1,10);
>>y=sign(x*w');
>>a=svmtrain(x,y,'kernel_function',@mink);
>>svmclassify(a, x)
Error using svmclassify (line 114)
An error was encountered during classification.
Attempted to access U(89,:); index out of bounds because size(U)=[88,10].

so now svmtrain works but svmclassify complains about size mismath (how did it get 88??)

1
btw when i do svmtrain(x,y,'kernel_function','linear'); or any other predefined kernel, everything works great - Troy McClure
Check your for loop. It seems like you want i=1:size(....) - Squazic
right. it was just a typo here. pls see my last edit - Troy McClure
What's the size of your y? It's not a vector of groups is it? - Squazic
do you know what are those u,v? they have the same dimension of x! - Troy McClure

1 Answers

1
votes

In order to pass a function, you need to use the @ symbol. This is shown in the docs, which quote:

@kfun — Function handle to a kernel function. A kernel function must be of the form

Bottom line, this will work.

a=svmtrain(x,y,'kernel_function',@mykernel);