凯鲁嘎吉
用书写铭记日常,最迷人的不在远方
 

TensorFlow通过名称作用域组织数据流图

 

作者:凯鲁嘎吉 - 博客园 http://www.cnblogs.com/kailugaji/

所用版本:python3.5.2,tensorflow1.8.0,tensorboard1.8.0

In [1]:
# 名称作用域的基本用法是将Op添加到with tf.name_scope(<name>)语句块中
In [2]:
import tensorflow as tf
In [3]:
with tf.name_scope("A"):
    a = tf.add(1, 2, name="A_add")
    b = tf.multiply(a, 3, name="A_mul")
In [4]:
with tf.name_scope("B"):
    c = tf.add(4, 5, name="B_add")
    d = tf.multiply(c, 6, name="B_mul")
In [5]:
e = tf.add(b, d, name="Output")
In [6]:
writer = tf.summary.FileWriter('./logs', graph=tf.get_default_graph())
In [7]:
writer.close()
In [8]:
sess = tf.Session()
In [9]:
sess.run([a, b, c, d, e])
Out[9]:
[3, 9, 9, 54, 63]
In [11]:
sess.close()
 

打开Anaconda Prompt
(base) C:\Users\hp>activate tensorflow
(tensorflow) C:\Users\hp>cd..
(tensorflow) C:\Users>D:
(tensorflow) D:>cd ./Python code
(tensorflow) D:\Python code>tensorboard --logdir=logs
在浏览器输入http://HP:6006 或者http://localhost:6006 即可看到对应的数据流图。

In [12]:
# 在每个名称作用域内,可看到已经添加到该数据流图中的各个Op,也可将名称作用域嵌入在其他名称作用域内
In [13]:
reset
 
Once deleted, variables cannot be recovered. Proceed (y/[n])? y
In [1]:
import tensorflow as tf
In [2]:
graph = tf.Graph()
In [3]:
with graph.as_default():
    in1 = tf.placeholder(tf.float32, shape=[], name="a")
    in2 = tf.placeholder(tf.float32, shape=[], name="b")
    const = tf.constant(3, dtype=tf.float32, name="fix")
In [4]:
with tf.name_scope("Transformation"):
    with tf.name_scope("A"):
        A_mul = tf.multiply(in1, const)
        A_out = tf.subtract(A_mul, in1)
    with tf.name_scope("B"):
        B_mul = tf.multiply(in2, const)
        B_out = tf.subtract(B_mul, in2)
    with tf.name_scope("C"):
        C_div = tf.div(A_out, B_out)
        C_out = tf.add(C_div, const)
    with tf.name_scope("D"):
        D_div = tf.div(B_out, A_out)
        D_out = tf.add(D_div, const)
        out = tf.maximum(C_out, D_out)
In [5]:
writer = tf.summary.FileWriter('./logs/2', graph=graph)
In [6]:
writer.close()
 

打开Anaconda Prompt
(base) C:\Users\hp>activate tensorflow
(tensorflow) C:\Users\hp>cd..
(tensorflow) C:\Users>D:
(tensorflow) D:>cd ./Python code
(tensorflow) D:\Python code>tensorboard --logdir=./logs/2
在浏览器输入http://HP:6006 或者http://localhost:6006 即可看到对应的数据流图。

不知道为啥没显示作用域的名称(Transformation, A, B, C, D)及范围。

 

posted on 2021-08-28 18:05  凯鲁嘎吉  阅读(76)  评论(0编辑  收藏  举报