2

I'm trying to compute the tensor product (update: what I wanted was actually called the Kronecker product, and this naming confusion was why I couldn't find np.kron) of multiple matrices, so that I can apply transformations to vectors that are themselves the tensor product of multiple vectors. I'm running into trouble with flattening the result correctly.

For example, say I want to compute the tensor product of [[0,1],[1,0]] against itself. The result should be something like:

| 0*|0,1|   1*|0,1| |
|   |1,0|     |1,0| |
|                   |
| 1*|0,1|   0*|0,1| |
|   |1,0|     |1,0| |

which I then want to flatten to:

| 0 0 0 1 |
| 0 0 1 0 |
| 0 1 0 0 |
| 1 0 0 0 |

Unfortunately, the things I try all either fail to flatten the matrix or flatten it too much or permute the entries so that some columns are empty. More specifically, the output of the python program:

import numpy as np
flip = np.matrix([[0, 1], [1, 0]])
print np.tensordot(flip, flip, axes=0)
print np.reshape(np.tensordot(flip, flip, axes=0), (4, 4))

is

[[[[0 0]
   [0 0]]
  [[0 1]
   [1 0]]]
 [[[0 1]
   [1 0]]
  [[0 0]
   [0 0]]]]

[[0 0 0 0]
 [0 1 1 0]
 [0 1 1 0]
 [0 0 0 0]]

Neither of which is what I want.

There are a lot of other questions similar to this one, but the things suggested in them haven't worked (or maybe I missed the ones that work). Maybe "tensor product" means something slightly different than I thought; but the example above should make it clear.

Craig Gidney
  • 17,763
  • 5
  • 68
  • 136

1 Answers1

4

From the answers to this and this question, I learned what you want is called the "Kronecker product". It's actually built into Numpy, so just do:

np.kron(flip, flip)

But if you want to make the reshape approach work, first rearrange the rows in the tensor:

flip = [[0,1],[1,0]]
tensor4d = np.tensordot(flip, flip, axes=0)
print tensor4d.swapaxes(2, 1).reshape((4,4))
Community
  • 1
  • 1