繁体   English   中英

在 python TypeError: unhashable type: 'numpy.ndarray'

[英]in python TypeError: unhashable type: 'numpy.ndarray'

我试图找到召回但发生类型错误

import pandas as pd
y_test = {'o1':  [0,1,0,1],'o2': [1,1,0,1],'o3':[0,0,1,1]}
y_test = pd.DataFrame (y_test)
y_pred = {'o1':  [1,1,0,1],'o2': [1,0,0,1],'o3':[1,0,1,1]}
y_pred = pd.DataFrame (y_pred)
y_pred = y_pred.to_numpy()


def precision(y_test, y_pred):
    i = set(y_test).intersection(y_pred)
    len1 = len(y_pred)
    if len1 == 0:
        return 0
    else:
        return len(i) / len1

print("recall of Binary Relevance Classifier: " + str(precision(y_test, y_pred)))

此代码显示错误:实际上我尝试在下面找到多个 label 分类错误详细信息的召回

TypeError                                 Traceback (most recent call last)
<ipython-input-41-8f3ca706a8e6> in <module>
16         return len(i) / len1
17 
---> 18 print("recall of Binary Relevance Classifier: " + str(precision(y_test, y_pred)))
<ipython-input-41-8f3ca706a8e6> in precision(y_test, y_pred)
 9 
10 def precision(y_test, y_pred):
---> 11     i = set(y_test).intersection(y_pred)
 12     len1 = len(y_pred)
 13     if len1 == 0:

TypeError: unhashable type: 'numpy.ndarray'

您的 numpy 数组y_test无法转换为集合(第 11 行),因为该数组是二维的。

对于要转换为集合的可迭代对象,所有项目都需要是可散列的。 对于 1-d numpy 数组很好,因为数字是可散列的:

>>> array_1d = np.array([1, 2, 3])
>>> array_1d
array([1, 2, 3])
>>> set(array_1d)
{1, 2, 3}

但是对于二维数组,您会收到此错误,因为嵌套的 arrays 本身不可哈希:

>>> array_2d = np.array([[1,2,3], [1,2,3], [1,2,3]])
>>> array_2d
array([[1, 2, 3],
       [1, 2, 3],
       [1, 2, 3]])
>>> set(array_2d)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'numpy.ndarray'

暂无
暂无

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

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