Python: 如何在不扩展矩阵的情况下增加其维度?

3

我对Python还很陌生,目前正在处理一个代码,在这个代码中,我想要存储一个三维矩阵的先前迭代版本,每次for循环都会创建一个新的版本。我想要采取的方法是通过连接一个新的3+1=4维数组来存储先前的值。现在,这是可行的,并且我已经让它像这样工作:

import numpy as np

matrix = np.ones((1,lay,row,col), dtype=np.float32)

for n in range(100):
    if n == 0:
        # initialize the storage matrix
        matrix_stored = matrix
    else:
        # append further matrices in first dimension
        matrix_stored = np.concatenate((matrix_stored,matrix),axis = 0)

这是我的问题:上面的代码要求矩阵已经是四维结构[1 x m x n x o]。然而,为了我的目的,我希望将变量矩阵保留为三维[m x n x o],并且只有在将其输入到变量matrix_stored时才将其转换为四维形式。
是否有一种方法可以简化这样的转换?

https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html - cs95
2个回答

3
你可以考虑使用np.reshape。特别是,在将矩阵传递给函数时,你需要按照如下方式重塑它:
your_function(matrix.reshape(1, *matrix.shape))

matrix.shape会打印出矩阵的现有维度。


1
回答你的问题:添加长度为1的维度的简写方法是使用None进行索引。
np.concatenate((matrix_stored,matrix[None]),axis = 0)

但是最重要的是,我想警告你不要在循环中连接数组。比较以下时间:

In [31]: %%timeit
    ...: a = np.ones((1,1000))
    ...: A = a.copy()
    ...: for i in range(1000):
    ...:     A = np.concatenate((A, a))
1 loop, best of 3: 1.76 s per loop

In [32]: %timeit a = np.ones((1000,1000))
100 loops, best of 3: 3.02 ms per loop

这是由于concatenate将源数组中的数据复制到全新的数组中,每次循环都需要复制更多的数据。事先分配空间会更好:
In [33]: %%timeit
    ...: A = np.empty((1000, 1000))
    ...: a = np.ones((1,1000))
    ...: for i in range(1000):
    ...:     A[i] = a
100 loops, best of 3: 3.42 ms per loop

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接