埃尔法哥哥■卷积神经网络使用Python的手写数字识别( 二 )


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'])

埃尔法哥哥■卷积神经网络使用Python的手写数字识别
本文插图

4、训练模型
Keras的model.fit()函数将开始对模型的训练 。 它获取训练数据、验证数据、周期和批大小 。
训练模型需要一些时间 。 在培训之后 , 我们将权重和模型定义保存在“ mnist.h5”文件中 。
hist = model.fit(x_train, y_train,batch_size=batch_size,epochs=epochs,verbose=1,validation_data=http://news.hoteastday.com/a/(x_test, y_test))
print("The model has successfully trained")
model.save('mnist.h5')
print("Saving the model as mnist.h5")
5、评估模型
我们的数据集中有10,000张图像 , 这些图像将用于评估模型的效果 。 测试数据不参与数据的训练 , 因此 , 这是我们模型的新数据 。 MNIST数据集平衡良好 , 因此我们可以获得约99%的准确性 。
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
6、创建GUI来预测数字
现在 , 对于GUI , 我们创建了一个新文件 , 在其中创建了一个交互式窗口以在对话框中绘制数字 , 并使用按钮可以识别数字 。 Tkinter库位于Python标准库中 。 我们创建了一个函数predict_digit() , 将图像作为输入 , 然后使用经过训练的模型来预测数字 。
然后 , 我们创建App类 , 他负责为我们的应用构建GUI 。 我们创建一个对话框 , 在其中可以通过捕获鼠标事件进行绘制 , 并使用一个按钮来触发predict_digit()函数并显示结果 。
以下是完整的gui_digit_recognizer.py文件的代码:
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
self.canvas = tk.Canvas(self, width=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)


推荐阅读