1. 程式人生 > >[Python ] Python 多維陣列轉換的維度對齊問題

[Python ] Python 多維陣列轉換的維度對齊問題

轉載自https://stackoverflow.com/questions/48373228/valueerror-could-not-broadcast-input-array-from-shape-25-1-into-shape-25

通過幾個例子簡單瞭解一下:

Here’s an example of the error:

>>> a = [np.zeros((224,224,3)), np.zeros((224,224,3)), np.zeros((224,224))]
>>> np.array(a)
ValueError: could not broadcast input
array from shape (224,224,3) into shape (224,224) or, different type of input, but the same error:
>>> a = [np.zeros((224,224,3)), np.zeros((224,224,3)), np.zeros((224,224,13))]
>>> np.array(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError:
could not broadcast input array from shape (224,224,3) into shape (224,224) Alternatively, similar but with a different error message:
>>> a = [np.zeros((224,224,3)), np.zeros((224,224,3)), np.zeros((224,100,3))]
>>> np.array(a)
Traceback (most recent call last):
  File "<stdin>"
, line 1, in <module> ValueError: could not broadcast input array from shape (224,224,3) into shape (224) But the following will work, albeit with different results than (presumably) intended:
>>> a = [np.zeros((224,224,3)), np.zeros((224,224,3)), np.zeros((10,224,3))]
>>> np.array(a)
# long output omitted
>>> newa = np.array(a)
>>> newa.shape
3  # oops
>>> newa.dtype
dtype('O')
>>> newa[0].shape
(224, 224, 3)
>>> newa[1].shape
(224, 224, 3)
>>> newa[2].shape
(10, 224, 3)
>>> 

原因在於,當如果list()中包含多個多維陣列,必須保證最後1維~n維是一致的。