Tensorflow - Variable

文章均迁移到我的主页 http://zhenlianghe.com

my github: https://github.com/LynnHo

tf.Variable

  1. 变量域?
    • tf.name_scope和tf.variable_scope都会对tf.Variable生成的变量域造成影响,tf.variable_scope中的reuse参数对tf.Variable没有影响(本质上是因为tf.Variable受到了tf.variable_scope中同时创建的tf.name_scope的影响)
  2. 重名?
    • 当变量名相同的时候,tf会自动打上序号
      with tf.name_scope('s'):    # or tf.variable_scope('s')
          a = tf.Variable(initial_value=10, name='a')
          b = tf.Variable(initial_value=10, name='a')
          print(a.name)
          print(b.name)
      
      [out]
      s/a:0
      s/a_1:0
      
  3. 初始化?
    • tf.Variable是用一个tensor来初始化的,
      a = tf.Variable(initial_value=[1, 2])
      b = tf.Variable(initial_value=tf.constant([1, 2]))
      c = tf.Variable(initial_value=tf.random_uniform(shape=(1, 2)))
      d = tf.Variable(initial_value=tf.zeros_initializer()(shape=(1, 2), dtype=tf.int64))
      e = tf.Variable(initial_value=slim.xavier_initializer()(shape=(1, 2)))
      
    • tf.zeros_initializer()返回的是一个对象,对象对应的类有相应的call函数,这个call函数负责产生一个相应类型的tensor
    • slim.xavier_initializer()则返回的是一个函数,调用这个函数能够产生一个相应类型的tensor
  4. 变量共享?
    • 用生成的变量去干不同的事情不就共享了嘛
    • tf.Variable产生的变量不能用tf.variable_scope的reuse设置共享,否则会报错

tf.get_variable

  1. 变量域?
    • tf.get_variable产生的变量只会受到tf.variable_scope的影响,不受tf.name_scope的影响
      with tf.name_scope('s'):
          a = tf.get_variable(name='a', shape=(10, 10))
      with tf.variable_scope('s'):
          b = tf.get_variable(name='a', shape=(10, 10))
      print(a.name)
      print(b.name)
      
      [out]
      a:0
      s/a:0
      
  2. 重名?变量共享?
    • 在同一个域下,重名是会报错的。
      with tf.variable_scope('s'):
          a = tf.get_variable(name='a', shape=(10, 10))
          b = tf.get_variable(name='a')
      
      [out]
      ValueError: Variable s/a already exists, disallowed. Did you mean to set reuse=True in VarScope?
      
      • 可以在需要复用变量之前改变scope的reuse状态
        with tf.variable_scope('s') as s:
            a = tf.get_variable(name='a', shape=(10, 10))
            s.reuse_variables()
            b = tf.get_variable(name='a')
        print(a == b)
        
        [out]
        True
        
      • 也可以设置tf.variable_scope的reuse参数为True来复用已经定义过的同名变量,但如果没定义过而设置reuse=True也是会报错的
        with tf.variable_scope('s', reuse=True):
            a = tf.get_variable(name='a')
        
        [out]
        ValueError: Variable s/a does not exist, or was not created with tf.get_variable(). Did you mean to set reuse=None in VarScope?
        
        with tf.variable_scope('s'):
            a = tf.get_variable(name='a', shape=(10, 10))
        with tf.variable_scope('s', reuse=True):
            b = tf.get_variable(name='a')
        print(a == b)
        
        [out]
        True
        
  3. 初始化?
    a = tf.get_variable(name='a', shape=(1, 2), initializer=tf.constant_initializer([1, 2]), dtype=tf.int64)
    b = tf.get_variable(name='b', shape=(1, 2), initializer=tf.random_uniform_initializer())
    c = tf.get_variable(name='c', shape=(1, 2), initializer=tf.zeros_initializer(), dtype=tf.int64)
    d = tf.get_variable(name='d', shape=(1, 2), initializer=slim.xavier_initializer())
    
    可见,只要给定相应的initializer就可以了,但是要注意dtype的设置,只有设置tf.get_variable的dtype参数才能正确生效,设置initializer的dtype参数是无效的

slim层里面的variable

  1. 注意,slim里面的variable生成机制实际上是和tf.get_variable是一样的,所以特性也是一样的,比如说变量域只受tf.variable_scope影响而不受tf.name_scope影响
  2. 层的命名
    1. 自动命名变量域,每一个slim层都有一个scope参数,如果不设置这个参数(默认为None),会有以下两种情况
      • 在同一个上下问管理器中(with tf.variable_scope('s'):)定义层,slim会按生成顺序自动命名变量域(本质上就是因为slim层里面利用了with tf.variable_scope(None, default_name, ...)的机制)
        x = tf.placeholder(tf.float32, shape=[None, 10])
        with tf.variable_scope('s'):
            a = slim.fully_connected(x, 10)
            b = slim.fully_connected(a, 10)
        for var in tf.trainable_variables():
            print(var.name)
        
        [out]  
        s/fully_connected/weights:0
        s/fully_connected/biases:0
        s/fully_connected_1/weights:0
        s/fully_connected_1/biases:0
        
      • 在不同的上下问管理器中定义层,但域名是一样的,slim将报错
        • 报错的例子
          x = tf.placeholder(tf.float32, shape=[None, 10])
          with tf.variable_scope('s'):
              a = slim.fully_connected(x, 10)
          with tf.variable_scope('s'):
              b = slim.fully_connected(x, 10)
          for var in tf.trainable_variables():
              print(var.name)
          
          [out]                
          Variable s/fully_connected/weights already exists, disallowed. Did you mean to set reuse=True in VarScope?
          
        • 报错的例子
          x = tf.placeholder(tf.float32, shape=[None, 10])
          with tf.variable_scope('s'):
              a = slim.layer_norm(x)
          with tf.variable_scope('s'):
              b = slim.layer_norm(x)
          for var in tf.trainable_variables():
              print(var.name)
          
          [out]
          ValueError: Variable s/LayerNorm/beta already exists, disallowed. Did you mean to set reuse=True in VarScope?
          
    2. 手动命名变量域,顾名思义。需要注意以下情况
      • 在同一个域中,如果两个层设置的scope参数是同一个名字,那么slim将报错
        • 报错的例子

          x = tf.placeholder(tf.float32, shape=[None, 2])
          with tf.variable_scope('s'):
              a = slim.fully_connected(x, 2, scope='a')
          with tf.variable_scope('s'): # 在这个例子中,这一行可有可无,效果相同
              b = slim.fully_connected(x, 2, scope='a')
          for var in tf.trainable_variables():
              print(var.name)
          
          [out]
          Variable s/a/weights already exists, disallowed. Did you mean to set reuse=True in VarScope?
          
        • 报错的例子

          x = tf.placeholder(tf.float32, shape=[None, 10])
          with tf.variable_scope('s'):
              a = slim.layer_norm(x, scope='a')
          with tf.variable_scope('s'): # 在这个例子中,这一行可有可无,效果相同
              b = slim.layer_norm(x, scope='a')
          
          [out]
          ValueError: Variable s/a/beta already exists, disallowed. Did you mean to set reuse=True in VarScope?
          
  3. 那么最合理的变量共享方式???实际上是和tf.get_variable定义的变量的共享机制是一样的,用reuse参数
    x = tf.placeholder(tf.float32, shape=[None, 2])
    with tf.variable_scope('s'):
        y = slim.fully_connected(x, 2, weights_initializer=tf.random_normal_initializer())
        a = slim.layer_norm(y)
    with tf.variable_scope('s', reuse=True):
        y = slim.fully_connected(x, 2)
        b = slim.layer_norm(y)
    for var in tf.trainable_variables():
        print(var.name)
    
    sess = tf.Session()
    sess.run(tf.global_variables_initializer())
    print(sess.run(a, feed_dict={x: [[1, 7]]}))
    print(sess.run(b, feed_dict={x: [[1, 7]]}))
    
    [out] 
    s/fully_connected/weights:0
    s/fully_connected/biases:0
    s/LayerNorm/beta:0
    s/LayerNorm/gamma:0
    [[-1.          1.00000012]]
    [[-1.          1.00000012]]
    
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,117评论 4 360
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,963评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 107,897评论 0 240
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,805评论 0 203
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,208评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,535评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,797评论 2 311
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,493评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,215评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,477评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,988评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,325评论 2 252
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,971评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,055评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,807评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,544评论 2 271
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,455评论 2 266

推荐阅读更多精彩内容