下面代碼的功能是先訓(xùn)練一個(gè)簡(jiǎn)單的模型,然后保存模型,同時(shí)保存到一個(gè)pb文件當(dāng)中,后續(xù)可以從pd文件里讀取權(quán)重值。
創(chuàng)新互聯(lián)堅(jiān)持“要么做到,要么別承諾”的工作理念,服務(wù)領(lǐng)域包括:網(wǎng)站制作、成都網(wǎng)站建設(shè)、企業(yè)官網(wǎng)、英文網(wǎng)站、手機(jī)端網(wǎng)站、網(wǎng)站推廣等服務(wù),滿足客戶于互聯(lián)網(wǎng)時(shí)代的石鼓網(wǎng)站設(shè)計(jì)、移動(dòng)媒體設(shè)計(jì)的需求,幫助企業(yè)找到有效的互聯(lián)網(wǎng)解決方案。努力成為您成熟可靠的網(wǎng)絡(luò)建設(shè)合作伙伴!import tensorflow as tf import numpy as np import os import h6py import pickle from tensorflow.python.framework import graph_util from tensorflow.python.platform import gfile #設(shè)置使用指定GPU os.environ['CUDA_VISIBLE_DEVICES'] = '1' #下面這段代碼是在訓(xùn)練好之后將所有的權(quán)重名字和權(quán)重值羅列出來,訓(xùn)練的時(shí)候需要注釋掉 reader = tf.train.NewCheckpointReader('./model.ckpt-100') variables = reader.get_variable_to_shape_map() for ele in variables: print(ele) print(reader.get_tensor(ele)) x = tf.placeholder(tf.float32, shape=[None, 1]) y = 4 * x + 4 w = tf.Variable(tf.random_normal([1], -1, 1)) b = tf.Variable(tf.zeros([1])) y_predict = w * x + b loss = tf.reduce_mean(tf.square(y - y_predict)) optimizer = tf.train.GradientDescentOptimizer(0.5) train = optimizer.minimize(loss) isTrain = False#設(shè)成True去訓(xùn)練模型 train_steps = 100 checkpoint_steps = 50 checkpoint_dir = '' saver = tf.train.Saver() # defaults to saving all variables - in this case w and b x_data = np.reshape(np.random.rand(10).astype(np.float32), (10, 1)) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) if isTrain: for i in xrange(train_steps): sess.run(train, feed_dict={x: x_data}) if (i + 1) % checkpoint_steps == 0: saver.save(sess, checkpoint_dir + 'model.ckpt', global_step=i+1) else: ckpt = tf.train.get_checkpoint_state(checkpoint_dir) if ckpt and ckpt.model_checkpoint_path: saver.restore(sess, ckpt.model_checkpoint_path) else: pass print(sess.run(w)) print(sess.run(b)) graph_def = tf.get_default_graph().as_graph_def() #通過修改下面的函數(shù),個(gè)人覺得理論上能夠?qū)崿F(xiàn)修改權(quán)重,但是很復(fù)雜,如果哪位有好辦法,歡迎指教 output_graph_def = graph_util.convert_variables_to_constants(sess, graph_def, ['Variable']) with tf.gfile.FastGFile('./test.pb', 'wb') as f: f.write(output_graph_def.SerializeToString()) with tf.Session() as sess: #對(duì)應(yīng)最后一部分的寫,這里能夠?qū)?duì)應(yīng)的變量取出來 with gfile.FastGFile('./test.pb', 'rb') as f: graph_def = tf.GraphDef() graph_def.ParseFromString(f.read()) res = tf.import_graph_def(graph_def, return_elements=['Variable:0']) print(sess.run(res)) print(sess.run(graph_def))