python-3.x - 标记为 TP、TN、FP、FN 的值的混淆矩阵
问题描述
我有一个 Pandas 数据框,想为一列绘制一个混淆矩阵。
该列的值是已标记为“假阴性”、“假阳性”、“真阴性”和“真阳性”的字符串。
由于这些不是典型的 True/False 值,我如何使用这些值生成混淆矩阵(类似于 scikit-learn/matplotlib 生成的混淆矩阵)?
(编辑澄清)假设我在一列中有以下值:
['True Positive', 'True Negative', 'False Positive', 'False Negative', 'True Negative', ..., True Positive', 'False Negative']
我可以将这些值汇总为 TP、TN、FP、FN 的总数。但是,我想显示一个混淆矩阵,类似于使用以下生成的混淆矩阵:
disp = sklearn.metrics.ConfusionMatrixDisplay(confusion_matrix=cm)
disp = disp.plot(cmap="Blues")
matplot.lib.pyplot.plt.show()
提前致谢!
解决方案
解决这个问题的最简单方法是这样的:
TP = 0
TN = 0
FP = 0
FN = 0
for label in df.ColumnName:
if label == "True Positive":
TP += 1
elif label == "True Negative":
TN += 1
elif label == "False Positive":
FP += 1
else:
FN += 1
print("Confusion Matrix : ")
print(f"[{TP}] [{FP}]")
print(f"[{FN}] [{TN}]")
这df
是数据框变量。因此,我们计算列的各个条目并简单地打印相同的条目。
另一种小得多的方法如下:
print(df['ColumnName'].value_counts()
然后使用以下代码绘制值
import matplotlib.pyplot as plt
import numpy as np
data = [[TP, FP],[FN, TN]]
heatmap = plt.pcolor(data)
plt.colorbar(heatmap)
plt.show()
推荐阅读
- python - 将scrapy设置为django中的应用程序时出现“moduleNotFoundError”
- java - 如何在循环中生成 Spark 数据集聚合长专家?
- bluetooth - 经典模式下的 BT 4.2 会连接到 BT 2.1+EDR 吗?
- javascript - jQuery 将两个 id 合并为一个
- python - AttributeError:模块“tensorflow”没有属性“get_default_graph”
- ruby - 似乎无法运行 ruby 2.6.0 自制版本 - 总是引用系统 ruby 2.3.0
- c# - 将数据从模型导入视图给我一个我无法解决的错误
- reactjs - 抓取 Google 显示空白页 - Reactjs
- java - 如何等待短信发送确认,然后发送下一条短信 Android
- javascript - 在 javascript 中读取 iFrame(不在同一域 - YouTube)中的 div 状态