09.05.2023 Views

pdfcoffee

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

An example to start with

We'll consider a simple example of adding two vectors. The graph we want to

build is:

Chapter 2

The corresponding code to define the computational graph is:

v_1 = tf.constant([1,2,3,4])

v_2 = tf.constant([2,1,5,3])

v_add = tf.add(v_1,v_2) # You can also write v_1 + v_2 instead

Next, we execute the graph in the session:

or

with tf.Session() as sess:

print(sess.run(v_add))

sess = tf.Session()

print(sess.run(v_add))

sess.close()

This results in printing the sum of two vectors:

[3 3 8 7]

Remember, each session needs to be explicitly closed using close().

The building of a computational graph is very simple – you go on adding the

variables and operations and passing them through (flow the tensors). In this way

you build your neural network layer by layer. TensorFlow also allows you to use

specific devices (CPU/GPU) with different objects of the computational graph using

tf.device(). In our example, the computational graph consists of three nodes, v_1

and v_2 representing the two vectors, and v_add, the operation to be performed on

them. Now to bring this graph to life we first need to define a session object using

tf.Session(). We named our session object sess. Next, we run it using the run

method defined in the Session class as:

run (fetches, feed_dict=None, options=None, run_metadata)

[ 53 ]

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!