无法使用给定的会话来评估张量:张量的图与会话的图不同

我实在不知道问题出在哪里…我之前尝试过使用InteractiveSession()并传递一个显式会话,但这个错误就是无法解决…我是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)

这是我的会话代码

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=1init = 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)        # 增加显示步长        if epoch%(display_step*10) == 0 and epoch:            display_step *= 10    # 在批次上训练    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.

请建议如何处理两个会话以及如何解决这个问题。主要问题是我尝试通过传递会话作为eval(session=sess)来解决,但它不起作用。它说我使用的计算图与准确性张量的图不同


回答:

我已经重新创建了可能导致错误的原因,并提供了解决方案。

在代码中添加了更多注释,以便更清楚地了解错误和解决方案。

注意 – 我使用了相同的代码,并做了一些小的调整,以重新创建可能导致错误的原因和相应的解决方案。

最佳修复代码位于此答案的末尾。

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

%tensorflow_version 1.ximport tensorflow as tfg = tf.Graph()with g.as_default():  x = tf.constant(1.0)  # x 在图 g 中创建with tf.Session().as_default() as sess:  y = tf.constant(2.0) # y 在TensorFlow的默认图中创建!!!  print(y.eval(session=sess)) # y 在TensorFlow的默认图中创建,并在默认会话中评估,所以一切正常。    print(x.eval(session=sess)) # x 在图 g 中创建,但在会话 s 中评估,会话 s 与图 g 关联,但它在会话 s 中评估 => 错误

输出 –

2.0---------------------------------------------------------------------------ValueError                                Traceback (most recent call last)<ipython-input-5-f35cb204cf59> in <module>()     10   print(y.eval(session=sess)) # y 在TensorFlow的默认图中创建,并在默认会话中评估,所以一切正常。     11                   # 默认会话,所以一切正常。---> 12   print(x.eval(session=sess)) # x 在图 g 中创建,但在会话 s 中评估,会话 s 与图 g 关联,但它在会话 s 中评估 => 错误     13                   # 会话 s 与图 g 关联,但它在会话 s 中评估 => 错误     14                   # 会话 s 与图 g 关联,但它在会话 s 中评估 => 错误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 – 使用图会话作为默认会话并使用在默认图中创建的变量时出错

%tensorflow_version 1.ximport tensorflow as tfg = tf.Graph()with g.as_default():  x = tf.constant(1.0)  # x 在图 g 中创建with tf.Session(graph=g).as_default() as sess:  print(x.eval(session=sess)) # x 在图 g 中创建,并在会话 s 中评估,会话 s 与图 g 关联,所以一切正常。  y = tf.constant(2.0) # y 在TensorFlow的默认图中创建!!!  print(y.eval()) # y 在TensorFlow的默认图中创建,但在会话 s 中评估,会话 s 与图 g 关联 => 错误

输出 –

1.0---------------------------------------------------------------------------ValueError                                Traceback (most recent call last)<ipython-input-15-6b8b687c5178> in <module>()     10                          # 会话 s 与图 g 关联,所以一切正常。     11   y = tf.constant(2.0) # y 在TensorFlow的默认图中创建!!!---> 12   print(y.eval()) # y 在TensorFlow的默认图中创建,但在会话 s 中评估,会话 s 与图 g 关联 => 错误     13                   # 会话 s 与图 g 关联 => 错误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 –输出中建议的那样,向eval(session=sess)传递一个显式会话。让我们尝试一下。

%tensorflow_version 1.ximport tensorflow as tfg = tf.Graph()with g.as_default():  x = tf.constant(1.0)  # x 在图 g 中创建with tf.Session(graph=g).as_default() as sess:  print(x.eval(session=sess)) # x 在图 g 中创建,并在会话 s 中评估,会话 s 与图 g 关联,所以一切正常。  y = tf.constant(2.0) # y 在TensorFlow的默认图中创建!!!  print(y.eval(session=sess)) # y 在TensorFlow的默认图中创建,但在会话 s 中评估,会话 s 与图 g 关联 => 错误

输出 –

1.0---------------------------------------------------------------------------ValueError                                Traceback (most recent call last)<ipython-input-16-83809aa4e485> in <module>()     10                          # 会话 s 与图 g 关联,所以一切正常。     11   y = tf.constant(2.0) # y 在TensorFlow的默认图中创建!!!---> 12   print(y.eval(session=sess)) # y 在TensorFlow的默认图中创建,但在会话 s 中评估,会话 s 与图 g 关联 => 错误     13                   # 会话 s 与图 g 关联 => 错误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 – 使用默认会话和未分配到任何图的变量的修复方法

%tensorflow_version 1.ximport tensorflow as tfx = tf.constant(1.0)  # x 未分配到任何图with tf.Session().as_default() as sess:  y = tf.constant(2.0) # y 在TensorFlow的默认图中创建!!!  print(y.eval(session=sess)) # y 在TensorFlow的默认图中创建,并在默认会话中评估,所以一切正常。    print(x.eval(session=sess)) # x 未分配到任何图,并在默认会话中评估,所以一切正常。  

输出 –

2.01.0

修复2 – 最佳修复方法 是清晰地分离构建阶段和执行阶段。

import tensorflow as tfg = tf.Graph()with g.as_default():  x = tf.constant(1.0)  # x 在图 g 中创建  y = tf.constant(2.0) # y 在图 g 中创建with tf.Session(graph=g).as_default() as sess:  print(x.eval()) # x 在图 g 中创建,并在会话 s 中评估,会话 s 与图 g 关联,所以一切正常。  print(y.eval()) # y 在图 g 中创建,并在会话 s 中评估,会话 s 与图 g 关联,所以一切正常。

输出 –

1.02.0

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注