ValueError:输入0与图层conv1d_1不兼容:预期ndim = 3,找到ndim = 4

时间:2018-04-15 10:38:39

标签: machine-learning neural-network deep-learning keras conv-neural-network

我正在使用Keras提供的conv1d层为序列数据构建预测模型。这就是我的做法

enduserdevicemap

但是,调试信息有

model= Sequential()
model.add(Conv1D(60,32, strides=1, activation='relu',padding='causal',input_shape=(None,64,1)))
model.add(Conv1D(80,10, strides=1, activation='relu',padding='causal'))
model.add(Dropout(0.25))
model.add(Conv1D(100,5, strides=1, activation='relu',padding='causal'))
model.add(MaxPooling1D(1))
model.add(Dropout(0.25))
model.add(Dense(300,activation='relu'))
model.add(Dense(1,activation='relu'))
print(model.summary())

训练数据和验证数据形状如下

Traceback (most recent call last):
File "processing_2a_1.py", line 96, in <module>
model.add(Conv1D(60,32, strides=1, activation='relu',padding='causal',input_shape=(None,64,1)))
File "build/bdist.linux-x86_64/egg/keras/models.py", line 442, in add
File "build/bdist.linux-x86_64/egg/keras/engine/topology.py", line 558, in __call__
File "build/bdist.linux-x86_64/egg/keras/engine/topology.py", line 457, in assert_input_compatibility
ValueError: Input 0 is incompatible with layer conv1d_1: expected ndim=3, found ndim=4

我认为第一层中的('X_train shape ', (1496000, 64, 1)) ('Y_train shape ', (1496000, 1)) ('X_val shape ', (374000, 64, 1)) ('Y_val shape ', (374000, 1)) 设置不正确。如何设置?

更新:使用input_shape后,即使模型摘要通过

,我收到以下错误消息
input_shape=(64,1)

3 个答案:

答案 0 :(得分:1)

您应该将input_shape更改为

input_shape=(64,1)

...或使用batch_input_shape

batch_input_shape=(None, 64, 1)

This discussion详细解释了两者在keras中的区别。

答案 1 :(得分:1)

我遇到了同样的问题。我发现扩展输入数据的维度使用 tf.expand_dims

x = expand_dims(x, axis=-1)

答案 2 :(得分:0)

我的情况是,我想在单个20 * 32要素地图上使用Conv2D,并做到了:

print(kws_x_train.shape)                     # (8000,20,32)
model = tf.keras.models.Sequential([
  tf.keras.layers.Conv2D(16, (3, 8), input_shape=(20,32)),
])
...
model.fit(kws_x_train, kws_y_train, epochs=15)

给出expected ndim=4, found ndim=3. Full shape received: [None, 20, 32]。但是,您需要告诉Conv2D只有1个特征图,并向输入向量添加额外的维度。这可行:

kws_x_train2 = kws_x_train.reshape(kws_x_train.shape + (1,))
print(kws_x_train2.shape)                     # (8000,20,32,1)
model = tf.keras.models.Sequential([
  tf.keras.layers.Conv2D(16, (3, 8), input_shape=(20,32,1)),
])
...
model.fit(kws_x_train2, kws_y_train, epochs=15)