一、会话的作用
(一)运行图的结构
tf.Session()运行TensorFlow操作图的类,使用默认注册的图(可以指定运行图)。例如:tf.Session(graph=某张图)
(二)分配资源计算
会话可能拥有很多资源,如 tf.Variable,tf.QueueBase和tf.ReaderBase,会话结束后需要进行资源释放。
1、sess = tf.Session() sess.run(…)启动整张图 sess.close()
2、使用上下文管理器
with tf.Session() as sess:
sess.run(…)
或 .eval()等价于run,主要有会话的上下文环境,就可以方便使用。
3、参数
config=tf.ConfigProto(log_device_placement=True)可以看到图里面有哪些资源以及在什么设备运行
交互式:tf.InteractiveSession()
(三)掌握资源(变量的资源、队列、线程)
二、会话的run()方法
run(fetches, feed_dict=None,graph=None)运行ops和计算tensor
(一)参数fetches
嵌套列表或元组,namedtuple,dict或 OrderedDict(重载的运算符也能运行)
(二)参数feed_dict(是一个字典)
feed_dict 允许调用者覆盖图中指定张量的值,提供给placeholder使用,placeholder是一个占位符。
例如:
plt = tf.placeholder(tf.float32,[2,3])
with tf.Session() as sess:
print(sess.run(plt,feed_dict={plt:[[1,2,3],[4,5,6]]}))
或者plt = tf.placeholder(tf.float32,[None,3])表示行数不固定
(三)返回值异常
RuntimeError:如果它Session处于无效状态(例如已关闭)。
TypeError:如果fetches或feed_dict键是不合适的类型。
ValueError:如果fetches或feed_dict键无效或引用 Tensor不存在。
tensorflow会话
最新推荐文章于 2024-12-07 20:46:11 发布