【问题标题】:Reshape tensor to matrix and back将张量重塑为矩阵并返回
【发布时间】:2021-03-07 11:38:41
【问题描述】:

我有两种方法:一种将 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,因为只有当矩阵是我才能按行排列列...有没有办法在没有循环的情况下从矩阵中支持张量?

【问题讨论】:

    标签: python matrix slice reshape tensor


    【解决方案1】:

    考虑以下更改:

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

      ValueError: 没有足够的值来解包(预期 4,得到 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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-16
      • 1970-01-01
      • 2013-05-17
      • 2023-01-25
      • 1970-01-01
      • 1970-01-01
      • 2020-02-09
      • 2021-10-05
      相关资源
      最近更新 更多