什么是TensorFlow
TensorFlow是Google开源的基于数据流图的科学计算库,适合用于机器学习、深度学习等人工智能领域;
Tensorflow的架构
- 前端:编程模型、构造计算图、Python、C++、Java
- 后端:运行计算图、C++
Graph
- 图描述了计算的过程,可以通过tensorboard图形化流程结构
- 声明(多种声明的形式)
//声明图
import tensorflow as tf
g = tf.Graph()
g = tf.get_default_graph()
x = tf.constant()
g = x.graph()
- 声明和交叉使用多个Graph
g1 = tf.Graph() with g1.as_default(): x1 = tf.constant(1.0,name='x1') g2 = tf.Graph() with g2.as_default(): x2 = tf.constant(2.0,name='x2') with tf.Session(graph=g2) as sess1: x1_list = tf.import_graph_def(g1.as_graph_def(),return_elements = ["x1:0"],name = '') print(sess1.run(x1_list[0] + x2)) //使用.run()来计算图的流程
- 保存为pb文件
g1 = tf.Graph() tf.train.write_graph(g1.as_graph_def(),'.','graph.pb',False)
- 从pb中恢复Graph
#load graph with gfile.FastGFile("graph.pb",'rb') as f: graph_def = tf.GraphDef() graph_def.ParseFromString(f.read()) tf.import_graph_def(graph_def,name='') //上面是作为前端创建流程计算图 //下面是开启会话 sess = tf.Session() c1_tensor = sess.graph.get_tensor_by_name("c1:0") c1 = sess.run(c1_tensor)
Session会话的补充
- 创建和关闭会话
sess = tf.Session()
sess = tf.InteractiveSession() //创建的交互性的会话
with tf.Session() as sess:
...
sess.close() //关闭会话
- 注入机制
sess.run(...)
sess.run(tf.global_variables_initializer()) //变量初始化
a = tf.placeholder(dtype=tf.float32)
b = tf.placeholder(dtype=tf.float32)//定义占位浮点数
add = a + b
add_val = sess.run(add,feed_dict={a:1,b:2})
- 指定资源设备
a = tf.placeholder(dtype=tf.float32)
b = tf.placeholder(dtype=tf.float32)
add = a+b
with tf.Session() as sess:
with tf.device("/cpu:0"): //指定0号的cpu
print(sess.run(add,feed_dict={a:1,b:2}))
- 资源分配-控制GPU资源使用率
//如此可以实现GPU的按需分配 config = tf.ConfigProto() config.gpu_options.allow_growth = True session = tf.Session(config=config,...)
Tensor
- 在TensorFlow中,所有在节点之间传递的数据都为Tensor对象
- N维数组,图像:(batch*height*width*channel)
Tensor定义
//定义常量
cons = tf.constant(value=[1,2],dtype=tf.float32,shape=(1,2),name='testconst',verify_shape=Flase)
//定义占位符变量,维度已知与未知
X = tf.placeholder(dtype=tf.float32,shape=[144,10],name='X')
X = tf.placeholder(dtype=tf.float32,shape=[None,None],name='X')
//定义变量
W = tf.Variable(tf.zeros([3,10]),dtype=tf.float64,name='W')
Operation
- TensorFlow Graph中的计算节点,输入输出均为Tensor
- 调用Session.run(tensor)或者tensor.eval()方获取该Tensor的值
Feed
- 通过feed为计算图注入值
a = tf.placeholder(tf.float32)
b = tf.placeholder(tf.float32)
c = tf.add(a,b)
with tf.Session() as sess:
result = sess.run(c,feed_dict={a:3,b:4})
print(result)
一个小例子
x = tf.placeholder(tf.float32,shape=(1,2))
//创建的w1,w2是符合随机分布的变量
w1 = tf.Variable(tf.random_normal([2,3],stddev=1,seed=1))
w2 = tf.Variable(tf.random_normal([3,1],stddev=1,seed=1))
#x,w1相乘;a,w2相乘
a = tf.matmul(x,w1)
y = tf.matmul(a,w2)
with tf.Session() as sess:
#变量运行前必须做初始化操作
init_op = tf.global_variables_initializer()
sess.run(init_op)
print(sess.run(y,feed_dict={x:[[0.7,0.5]]}))
Fetch
- 使用fetch获取计算结果
tf.Session.run(fetches,feed_dict=None)
TensorFlow中的数据操作
- TensorFlow提供TFRecord的格式来统一存储数据
- TFRecord将图像数据和标签在一起的二进制文件(protocol buffer),能更好的利用内存,实现快速的复制,移动,读取,存储
1.数据读取:tf.train.string_input_producer
2.数据解析:tf.TFRecordReader、tf.parse_single_example
3.数据写入:tf.python_io.TFRecordWriter
数据写入相关的API方法
- writer = tf.python_io.TFRecordWriter()
- example = tf.train.Example()
- writer.close()
- writer.write(example.SerializeToString())
TensorFlow数据读取机制:
为解决图片读取跟计算的异步性,设置了文件名列表
数据读取的相关API方法
- 直接从文件中读取图片
- 从TF-Record中解析打包的图片数据
- tf.train.string_input_producer、tf.train.slice_input_producer
- tf.data库(动态图机制)