gpt4 book ai didi

python - 无法使用给定 session 评估张量 : the tensor's graph is different from the session's graph

转载 作者:行者123 更新时间:2023-12-05 02:08:23 25 4
gpt4 key购买 nike

我只是不知道出了什么问题......我之前尝试过 InteractiveSession() 并传递了一个显式 session ,但这个错误没有得到解决......我是 tensorflow 的新手......请帮忙。

cost=-tf.reduce_sum(y*tf.log(y_))
train_step=tf.train.AdamOptimizer(LEARNING_RATE).minimize(cost)
correct_pred=tf.equal(tf.argmax(y,1),tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_pred, 'float'))
predict=tf.argmax(y,1)

这是我的 session

train_accuracies = []
validation_accuracies = []
x_range = []

num_examples=train_images.shape[0]
init=tf.global_variables_initializer()
minibatches=random_mini_batches(train_images,train_labels,
mini_batch_size = BATCH_SIZE)
display_step=1
init = tf.initialize_all_variables()
with tf.Session().as_default() as sess:
sess.run(init)
for epoch in range(TRAINING_ITERATIONS):
for minibatch in minibatches:
(minibatch_X,minibatch_Y)=minibatch
if epoch%display_step == 0 or (epoch+1) == TRAINING_ITERATIONS:

train_accuracy = accuracy.eval(session=sess,feed_dict={x:minibatch_X,
y: minibatch_Y,
keep_prob: 1.0})
if(VALIDATION_SIZE):
validation_accuracy = accuracy.eval(session=sess,feed_dict={ x: validation_images[0:BATCH_SIZE],
y: validation_labels[0:BATCH_SIZE],
keep_prob: 1.0})
print('training_accuracy / validation_accuracy => %.2f / %.2f for step %d'%(train_accuracy, validation_accuracy, epoch))

validation_accuracies.append(validation_accuracy)

else:
print('training_accuracy => %.4f for step %d'%(train_accuracy, epoch))
train_accuracies.append(train_accuracy)
x_range.append(epoch)

# increase display_step
if epoch%(display_step*10) == 0 and epoch:
display_step *= 10
# train on batch
sess.run(train_step, feed_dict={x: minibatch_X, y:minibatch_Y, keep_prob: DROPOUT})

并生成以下错误

---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-63-910bbc0840b2> in <module>
18 train_accuracy = accuracy.eval(session=sess,feed_dict={x:minibatch_X,
19 y: minibatch_Y,
---> 20 keep_prob: 1.0})
21 if(VALIDATION_SIZE):
22 validation_accuracy = accuracy.eval(session=sess,feed_dict={ x:
validation_images[0:BATCH_SIZE],

/opt/conda/lib/python3.6/site-packages/tensorflow_core/python/framework/ops.py in eval(self,
feed_dict, session)
788
789 """
--> 790 return _eval_using_default_session(self, feed_dict, self.graph, session)
791
792 def experimental_ref(self):

/opt/conda/lib/python3.6/site-packages/tensorflow_core/python/framework/ops.py in
_eval_using_default_session(tensors, feed_dict, graph, session)
5307 else:
5308 if session.graph is not graph:
-> 5309 raise ValueError("Cannot use the given session to evaluate tensor: "
5310 "the tensor's graph is different from the session's "
5311 "graph.")

ValueError: Cannot use the given session to evaluate tensor: the tensor's graph is different
from the session's graph.

请建议如何使用两个 session 以及如何解决此问题。主要问题是我尝试将 session 作为 eval(session=sess) 传递,但它不起作用。意思是我用的计算图和accuracy tensor的图不一样

最佳答案

我已经重新创建了由于可能的方式导致的错误,并且还提供了修复。

在代码中提供了更多注释,以便更清楚地了解错误和修复。

注意 - 我使用了相同的代码并稍作调整来重新创建错误原因的可能性并修复相同的错误。

最佳修复代码出现在这个答案的末尾。

错误代码 1 -默认 session 和使用在另一个图中创建的变量时出错

%tensorflow_version 1.x
import tensorflow as tf

g = tf.Graph()
with g.as_default():
x = tf.constant(1.0) # x is created in graph g

with tf.Session().as_default() as sess:
y = tf.constant(2.0) # y is created in TensorFlow's default graph!!!
print(y.eval(session=sess)) # y was created in TF's default graph, and is evaluated in
# default session, so everything is ok.
print(x.eval(session=sess)) # x was created in graph g and it is evaluated in session s
# which is tied to graph g, but it is evaluated in
# session s which is tied to graph g => ERROR

输出-

2.0
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-5-f35cb204cf59> in <module>()
10 print(y.eval(session=sess)) # y was created in TF's default graph, and is evaluated in
11 # default session, so everything is ok.
---> 12 print(x.eval(session=sess)) # x was created in graph g and it is evaluated in session s
13 # which is tied to graph g, but it is evaluated in
14 # session s which is tied to graph g => ERROR

1 frames
/tensorflow-1.15.2/python3.6/tensorflow_core/python/framework/ops.py in _eval_using_default_session(tensors, feed_dict, graph, session)
5402 else:
5403 if session.graph is not graph:
-> 5404 raise ValueError("Cannot use the given session to evaluate tensor: "
5405 "the tensor's graph is different from the session's "
5406 "graph.")

ValueError: Cannot use the given session to evaluate tensor: the tensor's graph is different from the session's graph.

错误代码 2 -默认图形 session 和使用在默认图形中创建的变量时出错

%tensorflow_version 1.x
import tensorflow as tf

g = tf.Graph()
with g.as_default():
x = tf.constant(1.0) # x is created in graph g

with tf.Session(graph=g).as_default() as sess:
print(x.eval(session=sess)) # x was created in graph g and it is evaluated in session s
# which is tied to graph g, so everything is ok.
y = tf.constant(2.0) # y is created in TensorFlow's default graph!!!
print(y.eval()) # y was created in TF's default graph, but it is evaluated in
# session s which is tied to graph g => ERROR

输出-

1.0
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-15-6b8b687c5178> in <module>()
10 # which is tied to graph g, so everything is ok.
11 y = tf.constant(2.0) # y is created in TensorFlow's default graph!!!
---> 12 print(y.eval()) # y was created in TF's default graph, but it is evaluated in
13 # session s which is tied to graph g => ERROR

1 frames
/tensorflow-1.15.2/python3.6/tensorflow_core/python/framework/ops.py in _eval_using_default_session(tensors, feed_dict, graph, session)
5396 "`eval(session=sess)`")
5397 if session.graph is not graph:
-> 5398 raise ValueError("Cannot use the default session to evaluate tensor: "
5399 "the tensor's graph is different from the session's "
5400 "graph. Pass an explicit session to "

ValueError: Cannot use the default session to evaluate tensor: the tensor's graph is different from the session's graph. Pass an explicit session to `eval(session=sess)`.

错误代码 3 - 按照 错误代码 2 - 输出中的建议,将显式 session 传递给 eval(session=sess)。让我们试试这个。

%tensorflow_version 1.x
import tensorflow as tf

g = tf.Graph()
with g.as_default():
x = tf.constant(1.0) # x is created in graph g

with tf.Session(graph=g).as_default() as sess:
print(x.eval(session=sess)) # x was created in graph g and it is evaluated in session s
# which is tied to graph g, so everything is ok.
y = tf.constant(2.0) # y is created in TensorFlow's default graph!!!
print(y.eval(session=sess)) # y was created in TF's default graph, but it is evaluated in
# session s which is tied to graph g => ERROR

输出-

1.0
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-16-83809aa4e485> in <module>()
10 # which is tied to graph g, so everything is ok.
11 y = tf.constant(2.0) # y is created in TensorFlow's default graph!!!
---> 12 print(y.eval(session=sess)) # y was created in TF's default graph, but it is evaluated in
13 # session s which is tied to graph g => ERROR

1 frames
/tensorflow-1.15.2/python3.6/tensorflow_core/python/framework/ops.py in _eval_using_default_session(tensors, feed_dict, graph, session)
5402 else:
5403 if session.graph is not graph:
-> 5404 raise ValueError("Cannot use the given session to evaluate tensor: "
5405 "the tensor's graph is different from the session's "
5406 "graph.")

ValueError: Cannot use the given session to evaluate tensor: the tensor's graph is different from the session's graph.

修复 1 - 修复默认 session 和未分配给任何图形的变量

%tensorflow_version 1.x
import tensorflow as tf

x = tf.constant(1.0) # x is in not assigned to any graph

with tf.Session().as_default() as sess:
y = tf.constant(2.0) # y is created in TensorFlow's default graph!!!
print(y.eval(session=sess)) # y was created in TF's default graph, and is evaluated in
# default session, so everything is ok.
print(x.eval(session=sess)) # x not assigned to any graph, and is evaluated in
# default session, so everything is ok.

输出-

2.0
1.0

修复 2 - 最佳修复 是将构造阶段和执行阶段完全分开。

import tensorflow as tf

g = tf.Graph()
with g.as_default():
x = tf.constant(1.0) # x is created in graph g
y = tf.constant(2.0) # y is created in graph g

with tf.Session(graph=g).as_default() as sess:
print(x.eval()) # x was created in graph g and it is evaluated in session s
# which is tied to graph g, so everything is ok.
print(y.eval()) # y was created in graph g and it is evaluated in session s
# which is tied to graph g, so everything is ok.

输出-

1.0
2.0

关于python - 无法使用给定 session 评估张量 : the tensor's graph is different from the session's graph,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61006702/

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