[英]arrays TP, TN, FP and FN in Python
我的預測結果是這樣的
測試數組
[1,0,0,0,1,0,1,...,1,0,1,1],
[1,0,1,0,0,1,0,...,0,1,1,1],
[0,1,1,1,1,1,0,...,0,1,1,1],
.
.
.
[1,1,0,1,1,0,1,...,0,1,1,1],
預測數組
[1,0,0,0,0,1,1,...,1,0,1,1],
[1,0,1,1,1,1,0,...,1,0,0,1],
[0,1,0,1,0,0,0,...,1,1,1,1],
.
.
.
[1,1,0,1,1,0,1,...,0,1,1,1],
這是我擁有的數組的大小
TestArray.shape
Out[159]: (200, 24)
PredictionArray.shape
Out[159]: (200, 24)
我想為這些陣列獲得 TP、TN、FP 和 FN
我試過這個代碼
cm=confusion_matrix(TestArray.argmax(axis=1), PredictionArray.argmax(axis=1))
TN = cm[0][0]
FN = cm[1][0]
TP = cm[1][1]
FP = cm[0][1]
print(TN,FN,TP,FP)
但我得到的結果
TN = cm[0][0]
FN = cm[1][0]
TP = cm[1][1]
FP = cm[0][1]
print(TN,FN,TP,FP)
125 5 0 1
我檢查了厘米的形狀
cm.shape
Out[168]: (17, 17)
125 + 5 + 0 + 1 = 131 這不等於我擁有的列數 200
我期望有 200,因為陣列中的每個單元格假設是 TF、TN、FP、TP,所以總數應該是 200
如何解決?
這是問題的一個例子
import numpy as np
from sklearn.metrics import confusion_matrix
TestArray = np.array(
[
[1,0,0,1,0,1,1,0,1,0,1,1,0,0,1,1,1,0,0,1],
[0,1,1,0,1,0,0,1,0,0,0,1,0,1,0,1,1,0,1,1],
[1,0,1,1,1,1,0,0,1,1,1,1,0,0,1,0,0,0,0,0],
[0,1,1,1,0,0,0,0,0,1,0,0,1,0,0,1,0,1,1,1],
[0,0,0,0,1,1,0,1,1,0,0,1,0,1,1,0,1,1,1,1],
[1,0,0,1,1,1,0,1,1,0,1,0,0,1,1,0,0,1,0,0],
[1,1,1,0,0,1,0,0,1,1,0,1,0,1,1,1,1,1,0,1],
[0,0,0,1,0,0,1,0,1,0,1,0,0,0,0,1,0,0,1,1],
[1,0,1,0,0,0,0,1,0,1,0,1,0,0,0,0,1,0,1,0],
[1,1,0,1,1,1,1,0,1,0,1,0,1,1,1,1,0,1,0,0]
])
TestArray.shape
PredictionArray = np.array(
[
[0,0,0,1,1,1,1,0,0,0,1,0,0,0,1,0,1,0,1,1],
[0,1,0,0,1,0,1,1,0,0,0,1,1,0,0,1,1,0,0,1],
[1,1,0,1,1,1,0,0,0,0,0,1,0,0,1,0,0,1,0,0],
[0,1,0,1,0,0,1,0,0,1,0,1,1,0,0,1,0,0,1,1],
[0,0,1,0,0,1,0,1,1,1,0,1,1,1,0,0,1,1,0,1],
[1,0,0,1,0,1,1,1,1,0,0,1,0,1,1,1,0,1,1,0],
[1,1,0,0,1,1,0,0,0,1,0,1,0,0,1,1,0,1,0,1],
[0,0,0,0,0,0,0,1,1,0,1,0,0,1,0,1,1,0,1,1],
[1,0,1,1,0,0,0,1,0,1,0,1,1,1,1,0,0,0,1,0],
[1,1,0,1,1,1,1,1,1,0,1,0,0,0,0,1,1,1,0,0]
])
PredictionArray.shape
cm=confusion_matrix(TestArray.argmax(axis=1), PredictionArray.argmax(axis=1))
TN = cm[0][0]
FN = cm[1][0]
TP = cm[1][1]
FP = cm[0][1]
print(TN,FN,TP,FP)
輸出是
5 0 2 0
= 5+0+2+0 = 7 !!
數組中有 20 列和 10 行
但厘米給總共 7 !
使用np.argmax
,您輸入的矩陣sklearn.metrics.confusion_matrix
不再是二進制的,因為np.argmax
返回第一個出現的最大值的索引。 在這種情況下,沿axis=1
。
當您的預測不是二進制時,您不會得到好的真陽性/命中、真陰性/正確拒絕等。
您應該會發現sum(sum(cm))
確實等於 200。
如果數組的每個索引代表一個單獨的預測,即您試圖獲得 TP/TN/FP/FN 總共 200 ( 10 * 20
) 個預測,每個預測的結果為0
或1
,那么您可以在將數組解析為confusion_matrix
矩陣之前,通過展平數組來獲得 TP/TN/FP/FN。 也就是說,您可以將TestArray
和PreditionArry
重塑為(200,)
,例如:
cm = confusion_matrix(TestArray.reshape(-1), PredictionArray.reshape(-1))
TN = cm[0][0]
FN = cm[1][0]
TP = cm[1][1]
FP = cm[0][1]
print(TN, FN, TP, FP, '=', TN + FN + TP + FP)
哪個返回
74 28 73 25 = 200
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.