TensorFlow-模型的保存及恢复

可放在ulibs.py中作为常用功能库函数用

TensorFlow提供了convert_variables_to_constants函数,通过这个函数可以将计算图中的变量及其聚会通过常量的方式保存,这样整个TensorFlow计算图可以统一放在一个文件中。

模型最终要关注的是输入和输出,因此保存模型的时候通常就指定导出这两个节点就够了:

import tensorflow as tf
from tensorflow.python.platform import gfile
from tensorflow.python.framework import graph_util

def model_save(sess, model_path, input_tensor_name, bottleneck_tensor_name):
    graph_def = tf.get_default_graph().as_graph_def()
    outpput_graph_def = graph_util.convert_variables_to_constants(sess, graph_def, [input_tensor_name, bottleneck_tensor_name])

    with tf.gfile.GFile(model_path, "wb") as wf:
        wf.write(outpput_graph_def.SerializeToString())


def model_restore(model_path, input_tensor_name, bottleneck_tensor_name):
    with gfile.FastGFile(model_path, 'rb') as rf:
        graph_def = tf.GraphDef()
        graph_def.ParseFromString(rf.read())

    in_tensor, out_tensor,  = tf.import_graph_def(graph_def, return_elements=[input_tensor_name, bottleneck_tensor_name])
    return in_tensor, out_tensor

参数:

    model_path:指定了模型文件所在的路径;

    input_tensor_name:  模型的输入张量名称;

    bottelneck_tensor_name: 模型的瓶颈张量;

    sess: 保存模型时需要传入当前的会话;


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值