[英]'numpy.int64' has no len()
错误:
TypeError: object of type 'numpy.int64' has no len()
代码:
import numpy as np
def apk(actual, predicted, k=10):
if len(predicted)>k: # here is the error
predicted = predicted[:k]
score = 0.0
num_hits = 0.0
for i,p in enumerate(predicted):
if p in actual and p not in predicted[:i]:
num_hits += 1.0
score += num_hits / (i+1.0)
if not actual:
return 1.0
return score / min(len(actual), k)
def mapk(actual, predicted, k=10):
print(type(predicted))
>>> <class 'list'> # here is predicted also from the value list
return np.mean([apk(a,p,k) for a,p in zip(actual, predicted)])
x = list(df_new['id'].to_numpy())
y = list(re['id'].to_numpy())
print(type(y))
>>> <class 'list'>
# So y is a list and not like later 'numpy.int64'
mapk(x,y)
当我开始以下调用时,出现以下错误,我该如何解决?
当我执行以下操作时,我得到长度len(y)
如何解决此错误? 我非常期待答案。
您正在迭代此行中的predicted
:
return np.mean([apk(a,p,k) for a,p in zip(actual, predicted)])
predicted
是一个列表,但p
只是该列表的一个元素。
在的范围apk
, predicted
是p
(不是predicted
从mapk
) - ,因此,很显然, int64
。
根据您提供的信息,问题是predicted
的类型是numpy.int64
。 而int
确实没有 len。 我想predicted
应该是一个list
?
尝试在出现错误的行之前打印predicted
的类型:
def apk(actual, predicted, k=10):
print(type(predicted)) # Add this code
if len(predicted)>k: # here is the error
错误出现在apk
函数中。
而@Daniel˚F解释了他的答案,为什么predicted
是不是类型list
:
因为你作为参数传递作为命名的参数predicted
的apk
功能不变量predicted
你在mapk
功能。 事实上,你通过变量p
到apk
,这不是list
命名的predicted
。 并且,从错误消息中,我们推断出p
的类型是numpy.64
。
这是您将p
作为名为predicted
的参数的参数传递给您的函数apk
: [apk(a,p,k) for a,p in zip(actual, predicted)]
如果您将此代码更改为此(我不是说您应该这样做,因为根据您提供的内容,我们只能做假设):
[apk(a,predicted,k) for a,p in zip(actual, predicted)]
然后,您不会传递p
,但您会将predicted
作为名为predicted
的参数的参数传递给您的函数apk
。
我会深入,如果它看起来太夸张了,我的借口。
我将在这里解释[apk(a,predicted,k) for a,p in zip(actual, predicted)]
:
以下是zip
工作原理的简单示例:
a = [1,2,3]
b = [4,5,6]
c = list(zip(a,b))
c
将是一个tuple
list
。
每个tuple
将包含两个int
类型的变量。 c
值:[(1, 4), (2, 5), (3, 6)]
因此,当您遍历c
您将得到:
示例代码:
for a_tuple in c:
a,p = a_tuple
print(a) # 1 at 1st iter, 2 at 2nd,and 3 at 3rd
print(p) # 4 at 1st iter, 5 at 2nd,and 6 at 3rd
当我们写:
a,p = (1,2)
我们将tuple
的第一个元素分配给a
,第二个元素分配给p
。 所以a == 1
和p == 2
。
如果我们写a,b,c = (1,2,3)
: a == 1
, b == 2
和c == 3
。
现在,我们将您的列表理解分解为一个 for 循环:
如果您设置actual = [1,2,3]
和predicted = [4,5,6]
,那么,写:
[apk(a,p,k) for a,p in zip(actual, predicted)]
和写一样:
k = 2
zipped = zip(actual, predicted)
# list(zipped) == [(1, 4), (2, 5), (3, 6)]
for a,p in zipped:
apk(a,p,k) # p == 4 at 1st iter, 5 at 2nd,and 6 at 3rd. p is an element of a tuple of the zipped list
总而言之:您必须在名为apk
的函数内部(在其范围内)确定actual
和predited
的类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.