仅在预测时出现 Keras 形状问题

Keras shape issue only when predicting

所以我在这里不知所措。我训练了我的模型,一切正常;但是当我尝试使用预测方法时,出现以下错误:

ValueError: Error when checking input: expected dense_1_input to have shape (64,) but got array with shape (1,)

我觉得很奇怪,因为我给出的输入是 (64,),我什至在 cli 中返回了这样的形状

    print(type(test_x[0]))
    print(test_x[0].shape)

哪个returns

<class 'numpy.ndarray'>
(64,)

在我看来,当我使用

时应该可以使用
print(str(np.argmax(model.predict(test_x[0]))))

谁能指出我做错了什么?

完整的错误输出:

File "/home/drbunsen/Downloads/code/neural/random/neuralPlaying.py", line 115, in
main()
File "/home/drbunsen/Downloads/code/neural/random/neuralPlaying.py", line 110, in main
print(np.argmax(model.predict(train_x[0])))
File "/home/drbunsen/.local/lib/python3.7/site-packages/keras/engine/training.py", line 1441, in predict
x, _, _ = self._standardize_user_data(x)
File "/home/drbunsen/.local/lib/python3.7/site-packages/keras/engine/training.py", line 579, in _standardize_user_data
exception_prefix='input')
File "/home/drbunsen/.local/lib/python3.7/site-packages/keras/engine/training_utils.py", line 145, in standardize_input_data
str(data_shape))
ValueError: Error when checking input: expected dense_1_input to have shape (64,) but got array with shape (1,)

模型期望输入形状为:(number_of_samples,number_of_features)

如果你想传递 1 个样本并且每个样本有 64 个特征,那么输入的形状应该是这样的:(1,64).
由于您已经使用 64 个特征训练了模型,因此输入始终应具有 (N,64) 形状。

如果您传递一个形状为 (64,) 的数组,模型会将其视为具有 1 个特征的 64 个样本,这与预期的 64 个特征不兼容。

要解决您的问题,请输入以下内容:

print(str(np.argmax(model.predict(test_x[0].reshape(1,-1))))) # add first dimension