【问题标题】:Fast way to compute matrix of the from (Matrix - constant)计算来自(矩阵 - 常数)的矩阵的快速方法
【发布时间】:2020-05-05 20:07:02
【问题描述】:

我想找到一种更快的方法来计算矩阵v。请注意,如果高度 = 宽度,则矩阵 v 是对称的,v = v.T。宽度和高度是任意正整数。

v = np.zeros((height, width)) # rows columns

# region center
cr = np.round(height / 2)
cc = np.round(width / 2)

# there has to be a quicker way to do this
for w in range(width):
    v[:, w] = [np.sqrt((w - cc) ** 2 + (h - cr) ** 2) for h in range(height)]

【问题讨论】:

  • 我不知道如何称呼这个操作,但它似乎与矩阵的 L2 范数无关,这是最大的特征值量级。也许标题应该调整一下?

标签: python performance numpy matrix


【解决方案1】:

您可以使用 numpy 的 broadcasting 来简化此操作:

out = np.sqrt((np.arange(width)-cc)**2 + (np.arange(height)[:,None]-cr)**2) 

width=5
height=8
v = np.zeros((height, width)) # rows columns
# region center
cr = np.round(height / 2)
cc = np.round(width / 2)
# there has to be a quicker way to do this
for w in range(width):
    v[:, w] = [np.sqrt((w - cc) ** 2 + (h - cr) ** 2) for h in range(height)]

np.allclose(v, out)
# True

【讨论】:

  • 这个答案是@alain T. 的答案的 2 倍左右。完全忘记了 numpy 广播。
  • 我也忘记了
【解决方案2】:

您可以使用scipy.spatial.distance.cdist,与numpy.indices

from scipy.spatial.distance import cdist
import numpy as np

shape = (height, width)
v = cdist(np.indices(shape).reshape(2, -1).T, [[cr, cc]]).reshape(shape)

这在所有情况下都与@yatu's broadcasting solution 产生相同的结果,但奇怪的是,对于各种输入大小,它的速度慢了约 3 倍。话虽如此,它可能更节省空间,因为它只分配一个输出大小的数组而不是两个(第二个是输入平方根的总和)。这不应该是您遇到的任何正常输入的考虑因素,因此请使用广播解决方案。这只是为了完整性。

【讨论】:

    【解决方案3】:

    您可以在没有任何循环的情况下执行此操作。生成行索引矩阵和列索引矩阵,并在两个矩阵之间应用公式:

    rows,cols = np.indices((height,width))
    v         = np.sqrt((rows-height//2)**2+(cols-width//2)**2)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-11
      • 2018-09-03
      • 2015-03-18
      • 1970-01-01
      • 2011-11-15
      • 2020-03-21
      • 2021-10-26
      相关资源
      最近更新 更多