[英]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.