添加SpatialDropout1D层报错:输入非符号张量问题求助
Hey there! Let's break down what's going wrong and how to fix it quickly.
The Root Cause of Your Error
The error pops up because you're passing an Embedding layer object directly to SpatialDropout1D, but this layer expects a symbolic tensor (the output generated by the Embedding layer, not the layer itself). Keras layers don't take other layers as inputs—they only work with the tensor outputs produced by previous layers.
Step-by-Step Solution
Let's adjust your code to use Keras's Functional API properly, which handles tensor flows correctly:
First, define an Input layer
This sets up the input shape for your model, matching your sequence lengthsent_maxlen:from keras.layers import Input # Define your input tensor with shape matching your max sequence length input_seq = Input(shape=(sent_maxlen,))Get your GloVe Embedding layer and generate its output tensor
Remove theinput_lengthparameter fromget_keras_embedding(we've already defined it in the Input layer), then pass the input tensor through the Embedding layer to get its output:emb = Glove(emb_filename) # Initialize the GloVe embedding layer (no input_length needed here) glove_emb_layer = emb.get_keras_embedding(trainable=True, name='word_embedding_layer') # Pass the input tensor through the embedding layer to get a tensor output emb_output = glove_emb_layer(input_seq)Apply SpatialDropout1D to the embedding output tensor
Now you can safely pass the tensor output from the Embedding layer toSpatialDropout1D:from keras.layers import SpatialDropout1D dropout_output = SpatialDropout1D(0.5)(emb_output)Build the rest of your model
You can now chaindropout_outputto any subsequent layers (like LSTM, Dense, etc.) and compile your model. Here's a quick example:from keras.layers import LSTM, Dense from keras.models import Model # Example: Add an LSTM layer and a classification output layer lstm_layer = LSTM(64)(dropout_output) final_output = Dense(your_num_classes, activation='softmax')(lstm_layer) # Assemble the full model model = Model(inputs=input_seq, outputs=final_output) model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
Why This Works
By using the Functional API, we're explicitly defining the flow of tensors: the Input tensor goes through the Embedding layer to produce an output tensor, which is then fed into SpatialDropout1D. This matches how Keras expects layers to interact—each layer processes a tensor and outputs a new tensor for the next layer.
内容的提问来源于stack exchange,提问作者IS92

