转载博客:http://blog.csdn.net/phdat101/article/details/52350611
1.概念
graph:图,表示具体的计算任务
session:会话,图需要在会话中执行,一个会话可以包含很多图
tensor:张量,在此表示数据,类型是numpy::ndarray
variable:就是本意变量,图的重要组成部分
operation:简称op,是图中计算的节点,输入tensor计算后产生tensor
feed、fetch:意思是给图添加数据和获取图中的数据,因为训练过程中有些数据需要动态获得、临时给予数据
运行:
考虑到python运算的性能,肯定需要使用外部运算库,但是内外环境切换也是个很大的开销,TF如同其他主流机器学习工具,把程序通常组织成一个构建阶段和一个执行阶段。构建就是说明需要一个怎样的网络模型,执行就是按照指定的优化训练模型,也包含检验输出等操作。可以看做先用python程序搭建模型,然后全部在python之外运行。
2. 例子
2.1 平面拟合
需要拟合的平面:y = W1 * x1_data + W2*x2_data + b,其中,已知x1_data、x2_data和y,但是都包含一点噪声。
程序:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
|
来自CODE的代码片
PlaneFitting.py
1 |
|
来自CODE的代码片
snippet_file_3.txt
2.2 矩阵相乘
两个比较大的矩阵相乘,分别使用GPU和CPU,比较运行时间
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
来自CODE的代码片
MatrixsMul.pyt
如果有GPU并且安装的是GPU版本的TF,程序默认是在GPU上运行的。通过指定"/gpu:0"或"/cpu:0"的形式,可以人为改变。GPU运行时间是11.6s,CPU是20.2s,节省了一些时间。
2.3 构建session的另一种方式
以上程序需要显示地使用sess.run(...)运行节点,想法自然,但TF也提供了另一种形式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
来自CODE的代码片
AnotherSession.py
2.4一个计数器--说明构建阶段和运行阶段
TF把很多操作都规定成内部的函数,先显式地规定网络,然后才是运行
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
|
来自CODE的代码片
ASimpleCounter.py
2.5获取数据fetch()
程序运行时需要获取一些数据,每个节点获取的数据可以理解为:对每个点单独有通路,从底部运行过来(实际不是这样,但数据同步行类似)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
来自CODE的代码片
AboutFetch.py
2.6填充数据feed()
随时给程序填充一些数据
1 2 3 4 5 6 7 8 9 10 |
|
来自CODE的代码片
AboutFeed.py
参考:
官方手册:https://www.tensorflow.org/versions/r0.10/get_started/index.html
中文社区:http://www.tensorfly.cn/