1. 什么是TensorFlow
这里摘出官网的两句措辞:
(1)TensorFlow is an open source software library for machine intelligence
(2)TensorFlow is an open source software library for numerical computation using data flow graphs
官网的定义并未将TensorFlow称为一个机器学习库,而是数值计算工具。 TensorFlow提供了一个可使用户用数学方法从零开始定义模型的函数和类的广泛套件。用户可以建立自定义的,具有高灵活性的模型。
import tensorflow as tf
import numpy as np
graph = tf.Graph()
with graph.as_default():
with tf.name_scope("variables"):
# 追踪数据流图的运行次数
global_step = tf.Variable(0, dtype=tf.int32, trainable=False, name="global_step")
# 追踪该模型的所有输出随时间的累加和的Variable
total_output = tf.Variable(0.0, dtype=tf.float32, trainable=False, name="total_output")
创建transformation name scope,里面包含input, intermediate_layer及output
# 主要的变换op
with tf.name_scope("transformation"):
# 独立的输入层
with tf.name_scope("input"):
# 创建可接收一个向量的占位符
a = tf.placeholder(tf.float32, shape=[None], name="input_placeholder_a")
# 独立的中间层
with tf.name_scope("intermediate_layer"):
b = tf.reduce_prod(a, name="product_b")
c = tf.reduce_sum(a, name="sum_c")
# 独立的输出层
with tf.name_scope("output"):
output = tf.add(b, c, name='output')
经过上述变换计算,需要对前面定义的variable对象进行更新,下面创建一个update名称作用域来容纳这些变化
with tf.name_scope("update"):
# 用最新的输出更新Variable对象total_output
update_total = total_output.assign_add(output)
# 计数器global_step +1
increment_step = global_step.assign_add(1)
更新完variable对象之后,便可创建我们感兴趣的TensorBoard汇总数据,可以放入到summaries名称作用域中
with tf.name_scope("summaries"):
avg = tf.div(update_total, tf.cast(increment_step, tf.float32), name="average")
# 为输出节点创建汇总数据
tf.summary.scalar('Output', output)
tf.summary.scalar('Sum_of_outputs', update_total)
tf.summary.scalar('average_of_outputs', avg)
为完成data flow graph的创建,还需要创建variable对象的初始化Op,和用于将 所有汇总数据组织到一个Op的辅助节点
with tf.name_scope("global_ops"):
init = tf.global_variables_initializer()
merged_summaries = tf.summary.merge_all()
2.运行数据流图
打开一个session对象,并加载已经创建好的Graph对象,
打开一个summary.FileWriter对象,利用它保存汇总数据
sess = tf.Session(graph=graph)
writer = tf.summary.FileWriter('./frame', graph)
with graph.as_default():
sess.run(tf.global_variables_initializer())
-》确保output, increment_step,merged_summaries Op得到执行
-》为写入汇总数据,需要保存global_step和merged_summaries的值
-》将汇总数据添加到SummaryWriter对象中,global_step参数创建了一个折线图的横轴
def run_graph(input_tensor):
feed_dict = {a: input_tensor}
_, step, summary = sess.run([output, increment_step, merged_summaries], feed_dict=feed_dict)
writer.add_summary(summary, global_step=step)
创建数据使用上面定义的函数,writer.flush()将汇总数据写入磁盘
for i in range(10):
test_input = np.random.randint(0, 20, 5)
run_graph(test_input)
writer.flush() # 数据填充完毕后,用flush()函数将汇总数据写入磁盘
writer.close()
sess.close()
tensorboard --logdir=frame
浏览器打开localhost:6006