tensorflow.variable_scope本質與變量共享解析

data1=tf.get_variable(“data1”,shape=[2])
上述python代碼可以爲&data1引用或者指針指向了一個tf.Variable對象,如果要使多個個python對象指向同一tf.Variable對象,需要通過variable_scope,
看如下代碼:
import tensorflow as tf
import numpy as np

with tf.variable_scope(“abc”):
data1=tf.get_variable(“a”,shape=[2])
data2=tf.get_variable(“b”,shape=[2])

with tf.variable_scope(“abc”,reuse=True):
data3=tf.get_variable(“a”,shape=[2])

init = tf.global_variables_initializer()

with tf.Session() as sess:
sess.run(init)
print(data1)
print(data2)
print(data3)
輸出爲:
<tf.Variable ‘abc/a:0’ shape=(2,) dtype=float32_ref>
<tf.Variable ‘abc/b:0’ shape=(2,) dtype=float32_ref>
<tf.Variable ‘abc/a:0’ shape=(2,) dtype=float32_ref>
variable_scope可以理解爲C++結構體,變量共享就是多個指針指向同一內存區域

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章