我想我在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)
我试了一些类似问题的代码, 但没有任何工作给我。我在这里错过了什么?您的帮助将是非常感激的
当你使用的图像尺寸与训练模型的尺寸不匹配时,就会出现这个错误。你的图像的形状是(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)