您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# 怎么用TensorFlow完成手写数字识别
## 一、项目概述
手写数字识别是计算机视觉和机器学习领域的经典入门项目。本文将通过TensorFlow 2.x实现一个基于MNIST数据集的卷积神经网络(CNN)模型,完整展示从数据预处理到模型部署的全流程。
## 二、环境准备
首先确保安装以下环境:
```python
pip install tensorflow==2.10
pip install matplotlib numpy
TensorFlow内置了MNIST数据集:
import tensorflow as tf
from tensorflow.keras.datasets import mnist
# 加载数据
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# 归一化到0-1范围
x_train = x_train / 255.0
x_test = x_test / 255.0
# 添加通道维度(CNN需要)
x_train = x_train[..., tf.newaxis]
x_test = x_test[..., tf.newaxis]
# One-hot编码标签
y_train = tf.keras.utils.to_categorical(y_train, 10)
y_test = tf.keras.utils.to_categorical(y_test, 10)
model = tf.keras.Sequential([
# 卷积层1
tf.keras.layers.Conv2D(32, (3,3), activation='relu', input_shape=(28,28,1)),
tf.keras.layers.MaxPooling2D((2,2)),
# 卷积层2
tf.keras.layers.Conv2D(64, (3,3), activation='relu'),
tf.keras.layers.MaxPooling2D((2,2)),
# 全连接层
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dropout(0.5),
tf.keras.layers.Dense(10, activation='softmax')
])
model.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
history = model.fit(x_train, y_train,
batch_size=128,
epochs=10,
validation_split=0.1)
test_loss, test_acc = model.evaluate(x_test, y_test)
print(f"Test accuracy: {test_acc:.4f}")
import matplotlib.pyplot as plt
plt.plot(history.history['accuracy'], label='accuracy')
plt.plot(history.history['val_accuracy'], label='val_accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend()
plt.show()
import numpy as np
# 随机选择测试样本
idx = np.random.randint(0, x_test.shape[0])
sample = x_test[idx].reshape(1,28,28,1)
# 预测
pred = model.predict(sample)
pred_num = np.argmax(pred)
# 显示图像
plt.imshow(x_test[idx].reshape(28,28), cmap='gray')
plt.title(f"Predicted: {pred_num}")
plt.show()
data_augmentation = tf.keras.Sequential([
tf.keras.layers.RandomRotation(0.1),
tf.keras.layers.RandomZoom(0.1)
])
lr_scheduler = tf.keras.callbacks.LearningRateScheduler(
lambda epoch: 1e-3 * 10**(epoch/20))
early_stopping = tf.keras.callbacks.EarlyStopping(
monitor='val_loss', patience=3)
model.save('mnist_cnn.h5') # HDF5格式
new_model = tf.keras.models.load_model('mnist_cnn.h5')
converter = tf.lite.TFLiteConverter.from_keras_model(model)
tflite_model = converter.convert()
with open('mnist.tflite', 'wb') as f:
f.write(tflite_model)
# 完整代码整合(省略部分可视化代码)
import tensorflow as tf
from tensorflow.keras.datasets import mnist
# 数据加载与预处理
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
x_train = x_train[..., tf.newaxis]
x_test = x_test[..., tf.newaxis]
y_train = tf.keras.utils.to_categorical(y_train, 10)
y_test = tf.keras.utils.to_categorical(y_test, 10)
# 构建模型
model = tf.keras.Sequential([
tf.keras.layers.Conv2D(32, (3,3), activation='relu', input_shape=(28,28,1)),
tf.keras.layers.MaxPooling2D((2,2)),
tf.keras.layers.Conv2D(64, (3,3), activation='relu'),
tf.keras.layers.MaxPooling2D((2,2)),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dropout(0.5),
tf.keras.layers.Dense(10, activation='softmax')
])
# 编译与训练
model.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
model.fit(x_train, y_train, epochs=10, validation_split=0.1)
# 评估
test_loss, test_acc = model.evaluate(x_test, y_test)
print(f"Test accuracy: {test_acc:.4f}")
通过本教程,我们实现了: 1. 使用TensorFlow加载和预处理MNIST数据集 2. 构建了一个简单的CNN模型 3. 完成了模型训练和评估 4. 实现了模型保存与转换
该模型准确率可达99%以上,可作为其他计算机视觉任务的基础模板。 “`
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。