简体   繁体   English

将 numpy.einsum 用于切片的张量点

[英]Using numpy.einsum for tensor dot of slices

I have an array of shape N, j, j and another of shape M, j, j .我有一个形状为N, j, j的数组和另一个形状为M, j, j的数组。 I want to calculate their tensor dot to eventually have a matrix where the i,j entry is np.tensordot(arr1[i, :, :], arr2[j, :, :]) I've tried looping but it is ridiculously slow, I've read about np.einsum but unfortunately cannot figure it out no matter how much I read.我想计算他们的张量点,最终得到一个矩阵,其中i,j条目是np.tensordot(arr1[i, :, :], arr2[j, :, :])我试过循环,但这很荒谬慢,我读过关于np.einsum的文章,但不幸的是,无论我读了多少,都无法弄清楚。 My most recent attempt;我最近的尝试; np.einsum('ilk,ium->lu', arr1, arr2) But I keep getting errors that the shapes can't be broadcasted. np.einsum('ilk,ium->lu', arr1, arr2)但我不断收到无法广播形状的错误。 Would appreciate any pointers, thanks!不胜感激任何指点,谢谢!

example code:示例代码:

  arr1 = np.zeros((5, 2, 2))
  arr2 = np.zeros((4, 2, 2))
  arr2[1,:,:][1,1] = 2
  arr1[1,:,:][1,1] = 3
  np.tensordot(arr1[1,:,:], arr2[1,:,:])

in this case, the tensor dot would give me 6. That is what I am interested in, for each i,j .在这种情况下,张量点会给我 6。这就是我感兴趣的,对于每个i,j

In [41]: x=np.arange(2*3*3).reshape(2,3,3)
In [42]: y=np.arange(4*3*3).reshape(4,3,3)

double contraction on the last 2 dim:最后 2 个暗淡的双重收缩:

In [43]: np.einsum('ikl,jkl->ij',x,y)
Out[43]: 
array([[ 204,  528,  852, 1176],
       [ 528, 1581, 2634, 3687]])

test one value:测试一个值:

In [44]: np.tensordot(x[0],y[0])
Out[44]: array(204)

Same thing dot (and extra dimension)相同的点(和额外的维度)

In [47]: np.dot(x.reshape(-1,9),y.reshape(-1,9,1))
Out[47]: 
array([[[ 204],
        [ 528],
        [ 852],
        [1176]],

       [[ 528],
        [1581],
        [2634],
        [3687]]])

np.tensordot with the various axis options can be a bit tricky to use.带有各种轴选项的np.tensordot使用起来可能有点棘手。 One way or other it reshapes and transposes the arrays so it can call np.dot .它以一种或其他方式重塑和转置 arrays 以便它可以调用np.dot Then it may do some further manipulation.然后它可能会做一些进一步的操作。

Or using broadcasting and multiaxis sum:或使用广播和多轴求和:

In [48]: (x[:,None,:,:]*y[None,:,:,:]).sum(axis=(2,3))
Out[48]: 
array([[ 204,  528,  852, 1176],
       [ 528, 1581, 2634, 3687]])

and a non-loop tensordot:和一个非循环张量点:

In [50]: np.tensordot(x,y,axes=((1,2),(1,2)))
Out[50]: 
array([[ 204,  528,  852, 1176],
       [ 528, 1581, 2634, 3687]])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM