<jupyter_start><jupyter_text>Practical 6A Implementing and training of CNN on MNIST dataset<jupyter_code># Working implementation and training CNN
import numpy as np
import cv2
from keras import models
from keras import layers 
from keras import optimizers
from keras import losses
from keras import metrics
from keras.datasets import mnist
from keras.utils.np_utils import to_categorical
# Load the data
(images_train, labels_train), (images_test, labels_test) = mnist.load_data()
# Building the first CNN
# Fully connected network
# Sometimes, due to this, it may overfit the data
model = models.Sequential()
model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)))
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'))
model.add(layers.Flatten())
model.add(layers.Dense(64, activation='relu'))
# output layer
model.add(layers.Dense(10, activation='softmax'))
print(model.summary())
images_train = images_train.reshape((60000, 28, 28, 1))
images_train = images_train.astype('float32')/255
images_test = images_test.reshape((10000, 28, 28, 1))
images_test = images_test.astype('float32')/255
labels_train = to_categorical(labels_train)
labels_test = to_categorical(labels_test)
model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])
model.fit(images_train, labels_train, epochs=5, batch_size=64)
test_loss, test_accuracy = model.evaluate(images_test, labels_test)
print('Test loss = {} and accuracy = {}'.format(test_loss, test_accuracy))
# Save model for future use
model.save('mnist_cnn_model.h5')<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.12869565217391304, 'fraction_numerical': 0.03826086956521739, 'mean_word_length': 7.8061224489795915, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '536980', 'license': 'MIT', 'n_tokens_mistral': 626, 'n_tokens_neox': 583, 'n_words': 143, 'path': '6A_training_CNN_on_MNIST_data.ipynb', 'repo_name': 'reeha-parkar/deep-learning', 'size': '1725'}