gpt4 book ai didi

python - 类型错误 : return arrays must be of ArrayType for a function that uses only floats

转载 作者:太空狗 更新时间:2023-10-30 02:45:21 28 4
gpt4 key购买 nike

这个真的难倒我了。我有一个计算单词权重的函数,我已经确认 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

为什么?

最佳答案

您正在使用 numpy.log函数在这里,它的第二个参数不是 base 而是 out array:

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

关于python - 类型错误 : return arrays must be of ArrayType for a function that uses only floats,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24911046/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com