1. 程式人生 > >tensorflow基礎知識(六) tensor變數 tf.Variable與tf.get_variable和tf.variable_scope

tensorflow基礎知識(六) tensor變數 tf.Variable與tf.get_variable和tf.variable_scope

tensorflow中的變數

1 tf.Variable與tf.get_variable建立變數

tf.Variabletf.get_variable都可以在tensorflow 定義變數,當他們用來建立變數時,他們的區別在於:

  • tf.Variable的變數名是一個 可選項。但是tf.get_variable必須指定變數名
  • tf.get_variable一旦指定了一個變數名,就不能再重複定義。除非結合tf.variable_scope中的reuse引數。tf.Variable用相同name引數指定兩個變數是不會報錯的。
v1 = tf.get_variable('v', shape=[1], initializer=tf.constant_initializer(1.0
)) v2 = tf.get_variable('v', shape=[1], initializer=tf.constant_initializer(1.0)) ValueError: Variable v already exists, disallowed. v1 = tf.Variable(tf.random_normal(shape=[2,2]), name='v') v2 = tf.Variable(tf.random_normal(shape=[2,2]), name='v') 不會報錯

函式定義格式如下:

  • tf.Variable(init_obj, name='v')
    用於生成一個初始值為init-obj的變數
    • init_obj為必須項,它是變數的初始化資料,一般對權重變數初始化採用正態隨機初始化
    • name是一個 可選項
  • tf.get_variabl(name, shape=None, dtype=tf.float32, initializer=None,
    regularizer=None, trainable=True, collections=None))
    獲取已存在的變數, 不存在則新建一個變數。

    • name是一個必要的引數選項
    • 變數的初始化可以利用initializer來實現。
      比如,Xavier初始化器
#變數建立的等價定義
v = tf.get_variable('v', shape=[1], initializer=tf.constant_initializer(1.0))
v = tf.Variable(tf.random_normal(shape=[2,2]), name='v')

2 tf.variable_scope()與tf.get_variable的配合使用

tf.variable_scope(name,resue=False)tf.get_variable經常配合使用,更加方便地管理引數命名

上面說到,tf.get_variable一旦指定了一個變數名,就不能再用該變數名重複定義。但是在神經網路中我們第一層和第二層的引數都可以稱為wight時,就不可以直接使用tf.get_variable,而是和要結合tf.variable_scope()定義不同的名稱空間將兩種變數區別開來。

with tf.variable_scope('layer1',resue=False):
    v = tf.get_variable('v',[1],initializer=tf.constant_initializer(1.0))

with tf.variable_scope('layer2',resue=False):
    v1 = tf.get_variable('v',[1])

另外,還必須知道:

  • 當reuse為False或者None時(這也是預設值),同一個tf.variable_scope下面的變數名不能相同;

  • 當reuse為True時,tf.variable_scope只能獲取已經建立過的變數

違反上面兩個情況都會報錯。

3 使用tf.get_variable的好處

  • 可以使用reuse引數,公共同一名稱空間下的變數
  • 可以和tf.variable_scope結合,管理變數