TensorFlow中的name 和python代码中的变量名

本文深入探讨TensorFlow中Python命名空间与TensorFlow命名空间的区别,解析如何在复杂程序中运用命名空间提升图结构的清晰度,以及如何有效管理和恢复TensorFlow变量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

在上篇文章(Tensorflow,CNN和MNIST数据 识别手写的数字(入门,完整代码,问题解析))中,使用CNN训练MNIST数据出现了模型恢复问题,其根源在于TensorFlow的命名空间。今天特地在此屡屡。

 

在学TensorFlow时必须看懂的一句话:

“Python命名空间和TensorFlow命名空间好比为两个平行线。TensorFlow空间中的命名实际上是属于任何TensorFlow变量的“真实”属性,而Python空间中的命名只是在脚本运行期间指向TensorFlow变量的临时指针。 这就是为什么在保存和恢复变量时,只使用TensorFlow名称的原因,因为脚本终止后Python命名空间不再存在,但Tensorflow命名空间仍然存在于保存的文件中。”

1.区分 TensorFlow空间中的命名 和 Python空间中的命名

不管是tf.constant()还是tf.Variable()还是tf.get_variable里面都有一个name的参数:

import tensorflow as tf
tf.reset_default_graph()
#定义了一个常量和两个变量
a= tf.constant([10.0,1.0],name='a1')
b=tf.Variable(tf.ones([2]),name='b1')
c=tf.get_variable(name="c1",shape=[2],initializer=tf.random_normal_initializer(mean=0, stddev=1))
#相加
output = tf.add_n([a,b,c],name = "add")
#
with tf.Session() as sess:
    #变量定义完后,还必须显式的执行一下初始化操作
    sess.run(tf.global_variables_initializer())
    ##生成一个写日志的writer,并将当前的tensorflow计算图写入日志,日志放在F盘1这个文件夹
    writer = tf.summary.FileWriter("F://1",sess.graph)
    print(sess.run(output))
writer.close()

我们现在定义了一个常量和两个变量,并将三者相加。运行这个代码可以得到相加的结果和用tensorboard打开的日志文件。

下面我们在tensorboard中查看日志文件。

在终端输入:

tensorboard --logdir=F://1

在浏览器中打开:

http://localhost:6006

即可看到三者的区别:

tf.get_variable()和tf.Variable()的效果是一样的,都是变量,需要初始化,而常量a1不需要。

我们可以简单对下面的图结构进行解读。图中的椭圆代表操作,阴影代表明明空间,小圆圈代表常量。虚线箭头代表依赖,实线箭头代表数据流。 
我们的程序想要完成一个加法操作,首先需要利用tf.get_variable()和tf.Variable()的指令生成一个2元的向量,输入到b1和c1变量节点中,然后b1和c1变量节点需要依赖init操作来完成变量初始化。b1和c1节点将结果输入到add操作节点中,同时常量节点a1也将数据输入到add中,最终add完成计算。上面的所有都是在TensorFlow graph空间的命名,而代码中的a,b,c是在python的代码空间的命名。
脚本终止后Python空间的命名不再存在,但Tensorflow空间的命名仍然存在于保存的文件中。


2.进一步了解下TensorFlow的命名空间:

在复杂的程序中,为了使图结构更加简洁明了,更利于对计算图进行分析,可将计算图的细节部分隐藏,保留关键部分。 命名空间给我们提供了这种机会。 

上面的计算图中,核心部分是三个输入传递给加法操作完成计算,因此,我们可将其他部分隐藏,只保留核心部分。
 

import tensorflow as tf
tf.reset_default_graph()
with tf.variable_scope('input1'):
    a= tf.constant([10.0,1.0],name='a1')
    print(a.name)
with tf.variable_scope('input2'):
    b=tf.Variable(tf.ones([2]),name='b1')
    print(b.name)
#with tf.variable_scope('input3'):
    c=tf.get_variable(name="c1",shape=[2],initializer=tf.random_normal_initializer(mean=0, stddev=1))
    print(c.name)
output = tf.add_n([a,b,c],name = "add")
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    writer = tf.summary.FileWriter("F://1",sess.graph)
    print(sess.run(output))
writer.close()

运行结果

tensorboard:

input2空间中包含两个需要初始化的tensors输入到add操作中。

3.使用和恢复tensorflow中的变量:

① Tensorflow可以使用tensor的name索引tensor,用于sess.run

import tensorflow as tf
tf.reset_default_graph()
with tf.variable_scope('input1'):
    a= tf.constant([10.0,1.0],name='a1')
    print(a.name)
with tf.variable_scope('input2'):
    b=tf.Variable(tf.ones([2]),name='b1')
    print(b.name)
#with tf.variable_scope('input3'):
    c=tf.get_variable(name="c1",shape=[2],initializer=tf.random_normal_initializer(mean=0, stddev=1))
    print(c.name)
output = tf.add_n([a,b,c],name = "add")
print(output.name)
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print(sess.run("add:0" ))

结果:

其中名字后面的’:’之后接数字为EndPoints索引值(An operation allocates memory for its outputs, which are available on endpoints :0, :1, etc, and you can think of each of these endpoints as a Tensor.),通常情况下为0,因为大部分operation都只有一个输出。

②当脚本终止运行的时候,也可以调用已经生成的图的name进行sess.run.

 with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    #writer = tf.summary.FileWriter("F://1",sess.graph)
    #print(sess.run(output))
    print(sess.run("input1/a1:0" ))

[10.  1.]

4. 探索 name_scope 和 variable_scope() ,有点意思

tf.name_scope() 主要是用来管理命名空间的,这样子让我们的整个模型更加有条理。而 tf.variable_scope() 的作用是为了实现变量共享,它和 tf.get_variable() 来完成变量共享的功能。

1.第一组,用 tf.Variable() 的方式来定义。

import tensorflow as tf

tf.reset_default_graph()
sess = tf.Session()

# 拿官方的例子改动一下
def my_image_filter():
    conv1_weights = tf.Variable(tf.random_normal([5, 5, 32, 32]),
        name="conv1_weights")
    conv1_biases = tf.Variable(tf.zeros([32]), name="conv1_biases")
    conv2_weights = tf.Variable(tf.random_normal([5, 5, 32, 32]),
        name="conv2_weights")
    conv2_biases = tf.Variable(tf.zeros([32]), name="conv2_biases")
    return None

# First call creates one set of 4 variables.
result1 = my_image_filter()
# Another set of 4 variables is created in the second call.
result2 = my_image_filter()
# 获取所有的可训练变量
vs = tf.trainable_variables()
print ('There are %d train_able_variables in the Graph: ' % len(vs))
for v1 in vs:
    print (v1)

2.第二种方式,用 tf.get_variable() 的方式

import tensorflow as tf

tf.reset_default_graph()
sess = tf.Session()
# 下面是定义一个卷积层的通用方式
def conv_relu(kernel_shape, bias_shape):
    # Create variable named "weights".
    weights = tf.get_variable("weights", kernel_shape, initializer=tf.random_normal_initializer())
    # Create variable named "biases".
    biases = tf.get_variable("biases", bias_shape, initializer=tf.constant_initializer(0.0))
    return None


def my_image_filter():
    # 按照下面的方式定义卷积层,非常直观,而且富有层次感
    with tf.variable_scope("conv1"):
        # Variables created here will be named "conv1/weights", "conv1/biases".
        relu1 = conv_relu([5, 5, 32, 32], [32])
    with tf.variable_scope("conv2"):
        # Variables created here will be named "conv2/weights", "conv2/biases".
        return conv_relu( [5, 5, 32, 32], [32])


with tf.variable_scope("image_filters") as scope:
    # 下面我们两次调用 my_image_filter 函数,但是由于引入了 变量共享机制
    # 可以看到我们只是创建了一遍网络结构。
    result1 = my_image_filter()
    scope.reuse_variables()
    result2 = my_image_filter()


# 看看下面,完美地实现了变量共享!!!
vs = tf.trainable_variables()
print ('There are %d train_able_variables in the Graph: ' % len(vs))
for v in vs:
    print (v)

 

 

参考链接:
https://blog.youkuaiyun.com/Jerr__y/article/details/70809528

https://blog.youkuaiyun.com/xiaohuihui1994/article/details/81022043

https://blog.youkuaiyun.com/silent56_th/article/details/75577320

https://blog.youkuaiyun.com/legend_hua/article/details/78875625

https://blog.youkuaiyun.com/qq_33297776/article/details/79339684

https://blog.youkuaiyun.com/fendouaini/article/details/80344591(tensorboard详解)

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值