Tensorflow学习记录8 scope

"""
命名方式

What's name_scope?
What's variable_scope?

基本上都是把变量的名字动一下手脚
"""

import tensorflow as tf


# # ############## name_scope #######################################################################
#
# # 创建一个name_scope,这个name_scope的名字是“a_name_scope”
# with tf.name_scope("a_name_scope") as scope:
#     # 定义初始化方式,为一个恒定不变的量,常量1
#     initializer = tf.constant_initializer(value=1)
#     # ##########创建变量的两种方式##############
#
#     # var1的初始化方式给出
#     # name_scope对get_variable这种变量创建方式的命名无效
#     var1 = tf.get_variable(name='var1', shape=[1], dtype=tf.float32, initializer=initializer)
#
#     # name_scope有效,会在它的name前面加上“a_name_scope/”,
#     # 在“a_name_scope”中创建的变量都会到“a_name_scope/”目录下
#     var2 = tf.Variable(name='var2', initial_value=[2], dtype=tf.float32)
#     # 在name_scope下,如果两个变量同名,那么框架会在同名变量后加序号“name_i”,不会覆盖
#     var21 = tf.Variable(name='var2', initial_value=[2.1], dtype=tf.float32)
#     var22 = tf.Variable(name='var2', initial_value=[2.2], dtype=tf.float32)
#
#     # ##########创建变量的两种方式##############
#
# with tf.Session() as sess:
#     sess.run(tf.global_variables_initializer())
#     print(var1.name)        # 输出为:var1:0
#     print(sess.run(var1))   # 输出为:[1.]
#     print(var2.name)        # 输出为:a_name_scope/var2:0
#     print(sess.run(var2))   # 输出为:[2.]
#     print(var21.name)       # 输出为:a_name_scope/var2_1:0
#     print(sess.run(var21))  # 输出为:[2.1]
#     print(var22.name)
#     print(sess.run(var22))
#
# # ############## name_scope #######################################################################


# ############## variable_scope #######################################################################

# 创建一个variable_scope,这个variable_scope的名字是“a_variable_scope”
with tf.variable_scope("a_variable_scope") as scope:
    initializer = tf.constant_initializer(value=3)

    # variable_scope对get_variable有效
    var3 = tf.get_variable(name='var3', shape=[1], dtype=tf.float32, initializer=initializer)
    scope.reuse_variables()   # 强调框架,以下变量将重复利用
    var3_reuse = tf.get_variable(name='var3')

    # variable_scope有效,会在它的name前面加上“a_variable_scope/”,
    # 在“a_variable_scope”中创建的变量都会到“a_variable_scope/”目录下
    var4 = tf.Variable(name='var4', initial_value=[4], dtype=tf.float32)
    # 使用Variable, 不会覆盖
    var4_reuse = tf.Variable(name='var2', initial_value=[2.1], dtype=tf.float32)

    # ##########创建变量的两种方式##############

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print(var3.name)
    print(sess.run(var3))
    print(var3_reuse.name)     # 虽然打印了两个a_variable_scope/var3:0,但是其实是同一个变量
    print(sess.run(var3_reuse))
    print(var4.name)
    print(sess.run(var4))
    print(var4_reuse.name)
    print(sess.run(var4_reuse))


# ############## variable_scope #######################################################################

variable_scope运行结果:

Tensorflow学习记录8 scope_第1张图片

name_scope运行结果:

Tensorflow学习记录8 scope_第2张图片

你可能感兴趣的:(python)