欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

keras 解决加载lstm+crf模型出错的问题

程序员文章站 2022-06-09 16:27:41
错误展示new_model = load_model(“model.h5”)报错:1、keras load_model valueerror: unknown layer :crf2、keras lo...

错误展示

new_model = load_model(“model.h5”)

报错:

1、keras load_model valueerror: unknown layer :crf

2、keras load_model valueerror: unknown loss function:crf_loss

错误修改

1、load_model修改源码:custom_objects = none 改为 def load_model(filepath, custom_objects, compile=true):

2、new_model = load_model(“model.h5”,custom_objects={‘crf': crf,‘crf_loss': crf_loss,‘crf_viterbi_accuracy': crf_viterbi_accuracy}

以上修改后,即可运行。

补充知识:用keras搭建bilstm crf

使用 实现的crf layer,

安装 keras-contrib

pip install git+https://www.github.com/keras-team/keras-contrib.git

code example:

# coding: utf-8
from keras.models import sequential
from keras.layers import embedding
from keras.layers import lstm
from keras.layers import bidirectional
from keras.layers import dense
from keras.layers import timedistributed
from keras.layers import dropout
from keras_contrib.layers.crf import crf
from keras_contrib.utils import save_load_utils

vocab_size = 2500
embedding_out_dim = 128
time_stamps = 100
hidden_units = 200
dropout_rate = 0.3
num_class = 5

def build_embedding_bilstm2_crf_model():
 """
 带embedding的双向lstm + crf
 """
 model = sequential()
 model.add(embedding(vocab_size, output_dim=embedding_out_dim, input_length=time_stamps))
 model.add(bidirectional(lstm(hidden_units, return_sequences=true)))
 model.add(dropout(dropout_rate))
 model.add(bidirectional(lstm(hidden_units, return_sequences=true)))
 model.add(dropout(dropout_rate))
 model.add(timedistributed(dense(num_class)))
 crf_layer = crf(num_class)
 model.add(crf_layer)
 model.compile('rmsprop', loss=crf_layer.loss_function, metrics=[crf_layer.accuracy])
 return model

def save_embedding_bilstm2_crf_model(model, filename):
 save_load_utils.save_all_weights(model,filename)

def load_embedding_bilstm2_crf_model(filename):
 model = build_embedding_bilstm2_crf_model()
 save_load_utils.load_all_weights(model, filename)
 return model

if __name__ == '__main__':
 model = build_embedding_bilstm2_crf_model()

注意:

如果执行build模型报错,则很可能是keras版本的问题。在keras-contrib==2.0.8且keras==2.0.8时,上面代码不会报错。

以上这篇keras 解决加载lstm+crf模型出错的问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。