[英]How to create variable outside of current scope in Tensorflow?
例如我有這樣的代碼:
def test():
v = tf.get_variable('test') # => foo/test
with tf.variable_scope('foo'):
test()
現在,我想在范圍'foo'之外創建一個變量:
def test():
with tf.variable_scope('bar'):
v = tf.get_variable('test') # foo/bar/test
但是它被放置為“ foo / bar / test”。 我應該如何在test()主體中將其放置為沒有'foo'根的'bar / test'?
您可以通過提供現有范圍的實例來清除當前變量范圍。 因此,為了實現這一點,只需引用頂級變量范圍並使用它:
top_scope = tf.get_variable_scope() # top-level scope
def test():
v = tf.get_variable('test', [1], dtype=tf.float32)
print(v.name)
with tf.variable_scope(top_scope): # resets the current scope!
# Can nest the scopes further, if needed
w = tf.get_variable('test', [1], dtype=tf.float32)
print(w.name)
with tf.variable_scope('foo'):
test()
輸出:
foo/test:0
test:0
tf.get_variable()
忽略name_scope
但不會忽略variable_scope
。 如果要獲取“ bar / test”,可以嘗試以下操作:
def test():
with tf.variable_scope('bar'):
v = tf.get_variable('test', [1], dtype=tf.float32)
print(v.name)
with tf.name_scope('foo'):
test()
請參閱此答案以獲取完整說明: https : //stackoverflow.com/a/37534656/8107620
一種解決方法是直接設置作用域名稱:
def test():
tf.get_variable_scope()._name = ''
with tf.variable_scope('bar'):
v = tf.get_variable('test', [1])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.