将张量重塑为矩阵并返回

Reshape tensor to matrix and back

我有两种方法:一种是将 4D 矩阵(张量)转换为矩阵,另一种是将 2D 矩阵转换为 4D。

从 4D 重塑到 2D 效果很好,但是当我再次尝试在张量中重新转换时,我没有获得相同的元素顺序。这些方法是:

# Method to convert the tensor in a matrix
def tensor2matrix(tensor):
    # rows, columns, channels and filters
    r, c, ch, f = tensor[0].shape
    new_dim = [r*c*ch, f] # Inferer the new matrix dims
    # Transpose is necesary because the columns are the channels weights 
    # flattened in columns
    return np.reshape(np.transpose(tensor[0], [2,0,1,3]), new_dim)

# Method to convert the matrix in a tensor
def matrix2tensor(matrix, fs):
    return np.reshape(matrix, fs, order="F")

我认为问题出在 np.transpose 因为什么时候只有一个矩阵我可以按行排列列... 是否有没有循环的矩阵来支持张量?

考虑以下更改:

  1. 把两个tensor[0]换成tensor,避免

    ValueError: not enough values to unpack (expected 4, got 3)

    当运行下面提供的例子

  2. 确保两个 np.reshape 调用使用相同的 order="F"

  3. matrix2tensor 中使用另一个 np.transpose 调用来撤消 tensor2matrix

    中的 np.transpose

更新后的代码是

import numpy as np

# Method to convert the tensor in a matrix
def tensor2matrix(tensor):
    # rows, columns, channels and filters
    r, c, ch, f = tensor.shape
    new_dim = [r*c*ch, f] # Inferer the new matrix dims
    # Transpose is necesary because the columns are the channels weights 
    # flattened in columns
    return np.reshape(np.transpose(tensor, [2,0,1,3]), new_dim, order="F")

# Method to convert the matrix in a tensor
def matrix2tensor(matrix, fs):
    return np.transpose(np.reshape(matrix, fs, order="F"), [1,2,0,3])

可以这样测试:

x,y,z,t = 2,3,4,5
shape = (x,y,z,t)
m1 = np.arange(x*y*z*t).reshape((x*y*z, 5))
t1 = matrix2tensor(m1, shape)
m2 = tensor2matrix(t1)
assert (m1 == m2).all()

t2 = matrix2tensor(m2, shape)
assert (t1 == t2).all()