dl-prac03devika
October 14, 2024
[24]: ''' Deep Learning : Practical No 3 Name:Devika Sawant Roll Number: 54 Year:
↪BE IT'''
[24]: ' Deep Learning : Practical No 3 Name:Devika Sawant Roll Number: 54 Year:BE
IT'
[2]: '''Build the Image classification model by dividing the model into following 4␣
↪stages:
1.Loading and preprocessing the image data
2.Defining the model's architecture
3.Training the model
4.Estimating the model's performance'''
[2]: "Build the Image classification model by dividing the model into following 4
stages:\n1.Loading and preprocessing the image data\n2.Defining the model's
architecture\n3.Training the model\n4.Estimating the model's performance"
[3]: import numpy as np
import pandas as pd
import random
import tensorflow as tf
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Flatten, Conv2D,Dense,MaxPooling2D
from tensorflow.keras.optimizers import SGD
from tensorflow.keras.utils import to_categorical
from tensorflow.keras.datasets import mnist
[4]: # Load the MNIST dataset
(images, labels), _ = mnist.load_data()
X = images
y = labels
1
[5]: # Loading and preprocessing the image data
(X_train, y_train),(X_test, y_test) = mnist.load_data()
[6]: print(X_train.shape)
(60000, 28, 28)
[7]: X_train[0].min(),X_train[0].max()
[7]: (0, 255)
[8]: X_train = (X_train - 0.0) / (255.0 - 0.0)
X_test = (X_test - 0.0) / (255.0 - 0.0)
X_train[0].min(), X_train[0].max()
(0.0, 1.0)
[8]: (0.0, 1.0)
[9]: def plot_digit(image, digit, plt, i):
plt.subplot(4, 5, i + 1)
plt.imshow(image, cmap=plt.get_cmap('gray'))
plt.title(f"Digit: {digit}")
plt.xticks([])
plt.yticks([])
plt.figure(figsize=(16, 10))
for i in range(20):
plot_digit(X_train[i], y_train[i], plt, i)
plt.show()
2
[10]: X_tarin = X_train.reshape((X_train.shape+ (1,)))
X_test = X_test.reshape((X_test.shape+(1,)))
[11]: y_train[0:20]
[11]: array([5, 0, 4, 1, 9, 2, 1, 3, 1, 4, 3, 5, 3, 6, 1, 7, 2, 8, 6, 9],
dtype=uint8)
[12]: # Defining the model's architecture
model = Sequential([
Conv2D(32,(3,3), activation="relu",input_shape=(28,28,1)),
MaxPooling2D((2,2)),
Flatten(),
Dense(100,activation="relu"),
Dense(10,activation="softmax")
])
[13]: optimizer = SGD(learning_rate=0.01, momentum=0.9)
model.compile(
optimizer=optimizer,
loss="sparse_categorical_crossentropy",
metrics=["accuracy"]
3
)
[14]: model.summary()
Model: "sequential"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
conv2d (Conv2D) (None, 26, 26, 32) 320
max_pooling2d (MaxPooling2D (None, 13, 13, 32) 0
)
flatten (Flatten) (None, 5408) 0
dense (Dense) (None, 100) 540900
dense_1 (Dense) (None, 10) 1010
=================================================================
Total params: 542,230
Trainable params: 542,230
Non-trainable params: 0
_________________________________________________________________
[15]: # Assuming you have X and y loaded, which represent the features and labels␣
↪respectively
# Split the data into training and validation sets (e.g., 80% train, 20%␣
↪validation)
X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2,␣
↪random_state=42)
# Now you can use X_val and y_val in model.fit
Model_log = model.fit(
X_train,
y_train,
epochs=10,
batch_size=15,
verbose=1,
validation_data=(X_val, y_val)
)
Epoch 1/10
3200/3200 [==============================] - 108s 15ms/step - loss: 3.1938 -
accuracy: 0.1095 - val_loss: 2.3031 - val_accuracy: 0.1016
Epoch 2/10
3200/3200 [==============================] - 47s 15ms/step - loss: 2.3027 -
4
accuracy: 0.1089 - val_loss: 2.3041 - val_accuracy: 0.0978
Epoch 3/10
3200/3200 [==============================] - 47s 15ms/step - loss: 2.3026 -
accuracy: 0.1108 - val_loss: 2.3037 - val_accuracy: 0.0995
Epoch 4/10
3200/3200 [==============================] - 46s 14ms/step - loss: 2.3029 -
accuracy: 0.1094 - val_loss: 2.3031 - val_accuracy: 0.1082
Epoch 5/10
3200/3200 [==============================] - 49s 15ms/step - loss: 2.3027 -
accuracy: 0.1081 - val_loss: 2.3035 - val_accuracy: 0.1102
Epoch 6/10
3200/3200 [==============================] - 49s 15ms/step - loss: 2.3027 -
accuracy: 0.1117 - val_loss: 2.3022 - val_accuracy: 0.1102
Epoch 7/10
3200/3200 [==============================] - 45s 14ms/step - loss: 2.3029 -
accuracy: 0.1086 - val_loss: 2.3033 - val_accuracy: 0.1102
Epoch 8/10
3200/3200 [==============================] - 47s 15ms/step - loss: 2.3028 -
accuracy: 0.1087 - val_loss: 2.3024 - val_accuracy: 0.1102
Epoch 9/10
3200/3200 [==============================] - 45s 14ms/step - loss: 2.3029 -
accuracy: 0.1099 - val_loss: 2.3034 - val_accuracy: 0.0981
Epoch 10/10
3200/3200 [==============================] - 49s 15ms/step - loss: 2.3027 -
accuracy: 0.1106 - val_loss: 2.3036 - val_accuracy: 0.1102
[16]: plt.figure(figsize=(16, 10))
for i in range(20):
image = random.choice(X_test).squeeze()
digit = np.argmax(model.predict(image.reshape((1, 28, 28, 1)))[0], axis=-1)
plot_digit(image, digit, plt, i)
plt.show()
1/1 [==============================] - 1s 528ms/step
1/1 [==============================] - 0s 71ms/step
1/1 [==============================] - 0s 32ms/step
1/1 [==============================] - 0s 32ms/step
1/1 [==============================] - 0s 21ms/step
1/1 [==============================] - 0s 21ms/step
1/1 [==============================] - 0s 21ms/step
1/1 [==============================] - 0s 21ms/step
1/1 [==============================] - 0s 20ms/step
1/1 [==============================] - 0s 21ms/step
1/1 [==============================] - 0s 21ms/step
1/1 [==============================] - 0s 21ms/step
1/1 [==============================] - 0s 20ms/step
1/1 [==============================] - 0s 21ms/step
1/1 [==============================] - 0s 27ms/step
5
1/1 [==============================] - 0s 20ms/step
1/1 [==============================] - 0s 21ms/step
1/1 [==============================] - 0s 21ms/step
1/1 [==============================] - 0s 36ms/step
1/1 [==============================] - 0s 20ms/step
[17]: predictions = np.argmax(model.predict(X_test),axis=-1)
accuracy_score(y_test,predictions)
313/313 [==============================] - 2s 6ms/step
[17]: 0.1135
[18]: n = random.randint(0,9999)
plt.imshow(X_test[n])
plt.show()
6
[19]: predicted_value = model.predict(X_test)
print("Handwritten number in the image is = %d" %np.argmax(predicted_value[n]))
313/313 [==============================] - 2s 6ms/step
Handwritten number in the image is = 1
[20]: # Estimating the model's performance
score = model.evaluate(X_test,y_test,verbose=0)
print('Test loss:' , score[0])
print('Testaccuracy:',score[1])
Test loss: 2.302887201309204
Testaccuracy: 0.11349999904632568
[ ]: