Operations as a Computational Graph
Summary
In this script, we create an array and feed it into a placeholder. We then multiply it by a constant.
Computational Graph Output
Viewing the computational graph in Tensorboard, as created by the script:
# 01_operations_on_a_graph.py
# Operations on a Computational Graph
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
import os
from tensorflow.python.framework import ops
ops.reset_default_graph()
# Create graph
sess = tf.Session()
# Create tensors
# Create data to feed in
x_vals = np.array([1., 3., 5., 7., 9.])
x_data = tf.placeholder(tf.float32)
m = tf.constant(3.)
# Multiplication
prod = tf.mul(x_data, m)
for x_val in x_vals:
print(sess.run(prod, feed_dict={x_data: x_val}))
merged = tf.merge_all_summaries()
if not os.path.exists('tensorboard_logs/'):
os.makedirs('tensorboard_logs/')
my_writer = tf.train.SummaryWriter('tensorboard_logs/', sess.graph)
#tensorboard_logs文件夹保存在程序当前位置
Multiple Operations on a Computational Graph
Summary
In this script, we will create an array and perform two multiplications on it, followed by addition:
output = (input) * (m1) * (m2) + (a1)
Computational Graph Output
Viewing the computational graph in Tensorboard:
# Layering Nested Operations
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
import os
from tensorflow.python.framework import ops
ops.reset_default_graph()
# Create graph
sess = tf.Session()
# Create tensors
# Create data to feed in
my_array = np.array([[1., 3., 5., 7., 9.],
[-2., 0., 2., 4., 6.],
[-6., -3., 0., 3., 6.]])
x_vals = np.array([my_array, my_array + 1])
x_data = tf.placeholder(tf.float32, shape=(3, 5))
m1 = tf.constant([[1.],[0.],[-1.],[2.],[4.]])
m2 = tf.constant([[2.]])
a1 = tf.constant([[10.]])
# 1st Operation Layer = Multiplication
prod1 = tf.matmul(x_data, m1)
# 2nd Operation Layer = Multiplication
prod2 = tf.matmul(prod1, m2)
# 3rd Operation Layer = Addition
add1 = tf.add(prod2, a1)
for x_val in x_vals:
print(sess.run(add1, feed_dict={x_data: x_val}))
#merged = tf.merge_all_summaries()
merged = tf.summary.merge_all()
if not os.path.exists('/tensorboard_logs/'):
os.makedirs('/tensorboard_logs/')
my_writer = tf.summary.FileWriter('/tensorboard_logs/', sess.graph)
[[ 102.]
[ 66.]
[ 58.]]
[[ 114.]
[ 78.]
[ 70.]]