Korbinian Kottmann
Korbinian Kottmann

Reputation: 153

Approriate reshaping of tensor T[a1,a2,a3] to matrix M[a2,a1*a3] in python

I am trying to reshape a tensor M[a1,a2,a3] with dimensions d1,d2,d3 to a matrix M[a2,a1*a3] of dimension d2, d1*d3. I tried with

M.reshape(d2,d1*d3)

but the result is not what it should be. To give a simple example:

    >>> M = np.array([[['a','b'],['c','d']],[['e','f'],['g','h']],[['i','j'],['k','l']]])
    ... array([[['a', 'b'],
     ['c', 'd']],

    [['e', 'f'],
     ['g', 'h']],

    [['i', 'j'],
     ['l', 'k']]], dtype='<U1')

    >>> M.reshape(2,3*2)
    ... array([['a', 'b', 'c', 'd', 'e', 'f'],
                 ['g', 'h', 'i', 'j', 'l', 'k']], dtype='<U1')

Is there a way of telling reshape which axes he should 'multiply'? (Or another function that does) I'm using this in the context of matrix product states.

Thanks!

EDIT: After the receiving some answer I might specify my question:

Given an array of dimension d1 x d2 x d3, how do I combine non-neighboring indices with reshape() and maintaining dependencies. I.e. reshaping a 3x2x2 tensor to a 2x6 matrix such that the rows correspond to the second (or third) index. As seen in the example, simple .reshape(2,6) gives neither.

Upvotes: 3

Views: 181

Answers (1)

javidcf
javidcf

Reputation: 59711

I think what you need is to first reorder the axes and then reshape:

import numpy as np

M = np.array([[['a','b'],['c','d']],[['e','f'],['g','h']],[['i','j'],['k','l']]])
M = M.transpose((1, 0, 2)).reshape((M.shape[1], -1))
print(M)

Output:

[['a' 'b' 'e' 'f' 'i' 'j']
 ['c' 'd' 'g' 'h' 'k' 'l']]

Upvotes: 1

Related Questions