您的位置:首页 > 运维架构

Tensorflow学习(二) name_scope和variable_scope

2018-03-19 07:24 543 查看
tf.name_scope()创建名称作用域,可以影响tf.Variable和tf.Operation,主要用于对节点名称命名,方便Tensorboard记录和分类节点创建名称作用域,可以影响tf.Variable和tf.Operationwith tf.name_scope('foo') as foo_scope:
    a = tf.Variable(1, name='a')
    assert a.name == 'foo/a:0'
    with tf.name_scope('bar') as bar_scope:
        b = tf.Variable(2, name='b')
        c = a * b
        assert b.name == 'foo/bar/b:0'
        assert c.op.name == 'foo/bar/mul'注:a.name是Tensor的name属性,name中‘:’后是Tensor的value_index属性,value_index表示该Tensor被产生它的操作的第几个输出,如#value是一个[5, 30]的矩阵
split0, split1, split2 = tf.split(value, [4, 15, 11], 1)则split0,split1,split2的value_index分别为0、1、2。
tf.variable_scope()用于创建变量作用域,可以通过tf.fet_variable()创建变量,tf.variable_scope()只影响由tf.get_variable()创建的变量,而不会影响tf.Variable()创建的变量,tf.get_variable()也可从内存中取出已有变量,tf.variable_scope()主要应用于需要大规模共享变量的场景,如RNN。tf.variable_scope().reuse默认为False,此时不可重复使用此变量域中的变量with tf.variable_scope('var_scope', reuse=tf.AUTO_REUSE) as var_scope
    v1 = tf.get_variable('v', [1])
    v2 = tf.get_variable('v', [1])
    assert v1.name =='var_scope/v:0')
    assert v1 == v2
    #id(var)查询变量在内存中的位置,发现v1、v2一样,是因为v1、v2同时调用内存中同一变量
    print(id(v1), id(v2))
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  tensorflow