我想创建一个混淆矩阵,而不依赖于任何包。我有两个列表(预测值和实际值),我想把它们和一个正类的指示器一起输入到一个函数中。
例如,当1
为正类时:
predicted_lst = [1, 0, 1, 0, 0]
actual_lst = [1, 0, 0, 1, 1]
我的函数目前看起来是这样的,但它的效率很低:
def confusion_matrix(predicted, actual, pos_class):
TP = 0
TN = 0
FP = 0
FN = 0
for i in range(len(actual)):
if actual[i] == pos_class and predicted[i] == pos_class:
TP +=1
elif actual[i] == pos_class and predicted[i] != pos_class:
FN +=1
elif actual[i] != pos_class and predicted[i] == pos_class:
FP +=1
else:
TN +=1
return TP, FP, TN, FN
我的问题是,有没有更有效的方法来编写这些代码?我看到了these posts,但它们并不像我希望的那样将正类作为函数输入。我也根本不想使用任何包(包括numpy)
发布于 2021-11-14 22:56:43
请看下面的几个替代解决方案。
选项1:
def confmat_1(actual, predicted, positive, negative):
tn = len([x for x in zip(predicted, actual) if x[0] == negative and x[1] == negative])
fp = len([x for x in zip(predicted, actual) if x[0] == positive and x[1] == negative])
fn = len([x for x in zip(predicted, actual) if x[0] == negative and x[1] == positive])
tp = len([x for x in zip(predicted, actual) if x[0] == positive and x[1] == positive])
return tn, fp, fn, tp
选项2:
def confmat_2(actual, predicted, positive, negative):
tn = 0
fp = 0
fn = 0
tp = 0
for x in zip(predicted, actual):
if x[0] == negative and x[1] == negative:
tn += 1
elif x[0] == positive and x[1] == negative:
fp += 1
elif x[0] == negative and x[1] == positive:
fn += 1
else:
tp += 1
return tn, fp, fn, tp
示例:
from sklearn.metrics import confusion_matrix
actual = [1, 0, 0, 1, 1]
predicted = [1, 0, 1, 0, 0]
# Option 1
tn, fp, fn, tp = confmat_1(actual, predicted, positive=1, negative=0)
print(tn, fp, fn, tp)
# 1 1 2 1
# Option 2
tn, fp, fn, tp = confmat_2(actual, predicted, positive=1, negative=0)
print(tn, fp, fn, tp)
# 1 1 2 1
# Scikit-learn
tn, fp, fn, tp = confusion_matrix(actual, predicted).ravel()
print(tn, fp, fn, tp)
# 1 1 2 1
发布于 2021-11-14 13:27:38
您可以假设1
是正数类来编写函数,如果0
是正数类,则只需相应地更改返回值的顺序就可以适应pos_class
参数。
在循环内部,您可以删除FP
和FN
的增量计算,因为这些值可以从循环外部的真值派生:
def confusion_matrix(predicted, actual, pos_class):
TP = 0
TN = 0
for pred, act in zip(predicted, actual):
if pred == act:
if act == 0:
TN += 1
else:
TP += 1
positive = sum(predicted)
negative = len(predicted) - positive
FP = positive - TP
FN = negative - TN
if pos_class == 1:
return TP, FP, TN, FN
else:
return TN, FN, TP, FP
https://stackoverflow.com/questions/69966608
复制相似问题