繁体   English   中英

'numpy.int64' 没有 len()

[英]'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只是该列表的一个元素。

在的范围apkpredictedp (不是predictedmapk ) - ,因此,很显然, 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

因为你作为参数传递作为命名的参数predictedapk功能不变量predicted你在mapk功能。 事实上,你通过变量papk ,这不是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您将得到:

  • (1, 4) 在第一次迭代
  • (2, 5) 在第二次迭代
  • 和 (3, 6) 在第三次迭代。

示例代码:

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 == 1p == 2

如果我们写a,b,c = (1,2,3)a == 1b == 2c == 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的函数内部(在其范围内)确定actualpredited的类型。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM