【发布时间】:2019-10-30 17:47:07
【问题描述】:
背景:
我正在尝试使用 MNIST 数据集创建一个基本的神经网络来识别手绘图像。在针对 MNIST 数据进行训练/预测时,我的工作正常。
目标:
我想开始将该模型应用于非 MNIST 图像(即我自己创建的手绘图像)。
问题:
我创建的对手绘图像的每个预测最终都是不正确的(这很奇怪,因为针对 MNIST 图像的预测准确率为 95%)。
代码:
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
import cv2
mnist = tf.keras.datasets.mnist # 28x28 images of handwritten digits (0-9)
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train = tf.keras.utils.normalize(x_train, axis=1)
x_test = tf.keras.utils.normalize(x_test, axis=1)
model = tf.keras.models.Sequential()
model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(128, activation=tf.nn.relu))
model.add(tf.keras.layers.Dense(128, activation=tf.nn.relu))
model.add(tf.keras.layers.Dense(10, activation=tf.nn.softmax))
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
model.fit(x_train, y_train, epochs=3)
val_loss, val_acc = model.evaluate(x_test, y_test)
print(val_loss, val_acc)
# prediction from MNIST dataset
index_of_mnist_img = 0
predictionsA = model.predict([x_test])
print(np.argmax(predictionsA[index_of_mnist_img]))
plt.imshow(x_test[index_of_mnist_img], cmap = plt.cm.binary)
plt.show()
# prediction from my own hand-drawn image (THIS IS WHERE THINGS START GOING WRONG)
img = cv2.imread('4.png')
img = cv2.resize(img, (28,28))
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img = np.reshape(img, [1,28,28])
predictionsB = model.predict(img)
print(np.argmax(predictionsB[0]))
plt.imshow(predictionsB[0])
plt.show()
有什么想法吗?
【问题讨论】:
-
您自己测试了多少张图片?它们的格式相同吗?它们看起来和 MNIST 一样吗?
-
mnist 数据集有 60,000 个训练图像和 10,000 个测试图像。训练图像、测试图像和我自己的图像都是 28x28 像素并且是灰度的。
标签: python tensorflow machine-learning keras deep-learning