Fast search for the coordinates of the maximum value in a gaussian kernel

99封情书 提交于 2020-01-03 17:10:49

问题


I have a simple code that generates a 2D gaussian kernel using scipy.stats.gaussian_kde function.

Here's the MWE:

def random_data(N):
    # Generate some random data.
    return np.random.uniform(0., 10., N)

# Data lists.
x_data = random_data(10000)
y_data = random_data(10000)

# Obtain the KDE for this region.
kernel = stats.gaussian_kde(np.vstack([x_data, y_data]), bw_method=0.05)

and here's the result:

What I need is a way to obtain the x,y coordinates of the maximum value in this KDE.

For what I could gather from various sources the direct way to locate the maximum value seem to be evaluating the kernel on a fine grid and then just use np.argmax to find it, see below:

# define grid.
xmin, xmax = min(x_data), max(x_data)
ymin, ymax = min(y_data), max(y_data)
x, y = np.mgrid[xmin:xmax:100j, ymin:ymax:100j]
positions = np.vstack([x.ravel(), y.ravel()])

# THIS IS TOO SLOW.
k_pos = kernel(positions)

# Print max value.
print k_pos[np.argmax(k_pos)]

# Print x,y coordinates of max value.
print positions.T[np.argmax(k_pos)]

The issue with this is that evaluating the kernel is terribly slow, almost to the point of being unusable for not too large datasets.

Is there a better way to get the coordinates of the max value?

Also accepted (perhaps even better since it would also allow fast plotting): is there a faster way to evaluate the kernel in a fine grid?


回答1:


np.argmax(kernel)

might be what you're looking for...

see: http://docs.scipy.org/doc/numpy/reference/generated/numpy.argmax.html



来源:https://stackoverflow.com/questions/22690397/fast-search-for-the-coordinates-of-the-maximum-value-in-a-gaussian-kernel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!