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

Aug 19 2020

Tôi đã cố gắng tìm thu hồi nhưng lỗi nhập xảy ra

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)))

Mã này hiển thị lỗi: thực sự tôi cố gắng tìm thu hồi cho các chi tiết lỗi phân loại nhiều nhãn ở bên dưới

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'

Trả lời

1 CarolynConway Aug 19 2020 at 20:14

Mảng numpy của bạn y_testkhông thể được chuyển đổi thành một tập hợp (trên dòng 11), vì mảng là 2 chiều.

Để có thể lặp lại được chuyển đổi thành một tập hợp, tất cả các mục cần phải có thể băm. Đối với mảng numpy 1-d thì không sao, vì các số có thể băm được:

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

Nhưng đối với mảng 2-d, bạn sẽ gặp lỗi này vì bản thân các mảng lồng nhau không thể băm được:

>>> 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'