gpt4 book ai didi

python - tensorflow 初始化变量错误

转载 作者:太空宇宙 更新时间:2023-11-03 14:39:16 26 4
gpt4 key购买 nike

众所周知,在 tensorflow 中初始化变量有多种方法。我尝试了一些与图形定义相结合的东西。请参阅下面的代码。

def Graph1a():
g1 = tf.Graph()
with g1.as_default() as g:
matrix1 = tf.constant([[3., 3.]])
matrix2 = tf.constant([[2.],[2.]])
product = tf.matmul( matrix1, matrix2, name = "product")

sess = tf.Session( graph = g )
sess.run(tf.global_variables_initializer())
return product

def Graph1b():
g1 = tf.Graph()
with g1.as_default() as g:
matrix1 = tf.constant([[3., 3.]])
matrix2 = tf.constant([[2.],[2.]])
product = tf.matmul( matrix1, matrix2, name = "product")

sess = tf.Session( graph = g )
sess.run(tf.initialize_all_variables())
return product

def Graph1c():
g1 = tf.Graph()
with g1.as_default() as g:
matrix1 = tf.constant([[3., 3.]])
matrix2 = tf.constant([[2.],[2.]])
product = tf.matmul( matrix1, matrix2, name = "product")

with tf.Session( graph = g ) as sess:
tf.global_variables_initializer().run()
return product

为什么 Graph1a()Graph1b() 不会返回乘积,而 Graph1c() 会返回乘积?我认为这些陈述是等效的。

最佳答案

问题是 global_variables_initializer 需要与 session 相同的图关联。在 Graph1c 中,发生这种情况是因为 global_variables_initializer 位于 session 的 with 语句的范围内。要让 Graph1a 工作,需要像这样重写

def Graph1a():
g1 = tf.Graph()
with g1.as_default() as g:
matrix1 = tf.constant([[3., 3.]])
matrix2 = tf.constant([[2.],[2.]])
product = tf.matmul( matrix1, matrix2, name = "product")
init_op = tf.global_variables_initializer()

sess = tf.Session( graph = g )
sess.run(init_op)
return product

关于python - tensorflow 初始化变量错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46672077/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com