[SciPy-user] scipy.stats.gaussian_kde for 2d kernel density estimation

Dave dave.hirschfeld@gmail....
Wed Jul 23 08:12:54 CDT 2008


massimo sandal <massimo.sandal <at> unibo.it> writes:

> 
> Hi,
> 
> I can't figure out how to do bivariate kernel density estimation with 
> the scipy.stats.gaussian_kde module .1D evaluation seems working, but 2D 
> evaluation escapes me.
> 
> I have two vectors representing x and y coordinates of points:
> 
> xvect=[72.11,81.52,66.46,52.34,81.12,76.83,...]
> yvect=[26.91,17.39,28.84,15.05,10.21,26.42,...]
> 
> The problem is: how do I build the grid to evaluate the points? 

Hopefully the example below will help...

-Dave

import numpy as np
import scipy.stats as stats
from matplotlib.pyplot import imshow

# Create some dummy data
rvs = np.append(stats.norm.rvs(loc=2,scale=1,size=(2000,1)),
                stats.norm.rvs(loc=0,scale=3,size=(2000,1)),
                axis=1)

kde = stats.kde.gaussian_kde(rvs.T)

# Regular grid to evaluate kde upon
x_flat = np.r_[rvs[:,0].min():rvs[:,0].max():128j]
y_flat = np.r_[rvs[:,1].min():rvs[:,1].max():128j]
x,y = np.meshgrid(x_flat,y_flat)
grid_coords = np.append(x.reshape(-1,1),y.reshape(-1,1),axis=1)

z = kde(grid_coords.T)
z = z.reshape(128,128)

imshow(z,aspect=x_flat.ptp()/y_flat.ptp())




More information about the SciPy-user mailing list