0%

TensorFlow:手写数字识别

加载库

1
import tensorflow as tf

加载数据集

1
2
3
4
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
#归一化处理
x_train, x_test = x_train / 255.0, x_test / 255.0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
def load_data(path="mnist.npz"):
"""Loads the MNIST dataset.

This is a dataset of 60,000 28x28 grayscale images of the 10 digits,
along with a test set of 10,000 images.
More info can be found at the
[MNIST homepage](http://yann.lecun.com/exdb/mnist/).

Args:
path: path where to cache the dataset locally
(relative to `~/.keras/datasets`).

Returns:
Tuple of NumPy arrays: `(x_train, y_train), (x_test, y_test)`.

**x_train**: uint8 NumPy array of grayscale image data with shapes
`(60000, 28, 28)`, containing the training data. Pixel values range
from 0 to 255.

**y_train**: uint8 NumPy array of digit labels (integers in range 0-9)
with shape `(60000,)` for the training data.

**x_test**: uint8 NumPy array of grayscale image data with shapes
(10000, 28, 28), containing the test data. Pixel values range
from 0 to 255.

**y_test**: uint8 NumPy array of digit labels (integers in range 0-9)
with shape `(10000,)` for the test data.

根据文档的介绍,发现数据的返回格式,以及数据集的形状

搭建网络模型

1
2
3
4
5
6
7
8
9
10
11
12
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(input_shape=(28, 28)),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(10)
])
loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
model.compile(optimizer='adam',
loss=loss_fn,
metrics=['accuracy'])
model.fit(x_train, y_train, epochs=5)
print(model.evaluate(x_test, y_test, verbose=2))