0% found this document useful (0 votes)
14 views5 pages

Hand Written

Uploaded by

Shambavi M.A
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views5 pages

Hand Written

Uploaded by

Shambavi M.A
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

hand-written

September 2, 2024

[1]: import keras


from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras import backend as K

# the data, split between train and test sets


(x_train, y_train), (x_test, y_test) = mnist.load_data()

print(x_train.shape, y_train.shape)

(60000, 28, 28) (60000,)

[2]: x_train = x_train.reshape(x_train.shape[0], 28, 28, 1)


x_test = x_test.reshape(x_test.shape[0], 28, 28, 1)
input_shape = (28, 28, 1)
batch_size = 128
num_classes = 10
epochs = 10

# convert class vectors to binary class matrices


y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)

x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
print('x_train shape:', x_train.shape)
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')

x_train shape: (60000, 28, 28, 1)


60000 train samples
10000 test samples

1
[3]: batch_size = 128
num_classes = 10
epochs = 10

model = Sequential()
model.add(Conv2D(32, kernel_size=(3,␣
↪3),activation='relu',input_shape=input_shape))

model.add(Conv2D(64, (3, 3), activation='relu'))


model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(256, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(num_classes, activation='softmax'))

model.compile(loss=keras.losses.categorical_crossentropy,optimizer=keras.
↪optimizers.Adadelta(),metrics=['accuracy'])

[4]: hist = model.fit(x_train,␣


↪y_train,batch_size=batch_size,epochs=epochs,verbose=1,validation_data=(x_test,␣

↪y_test))

print("The model has successfully trained")

model.save('mnist.h5')
print("Saving the model as mnist.h5")

Epoch 1/10
469/469 [==============================] - 179s 377ms/step - loss: 2.2703 -
accuracy: 0.1565 - val_loss: 2.2130 - val_accuracy: 0.3143
Epoch 2/10
469/469 [==============================] - 168s 359ms/step - loss: 2.1812 -
accuracy: 0.2974 - val_loss: 2.1024 - val_accuracy: 0.5759
Epoch 3/10
469/469 [==============================] - 164s 351ms/step - loss: 2.0640 -
accuracy: 0.4385 - val_loss: 1.9522 - val_accuracy: 0.6809
Epoch 4/10
469/469 [==============================] - 160s 341ms/step - loss: 1.9062 -
accuracy: 0.5353 - val_loss: 1.7496 - val_accuracy: 0.7299
Epoch 5/10
469/469 [==============================] - 177s 378ms/step - loss: 1.7020 -
accuracy: 0.6000 - val_loss: 1.5032 - val_accuracy: 0.7661
Epoch 6/10
469/469 [==============================] - 171s 363ms/step - loss: 1.4795 -
accuracy: 0.6421 - val_loss: 1.2504 - val_accuracy: 0.7886
Epoch 7/10
469/469 [==============================] - 182s 388ms/step - loss: 1.2751 -
accuracy: 0.6701 - val_loss: 1.0358 - val_accuracy: 0.8079

2
Epoch 8/10
469/469 [==============================] - 163s 348ms/step - loss: 1.1103 -
accuracy: 0.6978 - val_loss: 0.8739 - val_accuracy: 0.8236
Epoch 9/10
469/469 [==============================] - 164s 349ms/step - loss: 0.9877 -
accuracy: 0.7176 - val_loss: 0.7580 - val_accuracy: 0.8350
Epoch 10/10
469/469 [==============================] - 164s 351ms/step - loss: 0.8941 -
accuracy: 0.7386 - val_loss: 0.6750 - val_accuracy: 0.8457
The model has successfully trained
C:\Users\nasvi\anaconda3\Lib\site-packages\keras\src\engine\training.py:3079:
UserWarning: You are saving your model as an HDF5 file via `model.save()`. This
file format is considered legacy. We recommend using instead the native Keras
format, e.g. `model.save('my_model.keras')`.
saving_api.save_model(
Saving the model as mnist.h5

[5]: from keras.models import load_model


from tkinter import *
import tkinter as tk
import win32gui
from PIL import ImageGrab, Image
import numpy as np

model = load_model('mnist.h5')

def predict_digit(img):
#resize image to 28x28 pixels
img = img.resize((28,28))
#convert rgb to grayscale
img = img.convert('L')
img = np.array(img)
#reshaping to support our model input and normalizing
img = img.reshape(1,28,28,1)
img = img/255.0
#predicting the class
res = model.predict([img])[0]
return np.argmax(res), max(res)

class App(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)

self.x = self.y = 0

# Creating elements

3
self.canvas = tk.Canvas(self, width=300, height=300, bg = "white",␣
↪cursor="cross")
self.label = tk.Label(self, text="Thinking..", font=("Helvetica", 48))
self.classify_btn = tk.Button(self, text = "Recognise", command = ␣
↪ self.classify_handwriting)
self.button_clear = tk.Button(self, text = "Clear", command = self.
↪clear_all)

# Grid structure
self.canvas.grid(row=0, column=0, pady=2, sticky=W, )
self.label.grid(row=0, column=1,pady=2, padx=2)
self.classify_btn.grid(row=1, column=1, pady=2, padx=2)
self.button_clear.grid(row=1, column=0, pady=2)

#self.canvas.bind("<Motion>", self.start_pos)
self.canvas.bind("<B1-Motion>", self.draw_lines)

def clear_all(self):
self.canvas.delete("all")

def classify_handwriting(self):
HWND = self.canvas.winfo_id() # get the handle of the canvas
rect = win32gui.GetWindowRect(HWND) # get the coordinate of the canvas
im = ImageGrab.grab(rect)

digit, acc = predict_digit(im)


self.label.configure(text= str(digit)+', '+ str(int(acc*100))+'%')

def draw_lines(self, event):


self.x = event.x
self.y = event.y
r=8
self.canvas.create_oval(self.x-r, self.y-r, self.x + r, self.y + r,␣
↪fill='black')

app = App()
mainloop()

1/1 [==============================] - 1s 1s/step


1/1 [==============================] - 0s 41ms/step
1/1 [==============================] - 0s 44ms/step
1/1 [==============================] - 0s 47ms/step
1/1 [==============================] - 0s 45ms/step
1/1 [==============================] - 0s 34ms/step
1/1 [==============================] - 0s 35ms/step
1/1 [==============================] - 0s 38ms/step
1/1 [==============================] - 0s 23ms/step

4
1/1 [==============================] - 0s 35ms/step
1/1 [==============================] - 0s 38ms/step
1/1 [==============================] - 0s 36ms/step

[ ]:

[ ]:

[ ]:

[ ]:

[ ]:

You might also like