手写数字识别是机器学习和深度学习领域中的一个经典问题。在这个教程中,我们将使用 TensorFlow 来实现一个手写数字识别模型。
教程步骤
安装 TensorFlow 首先,确保你已经安装了 TensorFlow。你可以通过以下命令安装:
pip install tensorflow
导入数据集 TensorFlow 提供了 MNIST 数据集,这是一个包含 60,000 个训练样本和 10,000 个测试样本的手写数字数据集。
import tensorflow as tf mnist = tf.keras.datasets.mnist (train_images, train_labels), (test_images, test_labels) = mnist.load_data()
预处理数据 将图像数据缩放到 0 到 1 之间的值,并调整图像大小为 28x28。
train_images = train_images.reshape((60000, 28, 28, 1)).astype('float32') / 255 test_images = test_images.reshape((10000, 28, 28, 1)).astype('float32') / 255
构建模型 使用 TensorFlow 的 Keras API 构建一个简单的卷积神经网络模型。
model = tf.keras.models.Sequential([ tf.keras.layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)), tf.keras.layers.MaxPooling2D((2, 2)), tf.keras.layers.Flatten(), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dense(10, activation='softmax') ])
编译模型 编译模型,指定损失函数和优化器。
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
训练模型 使用训练数据来训练模型。
model.fit(train_images, train_labels, epochs=5)
评估模型 使用测试数据来评估模型的性能。
test_loss, test_acc = model.evaluate(test_images, test_labels) print('Test accuracy:', test_acc)
使用模型进行预测 使用训练好的模型来预测新的手写数字图像。
predictions = model.predict(test_images) print(predictions)
扩展阅读
如果你对 TensorFlow 和深度学习有更深入的兴趣,可以阅读以下教程:
TensorFlow Logo