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

标签 python numpy matrix

我正在尝试编写一个函数,它接受 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/

相关文章:

python - Tensorflow 中的多个分类输入变量

python - MQTT : Publish the last line from a file that is periodically updated

python - 使用 NumPy 生成几何序列

python - 将 numpy 数组转换为 CSV 字符串并将 CSV 字符串转换回 numpy 数组

python - 根据条件随机填充二维矩阵

java - EJML获取矩阵特征向量的实值

python - 使用 ET 删除 Python 中的元素

Python 聊天与异步获取 session 数据

python - 生成随机数组,其中每个条目只能属于一组离散值

r - 制作一个矩阵列表,其中每个矩阵都是数据帧的一行