Keras之BiLSTM+CRF实现语法错误判断出现shape不符合问题

keras之BiLSTM+CRF实现语法错误判断出现shape不符合问题

在用keras构建BiLSTM+CRF模型实现汉语语法错误诊断过程中,进行训练的时候总是报错:

ValueError: Cannot feed value of shape (128, 1) for Tensor u'crf_1_target:0', which has shape '(?,?,?)  

出现错误位置在:

#bilstm layer
bilstm_layer = Bidirectional(LSTM(hidden_dim, return_sequences=False))
model.add(bilstm_layer)
print('bilstm_layer.input_shape:', bilstm_layer.input_shape)
print('bilstm_layer.output_shape:', bilstm_layer.output_shape)
drop_layer = Dropout(dropout_rate)
model.add(drop_layer)
dense = Dense(num_class)
model.add(dense)
print('drop_layer.input_shape:', drop_layer.input_shape)
print('drop_layer.output_shape:', drop_layer.output_shape)
time_layer = TimeDistributed(Dense(num_class))
model.add(time_layer) 
print('time_layer.input_shape:', time_layer.input_shape)
print('time_layer.output_shape:', time_layer.output_shape)
#加载CRF层
crf_layer = CRF(num_class, sparse_target=True)
model.add(crf_layer)
print('crf_layer.input_shape:', crf_layer.input_shape)
print('crf_layer.output_shape:', crf_layer.output_shape)
#pdb.set_trace()
model.compile(loss='sparse_categorical_crossentropy', optimizer='sgd')

BiLSTM是一个时序序列,添加层的参数设置中return_sequence值应为Fasle,若设置为True则每个时间步都会有一个输出值返回,设为False只会返回序列中最后一个时间步的输出值。其次在BiLSTM后接的CRF层也是时许序列,对应着的输出也是每个时间有输出,因此CRF的最终输出为(batch_size,timesteps,num_class)。而在本次任务中,只要求判断输入句子是否有语法错误,真值是一个shape为(batch_size,num_class)d的输出。还有time_layer = TimeDistributed(Dense(num_class)),其中TimeDistributed这个包装器将一个层应用于输入的每个时间切片,所以都是导致最后shape不符的原因,因此会出现上述错误。

解决方法:
弃用CRF层和TimeDistributed层。发现不报错了……
但目前还不知道怎么能让CRF和TimeDistributed层存在的情况下不报错,后续有了解决方法会有更新。

代码参考:用keras搭建bilstm crf

-------------本文结束感谢您的阅读-------------
0%