Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tensorflow: 'tf.get_default_session()` after sess=tf.Session() is None

I was trying to figure out why tf.get_default_session() always returns None type:

import tensorflow as tf

tf.reset_default_graph()
init=tf.global_variables_initializer()

sess = tf.Session()
sess.run(init)

default = tf.get_default_session()
default == None # True

I do not know why default = tf.get_default_session() is None since I thought it should return the previous session. Could anyone figures out what's wrong with my code?

like image 851
ytutow Avatar asked Dec 08 '17 20:12

ytutow


People also ask

Does TensorFlow 2.0 have session?

A session. run() call is almost like a function call: You specify the inputs and the function to be called, and you get back a set of outputs. In TensorFlow 2.0, you can decorate a Python function using tf. function() to mark it for JIT compilation so that TensorFlow runs it as a single graph (Functions 2.0 RFC).

What does Sess run do?

In tensorflow, we often use sess. run() to call operations or calculate the value of a tensor.


1 Answers

Just creating a tf.Session() doesn't make it a default. This is basically the difference between tf.Session and tf.InteractiveSession:

sess = tf.InteractiveSession()
print(tf.get_default_session())    # this is not None!

Unlike tf.InteractiveSession, a tf.Session becomes a default only inside with block (it's a context manager):

sess = tf.Session()
with sess:
  print(tf.get_default_session())  # this is not None!
like image 56
Maxim Avatar answered Oct 19 '22 10:10

Maxim