Skip to content

模型评估

模型训练完,真正的问题才开始:它到底好不好?

flowchart LR
A[全部数据] --> B[训练集<br/>60%]
A --> C[验证集<br/>20%]
A --> D[测试集<br/>20%]
B -->|调参| E[模型]
C -->|评估| E
E -->|最终测试| D
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 TN
误报(假阳性)
from 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衡量拟合程度
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}")