Exploring the example code
You can download this example code from the "Downloads" link on Wiley.com. The archive’s name istf_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 python
or 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:
python simple_math.pyFeel 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 thech2
directory in this book’s example code, you find a module named hello_tensorflow.py
. This listing presents the code.
Hello TensorFlow!This code performs three important tasks:"""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))
- Creates a
Tensor
namedmsg
that contains two string elements. - Creates a
Session
namedsess
and makes it the default session. - Launches the new Session and prints its result.
ch2
directory in this book's example code. Then, if you’re using Python 2, you can execute the following command:
python hello_tensorflow.pyIf you’re using Python 3, you can run the module with the following command:
python3 hello_tensorflow.pyAs the Python interpreter does its magic, you should see the following message:
b'Hello TensorFlow'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.A 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.