一、会话
2.x版本由于是即时执行模式,所以不需要会话。但是可以手工开启会话
1、什么是会话
一个运行TensorFlow operation的类。会话包含以下两种开启方式
(1)tf.compat.v1.Session:用于完整的程序当中
(2)tf.compat.v1.InteractiveSession:用于交互式上下文中的TensorFlow,比如想验证下自己的想法
2、InteractiveSession例子
在2.x版本中没有eval()函数了,用numpy()函数代替
ipython
Python 3.6.8 (default, Nov 14 2023, 16:29:52)
Type 'copyright', 'credits' or 'license' for more information
IPython 7.16.3 -- An enhanced Interactive Python. Type '?' for help.
In [1]: import os
In [2]: os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
In [3]: import tensorflow as tf
In [4]: tf.compat.v1.InteractiveSession()
Out[4]: <tensorflow.python.client.session.InteractiveSession at 0x7fa7efc09e48>
In [5]: a = tf.constant(3)
In [6]: a
Out[6]: <tf.Tensor: shape=(), dtype=int32, numpy=3>
In [7]: a.eval()
---------------------------------------------------------------------------
NotImplementedError Traceback (most recent call last)
<ipython-input-7-90f91b557aeb> in <module>
----> 1 a.eval()
/usr/local/lib64/python3.6/site-packages/tensorflow/python/framework/ops.py in eval(self, feed_dict, session)
1279 def eval(self, feed_dict=None, session=None):
1280 raise NotImplementedError(
-> 1281 "eval is not supported when eager execution is enabled, "
1282 "is .numpy() what you're looking for?")
1283
NotImplementedError: eval is not supported when eager execution is enabled, is .numpy() what you're looking for?
In [8]: a.numpy()
Out[8]: 3
3、2.0不用专门教程,主要改变就是不用定义session了,2.0采用动态图,一旦print就会立即返回数值
4、tf.Session.close函数
会话可能拥有资源,如tf.Variable,tf.queue.QueueBase,tf.compat.v1.ReaderBase
当这些资源不再需要时,释放这些资源非常重要。因此,需要在会话中调用tf.Session.close函数,或将会话用作上下文管理器
# Using the `close()` method.
sess = tf.compat.v1.Session()
sess.run(...)
sess.close()
# Using the context manager.
with tf.compat.v1.Session() as sess:
sess.run(...)
5、tf.compat.v1.Session(target='', graph=None, config=None)
说明:
target:如果将此参数留空(默认设置),会话将仅使用本地计算机中的设备。可以指定grpc://网址,以便指定TensorFlow服务器的地址,这使得会话可以访问该服务器控制的计算机上的所有设备
graph:默认情况下,新的Session将绑定到当前的默认图
config:此参数允许您指定一个tf.compat.v1.ConfigProto以便控制会话的行为。例如ConfigProto协议用于打印设备使用信息
# 运行会话并打印设备信息
sess = tf.compat.v1.Session(config=tf.compat.v1.ConfigProto(
allow_soft_placement=True,
log_device_placement=True))
6、run方法
run(fetches, feed_dict=None, options=None, run_metadata=None)
说明:
通过使用sess.run()来运行operation
fetches:单一的operation,或者列表、元组(其他不属于tensorflow的类型不行)
feed_dict:参数允许调用者覆盖图中张量的值(将图形元素映射到值的字典上),运行时赋值。与tf.compat.v1.placeholder搭配使用,则会检查图的形状是否与占位符兼容
placeholder:提供占位符,run时候通过feed_dict指定参数
import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
import tensorflow as tf
def tensorflow_demo():
"""
TensorFlow的基本结构
"""
# TensorFlow实现加减法运算
a_t = tf.constant(2)
b_t = tf.constant(3)
c_t = a_t + b_t
print("TensorFlow加法运算结果:\n", c_t)
print(c_t.numpy())
# 2.0版本不需要开启会话,已经没有会话模块了
return None
def graph_demo():
"""
图的演示
"""
# TensorFlow实现加减法运算
a_t = tf.constant(2)
b_t = tf.constant(3)
c_t = a_t + b_t
print("TensorFlow加法运算结果:\n", c_t)
print(c_t.numpy())
# 查看默认图
# 方法1:调用方法
default_g = tf.compat.v1.get_default_graph()
print("default_g:\n", default_g)
# 方法2:查看属性
# print("a_t的图属性:\n", a_t.graph)
# print("c_t的图属性:\n", c_t.graph)
# 自定义图
new_g = tf.Graph()
# 在自己的图中定义数据和操作
with new_g.as_default():
a_new = tf.constant(20)
b_new = tf.constant(30)
c_new = a_new + b_new
print("c_new:\n", c_new)
print("a_new的图属性:\n", a_new.graph)
print("b_new的图属性:\n", b_new.graph)
# 开启new_g的会话
with tf.compat.v1.Session(graph=new_g) as sess:
c_new_value = sess.run(c_new)
print("c_new_value:\n", c_new_value)
print("我们自己创建的图为:\n", sess.graph)
# 可视化自定义图
# 1)创建一个writer
writer = tf.summary.create_file_writer("./tmp/summary")
# 2)将图写入
with writer.as_default():
tf.summary.graph(new_g)
return None
def session_run_demo():
"""
feed操作
"""
tf.compat.v1.disable_eager_execution()
# 定义占位符
a = tf.compat.v1.placeholder(tf.float32)
b = tf.compat.v1.placeholder(tf.float32)
sum_ab = tf.add(a, b)
print("a:\n", a)
print("b:\n", b)
print("sum_ab:\n", sum_ab)
# 开启会话
with tf.compat.v1.Session() as sess:
print("占位符的结果:\n", sess.run(sum_ab, feed_dict={a: 1.1, b: 2.2}))
return None
if __name__ == "__main__":
# 代码1:TensorFlow的基本结构
# tensorflow_demo()
# 代码2:图的演示
#graph_demo()
# feed操作
session_run_demo()
python3 day01_deeplearning.py
a:
Tensor("Placeholder:0", dtype=float32)
b:
Tensor("Placeholder_1:0", dtype=float32)
sum_ab:
Tensor("Add:0", dtype=float32)
占位符的结果:
3.3000002