评估指标
本节定位
训练完模型后,怎么判断模型好不好?准确率 95% 一定好吗?不一定!选错了指标,可能做出完全错误的决策。本节帮你掌握各种场景下应该关注什么指标。
学习目标
- 掌握分类指标:准确率、精确率、召回率、F1-score、混淆矩阵
- 理解 ROC 曲线与 AUC
- 掌握回归指标:MSE、RMSE、MAE、R²
- 理解多分类评估(macro、micro、weighted)
一、为什么准确率不够?
1.1 不平衡数据的陷阱
import numpy as np
# 假设:1000 封邮件中有 10 封是垃圾邮件
y_true = np.array([0] * 990 + [1] * 10)
# "聪明"的模型:全部预测为正常
y_pred = np.zeros(1000)
accuracy = np.mean(y_true == y_pred)
print(f"准确率: {accuracy:.1%}")
# 准确率 99%!但一封垃圾邮件都没抓到!
准确率的陷阱
在不平衡数据中,永远预测多数类就能获得很高的准确率。但这样的模型毫无用处。我们需要更精细的指标。
二、混淆矩阵——一切分类指标的基础
2.1 四个基本量
| 预测为正(Positive) | 预测为负(Negative) | |
|---|---|---|
| 实际为正 | TP(真正例) | FN(假负例/漏报) |
| 实际为负 | FP(假正例/误报) | TN(真负例) |
from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
import matplotlib.pyplot as plt
# 乳腺癌数据集
cancer = load_breast_cancer()
X_train, X_test, y_train, y_test = train_test_split(
cancer.data, cancer.target, test_size=0.2, random_state=42
)
model = LogisticRegression(max_iter=10000, random_state=42)
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
# 混淆矩阵
cm = confusion_matrix(y_test, y_pred)
print("混淆矩阵:")
print(cm)
fig, ax = plt.subplots(figsize=(6, 5))
disp = ConfusionMatrixDisplay(cm, display_labels=['恶性', '良性'])
disp.plot(ax=ax, cmap='Blues')
ax.set_title('乳腺癌分类混淆矩阵')
plt.tight_layout()
plt.show()
2.2 从混淆矩阵推导指标
三、分类指标详解
3.1 精确率(Precision)
Precision = TP / (TP + FP)
"模型说是正例的里面,有多少真的是正例?"
关注场景