Flowing with TensorFlow 02 – Hello World

In pure python the Hello World program is just one line. It looks like follows in python shell.

>>> print("Hello World")

The out put will be

Hello World

But when it comes to the Hello World program of TensorFlow things are little bit different.

First we have to import the tensorflow library (You have to have tensorflow installed. Although virtual environment installation is recommended.)

>>> import tensorflow as tf

Then we need to add a node to the graph. Tensorflow needs a graph to execute. Without a graph we cannot do even a small task. Even though this seems like a pain at beginning it is very useful to be defining things in a graph (we will see in the coming weeks). So we will define a node in the graph which is linked to a ‘constant’

>>> someName = tf.constant("Hello World")

Now at this point if we print the variable (tensorflow constant) it will give like the following.

>>> print(someName)

Tensor("Const:0", shape=(), dtype=string)

It didn’t print ‘Hello World’. It only told us ‘hey, the someName is a constant which is a scalar having a data type String‘. It will not tell us the value of ‘someName’. Because from the TensorFlow perspective it only has a graph, no one told it to execute the graph and assign the value ‘Hello World’ to the constant ‘someName’. So lets do it. For that we need a session.

>>> sess = tf.Session()

Then we execute the ‘someName’ node in the graph using this session and get the value to a variable result and then print it.

>>> result = sess.run(someName)
>>> print(result)
Hello World

So that’s it. The hello_world.py would look like following at the end.

import tensorflow as tf

someName = tf.constant("Hello World")
sess = tf.Session()
result = sess.run(someName)
print(result)

There are different ways of using the session and other stuff like placeholders and variables which we need before going in to more productive coding and also we still haven’t discussed what is a tensor. We will go in to those in the next few discussions.

Next on : Flowing with TensorFlow 03 – What the hell is a Session

Advertisements

One thought on “Flowing with TensorFlow 02 – Hello World

  1. Pingback: Flowing with TensorFlow 01 – An Introduction | The Puddle Jumper

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s