解決Keras 中加入lambda層無法正常載入模型問題
剛剛解決了這個問題,現(xiàn)在記錄下來
問題描述
當使用lambda層加入自定義的函數(shù)后,訓練沒有bug,載入保存模型則顯示Nonetype has no attribute 'get'
問題解決方法:
這個問題是由于缺少config信息導致的。lambda層在載入的時候需要一個函數(shù),當使用自定義函數(shù)時,模型無法找到這個函數(shù),也就構(gòu)建不了。
m = load_model(path,custom_objects={"reduce_mean":self.reduce_mean,"slice":self.slice})
其中,reduce_mean 和slice定義如下
def slice(self,x, turn):
""" Define a tensor slice function
"""
return x[:, turn, :, :]
def reduce_mean(self, X):
return K.mean(X, axis=-1)
補充知識:含有Lambda自定義層keras模型,保存遇到的問題及解決方案
一,許多應用,keras含有的層已經(jīng)不能滿足要求,需要透過Lambda自定義層來實現(xiàn)一些layer,這個情況下,只能保存模型的權(quán)重,無法使用model.save來保存模型。
保存時會報
TypeError: can't pickle _thread.RLock objects
二,解決方案,為了便于后續(xù)的部署,可以轉(zhuǎn)成tensorflow的PB進行部署。
from keras.models import load_model
import tensorflow as tf
import os, sys
from keras import backend as K
from tensorflow.python.framework import graph_util, graph_io
def h5_to_pb(h5_weight_path, output_dir, out_prefix="output_", log_tensorboard=True):
if not os.path.exists(output_dir):
os.mkdir(output_dir)
h5_model = build_model()
h5_model.load_weights(h5_weight_path)
out_nodes = []
for i in range(len(h5_model.outputs)):
out_nodes.append(out_prefix + str(i + 1))
tf.identity(h5_model.output[i], out_prefix + str(i + 1))
model_name = os.path.splitext(os.path.split(h5_weight_path)[-1])[0] + '.pb'
sess = K.get_session()
init_graph = sess.graph.as_graph_def()
main_graph = graph_util.convert_variables_to_constants(sess, init_graph, out_nodes)
graph_io.write_graph(main_graph, output_dir, name=model_name, as_text=False)
if log_tensorboard:
from tensorflow.python.tools import import_pb_to_tensorboard
import_pb_to_tensorboard.import_to_tensorboard(os.path.join(output_dir, model_name), output_dir)
def build_model():
inputs = Input(shape=(784,), name='input_img')
x = Dense(64, activation='relu')(inputs)
x = Dense(64, activation='relu')(x)
y = Dense(10, activation='softmax')(x)
h5_model = Model(inputs=inputs, outputs=y)
return h5_model
if __name__ == '__main__':
if len(sys.argv) == 3:
# usage: python3 h5_to_pb.py h5_weight_path output_dir
h5_to_pb(h5_weight_path=sys.argv[1], output_dir=sys.argv[2])
以上這篇解決Keras 中加入lambda層無法正常載入模型問題就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
python的scrapy框架之Pipeline文件的用法詳解
這篇文章主要介紹了python的scrapy框架之Pipeline文件的用法詳解,Pipeline是一個獨立的模塊,用于處理從Spider中提取的Item對象,實現(xiàn)對數(shù)據(jù)的進一步處理、存儲和清洗等操作,下面將詳細介紹Scrapy框架中Pipeline的用法,需要的朋友可以參考下2023-10-10
pytorch模型保存到本地后,如何實現(xiàn)繼續(xù)訓練
在PyTorch中,保存和加載模型對于實現(xiàn)模型訓練的中斷和恢復非常有用,保存模型主要有兩種方式:一是保存整個模型包括結(jié)構(gòu)與參數(shù);二是僅保存模型的state_dict,加載模型時,若保存了整個模型則直接加載,若僅保存了state_dict,則需先實例化模型結(jié)構(gòu)后加載2024-09-09
Jupyter Notebook讀入csv文件時出錯的解決方案
這篇文章主要介紹了Jupyter Notebook讀入csv文件時出錯的解決方案,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-03-03
如何用六步教會你使用python爬蟲爬取數(shù)據(jù)
網(wǎng)絡爬蟲就是按照一定規(guī)則自動訪問互聯(lián)網(wǎng)上的信息并把內(nèi)容下載下來的程序或腳本,下面這篇文章主要給大家介紹了關(guān)于如何用六步教會你使用python爬蟲爬取數(shù)據(jù)的相關(guān)資料,需要的朋友可以參考下2022-04-04

