# Import necessary libraries
import tensorflow as tf
from tensorflow.keras import layers, models
from tensorflow.keras.datasets import mnist
from tensorflow.keras.utils import to_categorical
# Load and preprocess the MNIST dataset
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
# Normalize pixel values to be between 0 and 1
train_images, test_images = train_images / 255.0, test_images / 255.0
# Expand dimensions to add a channel dimension (for CNN)
train_images = train_images.reshape((60000, 28, 28, 1))
test_images = test_images.reshape((10000, 28, 28, 1))
# One-hot encode the labels
train_labels = to_categorical(train_labels)
test_labels = to_categorical(test_labels)
# Implementation of sequential model
# Step 1: Create a sequential model
model = models.Sequential()
# Step 2: Add a convolutional layer with 32 filters, a 3x3 kernel, and ReLU activation function
model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)))
# Step 3: Add a max pooling layer with 2x2 pool size
model.add(layers.MaxPooling2D((2, 2)))
# Step 4: Add another convolutional layer with 64 filters and a 3x3 kernel
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
# Step 5: Add another max pooling layer
model.add(layers.MaxPooling2D((2, 2)))
# Step 6: Flatten the output to a 1D array
model.add(layers.Flatten())
# Step 7: Add a dense layer with 64 units and ReLU activation
model.add(layers.Dense(64, activation='relu'))
# Step 8: Add the output layer with 10 units (for 10 classes) and softmax activation
model.add(layers.Dense(10, activation='softmax'))
# Step 9: Compile the model
model.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
# Step 10: Train the model
model.fit(train_images, train_labels, epochs=5, batch_size=64, validation_data=(test_images, test_labels))
# Step 11: Evaluate the model on the test set
test_loss, test_acc = model.evaluate(test_images, test_labels)
print(f'Test accuracy: {test_acc}')