TensorFlow学习笔记(1):variable与get_variable, name_scope()和variable_scope()
生活随笔
收集整理的這篇文章主要介紹了
TensorFlow学习笔记(1):variable与get_variable, name_scope()和variable_scope()
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
Variable
tensorflow中有兩個(gè)關(guān)于variable的op,tf.Variable()與tf.get_variable()下面介紹這兩個(gè)的區(qū)別
使用tf.Variable時(shí),如果檢測(cè)到命名沖突,系統(tǒng)會(huì)自己處理。使用tf.get_variable()時(shí),系統(tǒng)不會(huì)處理沖突,而會(huì)報(bào)錯(cuò)
import tensorflow as tfw_1 = tf.get_variable(name="w_1",initializer=1) w_2 = tf.get_variable(name="w_1",initializer=2) #錯(cuò)誤信息 #ValueError: Variable w_1 already exists, disallowed. Did #you mean to set reuse=True in VarScope?
基于這兩個(gè)函數(shù)的特性,當(dāng)我們需要共享變量的時(shí)候,需要使用tf.get_variable()。在其他情況下,這兩個(gè)的用法是一樣的
- tf.get_variable() 以及 tf.Variable() 是 TensorFlow 中創(chuàng)建變量的兩種主要方式;
- 如果在 tf.name_scope() 環(huán)境下分別使用 tf.get_variable() 和 tf.Variable(),兩者的主要區(qū)別在于
-
- tf.get_variable() 創(chuàng)建的變量名不受 name_scope 的影響;
- tf.get_variable() 創(chuàng)建的變量,name 屬性值不可以相同;tf.Variable() 創(chuàng)建變量時(shí),name 屬性值允許重復(fù)(底層實(shí)現(xiàn)時(shí),會(huì)自動(dòng)引入別名機(jī)制
import tensorflow as tfwith tf.variable_scope("scope1"):w1 = tf.get_variable("w1", shape=[])w2 = tf.Variable(0.0, name="w2") with tf.variable_scope("scope1", reuse=True):w1_p = tf.get_variable("w1", shape=[])w2_p = tf.Variable(1.0, name="w2")assert w1 == w1_p assert w2 != w2_p get_variable() 函數(shù)的行為依賴(lài)于 reuse 的狀態(tài):
-
case1:reuse 設(shè)置為 False,創(chuàng)建并返回新變量:
with tf.variable_scope('foo'):v = tf.get_variable('v', [1]) assert v.name == 'foo/v:0
-
case2:reuse 設(shè)置為 True,將會(huì)按照給定的名字在以存的變量中搜尋:
with tf.variable_scope('foo'):v = tf.get_variable('v', [1]) with tf.variable_scope('foo', reuse=True):v1 = tf.get_variable('v') assert v1 == v
variable_scope()
一個(gè)雙層嵌套名稱(chēng)空間: with tf.variable_scope('foo'):with tf.variable_scope('bar'):v = tf.get_variable('v', [1]) assert v.name == 'foo/bar/v:0'with tf.name_scope('foo'):with tf.variable_scope('bar'):v = tf.get_variable('v', [1]) assert v.name == 'bar/v:0'
總結(jié)
以上是生活随笔為你收集整理的TensorFlow学习笔记(1):variable与get_variable, name_scope()和variable_scope()的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: pp越狱助手自制固件怎么降级
- 下一篇: [机器学习]一个例子完美解释朴素贝叶斯分