我试图用输入图像来测试训练有素的模型以进行预测,但这总是不准确的。
from __future__ import absolute_import, division, print_function
import tensorflow as tf
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(100, activation=tf.nn.relu),
tf.keras.layers.Dropout(0.10),
tf.keras.layers.Dense(10, activation=tf.nn.softmax)
])
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
history = model.fit(x_train, y_train, epochs=1)
model.evaluate(x_test, y_test)
import numpy as np
from keras.preprocessing import image
import PIL
test_image = image.load_img('Number 8_resized.jpg', target_size=(28, 28))
test_image = image.img_to_array(test_image)
test_image = np.expand_dims(test_image, axis=0)
result = model.predict(test_image.reshape(-1, 28, 28))
print("The predicited number is:")
print(np.argmax(result[0]))
我需要预处理上面的代码吗?如果可以,我该怎么办?谢谢。
答案 0 :(得分:1)
是的,您需要以与预处理和标准化训练集完全相同的方式对任何测试图像进行预处理。您可能缺少255除法。
答案 1 :(得分:0)
是的,还需要对测试图像进行预处理,就像预处理训练图像数据一样。因为模型非常基础,所以您得到了错误的预测。
尝试以下代码进行预测:
import numpy as np
from keras.preprocessing import image
import PIL
test_image = image.load_img('Number 8_resized.jpg', target_size=(28, 28))
test_image = image.img_to_array(test_image)
test_image /= 255.
result = model.predict(test_image.reshape(-1, 28, 28))
print("The predicited number is:")
print(np.argmax(result[0]))
完整的更新代码:
from __future__ import absolute_import, division, print_function
import tensorflow as tf
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(100, activation=tf.nn.relu),
tf.keras.layers.Dropout(0.10),
tf.keras.layers.Dense(10, activation=tf.nn.softmax)
])
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
history = model.fit(x_train, y_train, epochs=1)
model.evaluate(x_test, y_test)
import numpy as np
from keras.preprocessing import image
#import PIL
test_image = image.load_img('zero.png', target_size=(28, 28))
test_image = image.img_to_array(test_image)
# test_image = np.expand_dims(test_image, axis=0)
# print(test_image.shape)
test_image /= 255.
result = model.predict(test_image.reshape(-1, 28, 28))
print("The predicited number is:")
print(np.argmax(result[0]))