Tensorflow ValueError: 期望flatten_input具有形状:加载和处理图像的正确方法?

我尝试按照教程TensorFlow 2 初学者快速入门进行操作。确实,我成功运行了它。

然后我在Paint中创建了一张图像(7.jpg, 200×200像素)。

enter image description here

现在我想让模型尝试猜测这个数字是什么。我尝试处理图像:

import tensorflow as tfimport numpy as npmnist = 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.0model = 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'])# 教程示例中包含epochs=5,但为了运行得更快并得到更小的输出,我设置为1model.fit(x_train, y_train, epochs=1)  img_path = "7.jpg"img_raw = tf.io.read_file(img_path)img_tensor = tf.image.decode_image(img_raw)img_final = tf.image.resize(img_tensor, [28, 28])img_final = img_final / 255.0print("img_final.shape =", img_final.shape)predict = model.predict(img_final)

然后我得到了以下输出:

Train on 60000 samples                                                                                                                                60000/60000 [==============================] - 3s 52us/sample - loss: 0.3013 - accuracy: 0.9120                                                       img_final.shape = (28, 28, 3)                                                                                                                         Traceback (most recent call last):                                                                                                                      File "main.py", line 33, in <module>                                                                                                                    predict = model.predict(img_final)                                                                                                                  File "D:\user\python\tensor\venv\lib\site-packages\tensorflow_core\python\keras\engine\training.py", line 909, in predict                               use_multiprocessing=use_multiprocessing)                                                                                                            File "D:\user\python\tensor\venv\lib\site-packages\tensorflow_core\python\keras\engine\training_v2.py", line 462, in predict                            steps=steps, callbacks=callbacks, **kwargs)                                                                                                         File "D:\user\python\tensor\venv\lib\site-packages\tensorflow_core\python\keras\engine\training_v2.py", line 396, in _model_iteration                   distribution_strategy=strategy)                                                                                                                     File "D:\user\python\tensor\venv\lib\site-packages\tensorflow_core\python\keras\engine\training_v2.py", line 594, in _process_inputs                    steps=steps)                                                                                                                                        File "D:\user\python\tensor\venv\lib\site-packages\tensorflow_core\python\keras\engine\training.py", line 2472, in _standardize_user_data               exception_prefix='input')                                                                                                                           File "D:\user\python\tensor\venv\lib\site-packages\tensorflow_core\python\keras\engine\training_utils.py", line 574, in standardize_input_data          str(data_shape))                                                                                                                                  ValueError: Error when checking input: expected flatten_input to have shape (28, 28) but got array with shape (28, 3)

我添加了print("img_final.shape =", img_final.shape)来查看输入图像的形状。我看到img_final.shape = (28, 28, 3)

我知道数字3是通道数。根据文档tf.io.decode_image

注意:decode_gif返回一个4-D数组[num_frames, height, width, 3],而decode_bmp, decode_jpeg和decode_png返回3-D数组[height, width, num_channels]。

所以,我有一个3-D数组的图像,但模型期待一个形状为(28, 28)的数组作为输入。

我怎样才能将其转换为(28, 28)?我需要将其转换为单色还是进行其他处理?

更新:根据RonaldTaras的回答,我添加了转换为灰度的代码和一些打印。现在我有:

print("img_final.shape =", img_final.shape)img_final = tf.image.rgb_to_grayscale(img_final)print("grayscale img_final.shape =", img_final.shape)img_final = tf.expand_dims(img_final[:, :, :1], axis=0)print("expand_dims img_final.shape =", img_final.shape)predict = model.predict(img_final)

以及输出:

img_final.shape = (28, 28, 3)                                                                                                                         grayscale img_final.shape = (28, 28, 1)                                                                                                               expand_dims img_final.shape = (1, 28, 28, 1)Traceback (most recent call last):  File "main.py", line 42, in <module>     ...ValueError: Error when checking input: expected flatten_input to have 3 dimensions, but got array with shape (1, 28, 28, 1)

回答:

mnist数据库只有灰度图像,因此它们只有一个颜色通道。所以,是的,你需要通过将3个通道(我猜是RGB)转换为灰度来使其成为单色。你可以使用

tf.image.rgb_to_grayscale(images)

你可以查看文档以获取更多关于此的信息:tf.image.rgb_to_grayscale文档

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中创建了一个多类分类项目。该项目可以对…

发表回复

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