【问题标题】:How to create image of confusion matrix in Python如何在 Python 中创建混淆矩阵的图像
【发布时间】:2021-03-26 18:50:01
【问题描述】:

我是 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


    【解决方案1】:

    选项1 : h2>

    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 : h2>

    您可以使用sklearn直接从plot_confusion_matrix()直接从估计(即分类器)创建混淆矩阵的图像。

    例如

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

    两个选项使用savefig()将结果保存为png文件。 em>

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

    【讨论】:

      【解决方案2】:

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

      查看 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')
      

      【讨论】:

        猜你喜欢
        • 2021-03-02
        • 2017-02-01
        • 2018-04-27
        • 1970-01-01
        • 1970-01-01
        • 2020-10-01
        • 1970-01-01
        • 2018-11-22
        • 1970-01-01
        相关资源
        最近更新 更多