[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维是一致的。

猜你喜欢

转载自blog.csdn.net/sinat_21720047/article/details/82968000
今日推荐