tensorflow 完整基础代码
代码
# 创建图形
graph = tf.Graph()
# 默认图形
with graph.as_default():
# 占位符
a = tf.placeholder(tf.float32, name="a")
b = tf.placeholder(tf.float32, name="b")
# +, -, *, /
plus = tf.add(a, b, name="a_plus_b")
minus = tf.subtract(a, b, name="a_minus_b")
times = tf.multiply(a, b, name="a_times_b")
divided = tf.divide(a, b, name="a_divided_by_b")
# 变量
# trainable=False 训练时不更新
global_step = tf.Variable(0, trainable=False, dtype=tf.int32, name="global_step")
# tf.assign(a, b) 将b赋值给a
inc_step = tf.assign(global_step, global_step + 1, name="increment_step")
# 全局初始化变量
init = tf.global_variables_initializer()
# 定义图会话,用于启动、执行图
sess = tf.Session(graph=graph)
sess.run(init)
# 喂给数据
a_val, b_val = 8.0, 4.0
feed_dict = {a: a_val, b: b_val}
# 运行计算的节点列表
fetches = [inc_step, plus, minus, times, divided]
results = sess.run(fetches, feed_dict)
# 打印结果
print("a: {} b: {}".format(a_val, b_val))
for i, result in enumerate(results):
print("{}: {}".format(fetches[i].name[:-2], result))
sess.close() # 关闭会话
运行结果
a: 8.0 b: 4.0
increment_step: 1
a_plus_b: 12.0
a_minus_b: 4.0
a_times_b: 32.0
a_divided_by_b: 2.0
macos tensorboard可视化
import itertools as it
import os.path as osp
def get_fresh_dir(parent_dir):
for i in it.count():
possible_dir = osp.join(parent_dir, str(i))
if not osp.exists(possible_dir):
return possible_dir
summary_graph = tf.Graph()
with summary_graph.as_default():
a = tf.placeholder(tf.float32, name="a")
b = tf.placeholder(tf.float32, name="b")
a_summ = tf.summary.scalar("a_input_summary", a)
b_summ = tf.summary.scalar("b_input_summary", b)
plus = tf.add(a, b, name="a_plus_b")
minus = tf.subtract(a, b, name="a_minus_b")
times = tf.multiply(a, b, name="a_times_b")
divided = tf.divide(a, b, name="a_divided_by_b")
plus_summ = tf.summary.scalar("plus_op_summary", plus)
minus_summ = tf.summary.scalar("minus_op_summary", minus)
times_summ = tf.summary.scalar("times_op_summary", times)
divided_summ = tf.summary.scalar("divided_op_summary", divided)
global_step = tf.Variable(0, trainable=False, dtype=tf.int32, name="global_step")
inc_step = tf.assign(global_step, global_step + 1, name="increment_step")
init = tf.global_variables_initializer()
merged = tf.summary.merge_all()
sess = tf.Session(graph=summary_graph)
writer = tf.summary.FileWriter(get_fresh_dir('tbout/basic_summaries'),
graph=summary_graph)
sess.run(init)
命令行执行
# tbout/basic_summaries为你本机创建的目录
tensorboard --logdir=tbout/basic_summaries
在浏览器输入
TensorBoard 2.2.2 at
http://localhost:6006/
(Press CTRL+C to quit)
欢迎大家交流学习,任何问题都可以留言