I want to make use of the einsum to speed up a code as following:
As simple example using a list of 2 (3,3) arrays called dcx:
That i created:
In [113]: dcx = [np.arange(9).reshape(3,3), np.arange(10,19).reshape(3,3)]; dcx
Out[113]:
[array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]]),
array([[10, 11, 12],
[13, 14, 15],
[16, 17, 18]])]
I wanted to perform the following operation:
In [114]: Ax = np.zeros((2,2))
...: for i in range(2):
...: for j in range(2):
...: Ax[i, j] = np.sum(np.dot(dcx[i], dcx[j].T))
In [115]: Ax
Out[115]:
array([[ 450., 1530.],
[1530., 5310.]])
The time taken ~ 0.001009225845336914 sec
Then i tried using einsum as folowing:
x =np.array(dcx)
In [117]: np.einsum('ikl,jml->ij', x,x)
Out[117]:
array([[ 450, 1530],
[1530, 5310]])
And the time taken in second in almost zero,
So i thought that einsum should be faster, i extended my example to more complex case as following:
dCx is now a list of 40 (40,40) arrays.
I noticed that the time take by:
In [114]: Ax = np.zeros((40,40))
...: for i in range(40):
...: for j in range(40):
...: Ax[i, j] = np.sum(np.dot(dcx[i], dcx[j].T))
Is 0.02168726921081543 sec
while the time taken by the einsum:
array_list = []
for _ in range(40):
array = np.random.rand(40, 40)
array_list.append(array)
t0 = time.time()
x =np.array(array_list)
np.einsum('ikl,jml->ij', x,x)
t1 = time.time()
print(f"Execution time : {t1-t0} sec")
0.15755462646484375 sec
I am confused why einsum now takes longer time? i wanted to make use of ituse it to speed up more complex code with dCx of dimensions (3000,3000,3000) where my loops takes very long time.