为什么我的神经网络在应用于MNIST手绘图像时预测正确,但在应用于我自己手绘的图像时预测错误?

背景:

我正在尝试创建一个基本的神经网络来识别使用MNIST数据集的手绘图像。我在训练和预测MNIST数据时已经能够正常工作。

目标:

我希望开始将模型应用于非MNIST图像(即我自己创建的手绘图像)。

问题:

我对自己创建的所有手绘图像的预测结果都是错误的(这很奇怪,因为对MNIST图像的预测准确率为95%)。

代码:

import tensorflow as tfimport matplotlib.pyplot as pltimport numpy as npimport cv2mnist = 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 datasetindex_of_mnist_img = 0predictionsA = 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 imageindex_of_mnist_img = 0plt.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 imageplt.imshow(img, cmap = plt.cm.binary)

4_inverted

当我反转图像后,我从你上面训练的神经网络中得到了正确的预测。

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

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注