CNNClassifier / cnn_model_train.py
HarnithaS's picture
intial commit
2fabd6e
# Importing necessary libraries
import tensorflow as tf
from tensorflow.keras import layers, models, datasets
import numpy as np
# Load the MNIST dataset
(train_images, train_labels), (test_images, test_labels) = datasets.mnist.load_data()
# Normalize pixel values to be between 0 and 1
train_images = train_images.reshape((60000, 28, 28, 1)).astype('float32') / 255
test_images = test_images.reshape((10000, 28, 28, 1)).astype('float32') / 255
# Convert labels to categorical one-hot encoding
train_labels = tf.keras.utils.to_categorical(train_labels, 10)
test_labels = tf.keras.utils.to_categorical(test_labels, 10)
# Define the CNN model
def create_cnn_model(input_shape, num_classes):
model = models.Sequential()
# Convolutional layers
model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=input_shape))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
# Flatten layer to transition from convolutional layers to fully connected layers
model.add(layers.Flatten())
# Dense (fully connected) layers
model.add(layers.Dense(64, activation='relu'))
model.add(layers.Dense(num_classes, activation='softmax')) # Output layer with softmax activation for multiclass classification
return model
# Define input shape and number of classes
input_shape = (28, 28, 1) # Input shape for MNIST images
num_classes = 10 # Number of classes for digit classification (0-9)
# Create an instance of the model
model = create_cnn_model(input_shape, num_classes)
# Print model summary
model.summary()
# Compile the model
model.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
# Train the model
model.fit(train_images, train_labels, epochs=5, batch_size=64, validation_data=(test_images, test_labels))
# Save the trained model to disk
model.save("mnist_cnn_model.h5")
print("Model saved to disk.")
# Load the saved model
loaded_model = models.load_model("mnist_cnn_model.h5")
print("Model loaded from disk.")
# Evaluate the loaded model
test_loss, test_accuracy = loaded_model.evaluate(test_images, test_labels)
print(f"Test Accuracy: {test_accuracy}")