model 是什么?来自什么模块?看起来predictions 是一个二维数组。 predictions.shape 是什么?该错误表明[x for x in predictions] 中的x 是一个数组。它可能是一个单元素数组,但它绝不是一个数组。您可以尝试[x.shape for x in predictions] 来查看predictions 的每个元素(行)的形状。
我没有太多机会使用round,但显然Python 函数将操作委托给.__round__ 方法(就像+ 委托给__add__)。
In [932]: round?
Docstring:
round(number[, ndigits]) -> number
Round a number to a given precision in decimal digits (default 0 digits).
This returns an int when called with one argument, otherwise the
same type as the number. ndigits may be negative.
Type: builtin_function_or_method
In [933]: x=12.34
In [934]: x.__round__?
Docstring:
Return the Integral closest to x, rounding half toward even.
When an argument is passed, work like built-in round(x, ndigits).
Type: builtin_function_or_method
In [935]: y=12
In [936]: y.__round__?
Docstring:
Rounding an Integral returns itself.
Rounding with an ndigits argument also returns an integer.
Type: builtin_function_or_method
Python 整数的实现与 Python 浮点数不同。
Python 列表和字符串对此没有定义,因此round([1,2,3]) 将返回AttributeError: 'list' object has no attribute '__round__'。
ndarray 也是如此。但是numpy定义了np.round函数,numpy数组有.round方法。
In [942]: np.array([1.23,3,34.34]).round()
Out[942]: array([ 1., 3., 34.])
In [943]: np.round(np.array([1.23,3,34.34]))
Out[943]: array([ 1., 3., 34.])
help(np.around) 提供了最完整的 numpy 版本文档。
====================
从您的上一次打印中,我可以将您的predictions 部分重构为:
In [955]: arr = np.array([[ 0.79361773], [ 0.10443521], [ 0.90862566]])
In [956]: arr
Out[956]:
array([[ 0.79361773],
[ 0.10443521],
[ 0.90862566]])
In [957]: for x in arr:
...: print(x, end=' ')
...:
[ 0.79361773] [ 0.10443521] [ 0.90862566]
arr.shape 是 (3,1) - 具有 1 列的二维数组。
np.round 工作正常,无需迭代:
In [958]: np.round(arr)
Out[958]:
array([[ 1.],
[ 0.],
[ 1.]])
迭代会产生错误。
In [959]: [round(x) for x in arr]
TypeError: type numpy.ndarray doesn't define __round__ method