-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNeuralNetwork.py
More file actions
70 lines (62 loc) · 2.24 KB
/
Copy pathNeuralNetwork.py
File metadata and controls
70 lines (62 loc) · 2.24 KB
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
import os
import numpy as np
import cv2
import tensorflow as tf
import tensorflow_datasets as tfds
import matplotlib.pyplot as plt
#Data loading
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
#Data normalization
x_train = x_train/255.0
x_test = x_test/255.0
#Creating the actual model
model = tf.keras.models.Sequential()
model.add(tf.keras.layers.Flatten(input_shape=(28,28)))
model.add(tf.keras.layers.Dense(128, activation = 'relu'))
model.add(tf.keras.layers.Dense(128, activation = tf.nn.relu)) #Alternate way to use relu
model.add(tf.keras.layers.Dense(10, activation = 'softmax'))
#Training the model
model.compile(optimizer = 'adam', loss = 'sparse_categorical_crossentropy', metrics = ['accuracy'])
model.fit(x_train, y_train, epochs = 3)
#Saving and loading model
model.save('handwritten.keras')
model = tf.keras.models.load_model('handwritten.keras')
#Evaluate Model
loss, accuracy = model.evaluate(x_test, y_test)
#Test on Custom Images
image_number = 0
while os.path.isfile(f"Digit{image_number}.png"):
try:
img = cv2.imread(f"Digit{image_number}.png")[:,:,0]
img = cv2.resize(img, (28, 28), interpolation=cv2.INTER_AREA)
img = np.invert(np.array([img]))
prediction = model.predict(img)
plt.imshow(img[0], cmap = plt.cm.binary)
plt.show()
print(f"The number is probably: {np.argmax(prediction)}")
except FileNotFoundError:
print("File wasn't found")
except IndexError:
print("Index out of range")
except:
print("Unexpected error:", sys.exc_info()[0])
finally: image_number += 1
#Edge Cases
image_number = 10
while os.path.isfile(f"Digit_{image_number}.png"):
try:
img = cv2.imread(f"Digit_{image_number}.png")[:,:,0]
img = cv2.resize(img, (28, 28), interpolation=cv2.INTER_AREA)
img = np.invert(np.array([img]))
prediction = model.predict(img)
plt.imshow(img[0], cmap = plt.cm.binary)
plt.show()
print(f"The number is probably: {np.argmax(prediction)}")
except FileNotFoundError:
print("File wasn't found")
except IndexError:
print("Index out of range")
except:
print("Unexpected error:", sys.exc_info()[0])
finally: image_number += 1