zoukankan      html  css  js  c++  java
  • tensorflow的变量作用域

    一、由来

    深度学习中需要使用大量的变量集,以往写代码我们只需要做全局限量就可以了,但在tensorflow中,这样做既不方便管理变量集,有不便于封装,因此tensorflow提供了一种变量管理方法:变量作用域机制

    二、两个重要API

    tf.get_variable(name, shape=None)        # 根据给定的名字创建或返回一个变量

    tf.variable_scope(name_or_scope, reuse=None)  # 将name_or_scope下的所有变量组成一个命名空间  

    三、解读

    先说第一个API

    tf.get_variable(name, shape=None)这个方法在建立变量时与tf.Variable()完全相同,区别在于它还会搜索是否有同名变量;

    1 import tensorflow as tf
    2 
    3 
    4 with tf.variable_scope('const'):
    5     a = tf.get_variable('a', [1], initializer=tf.constant_initializer(1.))

    再说第二个API

    这个方法最重要的参数时reuse,有三个取值:None、True、tf.AUTO_REUSE

    reuse = None:继承父类的reuse标志

    reuse = True:只能复用,不能创建

     1 import tensorflow as tf
     2 
     3 
     4 with tf.variable_scope('const'):
     5     a = tf.get_variable('a', [1])
     6 
     7 with tf.variable_scope('const', reuse=tf.AUTO_REUSE):
     8     b = tf.get_variable('a', [1])
     9 
    10 print(a==b)     # True

    reuse = tf.AUTO_REUSE:没有就创建,有了就复用,这是最安全的用法

     1 import tensorflow as tf
     2 
     3 
     4 def test():
     5     with tf.variable_scope('const', reuse=tf.AUTO_REUSE):
     6         a = tf.get_variable('a', [1])
     7 
     8     return a
     9 
    10 x = test()  # 没有就创建
    11 y = test()  # 有了就复用
    12 print(x==y)     # True
  • 相关阅读:
    从mysql中dump数据到本地
    浮点数为何不能进行相等性比较
    Flume安装
    Java 一致性Hash算法的学习
    zookeeper 四字命令的使用
    Mac Eclipse安装lombok
    Linux Tomcat8 启动堆内存溢出
    Netty5+Jboss(Marshalling)完成对象序列化传输
    Elasticsearch基础
    Elasticsearch设置最大返回条数
  • 原文地址:https://www.cnblogs.com/shuaishuaidefeizhu/p/11200269.html
Copyright © 2011-2022 走看看