Keras/Tensorflow预测:阵列形状的错误

pep*_*epe 6 python reshape python-3.x keras tensorflow

我在这里关注Keras CIFAR10教程.我做的唯一改变是:

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

model.save_weights('./weights.h5', overwrite=True)
Run Code Online (Sandbox Code Playgroud)

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

{"floatx": "float32", "backend": "tensorflow", "epsilon": 1e-07}
Run Code Online (Sandbox Code Playgroud)

我可以成功运行模型.

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

[... 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)
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

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

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

我还没有"image_dim_ordering": "tf"./keras/keras.json.

Oli*_*rot 6

你必须重塑输入图像具有的形状[?, 3, 32, 32],其中?是批量大小.在您的情况下,由于您有1个图像,批量大小为1,因此您可以执行以下操作:

img = np.array(img)
img = img.reshape((1, 3, 32, 32))
Run Code Online (Sandbox Code Playgroud)