任意形状NumPy阵列的点积

2024-10-01 04:51:38 发布

您现在位置:Python中文网/ 问答频道 /正文

给定两个任意形状的numpy.ndarray对象A和{},我想计算一个numpy.ndarrayC,其属性为C[i] == np.dot(A[i], B[i])。我该怎么做?在

例1:A.shape==(2,3,4)和{},那么我们应该有C.shape==(2,3,5)。在

示例2:A.shape==(2,3,4)和{},那么我们应该有C.shape==(2,3)。在


Tags: 对象numpy示例属性npdot形状ndarray
2条回答

这里有一个通用的解决方案,可以使用一些reshaping^{}来覆盖所有类型的事例/任意形状。einsum在这里有帮助,因为我们需要沿着输入数组的第一个轴对齐,并沿着最后一个轴进行缩减。实现应该是这样的-

def dotprod_axis0(A,B):
    N,nA,nB = A.shape[0], A.shape[-1], B.shape[1]
    Ar = A.reshape(N,-1,nA)
    Br = B.reshape(N,nB,-1)
    return np.squeeze(np.einsum('ijk,ikl->ijl',Ar,Br))

案例

I.A:2D,B:2D

^{pr2}$

二。A:3D,B:3D

In [122]: # Inputs
     ...: A = np.random.randint(0,9,(2,3,4))
     ...: B = np.random.randint(0,9,(2,4,5))
     ...: 

In [123]: for i in range(A.shape[0]):
     ...:     print np.dot(A[i], B[i])
     ...:     
[[ 74  70  53 118  43]
 [ 47  43  29  95  30]
 [ 41  37  26  23  15]]
[[ 50  86  33  35  82]
 [ 78 126  40 124 140]
 [ 67  88  35  47  83]]

In [124]: dotprod_axis0(A,B)
Out[124]: 
array([[[ 74,  70,  53, 118,  43],
        [ 47,  43,  29,  95,  30],
        [ 41,  37,  26,  23,  15]],

       [[ 50,  86,  33,  35,  82],
        [ 78, 126,  40, 124, 140],
        [ 67,  88,  35,  47,  83]]])

III.A:3D,B:2D

^{4}$

IV.A:2D,B:3D

In [128]: # Inputs
     ...: A = np.random.randint(0,9,(2,4))
     ...: B = np.random.randint(0,9,(2,4,5))
     ...: 

In [129]: for i in range(A.shape[0]):
     ...:     print np.dot(A[i], B[i])
     ...:     
[76 93 31 75 16]
[ 33  98  49 117 111]

In [130]: dotprod_axis0(A,B)
Out[130]: 
array([[ 76,  93,  31,  75,  16],
       [ 33,  98,  49, 117, 111]])

假设你想要普通的矩阵乘法dot(不是,比如说,矩阵向量或者dot对于更高维所做的奇怪的废话),那么足够新的numy版本(1.10+)就可以了

C = numpy.matmul(A, B)

最新的Python版本(3.5+)允许您将其编写为

^{pr2}$

假设你的裸体也足够新。在

相关问题 更多 >