使用Keras + Tensorflow训练ConvNet时不兼容的形状错误

时间:2018-01-29 16:19:58

标签: python tensorflow neural-network keras conv-neural-network

我正在尝试构建一个简单的卷积神经网络,将时间序列分为六个类中的一个。由于不兼容的形状错误,我在训练网络时遇到问题。

在以下代码中,n_feats = 1000n_classes = 6

Fs = 100
input_layer = Input(shape=(None, n_feats), name='input_layer')
conv_layer = Conv1D(filters=32, kernel_size=Fs*4, strides=int(Fs/2), padding='same', activation='relu', name='conv_net_coarse')(input_layer)
conv_layer = MaxPool1D(pool_size=4, name='c_maxp_1')(conv_layer)
conv_layer = Dropout(rate=0.5, name='c_dropo_1')(conv_layer)
output_layer = Dense(n_classes, name='output_layer')(conv_layer)

model = Model(input_layer, output_layer)
model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])
print(model.summary())

这是模型摘要。

_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
input_layer (InputLayer)     (None, None, 1000)        0         
_________________________________________________________________
conv_net_coarse (Conv1D)     (None, None, 32)          12800032  
_________________________________________________________________
c_maxp_1 (MaxPooling1D)      (None, None, 32)          0         
_________________________________________________________________
c_dropo_1 (Dropout)          (None, None, 32)          0         
_________________________________________________________________
output_layer (Dense)         (None, None, 6)           198       
=================================================================
Total params: 12,800,230
Trainable params: 12,800,230
Non-trainable params: 0
_________________________________________________________________
None

当我运行时model.fit(X_train, Y_train)X_train形状为(30000, 1, 1000)Y_train形状为(30000, 1, 6)时,我会遇到不兼容的形状错误:

InvalidArgumentError (see above for traceback): Incompatible shapes: [32,0,6] vs. [1,6,1]
     [[Node: output_layer/add = Add[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/gpu:0"](output_layer/Reshape_2, output_layer/Reshape_3)]]
     [[Node: metrics_1/acc/Mean/_197 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/cpu:0", send_device="/job:localhost/replica:0/task:0/gpu:0", send_device_incarnation=1, tensor_name="edge_637_metrics_1/acc/Mean", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"]()]]

如果我移除MaxPool1DDropout图层,模型训练就好了。我没有正确指定这些图层吗?

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:2)

所以 - 问题在于两个事实:

  1. 输入形状应为(number_of_examples, timesteps, features),其中特征是每个时间步记录的内容。这意味着您应该将数据重新整形为(number_of_examples, 1000, 1),因为您的时间顺序有1000次步骤和1个功能。
  2. 在解决分类任务时 - 需要将输入压缩到矢量(从序列中)。我建议您在Flatten图层之前使用Dropout