手写数字识别.py 967 B

1234567891011121314151617181920212223
  1. from __future__ import absolute_import, division, print_function, unicode_literals
  2. import tensorflow as tf
  3. mnist = tf.keras.datasets.mnist
  4. #需要从 https://storage.googleapis.com/tensorflow/tf-keras-datasets/ 下载,执行过程非常缓慢,或者报证书错误可以直接从浏览器下载 https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz
  5. #并保存到 ~/.kreas/datasets/ 目录下(c盘根目录)即可
  6. (x_train, y_train), (x_test, y_test) = mnist.load_data()
  7. x_train, x_test = x_train / 255.0, x_test / 255.0
  8. model = tf.keras.models.Sequential([
  9. tf.keras.layers.Flatten(input_shape=(28, 28)),
  10. tf.keras.layers.Dense(128, activation='relu'),
  11. tf.keras.layers.Dropout(0.2),
  12. tf.keras.layers.Dense(10, activation='softmax')
  13. ])
  14. model.compile(optimizer='adam',
  15. loss='sparse_categorical_crossentropy',
  16. metrics=['accuracy'])
  17. model.fit(x_train, y_train, epochs=5)
  18. model.evaluate(x_test, y_test)