Created
January 21, 2021 12:39
-
-
Save kittinan/f39534c3f58d9fcca7731edc8763bf31 to your computer and use it in GitHub Desktop.
this code from https://www.tensorflow.org/datasets/keras_example to test my GPU training work
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import tensorflow.compat.v2 as tf | |
import tensorflow_datasets as tfds | |
tf.enable_v2_behavior() | |
(ds_train, ds_test), ds_info = tfds.load( | |
'mnist', | |
split=['train', 'test'], | |
shuffle_files=True, | |
as_supervised=True, | |
with_info=True, | |
) | |
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.experimental.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.experimental.AUTOTUNE) | |
ds_test = ds_test.map( | |
normalize_img, num_parallel_calls=tf.data.experimental.AUTOTUNE) | |
ds_test = ds_test.batch(128) | |
ds_test = ds_test.cache() | |
ds_test = ds_test.prefetch(tf.data.experimental.AUTOTUNE) | |
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, | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment