, :
import numpy as np
def do_sum(x, mat_lst):
a = np.array(x).flatten().reshape(1, -1)
print('A shape: ', a.shape)
b = np.stack(mat_lst)
print('B shape: ', b.shape)
return np.einsum('ij,jkl->kl', a, b)
A = [[1,2],[3,4]]
B = [[[1,1],[1,1]],[[2,2],[2,2]],[[3,3],[3,3]],[[4,4],[4,4]]]
do_sum(A,B)
A shape: (1, 4)
B shape: (4, 2, 2)
[[30 30]
[30 30]]
-
n-d. , x mat_lst.
def do_sum(x, mat_lst):
a = np.array(x).flatten()
b = np.stack(mat_lst)
print("A shape: {}\nB shape: {}".format(a.shape, b.shape))
return np.einsum('i,i...', a, b)
A = [[1,2],[3,4]]
B = [np.random.rand(2,2,2) for _ in range(4)]
do_sum(A,B)
(: , , , , ( , (1x3), (3) .) , .)
, . , a.shape = (n,) b.shape = (n,...), a b. b , , ... . (s) , (.. ...).
The index string passed in einsumcaptures all this information. On the input side of the line (everything to the left of ->), we mark the indices for each operand (i.e., the input matrices aand b), separated by commas. The indices for summation are repeated (i.e. i). On the output side of the line (to the right of ->) we indicate the output indices. Our function does not need an output line, because we want to display all dimensions not included in the summation (I think).