# 图

1,731次阅读

1. 输入节点
2. 模型参数
3. OP

## 默认计算图

v1 = tf.constant(value=1,name='v1',shape=(1,2),dtype=tf.float32)
v2 = tf.constant(value=2,name='v2',shape=(1,2),dtype=tf.float32)
with tf.Session() as sess:
# 判断v1所在的graph是否是默认的graph
print(v1.graph is tf.get_default_graph())
# 输出 True
# 输出 [[3. 3.]]


## 创建Graph

# 新增计算图
new_graph = tf.Graph()
with new_graph.as_default():
# 在新增的计算图中进行计算
v1 = tf.constant(value=3, name='v1', shape=(1, 2), dtype=tf.float32)
v2 = tf.constant(value=4, name='v2', shape=(1, 2), dtype=tf.float32)
#  通过graph=new_graph指定Session所在的计算图
with tf.Session(graph=new_graph) as sess:
sess.run(tf.global_variables_initializer())
# 在默认计算图中进行计算
v1 = tf.constant(value=1,name='v1',shape=(1,2),dtype=tf.float32)
v2 = tf.constant(value=2,name='v2',shape=(1,2),dtype=tf.float32)
# 通过graph=tf.get_default_graph()指定Session所在默认的计算图
with tf.Session(graph=tf.get_default_graph()) as sess:
sess.run(tf.global_variables_initializer())

# 输出：[[7. 7.]]
# 输出：[[3. 3.]]


## 带有PlaceHolder的计算图

import  tensorflow as tf

a=tf.placeholder(dtype=tf.float32,shape=[1])
b=tf.placeholder(dtype=tf.float32,shape=[1])
c=a+b
init=tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
print(sess.run(c,feed_dict={a:[2.1],b:[3.2]}))

[5.3]


## 多个图之间互不相干

import tensorflow as tf

g1=tf.Graph()
with g1.as_default():
v=tf.get_variable("v",[1],initializer=tf.zeros_initializer(dtype=tf.float32))

g2=tf.Graph()
with g2.as_default():
v=tf.get_variable("v",[1],initializer=tf.ones_initializer(dtype=tf.float32))

with tf.Session(graph=g1) as sess:
tf.initialize_all_variables().run()
with tf.variable_scope("",reuse=True):  # 当reuse=True时，tf.get_variable只能获取指定命名空间内的已创建的变量
print(sess.run(tf.get_variable("v")))

with tf.Session(graph=g2) as sess:
tf.initialize_all_variables().run()
with tf.variable_scope("",reuse=True):  # 当reuse=True时，tf.get_variable只能获取指定命名空间内的已创建的变量
print(sess.run(tf.get_variable("v")))

#输出：[0.]      [1.]


# 跟图相关的一些操作

1、根据 tensor name 来获取对应的tensor

import  tensorflow as tf

a=tf.placeholder(dtype=tf.float32,shape=[1],name='v1')
b=tf.placeholder(dtype=tf.float32,shape=[1],name='v2')
c=a+b
init=tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
print(sess.run(c,feed_dict={a:[2.1],b:[3.2]}))

print(sess.run(test1,feed_dict={a:[1.0],b:[2.0]}))

[5.3]
[3.]


2、获取 operation 信息