Last active
November 12, 2023 15:54
-
-
Save Mynuddin-dev/027e1b3dbae4c1696e63aaaa12905b65 to your computer and use it in GitHub Desktop.
LeNet5 handwritten digit recognition
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from keras.datasets import mnist | |
from keras.utils import to_categorical | |
from keras.layers import * | |
from keras.models import * | |
import numpy as np | |
## Load and preprocess the MNIST dataset | |
(train_images , train_labels) , (validation_images , validation_labels) = mnist.load_data() | |
## reshaping the images and normalizing the pixel values to be between 0 and 1. | |
train_images = train_images.reshape((60000, 28, 28, 1)).astype('float32') / 255 | |
validation_images = validation_images.reshape((10000, 28, 28, 1)).astype('float32') / 255 | |
train_labels = to_categorical(train_labels) | |
validation_labels = to_categorical(validation_labels) | |
# Define The LeNet-5 Architechture | |
model = Sequential() | |
#Layer 1 | |
#Conv Layer 1 | |
model.add(Conv2D(filters = 6, | |
kernel_size = 5, | |
strides = 1, | |
activation = 'relu', | |
input_shape = (28,28,1))) | |
#Pooling layer 1 | |
model.add(MaxPooling2D(pool_size = 2, strides = 2)) | |
#Layer 2 | |
#Conv Layer 2 | |
model.add(Conv2D(filters = 16, | |
kernel_size = 5, | |
strides = 1, | |
activation = 'relu', | |
input_shape = (14,14,6))) | |
#Pooling Layer 2 | |
model.add(MaxPooling2D(pool_size = 2, strides = 2)) | |
#Flatten | |
model.add(Flatten()) | |
#Layer 3 | |
#Fully connected layer 1 | |
model.add(Dense(units = 120, activation = 'relu')) | |
#Layer 4 | |
#Fully connected layer 2 | |
model.add(Dense(units = 84, activation = 'relu')) | |
model.add(Dropout(0.2)) | |
#Layer 5 | |
#Output Layer | |
model.add(Dense(units = 10, activation = 'softmax')) | |
# Compile the model | |
model.compile(optimizer = 'adam', loss = 'categorical_crossentropy', metrics = ['accuracy']) | |
print(model.summary()) | |
# Train the model | |
model.fit(train_images,train_labels , batch_size=128, epochs=20, verbose=1, validation_data=(validation_images, validation_labels)) | |
# Prediction for validation_images | |
y_pred = model.predict(validation_images) | |
#Converting one hot vectors to labels | |
labels = np.argmax(y_pred, axis = 1) | |
print(labels) | |
## Evaluate the model | |
Loss , Accuracy = model.evaluate(validation_images, validation_labels) | |
print(f"Loss :{Loss} , Accuracy : {Accuracy * 100:.3f}%") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment