分类模型混淆矩阵:从枯燥到精美的可视化升级
创作时间:
作者:
@小白创作中心
分类模型混淆矩阵:从枯燥到精美的可视化升级
引用
1
来源
1.
https://www.cainiaoxueyuan.com/ai/66183.html
混淆矩阵是评估分类模型性能的重要工具,但传统的混淆矩阵往往缺乏美感,信息表达不够直观。本文将介绍如何通过数据可视化技巧对混淆矩阵进行美化,使其在保持信息完整性的基础上,更加清晰直观。
二分类模型实现
模型构建
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.family'] = 'Times New Roman'
plt.rcParams['axes.unicode_minus'] = False
import warnings
# 忽略所有警告
warnings.filterwarnings("ignore")
from sklearn.model_selection import train_test_split
df = pd.read_excel('2025-1-9公众号Python机器学习AI.xlsx')
# 划分特征和目标变量
X = df.drop(['y'], axis=1)
y = df['y']
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3,
random_state=42, stratify=df['y'])
from xgboost import XGBClassifier
from sklearn.model_selection import GridSearchCV, StratifiedKFold
from sklearn.metrics import accuracy_score
# 定义 XGBoost 二分类模型
model_xgb = XGBClassifier(use_label_encoder=False, eval_metric='logloss', random_state=8)
# 定义参数网格
param_grid = {
'n_estimators': [50, 100, 200],
'max_depth': [3, 5, 7],
'learning_rate': [0.01, 0.1, 0.2],
'subsample': [0.8, 1.0],
'colsample_bytree': [0.8, 1.0]
}
# 定义 K 折交叉验证 (Stratified K-Fold)
kfold = StratifiedKFold(n_splits=5, shuffle=True, random_state=8)
# 使用网格搜索寻找最佳参数
grid_search = GridSearchCV(estimator=model_xgb, param_grid=param_grid, scoring='accuracy',
cv=kfold, verbose=1, n_jobs=-1)
# 拟合模型
grid_search.fit(X_train, y_train)
# 使用最优参数训练模型
xgboost = grid_search.best_estimator_
使用XGBoost二分类模型,通过网格搜索和K折交叉验证优化超参数,以找到最佳模型并对数据进行训练和测试划分,从而提升二分类任务的预测性能。
基础二分类混淆矩阵
from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay
# 使用测试集进行预测
y_pred = xgboost.predict(X_test)
# 计算混淆矩阵
cm = confusion_matrix(y_test, y_pred)
# 绘制混淆矩阵
disp = ConfusionMatrixDisplay(confusion_matrix=cm, display_labels=xgboost.classes_)
fig, ax = plt.subplots(figsize=(6, 6)) # 调整图大小
disp.plot(cmap='Blues', values_format='d', ax=ax)
# 设置标题和字体加粗
plt.title("Confusion Matrix for XGBoost Model", fontweight='bold', fontsize=14)
# 加粗坐标轴标签
ax.set_xlabel('Predicted Label', fontweight='bold', fontsize=12)
ax.set_ylabel('True Label', fontweight='bold', fontsize=12)
# 调整刻度字体
ax.tick_params(axis='both', labelsize=10, width=2)
# 调整矩阵中的数值字体大小
for text in disp.text_.ravel():
text.set_fontsize(14) # 设置字体大小
text.set_fontweight('bold') # 设置字体加粗
plt.savefig("1.png", format='png', bbox_inches='tight')
plt.show()
优化二分类混淆矩阵
加入标准化混淆矩阵、总计行列和颜色区分,并对数据进行精细标注(如百分比和数值),优化混淆矩阵的可视化效果,使其更加直观和易于解读。
多分类模型实现
模型构建
import numpy as np
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = 'SimHei' # 设置中文显示
plt.rcParams['axes.unicode_minus'] = False
import warnings
# 忽略所有警告
warnings.filterwarnings("ignore")
df = pd.read_excel('多类别数据.xlsx')
from sklearn.preprocessing import LabelEncoder
from sklearn.svm import SVC
from sklearn.model_selection import train_test_split
from hyperopt import fmin, tpe, hp
from sklearn.metrics import accuracy_score
# 对 Type 列进行编码
label_encoder = LabelEncoder()
df['Type_encoded'] = label_encoder.fit_transform(df['Type'])
# 分割数据集
X = df.drop(['Type', 'Type_encoded'], axis=1)
y = df['Type_encoded']
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, stratify=df['Type_encoded']
)
# 定义超参数空间
parameter_space_svc = {
'C': hp.loguniform('C', np.log(100), np.log(1000)), # 惩罚项
'kernel': hp.choice('kernel', ['rbf', 'poly']), # 核函数类型(选择 rbf 或 poly)
'gamma': hp.loguniform('gamma', np.log(100), np.log(1000)), # 核函数的系数
}
# 初始化计数器
count = 0
# 定义优化目标函数
def func(args):
global count
count += 1
print(f"\nIteration {count}: Hyperparameters - {args}")
# 创建 SVM 分类器,传递超参数
clf = SVC(**args)
# 训练模型
clf.fit(X_train, y_train)
# 预测测试集
prediction = clf.predict(X_test)
# 计算准确率
score = accuracy_score(y_test, prediction)
print(f'Test accuracy: {score}')
# 由于 fmin 函数默认是最小化目标函数,所以返回负准确率作为目标
return -score
# 使用 TPE 算法进行超参数优化,最大评估次数为 100
best = fmin(func, parameter_space_svc, algo=tpe.suggest, max_evals=100)
# 将最佳的核函数类型从索引值转换为相应的字符串
kernel_list = ['rbf', 'poly']
best['kernel'] = kernel_list[best['kernel']]
# 将最佳超参数保存到 best_params_ 中
best_params_ = {
'C': best['C'],
'kernel': best['kernel'],
'gamma': best['gamma']
}
# 输出最佳超参数
print('\nBest hyperparameters:', best_params_)
# 创建 SVM 分类器,并使用最佳超参数进行配置
clf = SVC(
C=best_params_['C'], # 惩罚项参数
kernel=best_params_['kernel'], # 核函数类型
gamma=best_params_['gamma'], # 核函数系数
decision_function_shape='ovr', # 多分类问题时使用 "ovr"(一对多)策略
cache_size=5000, # 缓存大小,单位为 MB
probability=True
)
# 使用训练数据进行模型训练
clf.fit(X_train, y_train)
通过超参数优化训练一个基于SVM的多分类模型,为后续生成和分析多分类混淆矩阵做好准备。
基础多分类混淆矩阵
from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay
# 使用测试集进行预测
y_pred = clf.predict(X_test)
# 计算混淆矩阵
cm = confusion_matrix(y_test, y_pred)
# 绘制混淆矩阵
disp = ConfusionMatrixDisplay(confusion_matrix=cm, display_labels=label_encoder.classes_) # 使用编码器的类标签
fig, ax = plt.subplots(figsize=(6, 6)) # 调整图大小
disp.plot(cmap='Blues', values_format='d', ax=ax)
# 设置标题和字体加粗
plt.title("Confusion Matrix for SVM Model", fontweight='bold', fontsize=14)
# 加粗坐标轴标签
ax.set_xlabel('Predicted Label', fontweight='bold', fontsize=12)
ax.set_ylabel('True Label', fontweight='bold', fontsize=12)
# 调整刻度字体
ax.tick_params(axis='both', labelsize=10, width=2)
# 调整矩阵中的数值字体大小
for text in disp.text_.ravel():
text.set_fontsize(14) # 设置字体大小
text.set_fontweight('bold') # 设置字体加粗
# 保存图像
plt.savefig("3.png", format='png', bbox_inches='tight')
plt.show()
优化多分类混淆矩阵
同样对于多分类模型,通过添加标准化、总计行列、颜色区分和精细标注,优化混淆矩阵的展示效果,使其更直观、全面且易于解读。
热门推荐
体验极寒魅力 就在“中国冷极”
婴儿回家需要什么讲究(婴儿回家吉日:喜气洋洋迎新丁)
羊群健康监测先锋:打造高端智能化养羊场的健康管理
移动转电信携号转网怎么办理
静力学分析与动力学分析之间有什么区别?
服务器宕机原因分析及应对措施:保证业务连续性的关键策略
广西经济看点丨中国“果盘子”的四季浪漫
热评丨让诗意栖居可触可感:文旅融合的乡村美学实践
偏头痛怎么办?营养调理和理疗双管齐下缓解头痛
肾积水患者的日常饮食注意事项有哪些
锦龙股份拟“彻底”变身:清仓全部券商股权,谋求向算力领域转型
一只羊的价格:品种、年龄、性别等因素如何影响价格?
“伦”字的意思和解释,“伦”字的成语和组词
人脑的结构与功能:从神经元到大脑皮层的全面解析
四元数在旋转变换和插值中的有趣的可视化解释
千岛之城的文旅新玩法
电池热管理加热元件专利在新能源汽车中的应用前景与技术挑战分析
厨房里的中药房:10种常见食材的药用价值
《四库全书》的功与过
如何分析黄金市场的库存情况?这些库存数据如何影响市场?
国七排放开始上会,油车不会死,但增程要靠藏电达标?
清明节上坟时间及注意事项:上午9点至11点阳气最盛,祭品准备与着装要求全解析
热重分析仪测试热分析温度的方法
生态环境部定调机动车国七标准两大方向
C照几年一审:了解我国驾驶员培训与考试制度
黄金储备是建设金融强国必需的战略资源
氯丁橡胶密封圈-CR密封圈
桂林有哪些风俗习惯?探秘桂林:山水间的独特风俗习惯!
种植红豆杉树苗犯法吗?法律解读与风险分析
氟桂利嗪是防治脑供血不足、偏头痛的常用药,科学服用应注意4点