![](/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.