【问题标题】:TensorFlow The Session graph is empty. Add operations to the graph before calling run()TensorFlow 会话图为空。在调用 run() 之前向图中添加操作
【发布时间】:2019-12-20 20:32:17
【问题描述】:

尝试运行代码时出现以下错误:

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

代码

h = tf.constant('Hello, this is TensorFlow')
s = tf.compat.v1.Session()
print(s.run(h))

【问题讨论】:

    标签: tensorflow


    【解决方案1】:

    你可以通过这三种方式来解决,

    降级到 TF 1.x

    tf.Session() 已成为过去。所以如果你想使用会话,你应该使用 TF 1.x。否则,您需要通过删除会话对象来更改代码以使用急切执行。

    使用 TF 2.x 但不使用 tf.Session()

    h = tf.constant('Hello, this is TensorFlow')
    print(tf.print(h))
    

    使用 TF 2.x

    您可以通过执行以下操作使您的示例正常工作。所以我们特意说这个操作进入默认的 TF 图中,然后会话将识别出这些操作。

    s = tf.compat.v1.Session()
    with tf.compat.v1.get_default_graph().as_default():
      h = tf.constant('Hello, this is TensorFlow')
      print(s.run(h))
    

    【讨论】:

      【解决方案2】:

      因为可能会出现这个错误:

      AttributeError:
      Tensor.graph is meaningless when eager execution is enabled.
      

      您需要在 TF2.x 中禁用 eager:

       tf.compat.v1.disable_eager_execution()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多