TensorFlow 上下文管理器

2021-08-21 14:42:23 字數 857 閱讀 9066

《tensorflow實戰google深度學習框架》

在定義神經網路引數時,第一層的權重已經叫weights了,第二層網路的引數名如果也叫weights,就會觸發變數重用的錯誤。為了命名的規範性,需要通過上下文管理器來統一命名生成的變數。

with tf.variable_scope("foo"):

v = tf.get_variable("v",[1],initializer=tf.constant_initializer(1.0))

因為在命名空間foo中已經存在名字為v的變數,下面**將會報錯

with tf.variable_scope("foo"):

v = tf.get_variable("v",[1])

將引數reuse設定為true,這樣函式將直接獲得已經宣告的變數

with tf.variable_scope("foo",reuse=true):

v1 = tf.get_variable("v",[1])

print v==v1

引數reuse設定為true時,只能獲取已經建立的變數。因為命名空間bar中還沒建立v,所以會報錯

with tf.variable_scope("bar",reuse=true):

v = tf.get_variable("v",[1])

管理變數名稱

with tf.variable_scope("foo"):

v2 = tf.get_variable("v",[1])

print v2.name #輸出foo/v:0

上下文 上下文棧

全域性 函式 區域性 在執行全域性 前將window確定為全域性執行上下文 對全域性資料進行預處理 var定義的全域性變數 undefined,新增為window的屬性 function宣告的全域性函式 賦值 fun 新增為window的方法 this 賦值 window 開始執行全域性 在呼叫函式...

上下文管理協議

class open def init self,name self.name name def enter self print 執行enter def exit self,exc type,exc val,exc tb print 執行exit with open a.txt as f with...

python flask上下文管理

類方法中有 enter 和 exit 兩個方法,可以使用with,管理上下文 請求上下文 物件 request封裝 request request requestcontext 請求上下文 通過上下文獲取flask和request核心物件 離線應用,單元測試 示例 class myresource ...