【问题标题】:predicting a single image in keras (dimension problem)在 keras 中预测单个图像(维度问题)
【发布时间】:2020-08-29 16:52:12
【问题描述】:

我认为 Keras 存在一个常见的维度问题。我尝试使用预训练模型('model.h5')来 预测单个测试图像('test.jpg')的类别。

使用以下代码:

model = load_model('model.h5')
model.summary()
# load dataset


# evaluate the model
score = model.evaluate(X, Y, verbose=0)
print("%s: %.2f%%" % (model.metrics_names[1], score[1]*100)) 

我正在获取有关模型的以下信息:

现在,跑完之后,

img = cv2.imread('test.jpg')

model.predict(img)

我收到错误消息:

---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

<ipython-input-43-c2dfe8703a1b> in <module>()
      1 img = cv2.imread('test.jpg')
      2 
----> 3 model.predict(img)

2 frames

/usr/local/lib/python3.6/dist-packages/keras/engine/training.py in predict(self, x, batch_size, verbose, steps, callbacks, max_queue_size, workers, use_multiprocessing)
   1439 
   1440         # Case 2: Symbolic tensors or Numpy array-like.
-> 1441         x, _, _ = self._standardize_user_data(x)
   1442         if self.stateful:
   1443             if x[0].shape[0] > batch_size and x[0].shape[0] % batch_size != 0:

/usr/local/lib/python3.6/dist-packages/keras/engine/training.py in _standardize_user_data(self, x, y, sample_weight, class_weight, check_array_lengths, batch_size)
    577             feed_input_shapes,
    578             check_batch_axis=False,  # Don't enforce the batch size.
--> 579             exception_prefix='input')
    580 
    581         if y is not None:

/usr/local/lib/python3.6/dist-packages/keras/engine/training_utils.py in standardize_input_data(data, names, shapes, check_batch_axis, exception_prefix)
    133                         ': expected ' + names[i] + ' to have ' +
    134                         str(len(shape)) + ' dimensions, but got array '
--> 135                         'with shape ' + str(data_shape))
    136                 if not check_batch_axis:
    137                     data_shape = data_shape[1:]

ValueError: Error when checking input: expected input_1 to have 4 dimensions, but got array with shape (194, 259, 3)

我尝试了一些类似问题的代码,但对我没有任何帮助。我在这里想念什么?非常感谢您的帮助!

【问题讨论】:

  • 它看起来像你的 model.predict 函数需要 4 个维度,其中 3 个可能是图像通道,第 4 个维度可能是模型需要预测的图像数量

标签: python image-processing keras deep-learning prediction


【解决方案1】:

当您使用的图像尺寸与用于训练模型的尺寸不匹配时,就会出现此错误。
您的图像的形状是 (194, 259, 3), 但该模型需要这样的东西:(1, 194, 259, 3),因为您使用的是单个样本。您可以通过numpy.expand_dims() 获得所需的尺寸。

img = cv2.imread('test.jpg')
img = np.expand_dims(img, axis=0)
model.predict(img)

【讨论】:

  • np.expand_dims() 应该在阅读图像后出现。编辑:我已经编辑了答案。
  • 非常感谢。结果,我得到了很长的数组列表。这是“预测”吗?
  • @Thesinus 使用 model.predict_classes(img) 作为类/类别输出。或者,您可以使用np.argmax
猜你喜欢
  • 2017-08-18
  • 2020-05-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-09
相关资源
最近更新 更多