|
| 1 | +""" |
| 2 | +This file describes implementation of a basic CNN made using Tensorflow and trained and tested with MNIST dataset. |
| 3 | +Initially we have all the required dependencies imported. |
| 4 | +
|
| 5 | +create_model() describes the CNN architecture used for training a model |
| 6 | +
|
| 7 | +plot() is used to plot the images along with their predicted/true labels. |
| 8 | +
|
| 9 | +""" |
| 10 | +import numpy as np |
| 11 | +import tensorflow as tf |
| 12 | +import matplotlib.pyplot as plt |
| 13 | +import cv2 |
| 14 | + |
| 15 | +# CNN Model |
| 16 | +def create_model(): |
| 17 | + model = tf.keras.models.Sequential([ |
| 18 | + tf.keras.layers.Conv2D(16, (3,3), activation="relu", input_shape=(28,28,1)), |
| 19 | + tf.keras.layers.MaxPooling2D((2,2)), |
| 20 | + tf.keras.layers.Conv2D(32, (2,2), activation="relu"), |
| 21 | + tf.keras.layers.MaxPooling2D((2,2)), |
| 22 | + tf.keras.layers.Flatten(), |
| 23 | + tf.keras.layers.Dense(64, activation="relu"), |
| 24 | + tf.keras.layers.Dropout(0.3), |
| 25 | + tf.keras.layers.Dense(10, activation="softmax") |
| 26 | + ]) |
| 27 | + return model |
| 28 | + |
| 29 | +# Plot images with labels |
| 30 | +def plot(subset_x, subset_y): |
| 31 | + for i in range(len(subset_y)): |
| 32 | + plt.figure(figsize=(10,20)) |
| 33 | + ax = plt.subplot(len(subset_y)/2,2,i+1) |
| 34 | + img = subset_x[i] |
| 35 | + ax.imshow(img) |
| 36 | + plt.show() |
| 37 | + print("LABEL : ",subset_y[i]) |
| 38 | + print() |
| 39 | + |
| 40 | +# Load Mnist dataset from tensorflow datasets |
| 41 | +(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data() |
| 42 | + |
| 43 | +# Normalize the pixel values and convert the lables to one-hot vectors |
| 44 | +x_train = x_train/255. |
| 45 | +x_test = x_test/255. |
| 46 | +x_train = x_train.reshape((-1,28,28,1)) |
| 47 | +x_test = x_test.reshape((-1,28,28,1)) |
| 48 | +y_train = tf.one_hot(y_train, depth=10) |
| 49 | +y_test = tf.one_hot(y_test, depth=10) |
| 50 | + |
| 51 | +# Create and compile the Model |
| 52 | +my_model = create_model() |
| 53 | +my_model.compile(optimizer = tf.keras.optimizers.Adam(lr=0.001), loss="categorical_crossentropy", metrics=["accuracy"]) |
| 54 | + |
| 55 | +# Fit the created model and store the information for plotting of loss and accuracy curves |
| 56 | +history = my_model.fit(x_train, y_train, validation_split=0.1, epochs=5, batch_size=32, shuffle=True, verbose=1) |
| 57 | + |
| 58 | +# Evaluate the model using the test data |
| 59 | +loss, acc = my_model.evaluate(x_test, y_test) |
| 60 | + |
| 61 | +# Make Predictions |
| 62 | +y_predictions = my_model.predict_classes(x_test) |
| 63 | + |
| 64 | +subset_x = x_test[0:10] |
| 65 | +subset_y = y_predictions[0:10] |
| 66 | + |
| 67 | +# Used to plot the predicted labels along with images. |
| 68 | +plot(subset_x, subset_y) |
| 69 | + |
0 commit comments