剛剛解決了這個問題,現在記錄下來
問題描述
當使用lambda層加入自定義的函數后,訓練沒有bug,載入保存模型則顯示Nonetype has no attribute 'get'
問題解決方法:
這個問題是由于缺少config信息導致的。lambda層在載入的時候需要一個函數,當使用自定義函數時,模型無法找到這個函數,也就構建不了。
m = load_model(path,custom_objects={"reduce_mean":self.reduce_mean,"slice":self.slice})
其中,reduce_mean 和slice定義如下
1
2
3
4
5
6
|
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含有的層已經不能滿足要求,需要透過Lambda自定義層來實現一些layer,這個情況下,只能保存模型的權重,無法使用model.save來保存模型。
保存時會報
TypeError: can't pickle _thread.RLock objects
二,解決方案,為了便于后續的部署,可以轉成tensorflow的PB進行部署。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
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層無法正常載入模型問題就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/weixin_39673686/article/details/90697587