-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmnist.py
77 lines (55 loc) · 2.23 KB
/
mnist.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# -*- coding: utf-8 -*-
"""MNIST.ipynb
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/drive/11Llu088xOJzB5R0RZta07OniSz_992i9
"""
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import classification_report
(xtrain , ytrain) , (xtest , ytest) = tf.keras.datasets.mnist.load_data()
xtrain[1].shape
plt.imshow(xtrain[1])
plt.title(f"digit = {ytrain[1]}" )
xtrain,xtest = xtrain/255 , xtest/255
model = tf.keras.Sequential([
tf.keras.Input(shape=(28,28)),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(100,activation = 'relu'),
tf.keras.layers.Dense(50,activation = 'relu'),
tf.keras.layers.Dense(10,activation = 'softmax')
])
model.compile(optimizer = 'adam', loss = 'sparse_categorical_crossentropy', metrics = ['accuracy'])
model.fit(xtrain,ytrain,epochs = 10,verbose = 1)
test_loss, test_accuracy = model.evaluate(xtest, ytest, verbose=1)
print(f"test_loss = {test_loss}")
print(f"test_accuracy = {test_accuracy}")
#CLASSIFICATION REPORT ON TEST DATA
y_pred = model.predict(xtest)
y_pred_classes = y_pred.argmax(axis=1)
print(classification_report(ytest, y_pred_classes))
#INCORRECT PREDICTIONS ON TEST DATA
misclassified_indices = [i for i, (true, pred) in enumerate(zip(ytest, y_pred_classes)) if true != pred]
count = len(misclassified_indices)
print(f"Total misclassified_indices are {count}")
for index in misclassified_indices[:5]:
plt.imshow(xtest[index].reshape(28, 28), cmap='gray')
plt.title(f"True: {ytest[index]}, Pred: {y_pred_classes[index]}")
plt.show()
#predict the test data
plt.imshow(xtest[110])
predict = np.argmax(model.predict(xtest)[110])
print(f"Number present in the image is {predict}")
#TESTING THE MODEL ON NEW DATA
test_image = tf.keras.preprocessing.image.load_img("new_image_path")
test_image = tf.image.rgb_to_grayscale(test_image)
test_image = tf.keras.preprocessing.image.img_to_array(test_image)
test_image.shape
test_image = tf.image.resize(test_image,[28,28])
test_image = test_image.numpy().squeeze()
test_image.astype("float64")
test_image = test_image/255
plt.imshow(test_image)
v = np.argmax(model.predict(test_image.reshape(1,28,28)))
print(f"Number present in the image is {v}")