国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

將TensorFlow的模型網絡導出為單個文件的方法

2020-02-22 23:50:14
字體:
來源:轉載
供稿:網友

有時候,我們需要將TensorFlow的模型導出為單個文件(同時包含模型架構定義與權重),方便在其他地方使用(如在c++中部署網絡)。利用tf.train.write_graph()默認情況下只導出了網絡的定義(沒有權重),而利用tf.train.Saver().save()導出的文件graph_def與權重是分離的,因此需要采用別的方法。

我們知道,graph_def文件中沒有包含網絡中的Variable值(通常情況存儲了權重),但是卻包含了constant值,所以如果我們能把Variable轉換為constant,即可達到使用一個文件同時存儲網絡架構與權重的目標。

我們可以采用以下方式凍結權重并保存網絡:

import tensorflow as tffrom tensorflow.python.framework.graph_util import convert_variables_to_constants# 構造網絡a = tf.Variable([[3],[4]], dtype=tf.float32, name='a')b = tf.Variable(4, dtype=tf.float32, name='b')# 一定要給輸出tensor取一個名字!!output = tf.add(a, b, name='out')# 轉換Variable為constant,并將網絡寫入到文件with tf.Session() as sess:  sess.run(tf.global_variables_initializer())  # 這里需要填入輸出tensor的名字  graph = convert_variables_to_constants(sess, sess.graph_def, ["out"])  tf.train.write_graph(graph, '.', 'graph.pb', as_text=False)

當恢復網絡時,可以使用如下方式:

import tensorflow as tfwith tf.Session() as sess:  with open('./graph.pb', 'rb') as f:    graph_def = tf.GraphDef()    graph_def.ParseFromString(f.read())     output = tf.import_graph_def(graph_def, return_elements=['out:0'])     print(sess.run(output))

輸出結果為:

[array([[ 7.],
       [ 8.]], dtype=float32)]

可以看到之前的權重確實保存了下來!!

問題來了,我們的網絡需要能有一個輸入自定義數據的接口啊!不然這玩意有什么用。。別急,當然有辦法。

import tensorflow as tffrom tensorflow.python.framework.graph_util import convert_variables_to_constantsa = tf.Variable([[3],[4]], dtype=tf.float32, name='a')b = tf.Variable(4, dtype=tf.float32, name='b')input_tensor = tf.placeholder(tf.float32, name='input')output = tf.add((a+b), input_tensor, name='out')with tf.Session() as sess:  sess.run(tf.global_variables_initializer())  graph = convert_variables_to_constants(sess, sess.graph_def, ["out"])  tf.train.write_graph(graph, '.', 'graph.pb', as_text=False)

用上述代碼重新保存網絡至graph.pb,這次我們有了一個輸入placeholder,下面來看看怎么恢復網絡并輸入自定義數據。

import tensorflow as tfwith tf.Session() as sess:  with open('./graph.pb', 'rb') as f:     graph_def = tf.GraphDef()    graph_def.ParseFromString(f.read())     output = tf.import_graph_def(graph_def, input_map={'input:0':4.}, return_elements=['out:0'], name='a')     print(sess.run(output))            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 武山县| 墨江| 克拉玛依市| 周至县| 西吉县| 勃利县| 柳林县| 马山县| 启东市| 苏尼特右旗| 鹰潭市| 屏山县| 牡丹江市| 冷水江市| 巴彦淖尔市| 湖北省| 吉木萨尔县| 汉川市| 威宁| 延庆县| 三原县| 沁源县| 清水县| 镇雄县| 商城县| 西乌珠穆沁旗| 景洪市| 乐都县| 介休市| 海口市| 奉节县| 大名县| 宿松县| 三原县| 新津县| 吴旗县| 武城县| 淮北市| 新竹市| 靖远县| 梅河口市|