下面的例子是摘自tensorflow官网
import tensorflow as tf
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
# 定义一个模型结构
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, activation='softmax')
])
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
model.fit(x_train, y_train, epochs=5)
model.evaluate(x_test, y_test)
运行结果如下:
Epoch 1/5
1875/1875 [==============================] - 2s 931us/step - loss: 0.2978 - accuracy: 0.9140
Epoch 2/5
1875/1875 [==============================] - 2s 889us/step - loss: 0.1388 - accuracy: 0.9593
Epoch 3/5
1875/1875 [==============================] - 2s 886us/step - loss: 0.1053 - accuracy: 0.9679
Epoch 4/5
1875/1875 [==============================] - 2s 885us/step - loss: 0.0848 - accuracy: 0.9739
Epoch 5/5
1875/1875 [==============================] - 2s 910us/step - loss: 0.0728 - accuracy: 0.9766
313/313 [==============================] - 0s 629us/step - loss: 0.0724 - accuracy: 0.9776
Out[5]:
[0.07242073118686676, 0.9775999784469604]