TypeError:对于仅使用浮点数的函数,返回数组必须是ArrayType

时间:2014-07-23 12:54:19

标签: python arrays function numpy

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

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

为什么?

2 个答案:

答案 0 :(得分:5)

你在这里使用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

答案 1 :(得分:0)

是的,我也面临这个问题,由于你的回答,我解决了我的问题!

Interface Builder

文件&#34; C:/PythonProj/ml-action/Decision_tree/trees.py",第26行,在calcShannonEnt中     shannonEnt - = prob *(log(prob,2)) TypeError:返回数组必须是ArrayType