【问题标题】:Python: How to increase the dimensions of a matrix without expanding it?Python:如何在不扩展矩阵的情况下增加矩阵的维度?
【发布时间】:2018-01-18 07:49:20
【问题描述】:

我是 Python 的新手,目前正在编写一个代码,我想在其中存储 3 维矩阵的先前迭代,其版本是在 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 时将其转换为四维形式。

有没有办法促进这种转换?

【问题讨论】:

标签: python arrays python-3.x numpy concatenation


【解决方案1】:

您可以考虑使用np.reshape。特别是,在将矩阵传递给函数时,您将像这样重塑它:

your_function(matrix.reshape(1, *matrix.shape))

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

【讨论】:

    【解决方案2】:

    回答您的问题:添加长度为 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
    

    【讨论】:

      猜你喜欢
      • 2022-11-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-02
      • 2021-12-06
      相关资源
      最近更新 更多