You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用plot_confusion_matrix报错:意外关键字参数'title'

解决plot_confusion_matrix() got an unexpected keyword argument 'title'错误

问题根源

  1. 参数顺序完全错误:plot_confusion_matrix的第一个参数必须是训练完成的模型(比如你的text_clf),你却把真实标签当成了第一个参数传入。
  2. 无title参数:这个函数本身不接受title关键字参数,标题需要通过matplotlib的轴对象手动设置。
  3. API已被弃用:scikit-learn 1.0及以上版本中,plot_confusion_matrix已被标记为过时,官方推荐使用ConfusionMatrixDisplay类的方法替代。

推荐解决方案:使用ConfusionMatrixDisplay.from_predictions

既然你已经有了预测结果predictions,直接用这个方法更简洁,且可以轻松设置标题:

from sklearn.metrics import ConfusionMatrixDisplay
import matplotlib.pyplot as plt

# 基于已有预测结果生成混淆矩阵可视化
disp = ConfusionMatrixDisplay.from_predictions(
    y_true=y_test.argmax(axis=1),
    y_pred=predictions,
    display_labels=encoder.classes_,
    cmap="viridis"
)
# 设置混淆矩阵标题
disp.ax_.set_title("Confusion matrix, without normalization")
# 显示图像
plt.show()

兼容旧版本的方案(不推荐)

如果必须使用plot_confusion_matrix,需要修正参数顺序,并手动添加标题:

import matplotlib.pyplot as plt
from sklearn.metrics import plot_confusion_matrix

# 创建绘图轴对象
fig, ax = plt.subplots()
# 正确调用:第一个参数是模型,然后是测试数据和真实标签
plot_confusion_matrix(
    estimator=text_clf,
    X=tokenizer.sequences_to_texts_generator(test_text_vec),
    y_true=y_test.argmax(axis=1),
    display_labels=encoder.classes_,
    ax=ax
)
# 手动设置标题
ax.set_title("Confusion matrix, without normalization")
plt.show()

注意事项

  • scikit-learn 1.0+版本优先选第一种方案,plot_confusion_matrix会在后续版本中被移除。
  • 确保导入对应模块:第一种方案需要导入ConfusionMatrixDisplay,第二种保留plot_confusion_matrix。

内容的提问来源于stack exchange,提问作者Rajat Das

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 16:01:12