So I am trying to compute the kronecker product of two matrices each of arbitrary dimension. (I use square matrices of the same dimension just for the examples)
Initially I tried using kron
:
a = np.random.random((60,60))
b = np.random.random((60,60))
start = time.time()
a = np.kron(a,b)
end = time.time()
Output: 0.160096406936645
To try and get a speed up I used tensordot
:
a = np.random.random((60,60))
b = np.random.random((60,60))
start = time.time()
a = np.tensordot(a,b,axes=0)
a = np.transpose(a,(0,2,1,3))
a = np.reshape(a,(3600,3600))
end = time.time()
Output: 0.11808371543884277
After searching the web a bit, I found that (or at least to my understanding) numpy makes an extra copy when it has to reshape a tensor that has been transposed.
So I then tried the following (this code obviously does not give the kronecker product of a and b, but I was just doing it as a test):
a = np.random.random((60,60))
b = np.random.random((60,60))
start = time.time()
a = np.tensordot(a,b,axes=0)
a = np.reshape(a,(3600,3600))
end = time.time()
Output: 0.052041053771972656
My question is: how can I compute the kronecker product without encountering this issue associated with the transpose?
I am just looking for a fast speed up, so the solution does not have to use tensordot
.
EDIT
I just found on this stack post: speeding up numpy kronecker products, that there is another way to do it:
a = np.random.random((60,60))
b = np.random.random((60,60))
c = a
start = time.time()
a = a[:,np.newaxis,:,np.newaxis]
a = a[:,np.newaxis,:,np.newaxis]*b[np.newaxis,:,np.newaxis,:]
a.shape = (3600,3600)
end = time.time()
test = np.kron(c,b)
print(np.array_equal(a,test))
print(end-start)
Output: True
0.05503702163696289
I am still interested in the question of whether or not you can speed up this computation further?