所以我在做knn,我的函数返回一个分类标签(1D),我使用散点图绘制它并得到这个:
如何将其转换为每行带有“n”个像素的 imshow() 图?
我最近这样做了:
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)
干杯,里卡多