如何将图像加载到TensorFlow中以用于模型?

我刚刚开始学习机器学习,并在使用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_dimreshapeimg[None,:,:]来实现。

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注