![](/img/trans.png)
[英]Keras Conv1d input shape problem, Input 0 of layer conv1d is incompatible with the layer: : expected min_ndim=3, found ndim=2
[英]Keras functional api: Input is incompatible with the layer with conv1d
我有一個大型工作 model ,我想將最后一個密集層更改為卷積層(具有池化和輸出)。 但是在使用 cnn 時出現以下錯誤:
ValueError: 層 conv1d_21 的輸入 0 與層不兼容:預期 ndim=3,發現 ndim=2。 收到的完整形狀:[無,768]
這是在嘗試使用 cnn 之前最后一層的樣子:
dense = model.get_layer('NSP-Dense').output
outputs = keras.layers.Dense(len(100), activation='sigmoid')(dense)
這是使用 CNN 時的外觀以及發生錯誤的位置(在第二行中):
dense = model.get_layer('NSP-Dense').output
conv = keras.layers.Conv1D(filters=32, kernel_size=8, activation='relu')(dense)
pooling = keras.layers.MaxPooling1D(pool_size=2)(conv)
flatten = keras.layers.Flatten()(pooling)
mid_dense = keras.layers.Dense(400, activation='relu' )(flatten)
outputs = keras.layers.Dense(len(test_y[0]), activation='sigmoid')(mid_dense)
我讀過this和this之類的問題,但我的似乎是另一個問題,因為CNN不是第一層而是在網絡的中間。
NSP 密集層的 output 形狀為(無,768)。 我嘗試將轉換層中的形狀設置為input_shape =(None, 768)
或input_shape =(None, 768, 1)
,但這並沒有解決問題。 有人有想法嗎?
我根據您的代碼整理了這個示例,這似乎避免了錯誤。 這可能會讓你指向正確的方向。 請注意 Reshape 層,它本質上添加了一個大小為 1 的虛擬三維,以解決來自 Conv1D 層的問題。 我希望這有幫助。
import tensorflow as tf
myInput = tf.keras.layers.Input(shape=(2,))
myOutput = tf.keras.layers.Dense(768,name='NSP-Dense')(myInput)
model = tf.keras.models.Model(myInput,myOutput)
model.summary()
newDense = model.get_layer('NSP-Dense').output
newReshape = tf.keras.layers.Reshape((768,1), name='newReshape')(newDense)
conv = tf.keras.layers.Conv1D(filters=32, kernel_size=8, activation='relu', name='newModelConv1D' )(newReshape)
newModel = tf.keras.models.Model(myInput, conv)
newModel.summary()
import numpy as np
x_train = np.random.random((5,2)) # 5 samples
print('prediction:')
newModel.predict(x_train)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.