【问题标题】:Plot multiple confusion matrices with plot_confusion_matrix使用 plot_confusion_matrix 绘制多个混淆矩阵
【发布时间】:2020-07-15 20:56:09
【问题描述】:

我正在使用来自sklearn.metricsplot_confusion_matrix。我想像子图一样将这些混淆矩阵彼此相邻表示,我该怎么做?

【问题讨论】:

    标签: python matplotlib machine-learning scikit-learn seaborn


    【解决方案1】:

    让我们使用 good'ol iris 数据集来重现这一点,并拟合几个分类器来绘制它们各自的混淆矩阵与plot_confusion_matrix

    from sklearn.ensemble import AdaBoostClassifier, GradientBoostingClassifier
    from sklearn.svm import SVC
    from sklearn.model_selection import train_test_split
    from sklearn.linear_model import LogisticRegression
    from matplotlib import pyplot as plt
    from sklearn.datasets import load_iris
    from sklearn.metrics import plot_confusion_matrix
    
    data = load_iris()
    X = data.data
    y = data.target
    

    设置 -

    X_train, X_test, y_train, y_test = train_test_split(X, y)
    classifiers = [LogisticRegression(solver='lbfgs'), 
                   AdaBoostClassifier(),
                   GradientBoostingClassifier(), 
                   SVC()]
    for cls in classifiers:
        cls.fit(X_train, y_train)
    

    因此,您可以一目了然地比较所有矩阵的方法是使用plt.subplots 创建一组子图。然后迭代轴对象和训练好的分类器(plot_confusion_matrix 期望作为输入)并绘制各个混淆矩阵:

    fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(15,10))
    
    for cls, ax in zip(classifiers, axes.flatten()):
        plot_confusion_matrix(cls, 
                              X_test, 
                              y_test, 
                              ax=ax, 
                              cmap='Blues',
                             display_labels=data.target_names)
        ax.title.set_text(type(cls).__name__)
    plt.tight_layout()  
    plt.show()
    

    【讨论】:

    • 谢谢,这正是我想要的。
    猜你喜欢
    • 2016-01-31
    • 2020-09-01
    • 1970-01-01
    • 2021-07-21
    • 1970-01-01
    • 2016-06-04
    • 2016-10-20
    • 2017-10-17
    相关资源
    最近更新 更多