简体   繁体   English

tensorflow - 会话图为空

[英]tensorflow - session graph empty

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)

As I am new in machine learning,I was trying to implement this code using tensorflow, but I am getting the following error:由于我是机器学习的新手,我试图使用 tensorflow 实现此代码,但出现以下错误:

RuntimeError: The Session graph is empty.运行时错误:会话图为空。 Add operations to the graph before calling run()在调用 run() 之前向图形添加操作

How can I solve this problem ?我怎么解决这个问题 ?

From this thread I changed my code to:这个线程我改变了我的代码:

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)

It also gives me the following error :它也给了我以下错误:

AttributeError: Tensor.graph is meaningless when eager execution is enabled AttributeError: Tensor.graph 在启用急切执行时毫无意义

You seem to be using TF 2.0, which enables eager execution by default.您似乎在使用 TF 2.0,默认情况下它启用了急切执行。 If that is the case, you should normally not be using graphs or sessions, as you can simply do:如果是这种情况,您通常不应使用图表或会话,因为您可以简单地执行以下操作:

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]

If you still want to use graphs for some reason, you need to do you operations within the context of a default graph:如果出于某种原因仍想使用图形,则需要在默认图形的上下文中进行操作:

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM