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運行結果:

name_scope運行結果:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章