keras模型儲存為tensorflow的二進位制模型方式
最近需要將使用keras訓練的模型移植到手機上使用, 因此需要轉換到tensorflow的二進位制模型。
折騰一下午,終於找到一個合適的方法,廢話不多說,直接上程式碼:
# coding=utf-8 import sys from keras.models import load_model import tensorflow as tf import os import os.path as osp from keras import backend as K def freeze_session(session,keep_var_names=None,output_names=None,clear_devices=True): """ Freezes the state of a session into a prunned computation graph. Creates a new computation graph where variable nodes are replaced by constants taking their current value in the session. The new graph will be prunned so subgraphs that are not neccesary to compute the requested outputs are removed. @param session The TensorFlow session to be frozen. @param keep_var_names A list of variable names that should not be frozen,or None to freeze all the variables in the graph. @param output_names Names of the relevant graph outputs. @param clear_devices Remove the device directives from the graph for better portability. @return The frozen graph definition. """ from tensorflow.python.framework.graph_util import convert_variables_to_constants graph = session.graph with graph.as_default(): freeze_var_names = list(set(v.op.name for v in tf.global_variables()).difference(keep_var_names or [])) output_names = output_names or [] output_names += [v.op.name for v in tf.global_variables()] input_graph_def = graph.as_graph_def() if clear_devices: for node in input_graph_def.node: node.device = "" frozen_graph = convert_variables_to_constants(session,input_graph_def,output_names,freeze_var_names) return frozen_graph input_fld = sys.path[0] weight_file = 'your_model.h5' output_graph_name = 'tensor_model.pb' output_fld = input_fld + '/tensorflow_model/' if not os.path.isdir(output_fld): os.mkdir(output_fld) weight_file_path = osp.join(input_fld,weight_file) K.set_learning_phase(0) net_model = load_model(weight_file_path) print('input is :',net_model.input.name) print ('output is:',net_model.output.name) sess = K.get_session() frozen_graph = freeze_session(K.get_session(),output_names=[net_model.output.op.name]) from tensorflow.python.framework import graph_io graph_io.write_graph(frozen_graph,output_fld,output_graph_name,as_text=False) print('saved the constant graph (ready for inference) at: ',osp.join(output_fld,output_graph_name))
上面程式碼實現儲存到當前目錄的tensor_model目錄下。
驗證:
import tensorflow as tf import numpy as np import PIL.Image as Image import cv2 def recognize(jpg_path,pb_file_path): with tf.Graph().as_default(): output_graph_def = tf.GraphDef() with open(pb_file_path,"rb") as f: output_graph_def.ParseFromString(f.read()) tensors = tf.import_graph_def(output_graph_def,name="") print tensors with tf.Session() as sess: init = tf.global_variables_initializer() sess.run(init) op = sess.graph.get_operations() for m in op: print(m.values()) input_x = sess.graph.get_tensor_by_name("convolution2d_1_input:0") #具體名稱看上一段程式碼的input.name print input_x out_softmax = sess.graph.get_tensor_by_name("activation_4/Softmax:0") #具體名稱看上一段程式碼的output.name print out_softmax img = cv2.imread(jpg_path,0) img_out_softmax = sess.run(out_softmax,feed_dict={input_x: 1.0 - np.array(img).reshape((-1,28,1)) / 255.0}) print "img_out_softmax:",img_out_softmax prediction_labels = np.argmax(img_out_softmax,axis=1) print "label:",prediction_labels pb_path = 'tensorflow_model/constant_graph_weights.pb' img = 'test/6/8_48.jpg' recognize(img,pb_path)
補充知識:如何將keras訓練好的模型轉換成tensorflow的.pb的檔案並在TensorFlow serving環境呼叫
首先keras訓練好的模型通過自帶的model.save()儲存下來是 .model (.h5) 格式的檔案
模型載入是通過 my_model = keras . models . load_model( filepath )
要將該模型轉換為.pb 格式的TensorFlow 模型,程式碼如下:
# -*- coding: utf-8 -*- from keras.layers.core import Activation,Dense,Flatten from keras.layers.embeddings import Embedding from keras.layers.recurrent import LSTM from keras.layers import Dropout from keras.layers.wrappers import Bidirectional from keras.models import Sequential,load_model from keras.preprocessing import sequence from sklearn.model_selection import train_test_split import collections from collections import defaultdict import jieba import numpy as np import sys reload(sys) sys.setdefaultencoding('utf-8') import tensorflow as tf import os import os.path as osp from keras import backend as K def freeze_session(session,clear_devices=True): from tensorflow.python.framework.graph_util import convert_variables_to_constants graph = session.graph with graph.as_default(): freeze_var_names = list(set(v.op.name for v in tf.global_variables()).difference(keep_var_names or [])) output_names = output_names or [] output_names += [v.op.name for v in tf.global_variables()] input_graph_def = graph.as_graph_def() if clear_devices: for node in input_graph_def.node: node.device = "" frozen_graph = convert_variables_to_constants(session,freeze_var_names) return frozen_graph input_fld = '/data/codebase/Keyword-fenci/brand_recogniton_biLSTM/' weight_file = 'biLSTM_brand_recognize.model' output_graph_name = 'tensor_model_v3.pb' output_fld = input_fld + '/tensorflow_model/' if not os.path.isdir(output_fld): os.mkdir(output_fld) weight_file_path = osp.join(input_fld,output_names=[net_model.output.op.name]) from tensorflow.python.framework import graph_io graph_io.write_graph(frozen_graph,as_text=True) print('saved the constant graph (ready for inference) at: ',output_graph_name))
然後模型就存成了.pb格式的檔案
問題就來了,這樣存下來的.pb格式的檔案是frozen model
如果通過TensorFlow serving 啟用模型的話,會報錯:
E tensorflow_serving/core/aspired_versions_manager.cc:358] Servable {name: mnist version: 1} cannot be loaded: Not found: Could not find meta graph def matching supplied tags: { serve }. To inspect available tag-sets in the SavedModel,please use the SavedModel CLI: `saved_model_cli`
因為TensorFlow serving 希望讀取的是saved model
於是需要將frozen model 轉化為 saved model 格式,解決方案如下:
from tensorflow.python.saved_model import signature_constants from tensorflow.python.saved_model import tag_constants export_dir = '/data/codebase/Keyword-fenci/brand_recogniton_biLSTM/saved_model' graph_pb = '/data/codebase/Keyword-fenci/brand_recogniton_biLSTM/tensorflow_model/tensor_model.pb' builder = tf.saved_model.builder.SavedModelBuilder(export_dir) with tf.gfile.GFile(graph_pb,"rb") as f: graph_def = tf.GraphDef() graph_def.ParseFromString(f.read()) sigs = {} with tf.Session(graph=tf.Graph()) as sess: # name="" is important to ensure we don't get spurious prefixing tf.import_graph_def(graph_def,name="") g = tf.get_default_graph() inp = g.get_tensor_by_name(net_model.input.name) out = g.get_tensor_by_name(net_model.output.name) sigs[signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY] = \ tf.saved_model.signature_def_utils.predict_signature_def( {"in": inp},{"out": out}) builder.add_meta_graph_and_variables(sess,[tag_constants.SERVING],signature_def_map=sigs) builder.save()
於是儲存下來的saved model 資料夾下就有兩個檔案:
saved_model.pb variables
其中variables 可以為空
於是將.pb 模型匯入serving再讀取,成功!
以上這篇keras模型儲存為tensorflow的二進位制模型方式就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。