层 "global_average_pooling1d" 的输入 0 与层不兼容:预期 ndim=3,发现 ndim=2。已收到完整形状:(None, 16)

Input 0 of layer "global_average_pooling1d" is incompatible with the layer: expected ndim=3, found ndim=2. Full shape received: (None, 16)

刚开始学习Tensorflow,报错了。我看了一个Neural Network Tutorial of Tech with Tim。我完成了这一集,最后遇到了一个问题。我无法预测价值。当我尝试时出现此错误:

Traceback (most recent call last):
  File "C:/Users/havil/Documents/GitHub/Python/Machine-Learning-Tutorial/Neural Network Tutorial/Tutorial 2.py", line 56, in <module>
    predict = model.predict([test_review])
  File "C:\Users\havil\anaconda3\envs\tf_3.7\lib\site-packages\keras\utils\traceback_utils.py", line 67, in error_handler
    raise e.with_traceback(filtered_tb) from None
  File "C:\Users\havil\anaconda3\envs\tf_3.7\lib\site-packages\tensorflow\python\framework\func_graph.py", line 1147, in autograph_handler
    raise e.ag_error_metadata.to_exception(e)
ValueError: in user code:

    File "C:\Users\havil\anaconda3\envs\tf_3.7\lib\site-packages\keras\engine\training.py", line 1801, in predict_function  *
        return step_function(self, iterator)
    File "C:\Users\havil\anaconda3\envs\tf_3.7\lib\site-packages\keras\engine\training.py", line 1790, in step_function  **
        outputs = model.distribute_strategy.run(run_step, args=(data,))
    File "C:\Users\havil\anaconda3\envs\tf_3.7\lib\site-packages\keras\engine\training.py", line 1783, in run_step  **
        outputs = model.predict_step(data)
    File "C:\Users\havil\anaconda3\envs\tf_3.7\lib\site-packages\keras\engine\training.py", line 1751, in predict_step
        return self(x, training=False)
    File "C:\Users\havil\anaconda3\envs\tf_3.7\lib\site-packages\keras\utils\traceback_utils.py", line 67, in error_handler
        raise e.with_traceback(filtered_tb) from None
    File "C:\Users\havil\anaconda3\envs\tf_3.7\lib\site-packages\keras\engine\input_spec.py", line 214, in assert_input_compatibility
        raise ValueError(f'Input {input_index} of layer "{layer_name}" '

    ValueError: Exception encountered when calling layer "sequential" (type Sequential).
    
    Input 0 of layer "global_average_pooling1d" is incompatible with the layer: expected ndim=3, found ndim=2. Full shape received: (None, 16)
    
    Call arguments received:
      • inputs=('tf.Tensor(shape=(None,), dtype=int32)',)
      • training=False
      • mask=None

我的整个代码如下所示:

    import tensorflow as tf
    from tensorflow import keras
    import numpy as np
    
    data = keras.datasets.imdb
    
    (train_data, train_labels), (test_data, test_labels) = data.load_data(num_words=10000)
    
    print(train_data[0])
    
    # decode Data
    word_index = data.get_word_index()
    
    word_index = {key: (value+3) for key, value in word_index.items()}
    word_index["<PAD>"] = 0
    word_index["<START>"] = 1
    word_index["<UNK>"] = 2
    word_index["<UNUSED>"] = 3
    
    reverse_word_index = dict([(value, key) for (key, value) in word_index.items()])
    
    
    train_data = keras.preprocessing.sequence.pad_sequences(train_data, value=word_index["<PAD>"], padding="post", maxlen=250)
    test_data = keras.preprocessing.sequence.pad_sequences(test_data, value=word_index["<PAD>"], padding="post", maxlen=250)
    
    
    def decode_review(text):
        return " ".join([reverse_word_index.get(i, "?") for i in text])
    
    
    print(decode_review(test_data[0]))
    
    model = keras.Sequential()
    model.add(keras.layers.Embedding(10000, 16))
    model.add(keras.layers.GlobalAveragePooling1D())
    model.add(keras.layers.Dense(16, activation="relu"))
    model.add(keras.layers.Dense(1, activation="sigmoid"))
    
    model.summary()
    
    model.compile(optimizer="adam", loss="binary_crossentropy", metrics=["accuracy"])
    
    x_val = train_data[:10000]
    x_train = train_data[10000:]
    
    y_val = train_labels[:10000]
    y_train = train_labels[10000:]
    
    fitModel = model.fit(x_train, y_train, epochs=40, batch_size=512, validation_data=(x_val, y_val), verbose=1)
    
    results = model.evaluate(test_data, test_labels)
    
    print(results)
    
    test_review = test_data[0]
    predict = model.predict([test_review])
    print("Review: ")
    print(decode_review(test_review))
    print("Prediction: " + str(predict[0]))
    print("Actual: " + str(test_labels[0]))
    print(results)

有人知道如何解决这个错误吗?

我有同样的问题,但我注意到预测不适用于单个输入,如果你对所有测试数据做同样的事情,它就可以正常工作

prediction = model.predict(test_data) 

for i in range(10):
    print("Review", test_data[i])
    print("Decoded: ", decode_review(test_data[i]))
    print("Actual: ", str(test_labels[i]))
    print("Predicted: ", str(prediction[i]))

它可能对你没有帮助,但我希望它能帮助你,因为我整天都在为此苦苦挣扎,真的很想知道如何解决它

我可以解决这个问题。 model.predict 不接受普通列表。我只是用 Numpy 数组替换它。

test_review = test_data[0]
prediction = model.predict(np.array([test_review]))
print("Review: " + decode_review(test_review))
print("Prediction: " + str(prediction[0]))
print("Actual: " + str(test_labels[0]))