如何在 Python 中创建混淆矩阵图像
How to create image of confusion matrix in Python
我是 Python 和机器学习的新手。我正在研究 multi-class classification (3 classes)。我想将混淆矩阵保存为图像。现在,sklearn.metrics.confusion_matrix()
帮助我找到像这样的混淆矩阵:
array([[35, 0, 6],
[0, 0, 3],
[5, 50, 1]])
接下来,我想知道如何将这个混淆矩阵转换成图像并保存为png。
选项 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")
选项 2:
您可以使用 sklearn
中的 plot_confusion_matrix()
直接从估计器(即分类器)创建混淆矩阵图像。
例如
cfm_plot = plot_confusion_matrix(<estimator>, <X>, <Y>)
cfm_plot.savefig("cfm.png")
两个选项都使用savefig()
将结果保存为png文件。
REF:https://scikit-learn.org/stable/modules/generated/sklearn.metrics.plot_confusion_matrix.html
要直观地查看分类报告,也许比保存奇数图更好的方法是将其保存为 table,或一些类似 table 的对象。
参见 sklearn 的 classification_report,它产生一个很好的 table 作为输出,它有一个参数 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')
我是 Python 和机器学习的新手。我正在研究 multi-class classification (3 classes)。我想将混淆矩阵保存为图像。现在,sklearn.metrics.confusion_matrix()
帮助我找到像这样的混淆矩阵:
array([[35, 0, 6],
[0, 0, 3],
[5, 50, 1]])
接下来,我想知道如何将这个混淆矩阵转换成图像并保存为png。
选项 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")
选项 2:
您可以使用 sklearn
中的 plot_confusion_matrix()
直接从估计器(即分类器)创建混淆矩阵图像。
例如
cfm_plot = plot_confusion_matrix(<estimator>, <X>, <Y>)
cfm_plot.savefig("cfm.png")
两个选项都使用savefig()
将结果保存为png文件。
REF:https://scikit-learn.org/stable/modules/generated/sklearn.metrics.plot_confusion_matrix.html
要直观地查看分类报告,也许比保存奇数图更好的方法是将其保存为 table,或一些类似 table 的对象。
参见 sklearn 的 classification_report,它产生一个很好的 table 作为输出,它有一个参数 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')