Compute Chisquared Kernel using “Matlab matrix style”

This is for whom just want to use matrix-style in Matlab rather than looping. The thumb of rule is simple: you want simpler codes, so you must trade it off with more memory. Sometimes, elegant code and speed is your choice.

The formula of \chi^2 kernel is as follows:

k(x,y) =\sum_{i=1}^p\frac{(x_i-y_i)^2}{x_i+y_i}

Given two matrices A\in\mathbb{R}^{m\times p} and B\in\mathbb{R}^{n\times p} in which p is the dimensionality of data. Says we want to compute the” Gram matrix” between A and B (strictly speaking, we call it Gram matrix iff A\equiv B). In other word, we would like to compute \chi^2 kernel value between every possible pairs (a_i,b_j),i=1,\ldots,m,j=1,\ldots,n.

The Matlab code for that stuff is the following:


[m p] = size(A);
n = size(B,1);

aa = repmat(A,[1 n]);
bb = repmat(reshape(B,1,[]),[m 1]);
D = reshape(((aa-bb).^2)./(aa+bb),[m*n p]);
D = reshape(sum(D,2),[m n]);

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.