簡體   English   中英

numpy 數組包含多維 numpy arrays 具有可變形狀

[英]numpy array containing multi-dimension numpy arrays with variable shape

我有一個 numpy arrays 的列表,其形狀是以下之一: (10,4,4,20), (10,4,6,20) 我想將列表轉換為 numpy 數組。 因為,它們的形狀不同,我不能把它們疊起來。 因此,我想創建 numpy 數組,將每個數組視為 object,如此處所示 我嘗試了以下方法:

b = numpy.array(a)
b = numpy.array(a, dtype=object)

其中 a 是 numpy arrays 的列表。 兩者都給我以下錯誤:

ValueError: could not broadcast input array from shape (10,4,4,20) into shape (10,4)

如何將該列表轉換為 numpy 數組?

示例

import numpy
a = [numpy.random.random((10,4,4,20)),
     numpy.random.random((10,4,6,20)),
     numpy.random.random((10,4,6,20)),
     numpy.random.random((10,4,4,20)),
     numpy.random.random((10,4,6,20)),
     numpy.random.random((10,4,6,20)),
     numpy.random.random((10,4,4,20)),
     numpy.random.random((10,4,4,20)),
     numpy.random.random((10,4,6,20))
    ]
b = numpy.array(a)

用例
我知道 numpy 對象數組效率不高,但我沒有對它們進行任何操作。 通常,我有一個相同形狀的列表 numpy arrays ,所以我可以輕松地將它們堆疊起來。 這個數組被傳遞給另一個 function,它只選擇某些元素。 如果我的數據是 numpy 數組,我可以做b[[1,3,8]] 但我不能對列表做同樣的事情。 如果我嘗試與 list 相同,我會收到以下錯誤

c = a[[1,3,8]]
TypeError: list indices must be integers or slices, not list

如果列表 arrays 在第一個維度上不同,則np.array(alist)將創建一個 object dtype 數組。 但是在您的情況下,它們在第三個方面有所不同,從而產生了此錯誤。 實際上,它無法明確確定包含維度的結束位置以及對象的開始位置。

In [270]: alist = [np.ones((10,4,4,20),int), np.zeros((10,4,6,20),int)]                                
In [271]: arr = np.array(alist)                                                                        
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-271-3fd8e9bd05a9> in <module>
----> 1 arr = np.array(alist)

ValueError: could not broadcast input array from shape (10,4,4,20) into shape (10,4)

相反,我們需要創建一個大小合適的 object 數組,並將列表復制到其中。 有時這個副本仍然會產生廣播錯誤,但這里似乎沒問題:

In [272]: arr = np.empty(2, object)                                                                    
In [273]: arr                                                                                          
Out[273]: array([None, None], dtype=object)
In [274]: arr[:] = alist                                                                               
In [275]: arr                                                                                          
Out[275]: 
array([array([[[[1, 1, 1, ..., 1, 1, 1],
         [1, 1, 1, ..., 1, 1, 1],
         [1, 1, 1, ..., 1, 1, 1],
...
         [0, 0, 0, ..., 0, 0, 0],
         [0, 0, 0, ..., 0, 0, 0]]]])], dtype=object)
In [276]: arr[0].shape                                                                                 
Out[276]: (10, 4, 4, 20)
In [277]: arr[1].shape                                                                                 
Out[277]: (10, 4, 6, 20)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM