【问题标题】:tensorflow - session graph emptytensorflow - 会话图为空
【发布时间】:2019-12-03 16:21:03
【问题描述】:
import tensorflow as tf

x1 = tf.constant([1,2,3,4])
x2 = tf.constant([5,6,7,8])

result = tf.multiply(x1, x2)

with tf.compat.v1.Session() as sess:
  output = sess.run(result)
  print(output)

由于我是机器学习的新手,我尝试使用 tensorflow 实现此代码,但出现以下错误:

RuntimeError:会话图为空。向图中添加操作 在调用 run() 之前

我该如何解决这个问题?

this 线程我将代码更改为:

import tensorflow as tf

x1 = tf.constant([1,2,3,4])
x2 = tf.constant([5,6,7,8])

result = tf.multiply(x1, x2)

g = tf.Graph() 
with g.as_default():   
    assert result.graph is g

sess = tf.compat.v1.Session(graph=g)
with tf.compat.v1.Session() as sess:
    output = sess.run(result)
    print(output)

它也给了我以下错误:

AttributeError: 当急切执行时,Tensor.graph 毫无意义 启用

【问题讨论】:

  • 在 google colab 中运行代码可以正常工作,这是您的所有代码吗?
  • @DavidS 是的,就是这样

标签: python tensorflow


【解决方案1】:

您似乎使用的是 TF 2.0,默认情况下启用了 Eager Execution。如果是这种情况,您通常不应该使用图表或会话,您可以这样做:

import tensorflow as tf

x1 = tf.constant([1,2,3,4])
x2 = tf.constant([5,6,7,8])

result = tf.multiply(x1, x2)
tf.print(result)  # or print(result.numpy())
# [5 12 21 32]

如果您出于某种原因仍想使用图表,则需要在默认图表的上下文中进行操作:

import tensorflow as tf

with tf.compat.v1.Graph().as_default():
    x1 = tf.constant([1,2,3,4])
    x2 = tf.constant([5,6,7,8])
    result = tf.multiply(x1, x2)
    with tf.compat.v1.Session() as sess:
        output = sess.run(result)
        print(output)
        # [ 5 12 21 32]

【讨论】:

  • 在我没有图表的机器上,我没有得到任何输出。感谢图形解决方案
猜你喜欢
  • 2020-02-10
  • 2017-07-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-02
  • 1970-01-01
  • 2020-01-04
  • 2019-08-29
相关资源
最近更新 更多