[英]Einsum multiply each row with every one for 3X3X3 array
Hello could someone please help me figure out how to use np.einsum to produce the below code's result.您好,有人可以帮我弄清楚如何使用 np.einsum 来生成以下代码的结果。 I have a (3,3,3) tensor and I will like to get this results which I got from using two for loops.
我有一个 (3,3,3) 张量,我想得到我使用两个 for 循环得到的结果。 the code I wrote to produce this output is below.
我为生成此输出而编写的代码如下。 I am trying to use np.einsum to produce this same result attained from using two for loops in the below code.
我正在尝试使用 np.einsum 来产生与在下面的代码中使用两个 for 循环所获得的相同结果。 I am not familar with using np.einsum.
我不熟悉使用 np.einsum。 Ideally I will also like to sum each of the resulting rows to get nine values.
理想情况下,我还想对每个结果行求和以获得九个值。
Command Line Arguments
result of code below
[1 1 1]
[2 2 2]
[1 1 1]
[2 2 2]
[4 4 4]
[2 2 2]
[1 1 1]
[2 2 2]
[1 1 1]
[1 1 1]
3
6
3
9
12
6
15
18
9
6
12
6
18
24
12
import numpy as np
bb=[]
for x in range(3):
for y in range(3):
bb.append((x,y))
a = np.array([[[1,2,1],[3,4,2],[5,6,3]],
[[1,2,1],[3,4,2],[5,6,3]],
[[1,2,1],[3,4,2],[5,6,3]]])
b = np.array([[[1,2,1],[3,4,2],[5,6,3]],
[[1,2,1],[3,4,2],[5,6,3]],
[[1,2,1],[3,4,2],[5,6,3]]])
for z in range(9):
llAI = bb[z]
aal = a[:,llAI[0],llAI[1]]
for f in range(9):
mmAI=bb[f]
aam = a[:,mmAI[0],mmAI[1]]
print(np.sum(aal*aam))
It took a bit to figure out what you are doing,花了一点时间才弄清楚你在做什么,
Since z
iterates on range(3)
, aal
is successively a[:,0,0]
, a[:,0,1]
, a[:,0,2]
.由于
z
在range(3)
上迭代, aal
依次a[:,0,0]
、 a[:,0,1]
、 a[:,0,2]
。
Or done all at once:或者一次完成:
In [178]: aaL = a[:,0,:]; aaL
Out[178]:
array([[1, 2, 1],
[1, 2, 1],
[1, 2, 1]])
aam
does the same iteration. aam
执行相同的迭代。 So the sum of their products, using matmul/@/dot
is:所以他们的产品总和,使用
matmul/@/dot
是:
In [179]: aaL.T@aaL
Out[179]:
array([[ 3, 6, 3],
[ 6, 12, 6],
[ 3, 6, 3]])
Or in einsum
:或者在
einsum
中:
In [180]: np.einsum('ji,jk->ik',aaL,aaL)
Out[180]:
array([[ 3, 6, 3],
[ 6, 12, 6],
[ 3, 6, 3]])
Your indexing array:您的索引数组:
In [183]: bb
Out[183]: [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)
In [185]: np.array(bb)[:3,:]
Out[185]:
array([[0, 0],
[0, 1],
[0, 2]])
If I generalize it to the remaining ranges of bb
:如果我将其概括为
bb
的剩余范围:
In [192]: for i in range(3):
...: aaL = a[:,i]
...: print(aaL.T@aaL)
...:
[[ 3 6 3]
[ 6 12 6]
[ 3 6 3]]
[[27 36 18]
[36 48 24]
[18 24 12]]
[[ 75 90 45]
[ 90 108 54]
[ 45 54 27]]
Adding a dimension to the einsum
:向
einsum
添加维度:
In [195]: np.einsum('jmi,jmk->mik', a,a)
Out[195]:
array([[[ 3, 6, 3],
[ 6, 12, 6],
[ 3, 6, 3]],
[[ 27, 36, 18],
[ 36, 48, 24],
[ 18, 24, 12]],
[[ 75, 90, 45],
[ 90, 108, 54],
[ 45, 54, 27]]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.