Python ProgrammingPython Programming

This is the second tutorial in our TensorFlow tutorial series.

Now we have a basic installation of TensorFlow, we can continue to our first working examples. We will adhere to the well-established tradition and starts with a "hello world" program.

I would personally recommend using Wing Python IDE which have powerful debugger and intelligent editor.

Hello World

Our first example is a simple program that merges two words "Hello" and "World!" and displays the output—"Hello World!". Basic and unambiguous, this example presents many of the core elements of TensorFlow and the ways in which it is distinct from a regular Python program.

1) “Hello world” with TensorFlow

##
# TensorFlow program to display Hello World

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import tensorflow as tf
# Create tensor
hello = tf.string_join(["Hello, World"])
# Launch session
sess = tf.Session()
print(sess.run(hello))

Sample output of above program, shown as below:
C:\tf\examples>pycodestyle --first example1.py

C:\tf\examples>python example1.py
b'Hello, World'

C:\tf\examples>

This code performs below list of tasks:

  • Creates a Tensor named hello that contains two string elements.
  • Creates a Session object named sess, acts as an interface to the external TensorFlow computation mechanism.
  • Launches the new Session and prints its result.

We understand that; you are aware with Python and imports, here first few important lines should be present in all Python files as per TensorFlow Style Guide:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function


This wraps up the first TensorFlow example. Next, we jump right in with a simple machine learning example, which reveals much of the potential of the TensorFlow framework.