模型评估
模型训练完,它到底好不好? 模型评估用数据回答这个问题。
flowchart LR A[全部数据] --> B[训练集 60%<br/>学习参数] A --> C[验证集 20%<br/>调超参] A --> D[测试集 20%<br/>最终评估]from sklearn.model_selection import train_test_split
X_temp, X_test, y_temp, y_test = train_test_split(X, y, test_size=0.2)X_train, X_val, y_train, y_val = train_test_split(X_temp, y_temp, test_size=0.25)print(f"训练:{len(X_train)} 验证:{len(X_val)} 测试:{len(X_test)}")数据量小时,K 折交叉验证更可靠:
from sklearn.model_selection import cross_val_score
scores = cross_val_score(LogisticRegression(), X, y, cv=5)print(f"每折: {scores}")print(f"平均: {scores.mean():.3f} ± {scores.std():.3f}") 预测正 预测负实际正 TP FN ← 漏报更危险!实际负 FP TNfrom sklearn.metrics import confusion_matrix, classification_report
y_true = [1, 0, 1, 1, 0, 1, 0, 0, 1, 0]y_pred = [1, 0, 1, 0, 0, 1, 1, 0, 1, 0]
print(confusion_matrix(y_true, y_pred))print(classification_report(y_true, y_pred))| 场景 | 指标 | 为什么 |
|---|---|---|
| 均衡分类 | 准确率 | 简单直观 |
| 垃圾邮件检测 | 精确率 | 不想误删正常邮件 |
| 疾病筛查 | 召回率 | 不想漏诊 |
| 不均衡数据 | F1 / AUC | 综合考虑 |
| 回归 | R² / MSE | 衡量拟合 |
ROC 与 AUC
Section titled “ROC 与 AUC”from sklearn.metrics import roc_auc_score
y_score = model.predict_proba(X_test)[:, 1]auc = roc_auc_score(y_test, y_score)print(f"AUC: {auc:.3f}")# 1.0 = 完美 0.5 = 随机 <0.5 = 比随机还差from sklearn.metrics import mean_squared_error, r2_score
y_true = [3.0, -0.5, 2.0, 7.0]y_pred = [2.5, 0.0, 2.0, 8.0]
print(f"MSE: {mean_squared_error(y_true, y_pred):.3f}")print(f"R²: {r2_score(y_true, y_pred):.3f}")