1. 程式人生 > >將tflearn的模型儲存為pb,給TensorFlow使用

將tflearn的模型儲存為pb,給TensorFlow使用

原博文

最後儲存的pb結果


注意:
原博文說的非常詳細正確親測可用。主要會出現的問題就兩點:
(1)在model.save之前、清除圖中的op操作、需要修改訓練的指令碼,加上這句話:

(2)輸出所有的node_names,修改成自己的node_names。我修改的倒是跟博主一樣:

原博文內容轉載如下:

參考:https://github.com/tflearn/tflearn/issues/964

解決方法:

複製程式碼
"""
Tensorflow graph freezer
Converts Tensorflow trained models in .pb

Code adapted from:
https://gist.github.com/morgangiraud/249505f540a5e53a48b0c1a869d370bf#file-medium-tffreeze-1-py
""" import os, argparse os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' import tensorflow as tf from tensorflow.python.framework import graph_util def freeze_graph(model_folder,output_graph="frozen_model.pb"): # We retrieve our checkpoint fullpath try: checkpoint = tf.train.get_checkpoint_state(model_folder) input_checkpoint
= checkpoint.model_checkpoint_path print("[INFO] input_checkpoint:", input_checkpoint) except: input_checkpoint = model_folder print("[INFO] Model folder", model_folder) # Before exporting our graph, we need to precise what is our output node # This is how TF decides what part of the Graph he has to keep and what part it can dump
output_node_names = "FullyConnected/Softmax" # NOTE: Change here # We clear devices to allow TensorFlow to control on which device it will load operations clear_devices = True # We import the meta graph and retrieve a Saver saver = tf.train.import_meta_graph(input_checkpoint + '.meta', clear_devices=clear_devices) # We retrieve the protobuf graph definition graph = tf.get_default_graph() input_graph_def = graph.as_graph_def() # We start a session and restore the graph weights with tf.Session() as sess: saver.restore(sess, input_checkpoint) # We use a built-in TF helper to export variables to constants output_graph_def = graph_util.convert_variables_to_constants( sess, # The session is used to retrieve the weights input_graph_def, # The graph_def is used to retrieve the nodes output_node_names.split(",") # The output node names are used to select the usefull nodes ) # Finally we serialize and dump the output graph to the filesystem with tf.gfile.GFile(output_graph, "wb") as f: f.write(output_graph_def.SerializeToString()) print("%d ops in the final graph." % len(output_graph_def.node)) print("[INFO] output_graph:",output_graph) print("[INFO] all done") if __name__ == '__main__': parser = argparse.ArgumentParser(description="Tensorflow graph freezer\nConverts trained models to .pb file", prefix_chars='-') parser.add_argument("--mfolder", type=str, help="model folder to export") parser.add_argument("--ograph", type=str, help="output graph name", default="frozen_model.pb") args = parser.parse_args() print(args,"\n") freeze_graph(args.mfolder,args.ograph) # However, before doing model.save(...) on TFLearn i have to do # ************************************************************ # del tf.get_collection_ref(tf.GraphKeys.TRAIN_OPS)[:] # ************************************************************ """ Then I call this command python tf_freeze.py --mfolder=<path_to_tflearn_model> Note The <path_to_tflearn_model> must not have the ".data-00000-of-00001". The output_node_names variable may change depending on your architecture. The thing is that you must reference the layer that has the softmax activation function. """
複製程式碼

注意:

1、需要在 tflearn的model.save前:

del tf.get_collection_ref(tf.GraphKeys.TRAIN_OPS)[:]

作用:去除模型裡訓練OP。

參考:https://github.com/tflearn/tflearn/issues/605#issuecomment-298478314

 2、如果是有batch normalzition,或者殘差網路層,會出現:

Error when loading the frozen graph with tensorflow.contrib.layers.python.layers.batch_norm
ValueError: graph_def is invalid at node u'BatchNorm/cond/AssignMovingAvg/Switch': Input tensor 'BatchNorm/moving_mean:0' Cannot convert a tensor of type float32 to an input of type float32_ref
freeze_graph.py doesn't seem to store moving_mean and moving_variance properly

An ugly way to get it working:
manually replace the wrong node definitions in the frozen graph
RefSwitch --> Switch + add '/read' to the input names
AssignSub --> Sub + remove use_locking attributes

則需要在restore模型後加入:

12345678910# fix batch norm nodesfornodeingd.node:ifnode.op=='RefSwitch':node.op='Switch'forindexinxrange(len(node.input)):if'moving_'innode.input[index]:node.input[index]=node.input[index]+'/read'elifnode.op=='AssignSub':node.op='Sub'if'use_locking'innode.attr:delnode.attr['use_locking']

 參考:https://github.com/tensorflow/tensorflow/issues/3628

I met the same issue when I was trying to export graph and variables by saved_model module. And finally I found a walk around to fix this issue:

Remove theTRAIN_OPScollections from graph collection. e.g.:

with dnn.graph.as_default():
     del tf.get_collection_ref(tf.GraphKeys.TRAIN_OPS)[:]

The dumped graphmay not be available for training again (by tflearn), but should be able to perform prediction and evaluation. This is usefulwhen serving model by another module or language (e.g. tensorflow serving or tensorflow go binding).I'll do more further tests about this.

If you wanna re-train the model, please use the builtin "save" method and re-construction the graph and load the saved data when re-training.

2、可能需要在程式碼修改這行,

output_node_names = "FullyConnected/Softmax" # NOTE: Change here


參考:https://gist.github.com/morgangiraud/249505f540a5e53a48b0c1a869d370bf#file-medium-tffreeze-1-py

@vparikh10@ratfury@rakashiI faced the same situation just like you.
From what I understood, you may have to change thislineaccording to your network definition.
In my case, instead of havingoutput_node_names = "Accuracy/prediction", I haveoutput_node_names = "FullyConnected_2/Softmax".

softmax

I made this change after reading thissuggestion


對我自己而言,寫成softmax或者Softmax都是不行的!然後我將所有的node names打印出來:
列印方法:
複製程式碼
    with tf.Session() as sess:
            model = get_cnn_model(max_len, volcab_size)
            model.fit(trainX, trainY, validation_set=(testX, testY), show_metric=True, batch_size=1000, n_epoch=1)
            init_op = tf.initialize_all_variables()
            sess.run(init_op)

            for v in sess.graph.get_operations():
                print(v.name)
複製程式碼

然後確保output_node_names在裡面。



附:gist裡的程式碼,將output node names轉換為引數

複製程式碼
import os, argparse

import tensorflow as tf

# The original freeze_graph function
# from tensorflow.python.tools.freeze_graph import freeze_graph 

dir = os.path.dirname(os.path.realpath(__file__))

def freeze_graph(model_dir, output_node_names):
    """Extract the sub graph defined by the output nodes and convert 
    all its variables into constant 
    Args:
        model_dir: the root folder containing the checkpoint state file
        output_node_names: a string, containing all the output node's names, 
                            comma separated
    """
    if not tf.gfile.Exists(model_dir):
        raise AssertionError(
            "Export directory doesn't exists. Please specify an export "
            "directory: %s" % model_dir)

    if not output_node_names:
        print("You need to supply the name of a node to --output_node_names.")
        return -1

    # We retrieve our checkpoint fullpath
    checkpoint = tf.train.get_checkpoint_state(model_dir)
    input_checkpoint = checkpoint.model_checkpoint_path
    
    # We precise the file fullname of our freezed graph
    absolute_model_dir = "/".join(input_checkpoint.split('/')[:-1])
    output_graph = absolute_model_dir + "/frozen_model.pb"

    # We clear devices to allow TensorFlow to control on which device it will load operations
    clear_devices = True

    # We start a session using a temporary fresh Graph
    with tf.Session(graph=tf.Graph()) as sess:
        # We import the meta graph in the current default Graph
        saver = tf.train.import_meta_graph(input_checkpoint + '.meta', clear_devices=clear_devices)

        # We restore the weights
        saver.restore(sess, input_checkpoint)

        # We use a built-in TF helper to export variables to constants
        output_graph_def = tf.graph_util.convert_variables_to_constants(
            sess, # The session is used to retrieve the weights
            tf.get_default_graph().as_graph_def(), # The graph_def is used to retrieve the nodes 
            output_node_names.split(",") # The output node names are used to select the usefull nodes
        ) 

        # Finally we serialize and dump the output graph to the filesystem
        with tf.gfile.GFile(output_graph, "wb") as f:
            f.write(output_graph_def.SerializeToString())
        print("%d ops in the final graph." % len(output_graph_def.node))

    return output_graph_def

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument("--model_dir", type=str, default="", help="Model folder to export")
    parser.add_argument("--output_node_names", type=str, default="", help="The name of the output nodes, comma separated.")
    args = parser.parse_args()

freeze_graph(args.model_dir, args.output_node_names)
複製程式碼

相關推薦

tflearn模型儲存pbTensorFlow使用

原博文:最後儲存的pb結果注意:原博文說的非常詳細正確親測可用。主要會出現的問題就兩點:(1)在model.save之前、清除圖中的op操作、需要修改訓練的指令碼,加上這句話:(2)輸出所有的node_names,修改成自己的node_names。我修改的倒是跟博主一樣:原博文內容轉載如下:參考:https:

OBJ模型轉換.h檔案Xcode使用

參考:http://heikobehrens.net/2009/08/27/obj2opengl/  (英文版的 這裡為翻譯成中文的作為學習記錄 每當您想要使用3D軟體(如攪拌器,3ds max或4D影院)在iPhone應用程式或任何其他OpenGL專案中建模時,您都必須使設計

tensorflow網路模型(圖+權值)儲存.pb檔案並從.pb檔案中還原網路模型

工程結構如下: 將網路模型(圖+權值)儲存為.pb檔案  write.py # -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from tensorflow.

頁面內容儲存圖片顯示長按儲存至本地(html2canvas)

載入的html2canvas為官網上的新版本。   style樣式: *{ margin: 0;padding: 0; font-family: "微軟雅黑"; } html,body{ width: 100%; } #capture,#imgDiv{ width: 100%; } .imgD

python訓練好的模型儲存pmml檔案供java呼叫

1、PMLL概述      用python訓練好的機器學習模型如果上線部署,被java呼叫,可以將模型儲存為pmml檔案,那麼什麼是pmml呢?PMML是資料探勘的一種通用的規範,它用統一的XML格式來描述我們生成的機器學習模型。這樣無論你的模型是sklearn,R還是Sp

docker例項儲存映象移除映象

1.有時候映象缺少某些安裝的軟體。但是當你進入docker安裝後重啟,安裝的軟體會消失。需要將安裝了軟體的例項儲存起來。 檢視createId : docker ps 進入docker,安裝軟體等。然後exit退出。 docker exec -it cr

tensorflow儲存圖和訓練的權重.pb然後讀取.pb並使用

(1)tensorflow儲存圖和訓練好的權重 from __future__ import absolute_import, unicode_literals import input_data import tensorflow as tf import shutil

使用Bitmap自身儲存檔案BitmapFactory從File中解析圖片並防止OOM

/** 獲得與需要的比例最接近的比例 */ static int calculateInSampleSize(BitmapFactory.Options bitmapOptions, int reqWidth, int reqHeight) { final int height = bitmapOpti

Java中如何根據圖片檔案建立Image物件Image物件儲存檔案形式

一.建立與儲存 1.根據一個檔案路徑建立Image物件     Image image = ImageIO.read(new File(filepath)); 2.將Image物件儲存為檔案形式   

“該檔案包含不能在當前內碼表(936)中表示的字元該檔案儲存 Unicode 格式以防止資料丟失”

這個警告怎麼破?其實很簡單: 以VS2012為例,去除方法見下: ------------------------------------------- 影象處理開發資料、影象處理開發需求、

opencv讀取視訊檔案視訊檔案儲存圖片

#include <iostream> #include <windows.h> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp

Numpy陣列儲存影象的幾種方法

將Numpy陣列儲存為影象,有以下幾種方法: 1、使用scipy.misc 程式碼如下: from PIL import Image import numpy as np from scipy import misc # 首先在該py檔案所在目錄下隨便放一張圖片,使用PIL.Ima

opencv3.3 該檔案包含不能在當前內碼表(936)中表示的字元。請該檔案儲存 Unicode 格式以防止資料丟失

VS2015 + opencv3.3 執行報錯: warning C4819: 該檔案包含不能在當前內碼表(936)中表示的字元。請將該檔案儲存為 Unicode 格式以防止資料丟失  error C2065: “ptr”: 未宣告的識別符號 error C2065: “ptr”:

使用mmdnncaffe模型轉換tensorflow模型

mmdnn是微軟推出的用於各個模型互轉的工具,支援主流框架,同類產品有onnx. 這兩個存在的共同問題是文件太舊,更新後很多命令不再適用 這裡給出mmdnn能用的命令 @echo off set PYTHONPATH=D:/CNN/caffe/python mmconvert -sf c

tensor flow 模型儲存和回覆儲存精度最高的模型python 程式碼

將訓練好的模型引數儲存起來,以便以後進行驗證或測試,這是我們經常要做的事情。tf裡面提供模型儲存的是tf.train.Saver()模組。 模型儲存,先要建立一個Saver物件:如 saver=tf.train.Saver() 在建立這個Saver物

Navicat實現資料模型匯出SQL檔案迅速生成表

Navicat實現將資料模型匯出SQL檔案,迅速生成表 這次我們不講高大上的程式碼,我們來說一說開發中一個實用的小技能。 直接進入正題 1.首先開啟Navicat工具 2.點選右上角的模型 3.點選新建模型按鈕 4.我們新建一張表,名字為user 4.在表中我們新增資料 5.

VS2017 報錯該檔案包含不能在當前內碼表(936)中表示的字元。請該檔案儲存 Unicode 格式以防止資料丟失

尤其程式碼是從linux平臺複製過來: 報錯如圖: 更有甚者基本函式都報錯: 當下檢查發現if else break case等基本函式並無問題時,報錯行數明顯不一致等一定要注意文件編碼格式, 最簡單的辦法是用notepad++,逐個將.

html 網頁儲存圖片

GitHub:https://github.com/niklasvh/html2canvas 官網:https://html2canvas.hertzen.com html2canva.js:https://html2canvas.hertzen.com/dist/html2canvas.m

告別手抄!實時語音、錄音轉文字並儲存Word只需30秒!

職場朋友的福利來了,特別是需要做會議記錄、新聞記者或者是經常需要開電話會議的朋友們,很多時候需要將錄音檔案轉換為文字然後儲存到Word裡。那大家是怎麼做的呢? 我不信有人是一個字一個字的敲到Word裡的,這樣簡直是太浪費時間了,小編今天在這裡告訴大家一個解放雙手的方法,一起來看看吧。 首先先允許小編在這裡

numpy矩陣儲存圖片

from PIL import Image import numpy as np x=np.load("universal.npy") # x.shape=m*n*3 x=(x-np.min(x))