您好,登錄后才能下訂單哦!
小編這次要給大家分享的是keras加載lstm+crf模型出錯怎么辦,文章內(nèi)容豐富,感興趣的小伙伴可以來了解一下,希望大家閱讀完這篇文章之后能夠有所收獲。
錯誤展示
new_model = load_model(“model.h6”)
報錯:
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.h6”,custom_objects={‘CRF': CRF,‘crf_loss': crf_loss,‘crf_viterbi_accuracy': crf_viterbi_accuracy}
以上修改后,即可運(yùn)行。
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()
注意:
如果執(zhí)行build模型報錯,則很可能是keras版本的問題。在keras-contrib==2.0.8且keras==2.0.8時,上面代碼不會報錯。
看完這篇關(guān)于keras加載lstm+crf模型出錯怎么辦的文章,如果覺得文章內(nèi)容寫得不錯的話,可以把它分享出去給更多人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。