Session

Session is a class for running TensorFlow operations. A session encapsulates the control and state of the TensorFlow runtime.


In [1]:
import tensorflow as tf

# create a graph
a = tf.constant(1)

# 1
with tf.Session() as session:
    print(session.run(a))

# 2
session = tf.Session()
print(session.run(a))
session.close()

# 3 Interactive session, usefull in shells
tf.InteractiveSession()
print(a.eval())


1
1
1

Constants


In [2]:
a = tf.constant([[1, 2, 3], [4, 5, 6]], dtype=tf.float32, name='constant')

with tf.Session() as session:
    print(session.run(a))
    print("shape: ", a.get_shape(), ",type: ", type(a.get_shape()))


[[ 1.  2.  3.]
 [ 4.  5.  6.]]
shape:  (2, 3) ,type:  <class 'tensorflow.python.framework.tensor_shape.TensorShape'>

Variables


In [3]:
var = tf.Variable(tf.random_normal([3], stddev=0.1), name='var')

with tf.Session() as session:
    # must initialize before usage
    init = tf.variables_initializer([var])
    session.run(init)
    # or initialize all vars
    init = tf.global_variables_initializer()
    session.run(init)
    print(session.run(var))


[ 0.03565044  0.0211431   0.07576992]

Placeholder


In [4]:
x = tf.placeholder(tf.int32)
y = tf.placeholder(tf.int32)

add = tf.add(x, y)
add = x + y

with tf.Session() as session:
    result = session.run(add, feed_dict={x: 1, y: 2})
    print("1 + 2 = {0}".format(result))


1 + 2 = 3