TensorFlow从CKPT和PB文件读取变量值的方法

Dylan
Dylan
发布时间:2026-10-13 | 4人浏览过
原创

本文详细介绍在TensorFlow中如何从保存的CKPT文件和PB文件中读取变量值,以验证量化后的权重是否转换为整型。通过NewCheckpointReader和图导入方法,展示获取变量形状、名称及张量数据的具体代码实现,帮助开发者快速定位和检查模型参数。

从CKPT和PB文件读取变量值概述

近期在研究TensorFlow内置量化工具时,遇到一个关键问题:如何从已保存的CKPT文件或包含权重与模型结构的PB文件中读取变量值,以便确认量化后的权重是否已成功转换为整型。

为解决上述问题,本文将具体解决方案整理记录,旨在为今后遇到类似情况提供参考,同时也希望能为其他有同样需求的开发者提供借鉴。

从CKPT文件读取变量

首先介绍如何从保存的CKPT文件中读取变量值,以下示例以读取第一个保存的权重为例。


from tensorflow.python import pywrap_tensorflow 
import tensorflow as tf
with tf.Graph().as_default(): 
 with tf.Session() as sess: 
 ckpt = tf.train.get_checkpoint_state('./model_ckpt') #保存ckpt文件的文件夹
 if ckpt and ckpt.model_checkpoint_path: 
 reader = pywrap_tensorflow.NewCheckpointReader('./model_ckpt/model.ckpt-999') #自己保存的ckpt文件名
 all_variables = reader.get_variable_to_shape_map() 
 w1 = reader.get_tensor("Variable_1") 
 print(w1.shape) 
 print(w1) 
 else: print('No checkpoint file found')

从PB文件读取变量

接着介绍如何从保存的PB文件中读取变量值,同样以读取第一个保存的权重为例进行说明。


import tensorflow as tf
from tensorflow.python.framework import graph_util
from tensorflow.python.platform import gfile
import numpy as np
sess = tf.Session()
with gfile.FastGFile('Yourpb.pb', 'rb') as f: #自己保存的pb文件
 graph_def = tf.GraphDef()
 graph_def.ParseFromString(f.read())
 sess.graph.as_default()
 tf.import_graph_def(graph_def, name='') 
 print(sess.run('Variable_1:0'))

检查点变量解析工具

补充知识:如何从现有的检查点文件(CKPT)中解析出内部变量,而无需重新构建原始计算图。

import tensorflow as tf import os

CheckpointReader核心方法

CheckpointReader

使用tf.train.NewCheckpointReader是创建检查点读取器(CheckpointReader)对象的有效方式。该对象提供了几个非常有用的方法:

get_variable_to_shape_map() - 返回一个包含变量名称及其形状的字典。

debug_string() - 返回由检查点文件中所有变量信息组成的字符串。

has_tensor(var_name) - 用于检查指定变量是否存在于检查点文件中。

get_tensor(var_name) - 返回指定变量名称对应的张量数据。

加载与验证检查点读取器

为了便于说明,这里定义一个函数来验证路径的有效性,并加载检查点读取器。

In [3]:


def load_reader(path):
 assert os.path.exists(path), "Provided incorrect path to the file. {} doesn't exist".format(path)
 return tf.train.NewCheckpointReader(path)

In [34]:

your_path = 'logs/squeezeDet1024x1024/train/model.ckpt-0' reader = load_reader(your_path)

获取变量详细信息与形状映射

reader.debug_string()

该方法返回一个包含以下内容的字符串:

variable name(变量名)

data type(数据类型)

tensor shape(张量形状)

返回字符串中的各元素之间均使用空格符' '进行分隔。你可以利用debug_string来创建一个变量名列表,示例如下:

In [53]:


all_var_descriptions = reader.debug_string().split()
var_names, var_shapes = all_var[::3], all_var[2::3]
print(var_names[:4])
print(var_shapes[:4])

输出:

['iou', 'fire9/squeeze1x1/kernels', 'fire9/squeeze1x1/biases', 'fire9/expand3x3/kernels/Momentum'] ['[10,36864]', '[1,1,512,64]', '[64]', '[3,3,64,256]']

然而,完成相同任务更推荐的方法是使用reader.get_variable_to_shape_map()。

reader.get_variable_to_shape_map()

该方法返回一个包含所有变量及其形状信息的字典,其中变量名作为字典的Key,形状信息作为Value。

In [66]:


saved_shapes = reader.get_variable_to_shape_map()
print('fire9/squeeze1x1/kernels:', saved_shapes['fire9/squeeze1x1/kernels'])
fire9/squeeze1x1/kernels: [1, 1, 512, 64]
reader.has_tensor(var_name)

检查变量存在性与恢复张量

返回bool值

这是一种便捷的方法,允许你检查检查点中是否存在相关变量。

In [51]:


names_that_exit = {var_name: reader.has_tensor(var_name) for var_name in var_names[:10]}
for key in names_that_exit:
 print(key.decode()+':', names_that_exit[key])

fire8/squeeze1x1/kernels/Momentum: True
fire9/expand3x3/kernels: True
iou: True
fire9/expand3x3/biases: True
fire9/expand1x1/kernels: True
fire9/expand3x3/kernels/Momentum: True
fire9/expand1x1/biases/Momentum: True
fire9/squeeze1x1/biases: True
fire9/expand1x1/kernels/Momentum: True
fire9/squeeze1x1/kernels: True
reader.get_tensor(tensor_name)

返回包含检查点中张量值的NumPy数组。

常规使用方法是先恢复一个张量,然后利用恢复的张量来初始化你自己的变量:

In [60]:


def recover_var(reader, var_name):
 recovered_var = 'var to be recovered'
 try:
  recovered_var = reader.get_tensor(var_name)
 except:
  assert reader.has_tensor(var_name),\
  "{} variable doesn't exist in the check point. Please check the variable name".format(var_name)
 return recovered_var

In [67]:


checkpoint_var = recover_var(reader, 'conv1/kernels')
print ("Recovered variable has the following shape: \n", checkpoint_var.shape)
new_var = tf.Variable(initial_value=checkpoint_var, name="new_conv1")
print ("New variable will be initialized with recovered values and the following shape: \n", new_var.get_shape())


Recovered variable has the following shape: 
(3, 3, 3, 64)
New variable will be initialized with recovered values and the following shape: 
(3, 3, 3, 64)

以上关于从TensorFlow的CKPT和PB文件中读取变量值的方法就是本文分享的全部内容,希望能对大家有所帮助,也欢迎大家继续支持本站。

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表