首页 > 解决方案 > 预测鼠标书写数字

问题描述

我想预测鼠标写的数字。我使用 TensorFlow 创建了一个模型并训练了整个数据集。

当我写一个数字并尝试预测时,它给我的答案不太准确。

请提出一些克服这个问题的方法。

源代码是:

import cv2
import numpy as np 
import matplotlib.pyplot as plt
from PIL import Image
import tensorflow as tf

def plot_digit(data):
    image = data.reshape(28, 28)
    plt.imshow(image, interpolation='nearest')
    plt.axis('off')

mnist = tf.keras.datasets.mnist

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

model = tf.keras.models.Sequential([
  tf.keras.layers.Flatten(input_shape=(28, 28)),
  tf.keras.layers.Dense(128, activation='relu'),
  tf.keras.layers.Dropout(0.2),
  tf.keras.layers.Dense(128, activation='relu'),
  tf.keras.layers.Dense(10)
])

predictions = model(x_train[:1]).numpy()
tf.nn.softmax(predictions).numpy()

loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
loss_fn(y_train[:1], predictions).numpy()

model.compile(optimizer='adam',
              loss=loss_fn,
              metrics=['accuracy'])

model.fit(x_train, y_train, epochs=10)

model.evaluate(x_test,  y_test, verbose=2)

drawing = False # true if mouse is pressed
pt1_x , pt1_y = None , None

# mouse callback function
def line_drawing(event,x,y,flags,param):
    global pt1_x,pt1_y,drawing

    if event==cv2.EVENT_LBUTTONDOWN:
        drawing=True
        pt1_x,pt1_y=x,y

    elif event==cv2.EVENT_MOUSEMOVE:
        if drawing==True:
            cv2.line(img,(pt1_x,pt1_y),(x,y),color=(255,255,255),thickness=3)
            pt1_x,pt1_y=x,y
    elif event==cv2.EVENT_LBUTTONUP:
        drawing=False
        cv2.line(img,(pt1_x,pt1_y),(x,y),color=(255,255,255),thickness=3)        


img = np.zeros((200,200), np.uint8)
cv2.namedWindow('test draw')
cv2.setMouseCallback('test draw',line_drawing)

while(1):
    cv2.imshow('test draw',img)
    if cv2.waitKey(1) & 0xFF == 27:
        break
cv2.destroyAllWindows()

img = Image.fromarray(img)
foo = img.resize((28,28),Image.ANTIALIAS)
foo = np.array(foo)/255.0
plot_digit(foo)

np.argmax(model.predict(foo.reshape(1,28,28)))

当我写 7 时,它预测 6。但是当我绘制我绘制的图形时,它显示 7。

标签: pythonopencvtensorflowmachine-learningimage-processing

解决方案


这可能是很多事情。一些想法:

1)也许是调整大小?在thickness=3a 上200,200,这变得更像是thickness=1在您调整到 后(28,28),它不再代表 MNIST 数据集。尝试可视化一些 MNIST 数据和鼠标写入的数据,看看它们是否真的相似(在(28,28))级别。

2)也许模型过拟合手写数字?考虑在你的模型中使用卷积层,我认为在这种情况下它会缓解这个问题。

3)也许是可视化?我看到您同时使用ANTIALIASnearest可视化图像。尝试删除nearest. 你仍然看到你所期望的吗?

如果您可以发布一些您绘制的图像,那将会有所帮助。


推荐阅读