Я воссоздал ошибку, вызванную возможными способами, а также предоставил исправление.
Предоставил больше комментариев в коде, чтобы быть более понятным об ошибке и ее исправлении.
Примечание - Я использовал один и тот же код с небольшими изменениями, чтобы воссоздать возможность возникновения ошибки и исправить ее.
Лучший код исправления присутствует в конце этого ответа.
Код ошибки 1 - Ошибка сеанса по умолчанию и использования переменной, созданной в другом графике
%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 - Ошибка с сеансом графика по умолчанию и использованием переменной, созданной в графике по умолчанию
%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 - выходной сигнал, чтобы передать явный сеанс в 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.
Fix 1 - Исправить сессией по умолчанию и переменной, не назначенной ни одному графику
%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