confusion_matrix 错误 'DataFrame' "object is not callable"

confusion_matrix error 'DataFrame' "object is not callable"

我做错了什么?我将两个变量都设置为列表。也试过 np.array.

y = list(y_test.values)
yhat = list(predictions)

print(y)
print(yhat)

confusion_matrix = pd.DataFrame(confusion_matrix(y, yhat), columns=["Predicted False", "Predicted True"], index=["Actual False", "Actual True"])
display(confusion_matrix)

输出:

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, ..., 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, ..., 0]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-159-e1640f0e3b13> in <module>()
     45 print(yhat)
     46 
---> 47 confusion_matrix = pd.DataFrame(confusion_matrix(y, yhat), columns=["Predicted False", "Predicted True"], index=["Actual False", "Actual True"])
     48 display(confusion_matrix)
     49 

TypeError: 'DataFrame' object is not callable

不确定这里发生了什么...

你是在笔记本上做的吗?如果是这样,可能 confusion_matrix 方法在您第一次调用它时已被 DataFrame 隐藏。尝试更改变量名并重新启动内核。

from sklearn.metrics import confusion_matrix
y_true = [2, 0, 2, 2, 0, 1]
y_pred = [0, 0, 2, 2, 0, 2]

当我运行confusion_matrix(y_true, y_pred)时,结果如下:

array([[2, 0, 0],
       [0, 0, 1],
       [1, 0, 2]], dtype=int64)

请注意,对于这个特定的输入,结果是一个 3x3 矩阵,因此对于这种情况,您需要一个包含三个名称的列和索引的列表。 您可以像这样将结果直接放入 Dataframe 中:

pd.DataFrame(confusion_matrix(y_true, y_pred),columns=['column 1','column 2','column 3'], index=['index 1', 'index 2','index 3'])

结果如下:

     column 1  column 2  column 3
index 1         2         0         0
index 2         0         0         1
index 3         1         0         2