TypeError:类型“numpy.int64”的对象没有 len() / TypeError:类型“int”的对象没有 len()/ 在 scikitlearn 中使用classification_report时

sak*_*esh 5 metrics python-3.x scikit-learn

有时,当使用 sklearn.metrics.classification_report 时,我们会收到以下错误

TypeError: object of type 'int' has no len()
Run Code Online (Sandbox Code Playgroud)

有时根据数据类型,我们也会得到如下错误

TypeError: object of type 'numpy.int64' has no len()
Run Code Online (Sandbox Code Playgroud)

当我们可能收到此错误时的示例代码

t=pd.Series([1,2,3,4])
p=np.asarray([1,2,3,4])
target_names=[1,2,3,4]
print(classification_report(t, p, target_names=target_names))
Run Code Online (Sandbox Code Playgroud)

sak*_*esh 4

target_names当使用的不是字符串时会发生这种情况;target_names为了解决这个问题,对变量进行了如下所示的转换

t=pd.Series([1,2,3,4])
p=np.asarray([1,2,3,4])
target_names=[1,2,3,4]
target_names=list(map(str,target_names))
print(classification_report(t, p, target_names=target_names))
Run Code Online (Sandbox Code Playgroud)