模型评估是机器学习流程中至关重要的一步,它帮助我们理解模型在未知数据上的泛化能力。以下是关键知识点和实践建议:
📌 评估指标详解
准确率(Accuracy)
分类任务中最直观的指标,但对类别不平衡数据不友好精确率(Precision) & 召回率(Recall)
用于衡量模型的分类能力,特别适合欺诈检测等场景F1 分数(F1 Score)
精确率和召回率的调和平均数,适合综合评估模型表现AUC-ROC 曲线
通过ROC曲线下的面积衡量分类器的整体性能
🧪 实战示例
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense
from sklearn.metrics import confusion_matrix
# 加载数据
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train = x_train.reshape(-1, 784).astype('float32')/255
x_test = x_test.reshape(-1, 784).astype('float32')/255
# 构建模型
model = Sequential([
Dense(512, activation='relu', input_shape=(784,)),
Dense(10, activation='softmax')
])
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
# 训练与评估
model.fit(x_train, y_train, epochs=5)
test_loss, test_acc = model.evaluate(x_test, y_test)
print(f"测试准确率: {test_acc:.4f}")
# 混淆矩阵分析
y_pred = model.predict_classes(x_test)
cm = confusion_matrix(y_test, y_pred)
⚠️ 注意事项
- 数据划分:确保训练集/测试集比例合理(如 80/20)
- 过拟合预防:使用早停(EarlyStopping)或模型简化
- 交叉验证:通过
sklearn.model_selection.KFold
提高评估可靠性 - 指标选择:根据业务场景选择最合适的评估标准
📚 扩展阅读
想深入了解模型训练技巧?请查看 Keras 模型训练教程 获取完整指南。