python人工智能——深度学习——TensorFlow——图和会话

图默认已经注册,一组表示 tf.Operation计算单位的对象和tf.Tensor表示操作之间流动的数据单元的对象。

获取调用:

tf.get_default_graph()
op、sess或者tensor 的graph属性
import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'

#实现一个加法运算
a=tf.constant(5.0)
b=tf.constant(6.0)

print(a,b)

sum1=tf.add(a,b)

#默认的这张图,相当于是给程序分配一段内存
graph=tf.get_default_graph()

print(graph)

print(sum1)

with tf.Session() as sess:
    print(sess.run(sum1))
    print(a.graph)
    print(sum1.graph)
    print(sess.graph)
Tensor("Const:0", shape=(), dtype=float32) Tensor("Const_1:0", shape=(), dtype=float32)
<tensorflow.python.framework.ops.Graph object at 0x00000184549AA390>
Tensor("Add:0", shape=(), dtype=float32)
11.0
<tensorflow.python.framework.ops.Graph object at 0x00000184549AA390>
<tensorflow.python.framework.ops.Graph object at 0x00000184549AA390>
<tensorflow.python.framework.ops.Graph object at 0x00000184549AA390>

图的创建

tf.Graph()

使用新创建的图

	g = tf.Graph() 
	with g.as_default(): 
	        a = tf.constant(1.0) 
	        assert c.graph is g
g=tf.Graph()

print(g)
with g.as_default():
    c=tf.constant(11.0)
    print(c.graph)
<tensorflow.python.framework.ops.Graph object at 0x000001BF67EBB390>
<tensorflow.python.framework.ops.Graph object at 0x000001BF67EBB390>

OP

op:只要使用TensorFlow的API定义的函数都是OP
在这里插入图片描述

会话

1.运行图的结构
2.分配资源计算
3.掌握资源(变量的资源,队列,线程)

tf.Session()
运行TensorFlow操作图的类,使用默认注册的图(可以指定运行图)

会话资源
会话可能拥有很多资源,如 tf.Variable,tf.QueueBase
和tf.ReaderBase,会话结束后需要进行资源释放

sess = tf.Session() sess.run(…) sess.close()
使用上下文管理器
with tf.Session() as sess:
sess.run(…)

config=tf.ConfigProto(log_device_placement=True)
交互式:tf.InteractiveSession()

会话的run()方法

run(fetches, feed_dict=None,graph=None)
运行ops和计算tensor
嵌套列表,元组,
namedtuple,dict或OrderedDict(重载的运算符也能运行)

feed_dict 允许调用者覆盖图中指定张量的值,提供给
placeholder使用

返回值异常
RuntimeError:如果它Session处于无效状态(例如已关闭)。
TypeError:如果fetches或feed_dict键是不合适的类型。
ValueError:如果fetches或feed_dict键无效或引用 Tensor不存在。

猜你喜欢

转载自blog.csdn.net/weixin_43336281/article/details/87436296