Created
August 8, 2023 10:39
-
-
Save berinaniesh/7028945386613c76e80dca02ab060350 to your computer and use it in GitHub Desktop.
Tensorflow MNIST CNN
This file contains 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 as tf | |
import tensorflow_datasets as tfds | |
(ds_train, ds_test), ds_info = tfds.load( | |
'mnist', | |
split=['train', 'test'], | |
shuffle_files=True, | |
as_supervised=True, | |
with_info=True, | |
data_dir="./tensorflow_datasets" | |
) | |
def normalize_img(image, label): | |
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) | |
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) | |
model = tf.keras.Sequential([ | |
tf.keras.layers.InputLayer(input_shape=(28, 28, 1)), | |
tf.keras.layers.Conv2D(filters=32, kernel_size=(3, 3), activation="relu"), | |
tf.keras.layers.Conv2D(filters=64, kernel_size=(3, 3), activation="relu"), | |
tf.keras.layers.MaxPool2D(), | |
tf.keras.layers.Dropout(0.25), | |
tf.keras.layers.Flatten(), | |
tf.keras.layers.Dense(128, activation="relu"), | |
tf.keras.layers.Dense(10, activation="softmax") | |
]) | |
optimizer = tf.keras.optimizers.Adadelta(learning_rate=1) | |
loss = tf.keras.losses.SparseCategoricalCrossentropy() | |
model.compile(optimizer=optimizer, loss=loss) | |
model.summary() | |
model.fit( | |
ds_train, | |
epochs=14, | |
validation_data=ds_test, | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment