Home > Software design >  Input 0 of layer "global_average_pooling1d" is incompatible with the layer: expected ndim=
Input 0 of layer "global_average_pooling1d" is incompatible with the layer: expected ndim=

Time:05-10

I just started to learn Tensorflow and got an error. I watched a Neural Network Tutorial of Tech with Tim. I finished this episode and got a problem to the end. I couldn't predict the value. when i try it this error shows up:

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

My whole code looks like this:

    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)

Does anyone have an idea how to fix this error?

CodePudding user response:

I have same issue, but i noticed that prediction does not work just for a single input, if you do the same with with all of the test data it works fine

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]))

It probably won't help you but i hope it does because i'm struggling with this all day long and really want to know how to fix it

  • Related