【问题标题】:TypeError: return arrays must be of ArrayType for a function that uses only floatsTypeError:对于仅使用浮点数的函数,返回数组必须是 ArrayType
【发布时间】:2014-09-14 16:05:42
【问题描述】:

这个真的难倒我。我有一个计算单词权重的函数,我已经确认 a 和 b 局部变量都是浮点类型:

def word_weight(term):
    a = term_freq(term)
    print a, type(a)
    b = idf(term)
    print b, type(b)
    return a*log(b,2)

运行 word_weight("the") 日志:

0.0208837518791 <type 'float'>
6.04987801572 <type 'float'>
Traceback (most recent call last):
  File "summary.py", line 59, in <module>
    print word_weight("the")
  File "summary.py", line 43, in word_weight
    return a*log(b,2)
TypeError: return arrays must be of ArrayType

为什么?

【问题讨论】:

  • log(b,2) 来自哪里?是自定义方法还是内置方法?

标签: python arrays function numpy


【解决方案1】:

你在这里使用numpy.log函数,它的第二个参数不是base而是数组:

>>> import numpy as np
>>> np.log(1.1, 2)
Traceback (most recent call last):
  File "<ipython-input-5-4d17df635b06>", line 1, in <module>
    np.log(1.1, 2)
TypeError: return arrays must be of ArrayType

您现在可以使用numpy.math.log 或Python 的math.log

>>> np.math.log(1.1, 2)
0.13750352374993502
>>> import math
>>> math.log(1.1, 2) #This will return a float object not Numpy's scalar value
0.13750352374993502

或者,如果您只处理基数 2,那么正如 @WarrenWeckesser 建议的那样,您可以使用 numpy.log2

【讨论】:

  • 另一种选择是使用numpy.log2
猜你喜欢
  • 2017-02-25
  • 2019-12-15
  • 2021-07-21
  • 1970-01-01
  • 2017-05-08
  • 2018-10-30
  • 2012-11-01
  • 2018-03-15
  • 2020-04-16
相关资源
最近更新 更多