bojone / bert4keras

keras implement of transformers for humans
https://kexue.fm/archives/6915
Apache License 2.0
5.37k stars 926 forks source link

keras.models.load_model 模型加载预测失败 #163

Open pk3725069 opened 4 years ago

pk3725069 commented 4 years ago

提问时请尽可能提供如下信息:

基本信息

model = Model(inputs=[model.input[0], model.input[1], K_Sep_indexs], outputs=unused1_output) print(model.inputs)

### 报错

ValueError: Error when checking model input: the list of Numpy arrays that you are passing to your model is not the size the model expected. Expected to see 2 array(s), but instead got the following list of 3 arrays:


# 尝试

save模型前打印model.inputs [<tf.Tensor 'Input-Token:0' shape=(?, ?) dtype=float32>, <tf.Tensor 'Input-Segment:0' shape=(?, ?) dtype=float32>, <tf.Tensor 'K-Sep-indexs:0' shape=(?, 4) dtype=int32>]

但是load模型时打印model.inputs [<tf.Tensor 'Input-Token:0' shape=(?, ?) dtype=float32>, <tf.Tensor 'Input-Segment:0' shape=(?, ?) dtype=float32>]

将input改成inputLayer load模型 打印model.inputs 还是没有 <tf.Tensor 'K-Sep-indexs:0' shape=(?, 4) dtype=int32> google也没找到解决方案



请求大神是什么回事呢?
bojone commented 4 years ago

能不能简化一下,提供一段可复现错误的代码呢

sataliulan commented 4 years ago

对苏神模型加载后预测失败的个人解读及解决方案:

  1. 问题 以example中的NER任务为例,模型核心源码如下: `model = build_transformer_model( config_path, checkpoint_path, )

output_layer = 'Transformer-%s-FeedForward-Norm' % (bert_layers - 1) output = model.get_layer(output_layer).output output = Dense(num_labels)(output) CRF = ConditionalRandomField(lr_multiplier=crf_lr_multiplier) output = CRF(output)

model = Model(model.input, output) model.summary()` 链接:[https://github.com/bojone/bert4keras/blob/master/examples/task_sequence_labeling_ner_crf.py],该任务源码中,苏神采用的是Bert/Albert+CRF的方案,其中,Bert/Albert 用来做embedding,Dense后接CRF。关键在CRF层,这里苏神使用的是自定义的 ConditionalRandomField(敲黑板),根据keras中对自定义layer的限定,模型保存后想通过简单的一句code: load_model('*.h5') 往往会报错。因为自定义层并非keras自带layer,若不加说明,keras会采用默认的model加载方式,这时很有可能出现自定义的loss提示找不到或者自定义layer变量无法初始化等情况。

  1. 解决思路 鉴于上述情况,个人解决方案如下:

ok,大体思路讲完了,顺带吐槽下github中码code太累了,源码请移步我的github: https://github.com/sataliulan/AlbertNerDemo