tensorflow保存模型和取出中间权重例子

  

下面代码的功能是先训练一个简单的模型,然后保存模型,同时保存到一个pb文件当中,后续可以从pd文件里读取权重值。

        进口tensorflow特遣部队   进口numpy np   进口操作系统   进口h6py   进口泡菜   从tensorflow.python.framework进口graph_util   从tensorflow.python。平台导入gfile   #设置使用指定GPU   操作系统。环境[' CUDA_VISIBLE_DEVICES ']=' 1 '   #下面这段代码是在训练好之后将所有的权重名字和权重值罗列出来,训练的时候需要注释掉   读者=tf.train.NewCheckpointReader (“。/model.ckpt - 100”)   变量=reader.get_variable_to_shape_map ()   避署的变量:   打印(避署)   print (reader.get_tensor(避署))         x=tf.placeholder (tf。float32、形状=[没有,1])   y=x + 4 * 4      w=tf.Variable (tf。random_normal ([1], 1,1))   b=tf.Variable (tf.zeros ([1]))   y_predict=w * x + b         损失=tf.reduce_mean (tf。平方(y - y_predict))   优化器=tf.train.GradientDescentOptimizer (0.5)   火车=optimizer.minimize(亏损)      isTrain=False #设成真正的去训练模型   train_steps=100   checkpoint_steps=50   checkpoint_dir="         储蓄者=tf.train.Saver() #默认为拯救所有的变量——在这种情况下,w和b   x_data=https://www.yisu.com/zixun/np.reshape (np.random.rand (10) .astype (np.float32), (10,1))      与tf.Session税():   sess.run (tf.global_variables_initializer ())   如果isTrain:   因为我在xrange (train_steps):   sess.run(火车,feed_dict={x: x_data})   如果(i + 1) % checkpoint_steps==0:   储蓄者。保存(税,checkpoint_dir +”模型。ckpt’, global_step=i + 1)   其他:   ckpt=tf.train.get_checkpoint_state (checkpoint_dir)   如果ckpt和ckpt.model_checkpoint_path:   储蓄者。ckpt.model_checkpoint_path恢复(税)   其他:   通过   print (sess.run (w))   打印(sess.run (b))   .as_graph_def graph_def=tf.get_default_graph () ()   #通过修改下面的函数,个人觉得理论上能够实现修改权重,但是很复杂,如果哪位有好办法,欢迎指教   output_graph_def=graph_util。convert_variables_to_constants(税、graph_def(“变量”))   与tf.gfile.FastGFile('/测试。pb”、“白平衡”)作为f:   f.write (output_graph_def.SerializeToString ())         与tf.Session税():   #对应最后一部分的写,这里能够将对应的变量取出来   与gfile.FastGFile('/测试。pb, rb) f:   graph_def=tf.GraphDef ()   graph_def.ParseFromString (f.read ())   res=特遣部队。import_graph_def (graph_def return_elements=['变量:0 '])   print (sess.run (res))   打印(sess.run (graph_def)            

以上这篇tensorflow保存模型和取出中间权重例子就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

tensorflow保存模型和取出中间权重例子