计算图
三种计算图
所谓计算图,计算图由节点

有三种计算图的构建方式:静态计算图,动态计算图,以及
而在
使用动态计算图即
如果需要在
静态计算图
在
import tensorflow as tf
#定义计算图
g = tf.Graph()
with g.as_default():
#placeholder为占位符,执行会话时候指定填充对象
x = tf.placeholder(name='x', shape=[], dtype=tf.string)
y = tf.placeholder(name='y', shape=[], dtype=tf.string)
z = tf.string_join([x,y],name = 'join',separator=' ')
#执行计算图
with tf.Session(graph = g) as sess:
print(sess.run(fetches = z,feed_dict = {x:"hello",y:"world"}))
import tensorflow as tf
g = tf.compat.v1.Graph()
with g.as_default():
x = tf.compat.v1.placeholder(name='x', shape=[], dtype=tf.string)
y = tf.compat.v1.placeholder(name='y', shape=[], dtype=tf.string)
z = tf.strings.join([x,y],name = "join",separator = " ")
with tf.compat.v1.Session(graph = g) as sess:
# fetches的结果非常像一个函数的返回值,而feed_dict中的占位符相当于函数的参数序列。
result = sess.run(fetches = z,feed_dict = {x:"hello",y:"world"})
print(result)
动态计算图
在
动态计算图已经不区分计算图的定义和执行了,而是定义后立即执行。因此称之为
# 动态计算图在每个算子处都进行构建,构建后立即执行
x = tf.constant("hello")
y = tf.constant("world")
z = tf.strings.join([x,y],separator=" ")
tf.print(z)
# 可以将动态计算图代码的输入和输出关系封装成函数
def strjoin(x,y):
z = tf.strings.join([x,y],separator = " ")
tf.print(z)
return z
result = strjoin(tf.constant("hello"),tf.constant("world"))
print(result)
Autograph
动态计算图运行效率相对较低。可以用
实践中,我们一般会先用动态计算图调试代码,然后在需要提高性能的的地方利用
import tensorflow as tf
# 使用autograph构建静态图
@tf.function
def strjoin(x,y):
z = tf.strings.join([x,y],separator = " ")
tf.print(z)
return z
result = strjoin(tf.constant("hello"),tf.constant("world"))
print(result)
import datetime
# 创建日志
import os
stamp = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
logdir = os.path.join('data', 'autograph', stamp)
## 在 Python3 下建议使用 pathlib 修正各操作系统的路径
# from pathlib import Path
# stamp = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
# logdir = str(Path('./data/autograph/' + stamp))
writer = tf.summary.create_file_writer(logdir)
# 开启autograph跟踪
tf.summary.trace_on(graph=True, profiler=True)
# 执行autograph
result = strjoin("hello","world")
# 将计算图信息写入日志
with writer.as_default():
tf.summary.trace_export(
name="autograph",
step=0,
profiler_outdir=logdir)
然后我们可以启动
# 启动 tensorboard在jupyter中的魔法命令
%load_ext tensorboard
# 启动tensorboard
%tensorboard --logdir ./data/autograph/