没有指定Graph的时候使用的是默认的
import tensorflow as tf
print(a.graph is tf.get_default_graph())
不同的Graph中张量计算是隔离的
import tensorflow as tf
li1=tf.Graph()
with li1.as_default():
v1=tf.get_variable("v1", tf.zeros_initializer(shape=[1]))
with tf.Session(graph=li1) as session1:
tf.initialize_all_variables().run()
with tf.variable_scope("",reuse=True):
print(sssion1.run(tf.get_variable("v1")))
li2=tf.Graph()
with li2.as_default():
v1=tf.get_variable("v1", tf.zeros_initializer(shape=[1]))
with tf.Session(graph=li2) as session2:
tf.initialize_all_variables().run()
with tf.variable_scope("",reuse=True):
print(sssion2.run(tf.get_variable("v1")))
Graph可以指定那个cpu运行
import tensorflow as tf
g=tf.Graph()
with g.device('/gpu:0'):
realut=a+b
Tensor的属性解析
import tensorflow as tf
a=tf.constant([1.0,2.0],name='a')
b=tf.constant([2.0,3.0],name='b')
result=tf.add(a,b,name='lijun')
print(result)
Tensor("lijun:0", shape=(2,), dtype=float32)
Tensor(节点名称:第几个结果,维度,属性)
属性:属性不同的张量tf会检验报错
import tensorflow as tf
a=tf.constant([1,2],name='a')
b=tf.constant([2.0,3.0],name='b')
result=tf.add(a,b,name='lijun')
print(result)-----------------------error
这时候可以显示指定
import tensorflow as tf
a=tf.constant([1,2],name='a',dtype=tf.float32)
b=tf.constant([2.0,3.0],name='b')
result=tf.add(a,b,name='lijun')
print(result)
Session有2种调用方式,显示调用,python上下文调用
显示调用
session=tf.Session()
session.run(...)
session.close()
python 上下文调用
with tf.Session() as session:
session.run(...)
2者的区别:显示调用可能由于程序异常不能closesession,上下文交给python上下文管理器解决这个问题
http://playground.tensorflow.org
网友评论