MNIST手写数字分类实战:从数据加载到模型评估的完整流程(附代码)
MNIST手写数字分类实战从数据加载到模型评估的完整流程附代码在机器学习领域MNIST数据集堪称经典中的经典。这个包含7万张手写数字图片的数据集已经成为无数数据科学家和机器学习工程师的入门必修课。本文将带你从零开始完整实现一个MNIST手写数字分类项目涵盖数据探索、模型构建、训练优化和性能评估的全流程。1. 环境准备与数据加载首先我们需要搭建Python环境并安装必要的库。推荐使用Anaconda创建虚拟环境conda create -n mnist python3.8 conda activate mnist pip install numpy pandas matplotlib scikit-learn tensorflowMNIST数据集可以通过多种方式获取。最便捷的方法是直接使用scikit-learn提供的APIfrom sklearn.datasets import fetch_openml mnist fetch_openml(mnist_784, version1, as_frameFalse) X, y mnist[data], mnist[target]数据加载后我们可以查看其基本结构样本数量70,000特征维度78428x28像素标签范围0-9为了更好地理解数据让我们可视化几个样本import matplotlib.pyplot as plt def plot_digit(image_data): image image_data.reshape(28, 28) plt.imshow(image, cmapbinary) plt.axis(off) plt.figure(figsize(10,5)) for i in range(10): plt.subplot(2,5,i1) plot_digit(X[i]) plt.show()2. 数据预处理与分割在建模前我们需要对数据进行适当的预处理类型转换将标签从字符串转为整数归一化将像素值从0-255缩放到0-1范围数据集分割划分训练集和测试集import numpy as np from sklearn.model_selection import train_test_split # 类型转换 y y.astype(np.uint8) # 归一化 X X / 255.0 # 数据集分割 X_train, X_test, y_train, y_test train_test_split(X, y, test_size0.2, random_state42)注意MNIST数据集已经预先进行了随机化处理前60,000个样本通常作为训练集后10,000个作为测试集。但为了演示通用流程我们使用train_test_split进行随机分割。3. 模型构建与训练我们将尝试两种不同的分类器随机梯度下降(SGD)分类器和随机森林分类器。3.1 SGD分类器from sklearn.linear_model import SGDClassifier sgd_clf SGDClassifier(max_iter1000, tol1e-3, random_state42) sgd_clf.fit(X_train, y_train)3.2 随机森林分类器from sklearn.ensemble import RandomForestClassifier forest_clf RandomForestClassifier(n_estimators100, random_state42) forest_clf.fit(X_train, y_train)4. 模型评估与性能分析评估分类器性能有多种方法我们将重点介绍几种常用指标。4.1 准确率评估最简单的评估指标是准确率from sklearn.model_selection import cross_val_score # SGD分类器交叉验证 sgd_scores cross_val_score(sgd_clf, X_train, y_train, cv3, scoringaccuracy) print(fSGD分类器准确率: {sgd_scores.mean():.2f} (±{sgd_scores.std():.2f})) # 随机森林交叉验证 forest_scores cross_val_score(forest_clf, X_train, y_train, cv3, scoringaccuracy) print(f随机森林准确率: {forest_scores.mean():.2f} (±{forest_scores.std():.2f}))4.2 混淆矩阵分析混淆矩阵能提供更详细的分类信息from sklearn.metrics import confusion_matrix from sklearn.model_selection import cross_val_predict y_train_pred cross_val_predict(sgd_clf, X_train, y_train, cv3) conf_mx confusion_matrix(y_train, y_train_pred) plt.matshow(conf_mx, cmapplt.cm.gray) plt.show()4.3 精度与召回率对于多分类问题我们可以计算每个类别的精度和召回率from sklearn.metrics import precision_score, recall_score precision precision_score(y_train, y_train_pred, averagemacro) recall recall_score(y_train, y_train_pred, averagemacro) print(f精度: {precision:.2f}, 召回率: {recall:.2f})4.4 ROC曲线分析虽然ROC曲线主要用于二分类问题但我们可以通过一对多策略将其扩展到多分类from sklearn.metrics import roc_curve, roc_auc_score from sklearn.preprocessing import label_binarize # 将标签二值化 y_train_bin label_binarize(y_train, classesnp.arange(10)) # 计算每个类别的ROC曲线 fpr dict() tpr dict() roc_auc dict() for i in range(10): y_score cross_val_predict(sgd_clf, X_train, y_train_bin[:,i], cv3, methoddecision_function) fpr[i], tpr[i], _ roc_curve(y_train_bin[:,i], y_score) roc_auc[i] roc_auc_score(y_train_bin[:,i], y_score) # 绘制ROC曲线 plt.figure(figsize(10,8)) for i in range(10): plt.plot(fpr[i], tpr[i], labelf数字{i} (AUC {roc_auc[i]:.2f})) plt.plot([0, 1], [0, 1], k--) plt.xlabel(假正类率) plt.ylabel(真正类率) plt.legend(loclower right) plt.show()5. 模型优化与调参5.1 特征缩放SGD分类器对特征缩放敏感我们可以尝试标准化from sklearn.preprocessing import StandardScaler scaler StandardScaler() X_train_scaled scaler.fit_transform(X_train) X_test_scaled scaler.transform(X_test) sgd_clf.fit(X_train_scaled, y_train) scaled_scores cross_val_score(sgd_clf, X_train_scaled, y_train, cv3, scoringaccuracy) print(f标准化后准确率: {scaled_scores.mean():.2f})5.2 超参数调优使用网格搜索优化随机森林参数from sklearn.model_selection import GridSearchCV param_grid [ {n_estimators: [50, 100, 200], max_depth: [None, 10, 20]}, {bootstrap: [False], n_estimators: [50, 100], max_depth: [5, 10]} ] forest_clf RandomForestClassifier(random_state42) grid_search GridSearchCV(forest_clf, param_grid, cv3, scoringaccuracy) grid_search.fit(X_train, y_train) print(f最佳参数: {grid_search.best_params_}) print(f最佳准确率: {grid_search.best_score_:.2f})6. 最终模型评估选择表现最好的模型在测试集上进行最终评估from sklearn.metrics import classification_report best_model grid_search.best_estimator_ y_pred best_model.predict(X_test) print(classification_report(y_test, y_pred))7. 模型部署与应用训练好的模型可以保存并用于实际应用import joblib # 保存模型 joblib.dump(best_model, mnist_classifier.pkl) # 加载模型 loaded_model joblib.load(mnist_classifier.pkl) # 使用模型预测新数据 sample X_test[0].reshape(1, -1) prediction loaded_model.predict(sample) print(f预测数字: {prediction[0]})8. 进阶探索方向完成基础分类后可以考虑以下进阶方向卷积神经网络(CNN)使用TensorFlow/Keras构建更强大的图像分类模型数据增强通过旋转、平移等变换增加训练数据多样性模型集成结合多个模型的预测结果提高准确率错误分析深入研究分类错误的样本特征# CNN示例代码 from tensorflow import keras from tensorflow.keras import layers model keras.Sequential([ layers.Reshape((28, 28, 1), input_shape(784,)), layers.Conv2D(32, kernel_size3, activationrelu), layers.MaxPooling2D(pool_size2), layers.Flatten(), layers.Dense(10, activationsoftmax) ]) model.compile(optimizeradam, losssparse_categorical_crossentropy, metrics[accuracy]) model.fit(X_train, y_train, epochs5, validation_data(X_test, y_test))在实际项目中我发现数据预处理和特征工程往往比模型选择更重要。例如对MNIST图像进行适当的去噪和增强可以显著提升模型性能。另外不同模型在不同数字上的表现差异明显通过分析混淆矩阵可以针对性地优化特定数字的分类效果。
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2419382.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!