Python 错误“类型错误:类型 numpy.ndarray 未定义 __round__ 方法”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41319292/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 00:47:38  来源:igfitidea点击:

Error "TypeError: type numpy.ndarray doesn't define __round__ method"

pythonnumpy

提问by user697911

import numpy

......

# Prediction
predictions = model.predict(X_test)
# round predictions
rounded = [round(x) for x in predictions]
print(rounded)

"predictions" is a list of decimals between [0,1] with sigmoid output. 

Why does it always report this error:

为什么老是报这个错误:

  File "/home/abigail/workspace/ml/src/network.py", line 41, in <listcomp>
    rounded = [round(x) for x in predictions]
TypeError: type numpy.ndarray doesn't define __round__ method

If i don't use the 'round', it prints decimals correctly. This "round" should be the Python built-in function. Why does it have anything to do with numpy?

如果我不使用“round”,它会正确打印小数。这个“round”应该是Python内置函数。为什么它与numpy有关?

Edited:

编辑:

for x in predictions:
    print(x, end=' ')

The output is:

输出是:

    [ 0.79361773] [ 0.10443521] [ 0.90862566] [ 0.10312044] [ 0.80714297] 
[ 0.23282401] [ 0.1730803] [ 0.55674052] [ 0.94095331] [ 0.11699325] 
[ 0.1609294] 

采纳答案by hpaulj

What is model? From what module? It looks like predictionsis a 2d array. What is predictions.shape? The error indicates that the xin [x for x in predictions]is an array. It may be a single element array, but it is never the less an array. You could try [x.shape for x in predictions]to see the shape of each element (row) of predictions.

什么是model?来自什么模块?它看起来像predictions一个二维数组。什么是predictions.shape?该错误表明xin[x for x in predictions]是一个数组。它可能是一个单元素数组,但它绝不是一个数组。您可以尝试[x.shape for x in predictions]查看每个元素(行)的形状predictions

I haven't had much occasion to use round, but evidently the Python function delegates the action to a .__round__method (much as +delegates to __add__).

我没有太多机会使用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 integers have a different implementation than python floats.

Python 整数与 Python 浮点数有不同的实现。

Python lists and strings don't have definition for this, so round([1,2,3])will return an AttributeError: 'list' object has no attribute '__round__'.

Python 列表和字符串对此没有定义,因此round([1,2,3])将返回一个AttributeError: 'list' object has no attribute '__round__'.

Same goes for a ndarray. But numpyhas defined a np.roundfunction, and a numpy array has a .roundmethod.

对于 a 也是如此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)gives the fullest documentation of the numpy version(s).

help(np.around)提供 numpy 版本的最完整文档。

===================

====================

From your last print I can reconstruct part of your predictionsas:

从您的上次打印中,我可以将您的一部分重建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.shapeis (3,1)- a 2d array with 1 column.

arr.shapeis (3,1)- 1 列的二维数组。

np.roundworks fine, without needing the iteration:

np.round工作正常,不需要迭代:

In [958]: np.round(arr)
Out[958]: 
array([[ 1.],
       [ 0.],
       [ 1.]])

the iteration produces your error.

迭代会产生您的错误。

In [959]: [round(x) for x in arr]    
TypeError: type numpy.ndarray doesn't define __round__ method

回答by gzc

TypeError: type numpy.ndarray doesn't define roundmethod

类型错误:类型 numpy.ndarray 没有定义圆形方法

You tried applying round to numpy.ndarray. Apparently, this isn't supported.

您尝试将 round 应用于 numpy.ndarray。显然,这不受支持。

Try this, use numpy.round:

试试这个,使用numpy.round

rounded = [numpy.round(x) for x in predictions]

x is numpy array. You can also try this:

x 是 numpy 数组。你也可以试试这个:

rounded = [round(y) for y in x for x in predictions]

回答by Xianwei Zeng

I encountered the same error when I was trying the tutorial of Keras.

我在尝试Keras的教程时遇到了同样的错误。

At first, I tried

起初,我试过

rounded = [numpy.round(x) for x in predictions]

but it showed the result like this:

但它显示了这样的结果:

[array([1.], dtype=float32), array([0.],dtype=float32), ...]

then I tried this:

然后我试过这个:

rounded = [float(numpy.round(x)) for x in predictions]

it showed the right outputs.

它显示了正确的输出。

I think the "numpy.round(x)" returns list of ndarray, and contains the dtype parameter. but the outputs are correct with the value. So converting each element of the list to float type will show the right outputs as same as the tutorial.

我认为“numpy.round(x)”返回 ndarray 列表,并包含 dtype 参数。但输出的值是正确的。因此,将列表的每个元素转换为浮点类型将显示与教程相同的正确输出。

My machine is Linux Mint 17.3(ubuntu 14.04) x64, and python interpreter is python 3.5.2, anaconda3(4.1.1), numpy 1.11.2

我的机器是Linux Mint 17.3(ubuntu 14.04) x64,python解释器是python 3.5.2、anaconda3(4.1.1)、numpy 1.11.2

回答by rb612

You're using a function that uses Numpyto store values. Instead of being a regular Python list, it is actually a Numpyarray. This is generally because with machine learning, Numpydoes a much better job at storing massive amounts of data compared to an ordinary list in Python. You can refer to the following documentation to convert to a regular list which you can then preform a comprehension:

您正在使用Numpy用于存储值的函数。它不是一个常规的 Python 列表,它实际上是一个Numpy数组。这通常是因为与NumpyPython 中的普通列表相比,机器学习在存储大量数据方面做得更好。您可以参考以下文档将其转换为常规列表,然后您可以对其进行理解:

https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.tolist.html

https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.tolist.html

Edit:

编辑:

What happens if you try:

如果您尝试会发生什么:

for x in predictions:
   for y in x.:
    print(y, end=' ')

回答by LJHW

This was driving me nuts too. I had stored a reference to a scipy function with type <class 'scipy.interpolate.interpolate.interp1d'>. This was returning a single value of type <class 'numpy.ndarray'>containing a single float. I had assumed this was actually a float and it propagated back up through my library code until roundproduced the same error described above.

这也让我发疯。我存储了一个对类型为 scipy 函数的引用<class 'scipy.interpolate.interpolate.interp1d'>。这是返回一个<class 'numpy.ndarray'>包含单个浮点类型的单个值。我原以为这实际上是一个浮点数,它会通过我的库代码向上传播,直到round产生上述相同的错误。

It was a case of debugging the call stack to check what actual type was being passed on after each function return. I then cast the return value from my original function call along the lines of result = float(interp1d_reference(x)). Then my code behaved as I had expected/wanted.

这是调试调用堆栈以检查每个函数返回后传递的实际类型的情况。然后,我将原始函数调用的返回值沿result = float(interp1d_reference(x)). 然后我的代码按照我的预期/想要的方式运行。