高斯人总和成快速的脾气暴躁? [英] Sum of Gaussians into fast Numpy?
问题描述
这是我的问题:
我有两组3d点.我们称它们为"Gausspoints"和"XYZ".我定义了一个函数,该函数是高斯和的总和,其中每个高斯都以一个高斯点为中心.现在,我想在XYZ点上评估此功能:我的方法运行良好,但速度很慢.知道如何通过更好地利用numpy来加快速度吗?
I have two sets of 3d points. Lets call them "Gausspoints" and "XYZ". I define a function which is a sum of Gaussians in which every Gaussian is centered at one of the Gausspoints. Now I want to evaluate this function on the XYZ points: My approach is working fine but it is rather slow. Any idea how to speed it up by exploiting numpy a little better?
def sumgaus(r):
t=r-Gausspoints
t=map(np.linalg.norm,t)
t = -np.power(t,2.0)
t=np.exp(t)
res=np.sum(t)
return res
result=map(sumgaus,XYZ)
感谢您的帮助
XYZ的形状为N * 3,高斯点为M * 3,其中M为整数,N为不同的整数
shape of XYZ N*3 and Gausspoints are M*3 with M, N being different integers
Edit2:我想在XYZ中的每个项目上应用以下功能
I want to apply the following function on each item in XYZ
推荐答案
棘手的部分是如何对点之间所有差异的计算进行矢量化处理,而无需任何显式的Python循环或映射.您可以通过以下方式使用广播来推出自己的实现:
The tricky part is how to vectorize the computation of all the differences between your points without any explicit Python looping or mapping. You can roll out your own implementation using broadcasting by doing something like:
dist2 = XYZ[:, np.newaxis, :] - Gausspoints
dist2 *= dist
dist2 = np.sum(dist, axis=-1)
如果XYZ
具有形状(n, 3)
并且Gausspoints
具有形状(m, 3)
,则dist
将具有形状(n, m)
,其中dist[i, j]
是点XYZ[i]
和Gausspoints[j]
之间的距离
And if XYZ
has shape (n, 3)
and Gausspoints
has shape (m, 3)
, then dist
will have shape (n, m)
, with dist[i, j]
being the distance between points XYZ[i]
and Gausspoints[j]
.
使用 scipy.spatial.distance.cdist
:
from scipy.spatial.distance import cdist
dist2 = cdist(XYZ, Gausspoints)
dist2 *= dist2
但是一旦您有了平方距离的数组,这就是孩子的游戏:
But once you have your array of squared distances, it's child's play:
f = np.sum(np.exp(-dist2), axis=1)
这篇关于高斯人总和成快速的脾气暴躁?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!