🎯 手写数字识别作业完整步骤总结
根据我们完整的对话过程,我为你总结了完成这个手写数字识别作业的完整步骤:
📋 完整步骤流程
第一阶段:环境准备
步骤1:安装Anaconda和必要库
bash
# 创建虚拟环境
conda create -n mnist python=3.9
conda activate mnist
# 安装必要库
pip install tensorflow keras scikit-learn matplotlib numpy pillow jupyter
步骤2:验证安装
python
import tensorflow as tf
import keras
import numpy as np
print("✅ 所有库安装成功!")
第二阶段:模型训练
步骤3:训练手写数字识别模型
python
from tensorflow import keras
from tensorflow.keras import layers
import numpy as np
# 加载MNIST数据集
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
# 数据预处理
x_train = x_train.reshape(60000, 28, 28, 1).astype('float32') / 255
x_test = x_test.reshape(10000, 28, 28, 1).astype('float32') / 255
# 构建CNN模型
model = keras.Sequential([
layers.Conv2D(32, (3,3), activation='relu', input_shape=(28,28,1)),
layers.MaxPooling2D((2,2)),
layers.Conv2D(64, (3,3), activation='relu'),
layers.MaxPooling2D((2,2)),
layers.Flatten(),
layers.Dense(128, activation='relu'),
layers.Dropout(0.5),
layers.Dense(10, activation='softmax')
])
# 编译和训练模型
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
model.fit(x_train, y_train, epochs=10, validation_split=0.1)
# 保存模型
model.save('mnist_model.h5')
print("✅ 模型训练完成并保存")
第三阶段:准备测试数据
步骤4:拍摄手写数字图片
在白纸上手写你的学号数字
每个数字单独拍摄一张照片
确保数字清晰、居中、光线均匀
按顺序命名为:digit_0.jpg, digit_1.jpg, digit_2.jpg...
步骤5:图片预处理函数
python
from PIL import Image
import numpy as np
def preprocess_handwritten_image(image_path):
img = Image.open(image_path).convert('L')
img = img.resize((28, 28))
img_array = np.array(img)
img_array = 255 - img_array # 反色处理
img_array = img_array / 255.0
img_array = img_array.reshape(1, 28, 28, 1)
return img_array
第四阶段:模型预测与验证
步骤6:进行手写数字识别
python
from tensorflow import keras
import numpy as np
import os
# 加载模型
model = keras.models.load_model('mnist_model.h5')
# 设置学号
student_id = "你的学号" # 替换为真实学号
# 进行预测
results = []
for i in range(len(student_id)):
image_path = f'digit_{i}.jpg'
processed_img = preprocess_handwritten_image(image_path)
prediction = model.predict(processed_img, verbose=0)
predicted_digit = np.argmax(prediction)
confidence = np.max(prediction)
actual_digit = int(student_id[i])
is_correct = (predicted_digit == actual_digit)
results.append({
'position': i,
'actual': actual_digit,
'predicted': predicted_digit,
'confidence': confidence,
'correct': is_correct
})
status = "✅" if is_correct else "❌"
print(f"{status} 第{i+1}位: 真实={actual_digit}, 预测={predicted_digit}, 置信度={confidence:.4f}")
# 计算准确率
correct_predictions = sum(1 for r in results if r['correct'])
accuracy = correct_predictions / len(results)
print(f"\n最终准确率: {accuracy:.2%}")
相似问题