Forked from agramfort/Density estimation with Gaussian Kernel with the scikit-learn API (draft)
Created
February 15, 2011 01:47
-
-
Save josef-pkt/826956 to your computer and use it in GitHub Desktop.
just trying out a gist
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from scipy import stats | |
class GaussianKernelDensityEstimation(object): | |
"""docstring for GaussianKernelDensityEstimation""" | |
def __init__(self): | |
self.gkde = None | |
def fit(self, X): | |
"""docstring for fit""" | |
self.gkde = stats.gaussian_kde(X.T) | |
return self | |
def predict(self, X): | |
return self.gkde.evaluate(X.T) | |
if __name__ == '__main__': | |
#I'm just adding some comments to see how gist work | |
import numpy as np | |
# Create some dummy data | |
X = np.random.randn(400,2) | |
X[200:,:] += 3.5 | |
# Regular grid to evaluate kde upon | |
n_grid_points = 128 | |
xmin, ymin = X.min(axis=0) | |
xmax, ymax = X.max(axis=0) | |
xx = np.linspace(xmin - 0.5, xmax + 0.5, n_grid_points) | |
yy = np.linspace(ymin - 0.5, ymax + 0.5, n_grid_points) | |
xg, yg = np.meshgrid(xx, yy) | |
grid_coords = np.c_[xg.ravel(), yg.ravel()] | |
# Compute density estimation | |
kde = GaussianKernelDensityEstimation() | |
kde.fit(X) # Fit | |
zz = kde.predict(grid_coords) # Evaluate density on grid points | |
zz = zz.reshape(*xg.shape) | |
import matplotlib.pylab as pl | |
pl.close('all') | |
pl.set_cmap(pl.cm.Paired) | |
pl.figure() | |
pl.contourf(xx, yy, zz, label='density') | |
pl.scatter(X[:,0], X[:,1], color='k', label='samples') | |
pl.axis('tight') | |
pl.legend() | |
pl.title('Kernel Density Estimation') | |
pl.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment