Deep Learning Tutorial in Google Colab in Hindi | Lecture 1 | Hand Written Digit Recognition
#deeplearning #googlecolab #keras #handwrittendigitrecognition
Code :
Install TensorFlow (if needed)
!pip install tensorflow
import tensorflow as tf
from tensorflow.keras import layers, models
import numpy as np
import matplotlib.pyplot as plt
Load the MNIST dataset
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
Normalize the data (convert pixel values from 0-255 to 0-1)
x_train, x_test = x_train / 255.0, x_test / 255.0
Create a Sequential model
model = models.Sequential([
layers.Flatten(input_shape=(28, 28)), # Flatten 28x28 images to 1D
layers.Dense(128, activation='relu'), # Add a dense layer with 128 units
layers.Dropout(0.2), # Add dropout for regularization
layers.Dense(10, activation='softmax') # Output layer for 10 classes
])
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
history = model.fit(x_train, y_train, epochs=5, validation_data=(x_test, y_test))
test_loss, test_acc = model.evaluate(x_test, y_test)
print(f'Test accuracy: {test_acc}')
Plot training & validation accuracy values
plt.plot(history.history['accuracy'])
plt.plot(history.history['val_accuracy'])
plt.title('Model accuracy')
plt.ylabel('Accuracy')
plt.xlabel('Epoch')
predictions = model.predict(x_test)
Show the first 5 test images and predictions
for i in range(5):
plt.imshow(x_test[i], cmap='gray')
plt.title(f'Predicted: {np.argmax(predictions[i])}, True: {y_test[i]}')
plt.show()
plt.legend(['Train', 'Test'], loc='upper left')
plt.show()
Plot training & validation loss values
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('Model loss')
plt.ylabel('Loss')
plt.xlabel('Epoch')
plt.legend(['Train', 'Test'], loc='upper left')
plt.show()