How to Launch Hello TensorFlow!
After you install TensorFlow, you’re ready to start creating and executing applications. This section walks through the process of running an application that prints a simple message.
Exploring the example code
You can download this example code from Dummies.com by searching for TensorFlow For Dummies and going to the Downloads tab. The archive’s name is
tf_dummies.zip, and if you decompress it, you see that it contains folders named after chapters (ch2, ch3, and so on).
Each chapter folder contains one or more Python files (
*.py). In each case, you can execute the module by changing to the directory and running
python3 followed by the filename.
For example, if you have Python 2 installed, you can execute the code in
simple_math.py by changing to the
ch3 directory and entering the following command:
Feel free to use this example code in professional products, academic work, and morally questionable experiments. But do not use any of this code to program evil robots!
Launching Hello TensorFlow!
Programming books have a long tradition of introducing their topic with a simple example that prints a welcoming message. If you open the
ch2 directory in this book’s example code, you find a module named
hello_tensorflow.py. This listing presents the code.
Hello TensorFlow! """A simple TensorFlow application""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf # Create tensor msg = tf.string_join(["Hello ", "TensorFlow!"]) # Launch session with tf.Session() as sess: print(sess.run(msg))
This code performs three important tasks:
- Creates a
msgthat contains two string elements.
- Creates a
sessand makes it the default session.
- Launches the new Session and prints its result.
Running the code is simple. Open a command line and change to the
ch2 directory in this book’s example code. Then, if you’re using Python 2, you can execute the following command:
If you’re using Python 3, you can run the module with the following command:
As the Python interpreter does its magic, you should see the following message:
The welcome message is straightforward, but the application’s code probably isn’t as clear. A
Tensor instance is an n-dimensional array that contains numeric or string data. Tensors play a central role in TensorFlow development.
Session serves as the environment in which TensorFlow operations can be executed. All TensorFlow operations, from addition to optimization, must be executed through a session.