node1 = tf.constant(3.0, dtype=tf.float32) node2 = tf.constant(4.0)# also tf.float32 implicitly print(node1, node2)
The final print result is:
Tensor("Const:0", shape=(), dtype=float32) Tensor("Const_1:0",shape=(), dtype=float32)
To print the final result, we must use a session: a session encapsulates the control and state of the TensorFlow runtime
sess = tf.Session () print (sess.run ([node1, node2]))
We can combine Tensor node operations (the operation is still a node) to construct more complex computations,
node3 = tf.add(node1, node2) print("node3:", node3) print("sess.run(node3):", sess.run(node3))
The print result is:
node3:Tensor("Add:0", shape=(), dtype=float32) sess.run (node3): 7.0
3. TensorFlow provides a unified call called TensorBoard, which can display a picture of a computational graph; the following screenshot shows the computational graph
4 A computational graph can be parameterized to receive external input, as a placeholder (placeholder), a placeholder is allowed to provide a value later.
a = tf.placeholder(tf.float32) b = tf.placeholder(tf.float32) adder_node = a + b # + provides a shortcut for tf.add(a, b)
print(sess.run(adder_node, {a:3, b:4.5})) print(sess.run(adder_node, {a: [1,3], b: [2,4]}))
turn out:
7.5
[3. 7.]
In TensorBoard, the computation graph looks like this:
We can add additional operations to make the computational graph more complex, such as
add_and_triple = adder_node *3. print(sess.run(add_and_triple, {a:3, b:4.5})) The output is: 22.5
5 It is important to implement the handling of TensorFlow subgraphs that initialize all global variables, which are uninitialized until we call sess.run. Since x is a placeholder, we can evaluate linear_model for multiple values of x simultaneously, for example:
W = tf.Variable([.3], dtype=tf.float32) b = tf.Variable([-.3], dtype=tf.float32) x = tf.placeholder(tf.float32) linear_model = W*x + b init = tf.global_variables_initializer() sess.run(init) print(sess.run(linear_model, {x: [1,2,3,4]}))
Evaluate linear_model
The output is
[0. 0.30000001 0.60000002 0.90000004]