TensorFlow中Variable()和get_variable()
tf.Variable()和tf.get_variable()都可以用來建立變數,但是前者會自動保證唯一性,而後者不能保證唯一性。
1 tf.Variable:
Variable(initial_value=None, trainable=True,
collections=None, validate_shape=True,
caching_device=None,name=None,
expected_shape=None, import_scope=None,
constraint=None)
新建一個變數,變數值是initial_value.
params:
initial_value:初始值
name:可選引數,變數的名字,會自動保證唯一性。
2 tf.get_variable():
get_variable(name, shape=None, dtype=None,
initializer=None, regularizer=None,
trainable=True, collections=None,
caching_device=None, partitioner=None,
validate_shape=True , use_resouce=None,
constraint=None)
獲取具有這些引數的現有變數或建立一個新變數。如果該name的變數還未定義,則新建立一個;如果已經定義了,則直接獲得該變數。
get_variable()可以用來建立共享變數。
下面用例子來說明二者的不同之處:
import tensorflow as tf
with tf.variable_scope('scope1'):
w1 = tf.Variable(1, name='w1')
w2 = tf.get_variable(name='w2', initializer=2. )
with tf.variable_scope('scope1', reuse=True):
w1_p = tf.Variable(1, name='w1')
w2_p = tf.get_variable(name='w2', initializer=3.)
print('w1', w1)
print('w1_p', w1_p)
print('w2', w2)
print('w2_p', w2_p)
print(w1 is w1_p, w2 is w2_p)
輸出結果如下:
w1 <tf.Variable 'scope1/w1:0' shape=() dtype=int32_ref>
w1_p <tf.Variable 'scope1_1/w1:0' shape=() dtype=int32_ref>
w2 <tf.Variable 'scope1/w2:0' shape=() dtype=float32_ref>
w2_p <tf.Variable 'scope1/w2:0' shape=() dtype=float32_ref>
False True
可以看出,tf.Variable()會自動處理衝突問題,如程式碼中所示,他會將scope1改為scope1_1。
而tf.get_variable()會判斷是否已經存在該name的變數,如果有,並且該變數空間的reuse=True,那麼就可以直接共享之前的值;如果沒有,則重新建立。注意,如果你沒有將reuse設為True,則會提示衝突發生。
程式碼中最後一條語句判斷上述變數是否相等,可以看出,通過get_variable()定義的變數是完全等價的,即使後一條get_variable將initializer設為3.,但是由於name=’w2’的變數已經存在,並且reuse=True,則直接引用之前定義的。這樣就可以用get_variable()來定義共享變數。
你會發現,tf.get_variable()使用時,一般會和tf.variable_scope()配套使用,需要指定它的作用域空間,這樣在引用的使用就可以通過設定指定的scope的reuse=True進行引用。下面講解一下tf.variable_scope()和tf.name_scope()。
name_scope()是給op_name加字首,指明op的作用域空間的,op是指操作。而variable_scope()是給get_variable()建立的變數的名字加字首,表明作用域空間,也可以用於處理命名衝突。
with tf.name_scope('name_test'):
n1 = tf.constant(1, name='cs1')
n2 = tf.Variable(tf.zeros([1]), name='v1')
nv1 = tf.get_variable(name='nv1', initializer=1.0)
with tf.variable_scope('v_test'):
v_n1 = tf.constant(2, name='cs2')
v_n2 = tf.Variable(tf.zeros([1]), name='v2')
v1 = tf.get_variable(name='vv1', initializer=2.0)
print('n1', n1.name)
print('n2', n2.name)
print('nv1', nv1.name)
print('v_n1', v_n1.name)
print('v_n2', v_n2.name)
print('v1', v1.name)
輸出結果如下:
n1 name_test/cs1:0
n2 name_test/v1:0
nv1 nv1:0
v_n1 v_test/cs2:0
v_n2 v_test/v2:0
v1 v_test/vv1:0
可以看出,variable_scope()不僅對get_variable()有效,對普通的op也有效,能給它們加上字首,指明作用域空間;而name_scope()僅僅對普通的op有效,對get_variable()無效,不能給後者加上字首,指明作用空間。