【问题标题】:How to assign to square submatrices in big matrix without loops in numpy如何在没有循环的情况下分配给大矩阵中的方形子矩阵
【发布时间】:2012-06-14 21:20:28
【问题描述】:

如何向量化这个循环,它使用 numpy 数组填充一个较大矩阵的两个方形子矩阵(也保持较大的矩阵对称):

for x in range(n):
    assert m[x].shape == (n,)
    M[i:i+n,j+x] = m[x]
    M[j+x,i:i+n] = m[x]

这很诱人,但不同意上面的循环(参见下面的示例不同意):

assert m.shape == (n,n)
M[i:i+n,j:j+n] = m
M[j:j+n,i:i+n] = m

这是一个小例子(n>1 时崩溃):

from numpy import arange,empty,NAN
from numpy.testing import assert_almost_equal

for n in (1,2,3,4):
    # make the submatrix
    m = (10 * arange(1, 1 + n * n)).reshape(n, n)

    N = n # example below, submatrix is the whole thing

    # M1 using loops, M2 "vectorized"
    M1 = empty((N, N))
    M2 = empty((N, N))
    M1.fill(NAN)
    M2.fill(NAN)

    i,j = 0,0 # not really used when (n == N)

    # this results in symmetric matrix
    for x in range(n):
        assert m[x].shape == (n,)
        M1[i:i+n,j+x] = m[x]
        M1[j+x,i:i+n] = m[x]

    # this does not work as expected
    M2[i:i+n,j:j+n] = m
    M2[j:j+n,i:i+n] = m

    assert_almost_equal(M1,M1.transpose(),err_msg="M not symmetric?")
    print "M1\n",M1,"\nM2",M2
    assert_almost_equal(M1,M2,err_msg="M1 (loop) disagrees with M2 (vectorized)")

我们最终得到:

M1 = [10 30
      30 40] # symmetric

M2 = [10 20
      30 40] # i.e. m

【问题讨论】:

    标签: python numpy vectorization


    【解决方案1】:

    您的测试不正确: 对于 i,j=0,0 您的 M2[]= 分配只是覆盖相同的矩阵块。

    使用 M1 时获得对称矩阵的原因是因为您分配 单个循环中的 M1 值。

    如果你将循环分成两部分:

    for x in range(n):
          M1[i:i+n,j+x] = m[x]
    for x in range(n): 
          M1[j+x,i:i+n] = m[x]
    

    M1 显然与 M2 相同。

    总而言之,以下代码有效(相当于您的 M2 计算)但是!只有在对角线上方和下方的块之间没有重叠时,它才会起作用。如果有你必须决定在那里做什么

    xs=np.arange(4).reshape(2,2)
    ys=np.zeros((7,7))
    ys[i:i+n,j:j+n]=xs
    ys[j:j+n,i:i+n]=xs.T
    print ys
    >> array([[ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
           [ 0.,  0.,  0.,  0.,  1.,  0.,  0.],
           [ 0.,  0.,  0.,  2.,  3.,  0.,  0.],
           [ 0.,  0.,  2.,  0.,  0.,  0.,  0.],
           [ 0.,  1.,  3.,  0.,  0.,  0.,  0.],
           [ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
           [ 0.,  0.,  0.,  0.,  0.,  0.,  0.]])
    

    【讨论】:

    • 啊,好点,编写的代码不容易向量化,因为循环中的两个赋值可以交互。我以为我遇到了索引的一个微妙功能,但这是一个更简单的解释。谢谢!
    猜你喜欢
    • 2013-02-07
    • 2020-05-12
    • 1970-01-01
    • 2016-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-06
    相关资源
    最近更新 更多