TensorFlow 使用變數共用

來源:互聯網
上載者:User

參考: www.tensorflow.org/programmers_guide/variable_scope

舉例說明

TensorFlow中的變數一般就是模型的參數。當模型複雜的時候共用變數會無比複雜。

官網給了一個case,當建立兩層卷積的過濾器時,每輸入一次圖片就會建立一次過濾器對應的變數,但是我們希望所有圖片都共用同一過濾器變數,一共有4個變數:conv1_weights, conv1_biases, conv2_weights, and conv2_biases。

通常的做法是將這些變數設定為全域變數。但是存在的問題是打破封裝性,這些變數必須文檔化被其他代碼檔案引用,一旦代碼變化,調用方也可能需要變化。還有一種保證封裝性的方式是將模型封裝成類。

不過TensorFlow提供了Variable Scope 這種獨特的機制來共用變數。這個機制涉及兩個主要函數:

#建立或返回給定名稱的變數tf.get_variable(<name>, <shape>, <initializer>) #管理傳給get_variable()的變數名稱的範圍tf.variable_scope(<scope_name>) 

在下面的代碼中,通過tf.get_variable()建立了名稱分別為weights和biases的兩個變數。

def conv_relu(input, kernel_shape, bias_shape):    # Create variable named "weights".    weights = tf.get_variable("weights", kernel_shape,        initializer=tf.random_normal_initializer())    # Create variable named "biases".    biases = tf.get_variable("biases", bias_shape,        initializer=tf.constant_initializer(0.0))    conv = tf.nn.conv2d(input, weights,        strides=[1, 1, 1, 1], padding='SAME')    return tf.nn.relu(conv + biases)

但是我們需要兩個卷積層,這時可以通過tf.variable_scope()指定範圍進行區分,如with tf.variable_scope("conv1")這行代碼指定了第一個卷積層範圍為conv1,在這個範圍下有兩個變數weights和biases。

def my_image_filter(input_images):    with tf.variable_scope("conv1"):        # Variables created here will be named "conv1/weights", "conv1/biases".        relu1 = conv_relu(input_images, [5, 5, 32, 32], [32])    with tf.variable_scope("conv2"):        # Variables created here will be named "conv2/weights", "conv2/biases".        return conv_relu(relu1, [5, 5, 32, 32], [32])

最後在image_filters這個範圍重複使用第一張圖片輸入時建立的變數,調用函數reuse_variables(),代碼如下:

with tf.variable_scope("image_filters") as scope:    result1 = my_image_filter(image1)    scope.reuse_variables()    result2 = my_image_filter(image2)

 

tf.get_variable()工作機制

tf.get_variable()工作機制是這樣的:

  • 當tf.get_variable_scope().reuse == False,調用該函數會建立新的變數

     with tf.variable_scope("foo"):      v = tf.get_variable("v", [1])  assert v.name == "foo/v:0"
  • 當tf.get_variable_scope().reuse == True,調用該函數會重用已經建立的變數

     with tf.variable_scope("foo"):      v = tf.get_variable("v", [1])  with tf.variable_scope("foo", reuse=True):      v1 = tf.get_variable("v", [1])  assert v1 is v

變數都是通過範圍/變數名來標識,後面會看到範圍可以像檔案路徑一樣嵌套。

tf.variable_scope理解

tf.variable_scope()用來指定變數的範圍,作為變數名的首碼,支援嵌套,如下:

with tf.variable_scope("foo"):    with tf.variable_scope("bar"):        v = tf.get_variable("v", [1])assert v.name == "foo/bar/v:0"

當前環境的範圍可以通過函數tf.get_variable_scope()擷取,並且reuse標誌可以通過調用reuse_variables()設定為True,這個非常有用,如下

with tf.variable_scope("foo"):    v = tf.get_variable("v", [1])    tf.get_variable_scope().reuse_variables()    v1 = tf.get_variable("v", [1])assert v1 is v

範圍中的resuse預設是False,調用函數reuse_variables()可設定為True,一旦設定為True,就不能返回到False,並且該範圍的子空間reuse都是True。如果不想重用變數,那麼可以退回到上層範圍,相當於exit當前範圍,如

with tf.variable_scope("root"):    # At start, the scope is not reusing.    assert tf.get_variable_scope().reuse == False    with tf.variable_scope("foo"):        # Opened a sub-scope, still not reusing.        assert tf.get_variable_scope().reuse == False    with tf.variable_scope("foo", reuse=True):        # Explicitly opened a reusing scope.        assert tf.get_variable_scope().reuse == True        with tf.variable_scope("bar"):            # Now sub-scope inherits the reuse flag.            assert tf.get_variable_scope().reuse == True    # Exited the reusing scope, back to a non-reusing one.    assert tf.get_variable_scope().reuse == False

一個範圍可以作為另一個新的範圍的參數,如:

with tf.variable_scope("foo") as foo_scope:    v = tf.get_variable("v", [1])with tf.variable_scope(foo_scope):    w = tf.get_variable("w", [1])with tf.variable_scope(foo_scope, reuse=True):    v1 = tf.get_variable("v", [1])    w1 = tf.get_variable("w", [1])assert v1 is vassert w1 is w

不管範圍如何嵌套,當使用with tf.variable_scope()開啟一個已經存在的範圍時,就會跳轉到這個範圍。

with tf.variable_scope("foo") as foo_scope:    assert foo_scope.name == "foo"with tf.variable_scope("bar"):    with tf.variable_scope("baz") as other_scope:        assert other_scope.name == "bar/baz"        with tf.variable_scope(foo_scope) as foo_scope2:            assert foo_scope2.name == "foo"  # Not changed.

variable scope的Initializers可以創遞給子空間和tf.get_variable()函數,除非中間有函數改變,否則不變。

with tf.variable_scope("foo", initializer=tf.constant_initializer(0.4)):    v = tf.get_variable("v", [1])    assert v.eval() == 0.4  # Default initializer as set above.    w = tf.get_variable("w", [1], initializer=tf.constant_initializer(0.3)):    assert w.eval() == 0.3  # Specific initializer overrides the default.    with tf.variable_scope("bar"):        v = tf.get_variable("v", [1])        assert v.eval() == 0.4  # Inherited default initializer.    with tf.variable_scope("baz", initializer=tf.constant_initializer(0.2)):        v = tf.get_variable("v", [1])        assert v.eval() == 0.2  # Changed default initializer.

運算元(ops)會受變數範圍(variable scope)影響,相當於隱式地開啟了同名的名稱範圍(name scope),如+這個運算元的名稱為foo/add

with tf.variable_scope("foo"):    x = 1.0 + tf.get_variable("v", [1])assert x.op.name == "foo/add"

除了變數範圍(variable scope),還可以顯式開啟名稱範圍(name scope),名稱範圍僅僅影響運算元的名稱,不影響變數的名稱。另外如果tf.variable_scope()傳入字元參數,建立變數範圍的同時會隱式建立同名的名稱範圍。如下面的例子,變數v的範圍是foo,而運算元x的運算元變為foo/bar,因為有隱式建立名稱範圍foo

with tf.variable_scope("foo"):    with tf.name_scope("bar"):        v = tf.get_variable("v", [1])        x = 1.0 + vassert v.name == "foo/v:0"assert x.op.name == "foo/bar/add"

 

注意: 如果tf.variable_scope()傳入的不是字串而是scope對象,則不會隱式建立同名的名稱範圍。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.