示例代码
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(512, activation=tf.nn.relu),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(10, activation=tf.nn.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)
运行结果
32/10000 [..............................] - ETA: 27s - loss: 0.0062 - acc: 1.0000
1408/10000 [===>..........................] - ETA: 0s - loss: 0.0861 - acc: 0.9723
2752/10000 [=======>......................] - ETA: 0s - loss: 0.0967 - acc: 0.9695
4256/10000 [===========>..................] - ETA: 0s - loss: 0.0913 - acc: 0.9711
5728/10000 [================>.............] - ETA: 0s - loss: 0.0788 - acc: 0.9750
7104/10000 [====================>.........] - ETA: 0s - loss: 0.0744 - acc: 0.9759
8512/10000 [========================>.....] - ETA: 0s - loss: 0.0658 - acc: 0.9786
10000/10000 [==============================] - 0s 44us/sample - loss: 0.0626 - acc: 0.9796
网友评论