Tensorflow: 从checkpoint文件中读取tensor(checkpoint.ckpt)

在使用pre-train model时候,我们需要restore variables from checkpoint files. 
经常出现在checkpoint 中找不到”Tensor name not found”. 
1. 这时候需要查看一下ckpt中到底有哪些变量

import os
from tensorflow.python import pywrap_tensorflow

checkpoint_path = os.path.join(model_dir, "model.ckpt")
# Read data from checkpoint file
reader = pywrap_tensorflow.NewCheckpointReader(checkpoint_path)
var_to_shape_map = reader.get_variable_to_shape_map()
# Print tensor name and values
for key in var_to_shape_map:
    print("tensor_name: ", key)
    print(reader.get_tensor(key))

可以显示ckpt中的tensor名字和值,当然也可以用pycharm调试。

2.

# 1、你想创建多少Saver对象就可以创建多少,如果你需要去保存和恢复不同的子图模型
# 同样的变量可以在不同的saver对象中被加载
# 只有在Saver.restore()方法被调用的时候才会对变量的值进行计算
# 2、如果你在session开始的时候只恢复一部分变量的值。
# 你必须重新初始化其他变量的值
# 3、如果想检查checkpoint文件中变量的值,可以使用print_tensors_in_checkpoint_file函数
# 4、默认情况下,Saver使用tf.Variable.name属性来保存变量
# 然而当你创建一个Saver对象的时候,你或许可以为checkpoint文件中的变量选择一个名字

# 检查checkpoint文件中的变量
import tensorflow as tf
# import the inspect_checkpoint library
from tensorflow.python.tools import inspect_checkpoint as chkp
# print all tensors in checkpoint file
chkp.print_tensors_in_checkpoint_file("tmp/model.ckpt", tensor_name=None, all_tensors=True)
# print only tensor v1 in checkpoint file
chkp.print_tensors_in_checkpoint_file("tmp/model.ckpt", tensor_name='v1', all_tensors=False, all_tensor_names=False)

# print only tensor v2 in checkpoint file
chkp.print_tensors_in_checkpoint_file("tmp/model.ckpt", tensor_name='v2', all_tensors=False, all_tensor_names=False)

3.

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值