Let's look at a simple arithmetic procedure in pure Python:
In [1]:
# Create input constants:
X = 2.0
Y = 3.0
# Perform addition:
Z = X + Y
# Print output:
print Z
Now let's try to do the same thing using TensorFlow:
In [2]:
# Import TensorFlow library:
import tensorflow as tf
# Print TensorFlow version, just for good measure:
print( 'TensorFlow Version: ' + tf.VERSION )
In [3]:
# Create input constants:
opX = tf.constant( 2.0 )
opY = tf.constant( 3.0 )
# Create addition operation:
opZ = tf.add( opX, opY )
# Print operation:
print opZ
Where's the resulting value?
Notice that in the pure Python code, calling:
print Z
prints the resulting value:
5.0
But in the TensorFlow code, the print
call gives us:
Tensor("Add:0", shape=(), dtype=float32)
TensorFlow uses a somewhat different programming model from what we're used to in conventional Python code.
Here's a brief overview from the TensorFlow Basic Usage tutorial:
Overview:
TensorFlow is a programming system in which you represent computations as graphs. Nodes in the graph are called ops (short for operations). An op takes zero or more Tensors, performs some computation, and produces zero or more Tensors. A Tensor is a typed multi-dimensional array. For example, you can represent a mini-batch of images as a 4-D array of floating point numbers with dimensions [batch, height, width, channels].
A TensorFlow graph is a description of computations. To compute anything, a graph must be launched in a Session. A Session places the graph ops onto Devices, such as CPUs or GPUs, and provides methods to execute them. These methods return tensors produced by ops as numpy ndarray objects in Python, and as tensorflow::Tensor instances in C and C++.
TensorFlow programs are usually structured into a construction phase, that assembles a graph, and an execution phase that uses a session to execute ops in the graph.
For example, it is common to create a graph to represent and train a neural network in the construction phase, and then repeatedly execute a set of training ops in the graph in the execution phase.
In other words:
The TensorFlow code above only assembles the graph to perform an addition operation on our two input constants.
To actually run the graph and retrieve the output, we need to create a session and run the addition operation through it:
In [4]:
# Create input constants:
opX = tf.constant( 2.0 )
opY = tf.constant( 3.0 )
# Create addition operation:
opZ = tf.add( opX, opY )
# Create session:
with tf.Session() as sess:
# Run session:
Z = sess.run( opZ )
# Print output:
print Z
In [ ]: