将3d矩阵列表转换为4d矩阵

时间:2016-04-13 06:17:02

标签: python numpy matrix

我正在尝试编写一个函数,它接收一个3d矩阵列表。

所以..列表中的每个元素都有(rows,cols, some_scalar).形状。 我正在尝试将其重塑为4d矩阵.. 所以output = (number_of_elements_in_matrix, rows,cols,some_scalar)

到目前为止,我有

output = np.zeros((len(list_of_matrices), list_of_matrices[0].shape[0], list_of_matrices[0].shape[1],
                      list_of_matrices[0].shape[2]), dtype=np.uint8)

我如何知道用值...填充此输出4d张量。

def reshape_matrix(list_of_matrices):
   output = np.zeros((len(list_of_matrices), list_of_matrices[0].shape[0], list_of_matrices[0].shape[1],
                          list_of_matrices[0].shape[2]), dtype=np.uint8)


   return output

1 个答案:

答案 0 :(得分:2)

您可以使用np.stack沿第一个轴(轴= 0)堆叠,就像这样 -

np.stack(list_of_matrices,axis=0)

示例运行 -

In [22]: # Create an input list of arrays
    ...: arr1 = np.random.rand(4,5,2)
    ...: arr2 = np.random.rand(4,5,2)
    ...: arr3 = np.random.rand(4,5,2)
    ...: list_of_matrices = [arr1,arr2,arr3]
    ...: 

In [23]: np.stack(list_of_matrices,axis=0).shape
Out[23]: (3, 4, 5, 2)