首页 > 解决方案 > 为什么我的神经网络预测在应用于 MNIST 手绘图像时是正确的,但在应用于我自己的手绘图像时却不正确?

问题描述

背景:

我正在尝试创建一个基本的神经网络来识别使用 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()

有任何想法吗?

标签: pythontensorflowmachine-learningkerasdeep-learning

解决方案


我相信您需要为新(手绘)图像反转颜色图。

当我查看 MNIST 示例图像时,我看到如下内容:

# show mnist image
index_of_mnist_img = 0
plt.imshow(x_test[index_of_mnist_img], cmap = plt.cm.binary)
plt.show()

7

但是,如果我制作一个手写数字示例,并按照您的方式读入,我会看到一个倒置的图像。

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)

4

您可以通过添加一行来使用 OpenCV 反转图像,cv2.bitwise_not().

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)

4_倒置

当我反转图像时,我会从您在上面训练的神经网络中得到正确的预测。

predictionsB = model.predict(img)
print(np.argmax(predictionsB[0]))
4

推荐阅读