手写数字识别:使用 TensorFlow MNIST 数据集训练模型
手写数字识别:使用 TensorFlow MNIST 数据集训练模型
本教程将指导您如何使用 TensorFlow 和 MNIST 数据集构建并训练一个手写数字识别模型。我们将涵盖数据预处理、模型构建、训练和评估等关键步骤。
1. 导入库和加载数据集
首先,导入所需的库并加载 MNIST 数据集。
import numpy as np
import tensorflow as tf
from tensorflow.keras.datasets import mnist
# 获取手写数字数据集
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
2. 数据预处理
MNIST 数据集包含 0 到 9 的手写数字图像。每个图像都是 28x28 像素的灰度图像。我们需要对数据进行预处理,以适合我们的模型。
# 训练集数据维度的调整:N H W C
train_images = np.reshape(train_images, (train_images.shape[0], train_images.shape[1], train_images.shape[2], 1))
# 测试集数据维度的调整:N H W C
test_images = np.reshape(test_images, (test_images.shape[0], test_images.shape[1], test_images.shape[2], 1))
# 定义函数获取训练样本和测试样本
def get_train(size):
# 随机生成要抽样的样本的索引
index = np.random.randint(0, np.shape(train_images)[0], size)
# 将这些数据resize成224*224大小
resized_images = tf.image.resize_with_pad(train_images[index], 224, 224)
# 返回抽取的
return resized_images.numpy(), train_labels[index]
# 获取测试集数据
def get_test(size):
# 随机生成要抽样的样本的索引
index = np.random.randint(0, np.shape(test_images)[0], size)
# 将这些数据resize成224*224大小
resized_images = tf.image.resize_with_pad(test_images[index], 224, 224)
# 返回抽样的测试样本
return resized_images.numpy(), test_labels[index]
# 获取训练样本和测试样本
train_images, train_labels = get_train(256)
test_images, test_labels = get_test(128)
3. 构建模型
我们将使用一个简单的卷积神经网络 (CNN) 来识别手写数字。
# 构建模型
model = tf.keras.models.Sequential([
tf.keras.layers.Conv2D(32, (3, 3), activation='relu', input_shape=(224, 224, 1)),
tf.keras.layers.MaxPooling2D((2, 2)),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(10, activation='softmax')
])
4. 编译模型
在训练模型之前,我们需要编译它。这包括指定优化器、损失函数和评估指标。
# 指定优化器,损失函数和评价指标
optimizer = tf.keras.optimizers.SGD(learning_rate=0.01, momentum=0.0)
model.compile(optimizer=optimizer, loss='sparse_categorical_crossentropy', metrics=['accuracy'])
5. 训练模型
现在,我们可以使用训练数据训练模型了。
# 模型训练:指定训练数据,batchsize,epoch,验证集
model.fit(train_images, train_labels, batch_size=128, epochs=3, verbose=1, validation_split=0.1)
6. 评估模型
最后,我们使用测试数据评估训练好的模型的性能。
# 指定测试数据
model.evaluate(test_images, test_labels, verbose=1)
总结
本教程介绍了如何使用 TensorFlow 和 MNIST 数据集构建并训练一个手写数字识别模型。您可以根据需要调整模型架构、训练参数和评估指标。
原文地址: https://www.cveoy.top/t/topic/pdyr 著作权归作者所有。请勿转载和采集!