本文将为您介绍如何使用 TensorFlow 构建一个手写数字识别模型。以下是教程的步骤概览:

  • 准备数据集
  • 构建模型
  • 训练模型
  • 评估模型

准备数据集

首先,我们需要一个手写数字数据集。TensorFlow 提供了 MNIST 数据集,这是一个常用的手写数字数据集。

from tensorflow.keras.datasets import mnist
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()

构建模型

接下来,我们使用 TensorFlow 的 Keras API 来构建模型。

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten

model = Sequential([
    Flatten(input_shape=(28, 28)),
    Dense(128, activation='relu'),
    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)

更多关于 TensorFlow 的教程,请访问本站教程页面


TensorFlow Logo