这里,我用激活函数relu和softmax在一个隐藏层上训练我的顺序模型。 我还仔细检查了数据集图像,然后输入相同类型的图像以通过简单的模型进行预测。但是它无法正确预测。如果准确性很高,那么为什么我得到错误的预测也无法理解。
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
x_train = x_train / 255.0
x_train = x_train.reshape(-1,28,28,1)
model =tf.keras.Sequential([
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(512,activation=tf.nn.relu),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(10,activation=tf.nn.softmax)
])
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
model.fit(x=x_train,y=y_train, epochs=40)
def input_image(filepath):
img_size = 28
# read in the image and convert to grayscale
img_array = cv2.imread(filepath, cv2.IMREAD_GRAYSCALE)
# resize image to match model's expected size
new_array = cv2.resize(img_array, (img_size, img_size))
# return the image with shaping that TF wants
return new_array.reshape(-1, img_size, img_size, 1)
#here call the input_image function which return an nested list
prediction = model.predict([input_image("/home/farhana/Desktop/image processing/code/2.png")])
print(prediction)
print(np.argmax(prediction))
答案 0 :(得分:0)
我认为问题可能在于您没有在input_image函数中规范测试数据。尝试添加一条行,在该行中,将加载的图像除以255.0,就像在训练集中的情况一样。请参见下面的代码:
def input_image(filepath):
img_size = 28
img_array = cv2.imread(filepath, cv2.IMREAD_GRAYSCALE)
new_array = cv2.resize(img_array, (img_size, img_size))
new_array = new_array / 255.0
return new_array.reshape(-1, img_size, img_size, 1)