zoukankan      html  css  js  c++  java
  • tensorflow 变量

    tf.get_variable(): 不受 name_scope 的影响,在未指定共享变量时,重名报错

    tf.Variable()    : 会自动检测有无重名,重名自行处理

    with tf.name_scope('name_scope_1'):# name_scope 的作用封装一堆操作,使数据流图有层次感
        var1 = tf.get_variable(name='var1', shape=[1], dtype=tf.float32)
        var2 = tf.get_variable(name='var1', shape=[1], dtype=tf.float32)
    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())
        print(var1.name, sess.run(var1))
        print(var2.name, sess.run(var2))
    
    # ValueError: Variable var1 already exists, disallowed. Did you mean 
    # to set reuse=True in VarScope? Originally defined at:
    # var1 = tf.get_variable(name='var1', shape=[1], dtype=tf.float32)

    当需要共享变量时,使用tf.variable_scope()

    
    
    with tf.variable_scope('variable_scope_y') as scope:
        var1 = tf.get_variable(name='var1', shape=[1], dtype=tf.float32)
        scope.reuse_variables()  # 设置共享变量
        var1_reuse = tf.get_variable(name='var1')
        var2 = tf.Variable(initial_value=[2.], name='var2', dtype=tf.float32)
        var2_reuse = tf.Variable(initial_value=[2.], name='var2', dtype=tf.float32)
    
    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())
        print(var1.name, sess.run(var1))
        print(var1_reuse.name, sess.run(var1_reuse))
        print(var2.name, sess.run(var2))
        print(var2_reuse.name, sess.run(var2_reuse))
    # 输出结果:
    # variable_scope_y/var1:0 [-1.59682846]
    # variable_scope_y/var1:0 [-1.59682846]   可以看到变量var1_reuse重复使用了var1
    # variable_scope_y/var2:0 [ 2.]
    # variable_scope_y/var2_1:0 [ 2.]
    也可以这样with tf.variable_scope('foo') as foo_scope:
        v = tf.get_variable('v', [1])
    with tf.variable_scope('foo', reuse=True):
        v1 = tf.get_variable('v')
    assert v1 == v
    或者这样:with tf.variable_scope('foo') as foo_scope:
        v = tf.get_variable('v', [1])
    with tf.variable_scope(foo_scope, reuse=True):
        v1 = tf.get_variable('v')
    assert v1 == v
  • 相关阅读:
    asp.net中读取带有加号(+)的Cookie,会自动把加号替换为空格
    简单实现分行输出的javascript代码
    大学我们应该做什么
    近日个人要闻
    WPF学习笔记“路由事件”一:路由事件基础
    WPF学习笔记“路由事件”二:路由事件基础
    WPF学习笔记“命令”三:执行命令
    WPF学习笔记“命令”二:命令库
    WPF学习笔记“命令”五:自定义高级命令的使用
    WPF学习笔记“布局”一:基础
  • 原文地址:https://www.cnblogs.com/fanhaha/p/7821705.html
Copyright © 2011-2022 走看看