TensorFlow進階(四)---名稱域和共用變數

來源:互聯網
上載者:User

標籤:inf   範圍   共用   作用   pre   style   建立   ==   flow   

變數範圍

tensorflow提供了變數範圍和共用變數這樣的概念,有幾個重要的作用。

  • 讓模型代碼更加清晰,作用分明
變數範圍域

通過tf.variable_scope(<scope_name>)建立指定名字的變數範圍

with tf.variable_scope("itcast") as scope:  print("----")

加上with語句就可以在整個itcast變數範圍下就行操作。

嵌套使用

變數範圍可以嵌套使用

with tf.variable_scope("itcast") as itcast:    with tf.variable_scope("python") as python:      print("----")
變數範圍下的變數

在同一個變數範圍下,如果定義了兩個相同名稱的變數(這裡先用tf.Variable())會怎麼樣呢?

with tf.variable_scope("itcast") as scope:    a = tf.Variable([1.0,2.0],name="a")    b = tf.Variable([2.0,3.0],name="a")

我們通過tensoflow提供的計算圖介面觀察

 

我們發現取了同樣的名字,其實tensorflow並沒有當作同一個,而是另外又增加了一個a_1,來表示b的圖

變數範圍

當每次在一個變數範圍中建立變數的時候,會在變數的name前面加上變數範圍的名稱

with tf.variable_scope("itcast"):    a = tf.Variable(1.0,name="a")    b = tf.get_variable("b", [1])    print(a.name,b.name)

 

得道結果

(u‘itcast/a:0‘, u‘itcast/b:0‘)

 

對於嵌套的變數範圍來說

with tf.variable_scope("itcast"):    with tf.variable_scope("python"):        python3 = tf.get_variable("python3", [1])assert python3.name == "itcast/python/python3:0"var2 = tf.get_variable("var",[3,4],initializer=tf.constant_initializer(0.0))

 

TensorFlow進階(四)---名稱域和共用變數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.