首页 > 解决方案 > 如何在 plot_confusion_matrix 中格式化数字

问题描述

如何改进矩阵中这种奇怪的、难以辨认的数字格式,使其只显示简单的数字?

from sklearn.naive_bayes import GaussianNB
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.ensemble import RandomForestClassifier
from lightgbm import LGBMClassifier
from sklearn.ensemble import RandomForestClassifier

NBC = GaussianNB() 
LRE = LogisticRegression(solver='lbfgs')
GBC = GradientBoostingClassifier()
RFC = RandomForestClassifier()
LGBM = LGBMClassifier()
CBC = CatBoostClassifier(verbose=0, n_estimators=100)


classifiers = [NBC,LRE,GBC,RFC,LGBM,CBC]


for cls in classifiers:
    cls.fit(X_train, y_train)


fig, axes = plt.subplots(nrows=2, ncols=3, figsize=(10,6))
target_names = ['0','1']


for cls, ax in zip(classifiers, axes.flatten()):
    plot_confusion_matrix(cls, 
                          X_test, 
                          y_test, 
                          ax=ax, 
                          cmap='Reds',
                         display_labels=target_names)
    ax.title.set_text(type(cls).__name__)
    
plt.tight_layout()  
plt.show()

在此处输入图像描述

标签: matplotlibplotmodel

解决方案


尝试将空值格式作为参数传递给plot_confusion_matrix. 文档状态_

values_format :str,默认=无

混淆矩阵中值的格式规范。如果没有,格式规范是“d”或“.2g”,以较短者为准。

plot_confusion_matrix(cls, X_test, y_test, ax=ax, cmap='Reds',
                     display_labels=target_names,
                     values_format='') # <--------- Passed here

推荐阅读