如何在Python中创建混淆矩阵图像

问题描述 投票:0回答:3

我是 Python 和机器学习的新手。我正在研究多类分类(3 类)。我想将混淆矩阵保存为图像。现在,

sklearn.metrics.confusion_matrix()
帮助我找到混淆矩阵,例如:

array([[35, 0, 6],
   [0, 0, 3],
   [5, 50, 1]])

接下来我想知道如何将这个混淆矩阵转换为图像并另存为png。

python machine-learning scikit-learn confusion-matrix multiclass-classification
3个回答
5
投票

选项 1:

sklearn.metrics
获取混淆矩阵数组后,您可以使用
matplotlib.pyplot.matshow()
seaborn.heatmap
从该数组生成混淆矩阵图。

例如

import pandas as pd
import seaborn as sn
import matplotlib.pyplot as plt

cfm = [[35, 0, 6],
       [0, 0, 3],
       [5, 50, 1]]
classes = ["0", "1", "2"]

df_cfm = pd.DataFrame(cfm, index = classes, columns = classes)
plt.figure(figsize = (10,7))
cfm_plot = sn.heatmap(df_cfm, annot=True)
cfm_plot.figure.savefig("cfm.png")

enter image description here


选项 2:

您可以使用

plot_confusion_matrix()
中的
sklearn
直接从估计器(即分类器)创建混淆矩阵图像。

例如

cfm_plot = plot_confusion_matrix(<estimator>, <X>, <Y>)
cfm_plot.savefig("cfm.png")

两个选项都使用

savefig()
将结果保存为 png 文件。

参考:https://scikit-learn.org/stable/modules/ generated/sklearn.metrics.plot_confusion_matrix.html


0
投票

要直观地查看分类报告,也许比保存奇怪的图更好的方法是将其保存为表格或类似表格的对象。

参见 sklearn 的 classification_report,它会生成一个漂亮的表作为输出,它有一个参数

output_dict
,默认情况下为
False
,将其作为 true 传递

import json
from sklearn.metrics import classification_report

def save_json(obj, path):
    with open(path, 'w') as jf:
        json.dump(obj, jf)

report = classification_report(y_true, y_pred, output_dict=True)
save_json(report, 'path/to/save_dir/myreport.json'

您还可以尝试使用

获取结果字典的数据帧
import pandas as pd

report_df = pd.DataFrame(report)
report_df.to_csv('saving/path/df.csv')

0
投票
from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay

cm = confusion_matrix(y_test, y_pred)
ConfusionMatrixDisplay(cm).plot()
plt.savefig("confusion_matrix.png")
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.