So i am doing knn and my function returns a classification label(1D), and I plot it using scatterplot and get this:
how can i convert this to a imshow() plot with "n" pixels for every row?
I've done this recently:
from sklearn.neighbors import KernelDensity
def kde2D(x, y, bandwidth, bins, **kwargs):
"""Build 2D kernel density estimate (KDE). Adapted from: https://stackoverflow.com/questions/41577705/how-does-2d-kernel-density-estimation-in-python-sklearn-work"""
# A grid representing the sampled space. Large bins make it faster
xx, yy = np.mgrid[df.x.min():df.x.max():bins,
df.y.min():df.y.max():bins]
xy_sample = np.vstack([yy.ravel(), xx.ravel()]).T
xy_train = np.vstack([y, x]).T
# Apply kernel density. Large bandwidth gives more regional effects and is slower
kde_skl = KernelDensity(bandwidth=bandwidth, **kwargs)
kde_skl.fit(xy_train)
# score_samples() returns the kernel density at the grid points linearly
z = np.exp(kde_skl.score_samples(xy_sample))
# Reshape it to x,y coordinates corresponding to the original grid
return np.reshape(z, xx.shape)
# Apply function and plot it
dens = kde2D(df.x, df.y, bandwidth = 80, bins = 100)
plt.imshow(dens)
Cheers, Ricardo