背景:
我正在尝试创建一个基本的神经网络来使用 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 示例图像时,我看到如下内容:
# show mnist image
index_of_mnist_img = 0
plt.imshow(x_test[index_of_mnist_img], cmap = plt.cm.binary)
plt.show()
但是,如果我制作一个手写数字示例,并像您一样读入它,我会看到一个倒置的图像。
img = cv2.imread("4.png")
img = cv2.resize(img, (28,28))
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
plt.imshow(img, cmap = plt.cm.binary)
您可以通过添加一行 cv2.bitwise_not()
使用 OpenCV 反转图像。
img = cv2.imread(r"4.png")
img = cv2.resize(img, (28,28))
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img= cv2.bitwise_not(img) # invert image
plt.imshow(img, cmap = plt.cm.binary)
当我反转图像时,我会从您在上面训练的神经网络中得到正确的预测。
predictionsB = model.predict(img)
print(np.argmax(predictionsB[0]))
4
我是一名优秀的程序员,十分优秀!