我想预测鼠标写的数字。我使用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。
发布于 2020-05-24 09:08:33
这可能是很多事情。一些想法:
( 1)也许是调整大小?对于thickness=3上的200,200,在调整大小为(28,28)之后,这就更像thickness=1了,(28,28)不再代表MNIST数据集。尝试可视化一些MNIST数据和鼠标编写的数据,看看它们是否真的相似(在(28,28)级别上)。
2)模型是否适合手写体数字?考虑在您的模型中使用卷积层,我认为在这种情况下它可以减轻这个问题。
3)也许是视觉化?我看到您正在使用ANTIALIAS和nearest来可视化图像。尝试删除nearest。你还能看到你想要的吗?
如果你能张贴一些图片,你的阴谋,它会有帮助。
https://stackoverflow.com/questions/61983242
复制相似问题