[英]Keras Conv1d input shape problem, Input 0 of layer conv1d is incompatible with the layer: : expected min_ndim=3, found ndim=2
[英]Error 'Input 0 is incompatible with layer conv1d_48: expected ndim=3, found ndim=2' when adding Conv1D layer
我正在嘗試構建以下模型:
model = Sequential()
model.add(Embedding(input_dim = num_top_words, output_dim = 64, input_length = input_length))
model.add(LSTM(100, activation = 'relu'))
model.add(Conv1D(64, kernel_size = 5, activation = 'relu'))
model.add(MaxPooling1D())
model.add(Dense(5, activation = 'softmax'))
model.compile(loss = 'categorical_crossentropy', optimizer = 'adam', metrics = ['accuracy'])
但是運行它時出現以下錯誤:
Input 0 is incompatible with layer conv1d_48: expected ndim=3, found ndim=2
指出以下行存在錯誤:
model.add(Conv1D(64, kernel_size = 5, activation = 'relu'))
可能是什么問題?
問題在於,當前LSTM
層的輸出形狀為(None, 100)
,但是,正如錯誤所暗示的,像LSTM
層一樣的Conv1D
層希望輸入3D形狀(None, n_steps, n_features)
。 因此,解決此問題的一種方法是將return_sequences=True
傳遞到LSTM層以獲取每個時間步的輸出,因此其輸出將為3D:
model.add(LSTM(100, activation = 'relu', return_sequences=True))
或者,您可以將Conv1D
和MaxPooling1D
層放在LSTM
層之前(這可能比當前體系結構更好,因為Conv1D
加上池化層的一種用法是減小LSTM層的輸入維,從而降低計算復雜度):
model.add(Conv1D(64, kernel_size = 5, activation = 'relu'))
model.add(MaxPooling1D())
model.add(LSTM(100, activation = 'relu'))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.