2017-08-10 168 views
3

我是Python新手,目前正在研究一個代碼,我想在其中存儲以前迭代的三維矩陣,其中的一個版本是在for循環的每個單獨步驟中創建的。我想要這樣做的方式是連接一個新的維數3 + 1 = 4的數組,其中存儲了以前的值。現在,這是可能的串聯,我得到它像這樣工作:Python:如何增加矩陣的大小而不擴展它?

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×M×N的X O]。但是,對於我的目的,我寧願保留可變矩陣的三維[m x n x o],並且只在將它提供給變量matrix_stored時將其轉換爲四維形式。

有沒有辦法促成這種轉換?

+0

https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html –

回答

3

你可能會考慮使用np.reshape。特別是,在你的矩陣傳遞給函數的時候,你會喜歡這個重塑它:

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

matrix.shape打印出你的矩陣的現有尺寸。

+0

完全,做的伎倆!非常感謝! –

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