Skip to content

Instantly share code, notes, and snippets.

@arshren
Created September 16, 2021 10:48
Show Gist options
  • Save arshren/8ddd558caa52376226ed6a540c7a28c1 to your computer and use it in GitHub Desktop.
Save arshren/8ddd558caa52376226ed6a540c7a28c1 to your computer and use it in GitHub Desktop.
Build Keras Model using Sequential Technique
#Import required libraries
import tensorflow as tf
from keras.datasets import mnist
#Creating the MNIST Dataset
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test= x_train/255.0, x_test/255.0
x_train=x_train[...,tf.newaxis].astype('float32')
x_test=x_test[...,tf.newaxis].astype('float32')
#Building the Keras model using Sequential
#Approach1
model_seq=tf.keras.Sequential()
model_seq.add(tf.keras.layers.Conv2D(32,3, activation='relu'))
model_seq.add(tf.keras.layers.Flatten())
model_seq.add(tf.keras.layers.Dense(128, activation='relu'))
model_seq.add(tf.keras.layers.Dense(10, activation='softmax'))
# Approach2
model_seq_layer = tf.keras.Sequential(
[
tf.keras.layers.Conv2D(32, 3, activation="relu"),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(128, activation="relu"),
tf.keras.layers.Dense(10, activation='softmax'),
]
)
# compile the mode;
model_seq.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
# Fit the model on MNIST dataset
model_seq.fit(x_train, y_train, epochs=10)
#Evaluate the model on the test data
test_loss, test_acc=model_seq.evaluate(x_test, y_test)
@arshren
Copy link
Author

arshren commented Sep 16, 2021

This code snippet creates a Keras model using Sequential technique

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment