Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate a Gaussian kernel matrix efficiently in numpy?

Tags:

python

numpy

def GaussianMatrix(X,sigma):     row,col=X.shape     GassMatrix=np.zeros(shape=(row,row))     X=np.asarray(X)     i=0     for v_i in X:         j=0         for v_j in X:             GassMatrix[i,j]=Gaussian(v_i.T,v_j.T,sigma)             j+=1         i+=1     return GassMatrix def Gaussian(x,z,sigma):     return np.exp((-(np.linalg.norm(x-z)**2))/(2*sigma**2)) 

This is my current way. Is there any way I can use matrix operation to do this? X is the data points.

like image 769
hidemyname Avatar asked Apr 19 '15 15:04

hidemyname


1 Answers

I myself used the accepted answer for my image processing, but I find it (and the other answers) too dependent on other modules. Therefore, here is my compact solution:

import numpy as np     def gkern(l=5, sig=1.):     """\     creates gaussian kernel with side length `l` and a sigma of `sig`     """     ax = np.linspace(-(l - 1) / 2., (l - 1) / 2., l)     gauss = np.exp(-0.5 * np.square(ax) / np.square(sig))     kernel = np.outer(gauss, gauss)     return kernel / np.sum(kernel) 

Edit: Changed arange to linspace to handle even side lengths

Edit: Use separability for faster computation, thank you Yves Daoust.

like image 139
clemisch Avatar answered Sep 20 '22 14:09

clemisch