Chapter 1 Basic concepts of TensorFlow

TensorFlow Tutorial: Understanding Deep Learning

TensorFlow tutorial: Tensor Basics

TensorFlow tutorial: Session basics

TensorFlow TensorFlow Graph tutorial

Session

Sessions in TensorFlow are used to perform defined operations. The session owns and manages all the resources that the TensorFlow program runs on. After all calculations are complete, the session needs to be closed to help the system reclaim resources, otherwise resource leakage may occur.

It is easy to understand that when TensorFlow defines variables and computes, it does not calculate immediately. It needs to be performed through session. This is like a circuit diagram, when the circuit is connected, when the plug is energized, the whole circuit starts to operate.

# define tensor
v1 = tf.constant(value=1,name='v1',shape=(1.2),dtype=tf.float32)
v2 = tf.constant(value=2,name='v1',shape=(1.2),dtype=tf.float32)
# define the calculation
add = v1 + v2
# to create the session
sess = tf.Session()
# execute calculation
result = sess.run(add)
print(reslut)
# close session to avoid resource leakage
sess.close()

[3. 3.]]
Copy the code

Calling a session in this way requires an explicit call to session.close () to close the session and free up resources to avoid resource leakage.

Of course, we are more likely to use sessions through Python’s context manager to automatically release all resources.

# define tensor
v1 = tf.constant(value=1,name='v1', shape = (1, 2), dtype = tf. Float32) v2 = tf. Constant (value = 2, name ='v1', shape = (1, 2), dtype = tf. Float32)# define the calculation
add = v1 + v2
# to create the session
with tf.Session() as sess:
    # execute calculation
    sess.run(add)
Copy the code

This allows us to close the Session without manually calling session.close ().

analyse

Today we looked at two ways to use a Session. It’s not that simple, but we’ll see it a lot in this tutorial.