最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

keras模型保存為tensorflow的二進制模型方式

 更新時間:2020年05月25日 09:26:04   作者:Eileng  
這篇文章主要介紹了keras模型保存為tensorflow的二進制模型方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧

最近需要將使用keras訓(xùn)練的模型移植到手機上使用, 因此需要轉(zhuǎn)換到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))

上面代碼實現(xiàn)保存到當(dāng)前目錄的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, 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訓(xùn)練好的模型轉(zhuǎn)換成tensorflow的.pb的文件并在TensorFlow serving環(huán)境調(diào)用

首先keras訓(xùn)練好的模型通過自帶的model.save()保存下來是 .model (.h5) 格式的文件

模型載入是通過 my_model = keras . models . load_model( filepath )

要將該模型轉(zhuǎn)換為.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, keep_var_names=None, output_names=None, 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, input_graph_def,
              output_names, 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, 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=True)

print('saved the constant graph (ready for inference) at: ', osp.join(output_fld, 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 轉(zhuǎn)化為 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 模型導(dǎo)入serving再讀取,成功!

以上這篇keras模型保存為tensorflow的二進制模型方式就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • Django項目中實現(xiàn)使用qq第三方登錄功能

    Django項目中實現(xiàn)使用qq第三方登錄功能

    使用qq登錄的前提是已經(jīng)在qq互聯(lián)官網(wǎng)創(chuàng)建網(wǎng)站應(yīng)用并獲取到QQ互聯(lián)中網(wǎng)站應(yīng)用的APP ID和APP KEY。這篇文章主要介紹了Django項目中實現(xiàn)使用qq第三方登錄功能,需要的朋友可以參考下
    2019-08-08
  • python利用pyttsx3 API實現(xiàn)文本轉(zhuǎn)語音處理

    python利用pyttsx3 API實現(xiàn)文本轉(zhuǎn)語音處理

    這篇文章主要為大家詳細介紹了Python如何利用pyttsx3 API實現(xiàn)文本轉(zhuǎn)語音處理,文中有詳細的示例代碼,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2023-06-06
  • 利用Python的tkinter模塊實現(xiàn)界面化的批量修改文件名

    利用Python的tkinter模塊實現(xiàn)界面化的批量修改文件名

    這篇文章主要介紹了利用Python的tkinter模塊實現(xiàn)界面化的批量修改文件名,用Python編寫過批量修改文件名的腳本程序,代碼很簡單,運行也比較快,詳細內(nèi)容需要的小伙伴可以參考一下下面文章內(nèi)容
    2022-08-08
  • PyQt5主窗口動態(tài)加載Widget實例代碼

    PyQt5主窗口動態(tài)加載Widget實例代碼

    這篇文章主要介紹了PyQt5主窗口動態(tài)加載Widget實例代碼,分享了相關(guān)代碼示例,小編覺得還是挺不錯的,具有一定借鑒價值,需要的朋友可以參考下
    2018-02-02
  • Python中ttkbootstrap的介紹與基本使用

    Python中ttkbootstrap的介紹與基本使用

    ttkbootstrap是一個基于?tkinter?的界面美化庫,使用這個工具可以開發(fā)出類似前端bootstrap風(fēng)格的tkinter桌面程序,下面這篇文章主要給大家介紹了關(guān)于Python中ttkbootstrap的介紹與基本使用的相關(guān)資料,需要的朋友可以參考下
    2023-01-01
  • 哪種Python框架適合你?簡單介紹幾種主流Python框架

    哪種Python框架適合你?簡單介紹幾種主流Python框架

    這篇文章主要介紹了幾種主流的Python框架,幫助大家更好的理解和學(xué)習(xí)Python,感興趣的朋友可以了解下
    2020-08-08
  • Python Django中的STATIC_URL 設(shè)置和使用方式

    Python Django中的STATIC_URL 設(shè)置和使用方式

    這篇文章主要介紹了Python Django中的STATIC_URL 設(shè)置和使用方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-03-03
  • python tkinter之頂層菜單、彈出菜單實例

    python tkinter之頂層菜單、彈出菜單實例

    這篇文章主要介紹了python tkinter之頂層菜單、彈出菜單實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-03-03
  • Python實現(xiàn)視頻目標(biāo)檢測與軌跡跟蹤流程詳解

    Python實現(xiàn)視頻目標(biāo)檢測與軌跡跟蹤流程詳解

    通過閱讀相關(guān)文獻及測試,找到了一種基于多模板匹配的改進方法,可以對遙感視頻衛(wèi)星中的移動目標(biāo)進行探測,并繪制其軌跡。根據(jù)實驗結(jié)果發(fā)現(xiàn),可以比較有效的對運動目標(biāo)進行跟蹤
    2023-01-01
  • Python?lambda函數(shù)使用方法深度總結(jié)

    Python?lambda函數(shù)使用方法深度總結(jié)

    在本文中,小編將帶大家學(xué)習(xí)一下Python中的lambda函數(shù),并探討使用它的優(yōu)點和局限性。文中的示例代碼講解詳細,感興趣的可以了解一下
    2022-05-05

最新評論

西贡区| 东台市| 闽侯县| 平定县| 南靖县| 广元市| 武山县| 连江县| 东兰县| 龙州县| 凯里市| 宜州市| 德钦县| 洛扎县| 连山| 司法| 旅游| 拉萨市| 迭部县| 沙田区| 古蔺县| 长汀县| 环江| 新兴县| 巫山县| 定南县| 琼中| 百色市| 宿松县| 宁城县| 白城市| 舒兰市| 金秀| 安乡县| 漾濞| 抚州市| 汶川县| 丹东市| 山阳县| 壤塘县| 宁强县|