我已经用Anaconda笔记本完成了这个基本项目。一切运行良好,但是用我自己的数字图片进行的每个预测都是错误的。我正在使用MNIST设置数字,并且尝试用黑色背景和白色绘画来绘制自己的数字。但是每个预测都是错误的。可以看看代码中缺少什么吗?
enter code here
# Install TensorFlow
import tensorflow as tf
# Import matplotlib library
import matplotlib.pyplot as plt
#Import numpy
import numpy as np
#import cv
import cv2
#Dataset
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(input_shape=(28, 28)),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(10, activation='softmax')])
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
model.fit(x_train, y_train, epochs=5)
print("Evaluierung");
model.evaluate(x_test, y_test)
plt.imshow(x_train[1], cmap="gray") # Import the image
plt.show() # Plot the image
predictions = model.predict([x_train]) # Make prediction, works perfect
print(np.argmax(predictions[1])) # Print out the number, works perfect
# my own picture, black background, white color, 28 px * 28 px in size
img = cv2.imread("bild1.png", cv2.IMREAD_GRAYSCALE)
plt.imshow(img) # Import the image
plt.show() # Plot the image
cv2.imshow("image",img)
cv2.waitKey(2000)
img = img/255.0
img = img.reshape(1,28,28)
pred = model.predict_classes(img)
print("Prediction: ", pred)
每次从训练和测试数据得出的预测都是正确的,我自己的图片全都错了,没有错误代码!如果您能帮助我,那就太好了
您执行此操作的方式没有什么特别的错误。但是,我很少指出为什么会得到这些结果。
有时,当您使用图像加载库加载图像时,它们的值将被裁剪,而不是介于0-255之间。因此,规范化时,请使用类似的方法,
img = img - np.min(img)
img = img/np.max(img)
对原始的60000个样本进行训练模型,并期望它可以在现实世界的数据上工作……那是行不通的。例如,与您的模型训练数据相比,您将具有以下差异。
因此,如果您希望模型表现更好,请使用数据扩充
非常感谢您的回答
我像您告诉我的那样更改了用于规范化的代码,但没有任何改变。
然后,我在Google中查找了黑色背景下的一些手写数字(在mnist数据库之外),我调整了大小并把它们用作预测->使我惊讶的是,每张照片都被正确识别了!所以我想的问题不是我的代码,而是我画自己的手写数字的方式。我使用photoshop,新的灰度模板,黑色背景,白色绘画将其调整为28 * 28像素。但是我自己的绘画没有被正确识别-没有错误代码,而仅仅是一个错误的预测。你知道我的画怎么了吗?再次感谢!