# 2-2,三种计算图

### 二，静态计算图

TensorFlow 1.0静态计算图范例

``````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"}))

``````

TensorFlow2.0 怀旧版静态计算图

TensorFlow2.0为了确保对老版本tensorflow项目的兼容性，在tf.compat.v1子模块中保留了对TensorFlow1.0那种静态计算图构建风格的支持。

``````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)

``````
``````b'hello world'
``````

### 三，动态计算图

Eager这个英文单词的原意是"迫不及待的"，也就是立即执行的意思。

``````# 动态计算图在每个算子处都进行构建，构建后立即执行

x = tf.constant("hello")
y = tf.constant("world")
z = tf.strings.join([x,y],separator=" ")

tf.print(z)
``````
``````hello world
``````
``````# 可以将动态计算图代码的输入和输出关系封装成函数

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)
``````
``````hello world
tf.Tensor(b'hello world', shape=(), dtype=string)
``````

### 四，TensorFlow2.0的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)
``````
``````hello world
tf.Tensor(b'hello world', shape=(), dtype=string)
``````
``````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中的魔法命令
``````#启动tensorboard
``````