我刚刚开始学习机器学习,并在使用TensorFlow 1.14。我刚刚使用内置的tensorflow.keras.datasets.mnist
数据集创建了我的第一个模型。以下是我的模型代码:
import tensorflow as tffrom tensorflow import kerasmnist = keras.datasets.mnist(x_train, y_train), (x_test, y_test) = mnist.load_data()class Stopper(keras.callbacks.Callback): def on_epoch_end(self, epoch, log={}): if log.get('acc') >= 0.99: self.model.stop_training = True print('\nReached 99% Accuracy. Stopping Training...')model = keras.Sequential([ keras.layers.Flatten(), keras.layers.Dense(1024, activation=tf.nn.relu), keras.layers.Dense(10, activation=tf.nn.softmax)])model.compile( optimizer=tf.train.AdamOptimizer(), loss='sparse_categorical_crossentropy', metrics=['accuracy'])x_train, x_test = x_train / 255, x_test / 255model.fit(x_train, y_train, epochs=10, callbacks=[Stopper()])
现在模型已经训练好了,我可以将x_test
图像输入到model.predict()
中,这一切运行正常。但我想知道如何将我自己的图像(JPG和PNG)输入到我的模型的predict()
方法中?
我查看了文档,但他们的方法对我来说会导致错误。特别是我尝试了以下方法:
img_raw = tf.read_file(<my file path>)img_tensor = tf.image.decode_image(img_raw)img_final = tf.image.resize(img_tensor, [192, 192])^^^ 这一行会抛出错误 'ValueError: 'images' contains no shape.'
请提供一个逐步指南,介绍如何将图像(JPG和PNG)加载到我的模型中进行预测。非常感谢。
回答:
from PIL import Imageimg = Image.open("image_file_path").convert('L').resize((28, 28), Image.ANTIALIAS)img = np.array(img)model.predict(img[None,:,:])
您已经用大小为(28 x 28)的图像训练了模型,因此必须将您的图像调整到相同的大小。您不能使用不同尺寸的图像。
Predict方法需要一批图像,但由于您想对单个图像进行预测,您必须为这张单个图像添加一个额外的批次维度。这可以通过expand_dim
或reshape
或img[None,:,:]
来实现。