首页 > 解决方案 > 将张量重塑为矩阵并返回

问题描述

我有两种方法:一种将 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因为什么时候只有一个矩阵我可以逐行排列列......无论如何要从没有循环的矩阵中支持张量?

标签: pythonmatrixslicereshapetensor

解决方案


考虑以下变化:

  1. 将两者替换为tensor[0],tensor以避免

    ValueError:没有足够的值来解包(预期 4,得到 3)

    运行下面提供的示例时

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

  3. 在内部使用另一个np.transpose调用matrix2tensor来撤消np.transposefromtensor2matrix

更新的代码是

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

推荐阅读