Keras/Tensorflow 预测:数组形状错误

Keras/Tensorflow predict: error in array shape

我正在关注 Keras CIFAR10 tutorial here。 我所做的唯一更改是:

[a] 添加到教程文件的末尾

model.save_weights('./weights.h5', overwrite=True)

[b] 将 ~./keras/keras.json 更改为

{"floatx": "float32", "backend": "tensorflow", "epsilon": 1e-07}

我可以运行模型成功。

然后我想针对经过训练的模型测试单个图像。我的代码:

[... similar to tutorial file with model being created and compiled...]
...
model = Sequential()
...
model.compile()

model.load_weights('./ddx_weights.h5')

img = cv2.imread('car.jpeg', -1) # this is is a 32x32 RGB image
img = np.array(img)
y_pred = model.predict_classes(img, 1)
print(y_pred)

我收到这个错误:

ValueError: Cannot feed value of shape (1, 32, 3) for Tensor 'convolution2d_input_1:0', which has shape '(?, 3, 32, 32)'

为要测试的单个图像重塑输入数据的正确方法是什么?

没有./keras/keras.json中添加"image_dim_ordering": "tf"

您必须重塑输入图像以具有 [?, 3, 32, 32] 的形状,其中 ? 是批量大小。在你的例子中,因为你有 1 张图片,批量大小是 1,所以你可以这样做:

img = np.array(img)
img = img.reshape((1, 3, 32, 32))

我现在正在处理 cifar10 数据,我发现简单的 reshape 不起作用,应该改用 numpy.transpose。