Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
tensorflow
GitHub Repository: tensorflow/docs-l10n
Path: blob/master/site/ja/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: MNIST データは、単一のファイルにのみ保存されていますが、ディスク上の複数のファイルを伴うより大きなデータセットについては、トレーニングの際にシャッフルすることが良い実践です。

  • as_supervised: dict {'image': img, 'label': label} の代わりに tuple (img, 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, )