背景:
我正在尝试创建一个基本的神经网络来识别使用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()
然而,如果我制作一个手写数字的示例,并按你的方式读取它,我看到的是一个反转的图像。
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)
你可以通过在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)
当我反转图像后,我从你上面训练的神经网络中得到了正确的预测。
predictionsB = model.predict(img)print(np.argmax(predictionsB[0]))
4