Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
tensorflow
GitHub Repository: tensorflow/docs-l10n
Path: blob/master/site/zh-cn/datasets/keras_example.ipynb
25115 views
Kernel: Python 3

Training a neural network on MNIST with Keras

This simple example demonstrates how to plug TensorFlow Datasets (TFDS) into a Keras model.

Copyright 2020 The TensorFlow Datasets Authors, Licensed under the Apache License, Version 2.0

import tensorflow as tf import tensorflow_datasets as tfds

第 1 步:创建输入流水线

首先,使用以下指南中的建议构建有效的输入流水线:

加载数据集

使用以下参数加载 MNIST 数据集:

  • shuffle_files=True:MNIST 数据仅存储在单个文件中,但是对于大型数据集则会以多个文件存储在磁盘中,在训练时最好将它们打乱顺序。

  • as_supervised=True:返回元组 (img, label) 而非字典 {'image': img, 'label': label}

(ds_train, ds_test), ds_info = tfds.load( 'mnist', split=['train', 'test'], shuffle_files=True, as_supervised=True, with_info=True, )

构建训练流水线

应用以下转换:

  • tf.data.Dataset.map:TFDS 提供 tf.uint8 类型的图像,而模型期望 tf.float32。因此,您需要对图像进行归一化。

  • tf.data.Dataset.cache:将数据集装入内存时,先缓存再打乱顺序以提高性能。
    :应在缓存后应用随机转换。

  • tf.data.Dataset.shuffle:要获得真正的随机性,请将打乱顺序缓冲区设置为完整的数据集大小。
    **注:**对于无法装入内存的大型数据集,如果系统允许,请使用 buffer_size=1000

  • tf.data.Dataset.batch:打乱顺序后对数据集的元素进行批处理,以在每个周期获得唯一的批次。

  • tf.data.Dataset.prefetch:最好通过预提取结束流水线以提升性能

def normalize_img(image, label): """Normalizes images: `uint8` -> `float32`.""" return tf.cast(image, tf.float32) / 255., label ds_train = ds_train.map( normalize_img, num_parallel_calls=tf.data.AUTOTUNE) ds_train = ds_train.cache() ds_train = ds_train.shuffle(ds_info.splits['train'].num_examples) ds_train = ds_train.batch(128) ds_train = ds_train.prefetch(tf.data.AUTOTUNE)

构建评估流水线

您的测试流水线与训练流水线类似,只有几点细微差异:

  • 您无需调用 tf.data.Dataset.shuffle

  • 在批处理后进行缓存,因为各个周期之间的批次可以相同。

ds_test = ds_test.map( normalize_img, num_parallel_calls=tf.data.AUTOTUNE) ds_test = ds_test.batch(128) ds_test = ds_test.cache() ds_test = ds_test.prefetch(tf.data.AUTOTUNE)

第 2 步:创建并训练模型

将 TFDS 输入流水线插入一个简单的 Keras 模型、编译模型并训练它。

model = tf.keras.models.Sequential([ tf.keras.layers.Flatten(input_shape=(28, 28)), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dense(10) ]) model.compile( optimizer=tf.keras.optimizers.Adam(0.001), loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=[tf.keras.metrics.SparseCategoricalAccuracy()], ) model.fit( ds_train, epochs=6, validation_data=ds_test, )