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

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

当我 运行 this tutorial 中的代码时出现一些错误。我想预测一些测试数据。当我 运行 以下它起作用时:

res = model.predict(test_data[0:2], verbose=1)   # this works
[[0.25896776]
 [0.9984256 ]]

然而,当我运行下面这段代码时:

res = model.predict(test_data[0], verbose=1)     # this does not work 

它给我以下错误:

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

This是test_data[0]的形状和细节。我该如何解决这个问题?

简答:使用test_data[0:1]代替test_data[0]

长答案: Keras/TF 模型适用于 batch 输入样本。因此,当你只给他们一个输入样本时,它的形状应该仍然是 (1, sample_shape)。但是,当您将 test_data 数组切片为 test_data[0] 时,它将为您提供第一个元素,其中第一个 axis/dimension 被删除,即具有 (sample_shape,) 的形状(在这种情况下 (256,)).要解决此问题,请使用 test_data[0:1] 以保留第一个 axis/dimension(即形状为 (1, 256))。