我正在尝试编写一个函数,它接受 3d 矩阵列表..
所以..列表中的每个元素都有形状 (rows,cols, some_scalar).
。
我正在尝试将其 reshape 为 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
最佳答案
您可以使用np.stack
沿着第一个轴(axis=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)
关于python - 将 3d 矩阵列表转换为 4d 矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36590107/