Skip to main content
 首页 » 编程设计

python之高斯总和到快速 Numpy

2024年11月01日11jirigala

这是我的问题:

我有两组 3d 点。让我们称它们为“Gausspoints”和“XYZ”。我定义了一个函数,它是高斯函数的总和,其中每个高斯函数都以其中一个高斯点为中心。现在我想在 XYZ 点上评估这个函数:我的方法工作正常但速度很慢。知道如何通过更好地利用 numpy 来加快速度吗?

  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的shape和Gausspoints为M*3,其中M、N为不同的整数

Edit2:我想对 XYZ 中的每个项目应用以下功能

enter image description here

请您参考如下方法:

棘手的部分是如何在没有任何显式 Python 循环或映射的情况下向量化点之间所有差异的计算。您可以通过执行以下操作使用广播推出您自己的实现:

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]。

使用scipy.spatial.distance.cdist可能更容易理解:

from scipy.spatial.distance import cdist 
 
dist2 = cdist(XYZ, Gausspoints) 
dist2 *= dist2 

但是一旦你有了平方距离数组,这就很容易了:

f = np.sum(np.exp(-dist2), axis=1)