如何使用训练有素的模型编写 keras 代码以读取我自己的图片?

新手上路,请多包涵

我使用 minst 来训练我自己的数字读取模型,但是当我尝试上传自己的图片进行预测时,它告诉我一个错误说“ValueError: Input 0 of layer dense_3 is incompatible with the layer: expected axis -1 of input shape 的值为 784 但接收到的输入的形状为 [None, 84]”(我的模型训练正确,在 minst 中预测图片成功。这是我的代码:

 import numpy as np
from keras.applications.imagenet_utils import decode_predictions
from keras.preprocessing import image
from keras.applications import *
import glob

import os

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

img = []
x = []

images = image.load_img("/content/gdrive/My Drive/Colab Notebooks/num.png", target_size=(28, 28))
x = image.img_to_array(images)
x = np.expand_dims(x, axis=1)
img.append(x)

print(len(x))
x = np.concatenate([x for x in img])

model = tf.keras.models.load_model('num_reader.model')
y = model.predict(x)
print('Predicted:', decode_predictions(y, top=3))

这是我的错误:

 28    #This is printed by "print(len(x))"
WARNING:tensorflow:Model was constructed with shape (None, 28, 28) for input Tensor("flatten_1_input_3:0", shape=(None, 28, 28), dtype=float32), but it was called on an input with incompatible shape (None, 1, 28, 3).
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-18-cd1af7600aac> in <module>()
     27
     28 model = tf.keras.models.load_model('num_reader.model')
---> 29 y = model.predict(x)
     30 print('Predicted:', decode_predictions(y, top=3))

10 frames
/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs)
    971           except Exception as e:  # pylint:disable=broad-except
    972             if hasattr(e, "ag_error_metadata"):
--> 973               raise e.ag_error_metadata.to_exception(e)
    974             else:
    975               raise

ValueError: in user code:

    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py:1462 predict_function  *
        return step_function(self, iterator)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py:1452 step_function  **
        outputs = model.distribute_strategy.run(run_step, args=(data,))
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/distribute/distribute_lib.py:1211 run
        return self._extended.call_for_each_replica(fn, args=args, kwargs=kwargs)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/distribute/distribute_lib.py:2585 call_for_each_replica
        return self._call_for_each_replica(fn, args, kwargs)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/distribute/distribute_lib.py:2945 _call_for_each_replica
        return fn(*args, **kwargs)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py:1445 run_step  **
        outputs = model.predict_step(data)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py:1418 predict_step
        return self(x, training=False)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/base_layer.py:985 __call__
        outputs = call_fn(inputs, *args, **kwargs)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/sequential.py:372 call
        return super(Sequential, self).call(inputs, training=training, mask=mask)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/functional.py:386 call
        inputs, training=training, mask=mask)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/functional.py:508 _run_internal_graph
        outputs = node.layer(*args, **kwargs)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/base_layer.py:976 __call__
        self.name)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/input_spec.py:216 assert_input_compatibility
        ' but received input with shape ' + str(shape))

    ValueError: Input 0 of layer dense_3 is incompatible with the layer: expected axis -1 of input shape to have value 784 but received input with shape [None, 84]

Minst 是一张 28x28 的图片,所以这段代码使用的是 28x28 图片。我的开发环境是:“Google Colab”和“Juypter Notebook”,这个错误我已经尝试了这两个环境,但仍然出现这个错误。有人可以帮忙吗? import tensorflow as tf # 深度学习库。张量只是多维数组

mnist = tf.keras.datasets.mnist  # mnist is a dataset of 28x28 images of handwritten digits and their labels
(x_train, y_train),(x_test, y_test) = mnist.load_data()  # unpacks images to x_train/x_test and labels to y_train/y_test

x_train = tf.keras.utils.normalize(x_train, axis=1)  # scales data between 0 and 1
x_test = tf.keras.utils.normalize(x_test, axis=1)  # scales data between 0 and 1

model = tf.keras.models.Sequential()  # a basic feed-forward model
model.add(tf.keras.layers.Flatten())  # takes our 28x28 and makes it 1x784
model.add(tf.keras.layers.Dense(128, activation=tf.nn.relu))  # a simple fully-connected layer, 128 units, relu activation
model.add(tf.keras.layers.Dense(10, activation=tf.nn.softmax))  # our output layer. 10 units for 10 classes. Softmax for probability distribution

model.compile(optimizer='adam',  # Good default optimizer to start with
              loss='sparse_categorical_crossentropy',  # how will we calculate our "error." Neural network aims to minimize loss.
              metrics=['accuracy'])  # what to track

model.fit(x_train, y_train, epochs=10)  # train the model

val_loss, val_acc = model.evaluate(x_test, y_test)  # evaluate the out of sample data with model
print(val_loss)  # model's loss (error)
print(val_acc)  # model's accuracy

这是num.png的图片

原文由 Stackoverflow 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 528
1 个回答

如果不确切知道您的模型是如何构建的以及 num.png 的外观,则很难说清楚。然而,从错误消息看来你有两个错误:你正在加载 rgb 彩色图像(尽管 MNIST 并且你的模型可能是在灰度图像上训练的)因此(或者这是第二个错误)你的尺寸错误(3 for RGB 而不是灰度)。 28*3 = 84 是我解释错误消息的方式:

但收到形状为 [None, 84] 的输入

尝试 add rgb_to_grayscaleaxis=0

 import tensorflow as tf
from keras_preprocessing import image
images = image.load_img("/content/gdrive/My Drive/Colab Notebooks/num.png", target_size=(28, 28))
x = image.img_to_array(images)
x = tf.image.rgb_to_grayscale(x)
x = np.expand_dims(x, axis=0)
x = x/255.0
img.append(x)

print(len(x))
x = np.concatenate([x for x in img])

model = tf.keras.models.load_model('num_reader.model')
y = model.predict(x)
print('Predicted:', decode_predictions(y, top=3))

请注意,我添加了 x=x/255.0,因为我假设您也忘记了重新缩放到 [0,1]。我假设如果您严格遵守 MNIST ML 教程,您会在预处理过程中对图像应用重新缩放来训练模型。你也必须应用它。

更新:将 x 直接传递给 model.predict 也对我有用:

 images = image.load_img("/content/gdrive/My Drive/Colab Notebooks/num.png", target_size=(28, 28))
x = image.img_to_array(images)
x = tf.image.rgb_to_grayscale(x)
x = np.expand_dims(x, axis=0)
x = x/255.0

model = tf.keras.models.load_model('num_reader.model')
model.predict(x)

原文由 Stat Tistician 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题