【问题标题】:Compute outer product of arrays with arbitrary dimensions计算任意维度数组的外积
【发布时间】:2012-07-22 04:06:03
【问题描述】:

我有两个数组A,B 并希望在它们的最后一个维度上取外积, 例如 result[:,i,j]=A[:,i]*B[:,j]A,B 是二维时。

如果我不知道它们是 2 维还是 3 维,我该怎么做?

在我的具体问题中A,B 是从更大的 3 维数组Z 中切出的部分, 有时这可以用整数索引A=Z[:,1,:], B=Z[:,2,:] 和其他时候调用 切片A=Z[:,1:3,:],B=Z[:,4:6,:]。 由于 scipy “挤压”单例维度,我不知道我的输入是什么维度 会的。

我试图定义的数组外积应该满足

array_outer_product( Y[a,b,:], Z[i,j,:] ) == scipy.outer( Y[a,b,:], Z[i,j,:] )
array_outer_product( Y[a:a+N,b,:], Z[i:i+N,j,:])[n,:,:] == scipy.outer( Y[a+n,b,:], Z[i+n,j,:] ) 
array_outer_product( Y[a:a+N,b:b+M,:], Z[i:i+N, j:j+M,:] )[n,m,:,:]==scipy.outer( Y[a+n,b+m,:] , Z[i+n,j+m,:] )

对于任何 rank-3 数组 Y,Z 和整数 a,b,...i,j,k...n,N,...

我正在处理的问题涉及二维空间网格,每个网格点都有一个向量值函数。我希望能够在前两个轴上的切片定义的区域上计算这些向量的协方差矩阵(外积)。

【问题讨论】:

  • 你能发布一些示例输入和输出吗?
  • 你看过 numpy.multiply.outer 吗?我认为这就是它的作用(但我没有仔细阅读这篇文章)。

标签: python arrays numpy scipy slice


【解决方案1】:

【讨论】:

  • 我不知道这个功能。看起来很有用。谢谢。
  • 如果我使用 numpy >1.6.0(我不是),我会试试这个
【解决方案2】:

在发现 numpy/scipy 数组中使用省略号之后 我最终将它实现为递归函数:

def array_outer_product(A, B, result=None):
    ''' Compute the outer-product in the final two dimensions of the given arrays.
    If the result array is provided, the results are written into it.
    '''
    assert(A.shape[:-1] == B.shape[:-1])
    if result is None:
        result=scipy.zeros(A.shape+B.shape[-1:], dtype=A.dtype)
    if A.ndim==1:
        result[:,:]=scipy.outer(A, B)
    else:
        for idx in xrange(A.shape[0]):
            array_outer_product(A[idx,...], B[idx,...], result[idx,...])
    return result

【讨论】:

    【解决方案3】:

    假设我对您的理解正确,几周前我在研究中遇到了类似的问题。我意识到克罗内克积只是一个保持维度的外积。因此,您可以这样做:

    import numpy as np
    
    # Generate some data
    a = np.random.random((3,2,4))
    b = np.random.random((2,5))
    
    # Now compute the Kronecker delta function
    c = np.kron(a,b)
    
    # Check the shape
    np.prod(c.shape) == np.prod(a.shape)*np.prod(b.shape)
    

    我不确定你最后想要什么形状,但你可以结合使用数组切片和np.rollaxisnp.reshapenp.ravel(等等)来随意调整。我想这样做的缺点是它做了一些额外的计算。这可能很重要,也可能无关紧要,具体取决于您的限制。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-22
      • 2012-04-12
      • 2017-12-24
      • 1970-01-01
      • 1970-01-01
      • 2018-05-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多