1 初始TensorFlow
TensorFlow程序通常被组织成一个构件图阶段和一个执行图阶段。
在构建图阶段,数据与操作的执行步骤被描述为一个图
在执行图阶段,使用会话(调用系统资源)执行构建好的图中的操作
- 图和会话
图:这是TensorFlow将计算表示为指令之间的依赖关系的一种表示法,(数据+操作)
会话:TensorFlow跨一个或多个本地或远程设备运行数据流图的机制
- 张量(数据):TensorFlow中的基本数据对象
- 节点(操作):提供图当中执行的操作W
import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # 去警告
def tensorflow_demo1():
"""
tensoflow的基本结构
"""
# python版本
a=2
b=3
c=a+b
print('python版本的加法操作:\n',c)
# 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())
# 开启会话(TensorFlow1.0的写法,手动开启会话,tensorflow2.0不需要)
# with tf.Session() as sess:
# c_t_value=sess.run(c_t)
# print('开启会话的结果\n',c_t_value)
if __name__ == '__main__':
tensorflow_demo1()
输入结果:
python版本的加法操作:
5
tensorflow版本的加法操作:
tf.Tensor(5, shape=(), dtype=int32)
结果:5
2 数据流图介绍
TensorFlow是一个采用数据流图 (data flow graphs),用于数值计算的开源框架。
节点 (Operation)在图中表示数学操作,线 (edges)则表示在节点间相互联系的多维数据数组,即张量 (tensor)。