问题描述
我有一个简单的代码,可以使用 scipy.stats.gaussian_kde 函数.
I have a simple code that generates a 2D gaussian kernel using scipy.stats.gaussian_kde function.
这是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)
结果如下:
我需要的是一种在此KDE中获取最大值的x,y
坐标的方法.
What I need is a way to obtain the x,y
coordinates of the maximum value in this KDE.
对于我可以从各种来源收集到的信息,找到最大值的直接方法似乎是在细网格上评估kernel
,然后仅使用np.argmax
来找到它,请参见下文:
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?
推荐答案
np.argmax(kernel)
可能就是您想要的...
might be what you're looking for...
请参阅: http://docs.scipy.org/doc/numpy/reference/generation/numpy.argmax.html
这篇关于快速搜索高斯核中最大值的坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!