简体   繁体   English

在 python 中实现此公式的更快方法

[英]Faster way to implement this formula in python

n and F are 3d matrices of dimensions m * l * l , where m =5 and l =174. nF是 3d 个维度为m * l * l的矩阵,其中m =5 且l =174。 n is given by gamma multiplied by the square of norm 2 of Fi-Fj. n由 gamma 乘以 Fi-Fj 的范数 2 的平方给出。 Formula here公式在这里
My current brute force implementation is我目前的蛮力实施是

for k in range(0,m):
  for i in range(0,l):
    for j in range(0,l):
      dist = gamma*(np.linalg.norm(F[0][i] - F[0][j]))
      m3.append(dist)
    m2.append(m3)
  m1.append(m2)

But my program crashes.但是我的程序崩溃了。 Is there an optimized way to compute this?有没有优化的方法来计算这个?

Right now your operation is done using 3 nested slow Python-style loops.现在您的操作是使用 3 个嵌套的慢速 Python 样式循环完成的。 Use the power of Numpy, broadcasting along the last-but-one axis and vectorizing the operations:使用 Numpy 的力量,沿着最后一个轴广播并对操作进行矢量化:

n = gamma * np.sum((F[:,np.newaxis,:,:] - F[:,:,np.newaxis,:])**2, axis=-1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM