ValueError:无法将输入数组从形状(224,3)广播到形状(224)

2024-04-19 08:43:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个列表,例如,临时列表,具有以下属性:

len(temp_list) = 9260  
temp_list[0].shape = (224,224,3)  

现在,当我转换成numpy数组时

x = np.array(temp_list)  

我得到一个错误:

ValueError: could not broadcast input array from shape (224,224,3) into shape (224,224)  

有人能帮我吗


Tags: numpy列表len属性错误npnot数组
3条回答

列表中至少有一项不是三维的,或者其第二或第三维度与其他元素不匹配。如果只有第一个维度不匹配,则数组仍然匹配,但作为单个对象,不会尝试将它们协调到新的(四维)数组中。以下是一些例子:

也就是说,有问题的元素的shape != (?, 224, 3)
ndim != 3(其中?为非负整数)。
这就是给你带来错误的原因

您需要解决这个问题,以便能够将列表转换为四维(或三维)数组。如果没有上下文,则无法确定是否要从三维项目中丢失一个标注,或将一个标注添加到二维项目(在第一种情况下),或更改第二个或第三个标注(在第二种情况下)


下面是一个错误示例:

>>> 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)

或者,输入类型不同,但错误相同:

>>> 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)

或者,类似但有不同错误消息:

>>> 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)

但以下方法将起作用,尽管结果与(推测的)预期不同:

>>> 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)
>>> 

是的,的确@Evert的答案是完全正确的。 此外,我想补充一个原因,可能会遇到这样的错误

>>> np.array([np.zeros((20,200)),np.zeros((20,200)),np.zeros((20,200))])

这很好,但是会导致错误:

>>> np.array([np.zeros((20,200)),np.zeros((20,200)),np.zeros((20,201))])

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

列表中的numpy arry也必须具有相同的大小

您可以使用astype(object)numpy.ndarray转换为object

这将有助于:

>>> a = [np.zeros((224,224,3)).astype(object), np.zeros((224,224,3)).astype(object), np.zeros((224,224,13)).astype(object)]

相关问题 更多 >