tensorflow中很重要的概念Tensor和ops
2.1 Tensor和ops
- Tensor, 类似numpy中的array,但是区别是tensor中不存储任何数据,tensor只是数据的引用.
- ops是tensorflow中计算图中的节点,ops接收若干个tensor,并且返回若干个tensor
a = tf.constant([1, 2], name='a', dtype=tf.int32)
b = tf.constant([2, 3], name='b')
result = a + b
print(result) # Tensor("add:0", shape=(2,), dtype=int32)
从上面的程序可以看出result是个tensor,但是并不存储任何数据,只是数据的引用,从上面可以看出tensor有三个属性
- name: “add:0”, 表明result这个tensor是add这个ops的第一个输出
- shape: tensor的shape
- dtype : tensor的数据格式
注意事项: 尽量把dtype写上,因为如果不写tensorflow会自动写默认值。不带小数点的默认为tf.int32,带小数点的默认为tf.float32
2.2 Session
会话拥有并管理tensorflow程序运行的时候的所有资源,所有计算完成后,需要关闭会话来帮助系统回收资源,否则就可能出现资源泄露。
- 可以使用with tf.Session() as sess:进行创建
with tf.Session() as sess:
sess.run(tf.global_variable_initializer())
sess.run(result) # [3, 5]
当然还可以通过对Session进行配置类似,并行的线程数量,GPU分配策略,常用的参数有两个
- allow_soft_placement=True
- 该参数如果为True,则下面三种情况出现,GPU上的运算都会放到CPU上运行
-1. 运算无法在GPU上运行
-2.没有GPU资源
-3.运算输入包含CPU计算结果的引用
- log_device_placement=True
为了代码的可移植性更强,在有GPU的环境下,allow_soft_placement设为True, 而log_device_placement的作用是记录每个节点被安排在哪个设备上以便调试,而在生产环境中将这个参数设置为False.
config = tf.ConfigProto(allow_soft_placement=True, log_device_placement=False)
with tf.Session(config=config) as sess:
sess.run(....)