tf.name_scope用法

tf.name_scope:用于定义Python op的上下文管理器。

tf.name_scope(
    name
)

此上下文管理器将推送名称范围,这将使在其中添加的所有操作名称带有前缀

例如,定义一个新的Python op my_op

def my_op(a, b, c, name=None):
  with tf.name_scope("MyOp") as scope:
    a = tf.convert_to_tensor(a, name="a")
    b = tf.convert_to_tensor(b, name="b")
    c = tf.convert_to_tensor(c, name="c")
    # Define some computation that uses `a`, `b`, and `c`.
    return foo_op(..., name=scope)

在执行时,张量abc,将有名字MyOp/aMyOp/bMyOp/c

tf.function范围内,如果范围(scope)名称已经存在,则通过追加_n将名称唯一。例如,my_op第二次调用将生成MyOp_1/a,等等。

Args:

name:在名称范围内创建的所有名称上使用的前缀。

Raises:

ValueError:如果name不是字符串。

Attributes:

name:在名称范围内创建的所有名称上使用的前缀。

注意:

tf.variable_scope可以让变量有相同的命名方式,包括tf.get_variable变量和tf.Variable变量

tf.name_scope可以让变量有相同的命名方式,只限于tf.Variable变量

import tensorflow as tf

with tf.variable_scope('V1'):
    a1 = tf.get_variable(name='a11', shape=[1], initializer=tf.constant_initializer(1))
    a2 = tf.Variable(tf.random_normal(shape=[2, 3], mean=0, stddev=1), name='a21')
with tf.variable_scope('V2'):
    a3 = tf.get_variable(name='a12', shape=[1], initializer=tf.constant_initializer(1))
    a4 = tf.Variable(tf.random_normal(shape=[2, 3], mean=0, stddev=1), name='a22')

with tf.Session() as sess:
    sess.run(tf.initialize_all_variables())
    print(a1.name)
    print(a2.name)
    print(a3.name)
    print(a4.name)

# 输出结果:
# V1/a11:0
# V1/a21:0
# V2/a12:0
# V2/a22:0
import tensorflow as tf

with tf.name_scope('V1'):
    a1 = tf.get_variable(name='a11', shape=[1], initializer=tf.constant_initializer(1))
    a2 = tf.Variable(tf.random_normal(shape=[2, 3], mean=0, stddev=1), name='a21')
with tf.name_scope('V2'):
    a3 = tf.get_variable(name='a12', shape=[1], initializer=tf.constant_initializer(1))
    a4 = tf.Variable(tf.random_normal(shape=[2, 3], mean=0, stddev=1), name='a22')

with tf.Session() as sess:
    sess.run(tf.initialize_all_variables())
    print(a1.name)
    print(a2.name)
    print(a3.name)
    print(a4.name)

# 输出结果:
# a11:0
# V1/a21:0
# a12:0
# V2/a22:0

猜你喜欢

转载自blog.csdn.net/qq_36201400/article/details/108273631