TensorFlow 是一个强大的开源机器学习框架,它可以帮助我们轻松地构建和训练各种机器学习模型。MNIST 数据集是一个包含手写数字的图像数据集,是机器学习和深度学习中的经典入门数据集。本教程将带你通过 TensorFlow 构建 MNIST 手写数字识别模型。

安装 TensorFlow

在开始之前,请确保你已经安装了 TensorFlow。可以使用以下命令进行安装:

pip install tensorflow

数据准备

MNIST 数据集包含 60,000 个训练样本和 10,000 个测试样本。每个样本都是一个 28x28 的灰度图像,表示一个手写数字。

import tensorflow as tf

mnist = tf.keras.datasets.mnist
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()

数据预处理

在训练模型之前,需要对数据进行一些预处理,包括归一化和图像缩放。

train_images = train_images / 255.0
test_images = test_images / 255.0

构建模型

接下来,我们将使用 TensorFlow 的 Keras API 构建一个简单的卷积神经网络模型。

model = tf.keras.models.Sequential([
    tf.keras.layers.Flatten(input_shape=(28, 28)),
    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, verbose=2)
print('\nTest accuracy:', test_acc)

模型预测

predictions = model.predict(test_images)

扩展阅读

想要了解更多关于 TensorFlow 和机器学习的知识,可以访问我们的 TensorFlow 教程

[

MNIST_image
]

[

TensorFlow_logo
]