将张量 T[a1,a2,a3] 适当重塑为 python 中的矩阵 M[a2,a1*a3]

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

我正在尝试将维度为 d1、d2、d3 的张量 M[a1,a2,a3] 重塑为维度为 d2、d1*d3 的矩阵 M[a2,a1*a3]。我试过

M.reshape(d2,d1*d3)

但结果不尽如人意。举个简单的例子:

    >>> 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')

有没有办法告诉 reshape 他应该 'multiply' 哪个轴? (或另一个函数)我在矩阵乘积状态的上下文中使用它。

谢谢!

编辑: 在收到一些答案后,我可能会说明我的问题:

给定一个维度为 d1 x d2 x d3 的数组,我如何将非相邻索引与 reshape() 结合起来并保持依赖关系。 IE。将 3x2x2 张量重塑为 2x6 矩阵,使行对应于第二个(或第三个)索引。如示例所示,简单的 .reshape(2,6) 两者都不给出。

我想你需要的是先重新排序轴然后再整形:

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)

输出:

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