tf.compat.v1.Session

A class for running TensorFlow operations.

Used in the notebooks

Used in the guide Used in the tutorials

A Session object encapsulates the environment in which Operation objects are executed, and Tensor objects are evaluated. For example:

tf.compat.v1.disable_eager_execution() # need to disable eager in TF2.x
# Build a graph.
a = tf.constant(5.0)
b = tf.constant(6.0)
c = a * b

# Launch the graph in a session.
sess = tf.compat.v1.Session()

# Evaluate the tensor `c`.
print(sess.run(c)) # prints 30.0

A session may own resources, such as tf.Variable, tf.queue.QueueBase, and tf.compat.v1.ReaderBase. It is important to release these resources when they are no longer required. To do this, either invoke the tf.Session.close method on the session, or use the session as a context manager. The following two examples are equivalent:

# Using the `close()` method.
sess = tf.compat.v1.Session()
sess.run(...)
sess.close()

# Using the context manager.
with tf.compat.v1.Session() as sess:
  sess.run(...)

The ConfigProto protocol buffer exposes various configuration options for a session. For example, to create a session that uses soft constraints for device placement, and log the resulting placement decisions, create a session as follows:

# Launch the graph in a session that allows soft device placement and
# logs the placement decisions.
sess = tf.compat.v1.Session(config=tf.compat.v1.ConfigProto(
    allow_soft_placement=True,
    log_device_placement=True))

target (Optional.) The execution engine to connect to. Defaults to using an in-process engine. See Distributed TensorFlow for more examples.
graph (Optional.) The Graph to be launched (described above).
config (Optional.) A ConfigProto protocol buffer with configuration options for the session.

graph The graph that was launched in this session.
graph_def A serializable version of the underlying TensorFlow graph.
sess_str The TensorFlow process to which this session will connect.

Methods

as_default

View source

Returns a context manager that makes this object the default session.

Use with the with keyword to specify that calls to tf.Operation.run or tf.Tensor.eval should be executed in this session.

c = tf.constant(..)
sess = tf.compat.v1.Session()

with sess.as_default():
  assert tf.compat.v1.get_default_session() is sess
  print(c.eval())

To get the current default session, use tf.compat.v1.get_default_session.

c = tf.constant(...)
sess = tf.compat.v1.Session()
with sess.as_default():
  print(c.eval())
# ...
with sess.as_default():
  print(c.eval())

sess.close()

Alternatively, you can use with tf.compat.v1.Session(): to create a session that is automatically closed on exiting the context, including when an uncaught exception is raised.

Returns
A context manager using this session as the default session.

close

View source

Closes this session.

Calling this method frees all resources associated with the session.

Raises
tf.errors.OpError Or one of its subclasses if an error occurs while closing the TensorFlow session.

list_devices

View source

Lists available devices in this session.

devices = sess.list_devices()
for d in devices:
  print(d.name)

Where:

Each element in the list has the following properties

  • name: A string with the full name of the device. ex: /job:worker/replica:0/task:3/device:CPU:0
  • device_type: The type of the device (e.g. CPU, GPU, TPU.)
  • memory_limit: The maximum amount of memory available on the device. Note: depending on the device, it is possible the usable memory could be substantially less.

Raises
tf.errors.OpError If it encounters an error (e.g. session is in an invalid state, or network errors occur).

Returns
A list of devices in the session.

make_callable

View source

Returns a Python callable that runs a particular step.

The returned callable will take len(feed_list) arguments whose types must be compatible feed values for the respective elements of feed_list. For example, if element i of feed_list is a tf.Tensor, the ith argument to the returned callable must be a numpy ndarray (or something convertible to an ndarray) with matching element type and shape. See tf.Session.run for details of the allowable feed key and value types.

The returned callable will have the same return type as tf.Session.run(fetches, ...). For example, if fetches is a tf.Tensor, the callable will return a numpy ndarray; if fetches is a tf.Operation, it will return None.

Args
fetches A value or list of values to fetch. See tf.Session.run for details of the allowable fetch types.
feed_list (Optional.) A list of feed_dict keys. See tf.Session.run for details of the allowable feed key types.
accept_options (Optional.) If True, the returned Callable will be able to accept tf.compat.v1.RunOptions and tf.compat.v1.RunMetadata as optional keyword arguments options and run_metadata, respectively, with the same syntax and semantics as tf.Session.run, which is useful for certain use cases (profiling and debugging) but will result in measurable slowdown of the Callable's performance. Default: False.

Returns
A function that when called will execute the step defined by feed_list and fetches in this session.

Raises
TypeError If fetches or feed_list cannot be interpreted as arguments to tf.Session.run.

partial_run

View source