Python 计算任意维数组的外积

Python 计算任意维数组的外积,python,arrays,numpy,scipy,slice,Python,Arrays,Numpy,Scipy,Slice,我有两个数组A,B,我想在它们的最后一个维度上取外积, 例如 result[:,i,j]=A[:,i]*B[:,j] 当A时,B是二维的 如果我不知道它们是二维的还是三维的,我该怎么做 在我的具体问题中,A,B是一个更大的三维数组Z的切片, 有时,可以使用整数索引A=Z[:,1,:],B=Z[:,2,:]和其他时间调用此函数 使用切片A=Z[:,1:3,:],B=Z[:,4:6,:]。 由于scipy“挤压”了单态维度,我不知道我的输入是什么维度 会的 我试图定义的数组外部产品应该满足 arra

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

如果我不知道它们是二维的还是三维的,我该怎么做

在我的具体问题中,
A,B
是一个更大的三维数组
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,:] )
对于任何秩3数组
Y,Z
和整数
a,b,…i,j,k…n,n,…


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

您可能会对einsum有一些运气:


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

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.rollaxis
np.reshave
np.ravel
(等等)来随意移动。我想这样做的缺点是它会做一些额外的计算。这可能重要,也可能不重要,取决于您的限制。

在发现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

你能发布一些输入和输出的例子吗?你看过numpy.multiply.outer吗?我想这就是它的功能(但我没有仔细阅读这篇文章),我不知道这个功能。看起来很有用。谢谢。如果我使用的是numpy>1.6.0,我会试试这个(我不是)