2016-04-13 218 views
0

我试图写一个函数,该函数在三维矩阵的列表..转换3D矩阵的列表到4D矩阵

所以..在列表中的每个元素具有形状(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 
+0

@Divakar:是的..这做的工作。如果你想将它写成一个答案? – Fraz

回答

1

您可以使用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)