In [1]:
from keras.datasets import mnist
In [2]:
# Importing the data
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
In [3]:
# Preprocessing the training images
train_images = train_images.reshape((60000, 28 * 28))
train_images = train_images.astype('float32')
train_images = train_images / 255
In [4]:
train_images.shape
Out[4]:
In [5]:
# Preprocessing the test images
test_images = test_images.reshape((10000, 28 * 28))
test_images = test_images.astype('float32')
test_images = test_images / 255
In [6]:
test_images.shape
Out[6]:
In [7]:
# Importing - to_categorical
from keras.utils import to_categorical
In [8]:
train_labels.shape
Out[8]:
In [9]:
# One-hot encoding the training labels
train_labels = to_categorical(train_labels)
In [10]:
train_labels.shape
Out[10]:
In [11]:
test_labels = to_categorical(test_labels)
In [12]:
test_labels.shape
Out[12]:
In [13]:
# Importing Sequential model
from keras.models import Sequential
In [14]:
# Initializing a sequantial model
model_sequential = Sequential()
In [15]:
# Importing layers
from keras import layers
In [16]:
# Adding a hidden layers
model_sequential.add(layers.Dense(units = 32,
activation = 'relu',
input_shape = (784,)))
In [17]:
model_sequential.add(layers.Dense(units = 10, activation = 'softmax'))
In [18]:
# Importing Functional API model
from keras.models import Model
In [19]:
# Importing layers (obsolete, but consistent)
from keras import layers
In [20]:
# Input layers
input_layer = layers.Input(shape = (784,))
In [21]:
# Hidden layer (fully connected to the input layer)
hidden_layers = layers.Dense(units = 32, activation = 'relu')(input_layer)
In [22]:
# Output layers
output_layer = layers.Dense(units = 10, activation = 'softmax')(hidden_layers)
In [23]:
model_functional = Model(inputs = input_layer, outputs = output_layer)
In [24]:
# Importing optimizers
from keras import optimizers
In [25]:
# Compiling the Sequential model
model_sequential.compile(optimizer = optimizers.RMSprop(lr = 0.001),
loss = 'mse',
metrics = ['accuracy'])
In [26]:
# Compiling the Functional model
model_functional.compile(optimizer = optimizers.RMSprop(lr = 0.001),
loss = 'mse',
metrics = ['accuracy'])
In [27]:
# Sequential
model_sequential.fit(x = train_images,
y = train_labels,
batch_size = 128,
epochs = 10)
Out[27]:
In [28]:
model_functional.fit(x = train_images,
y = train_labels,
batch_size = 128,
epochs = 10)
Out[28]: