1.TensorFlow计算模型--计算图
1.1 计算图概念
- TensorFlow中的每一个计算都是计算图上的一个节点,而节点之间的边描述了计算之间的依赖关系

1.2计算图的使用
- Tensorflow 会自动将定义的计算转化为计算图上的节点。在TensorFlow程序中,系统会自动维护一个默认的计算图,通过tf.get_default_graph函数可以获得当前默认的计算图
print (a.graph is tf.get_dafault_graph())
- TensorFlow中计算图不仅仅可以用来隔离张量和计算
import tensorflow as tf
g1 = tf.Graph()
with g1.as_default():
v = tf.get_variable(
"v", initalizer= zeros_initalizer(shape[1])
)
g2 = tf.Graph()
with g2.as_default():
v = tf.get_variable(
"v", initalizer= one_initalizer(shape[1])
)
with tf.Session(graph=g1) as sess:
tf.initialize_all_variables().run()
with tf.variable_scope("",reuse=True):
print(sess.run(tf.get_variable("v")))
with tf.Session(graph=g1) as sess:
tf.initialize_all_variables().run()
with tf.variable_scope("",reuse=True):
print(sess.run(tf.get_variable("v")))
print [0.]
print [1.]
tensorflow 要求手动关闭资源,避免资源浪费。即sess.close,使用with方式可以自动释放,避免异常退出时,导致资源不能释放。
- 还提供了管理张量和计算的机制
g = tf.Graph()
with g.device('/gpu:0'):
result = a + b
2 TensorFlow数据模型--张量
2.1 张量的概念
- 在tensorflow中,所有的数据都通过张量的形式来表示,张量简单理解就是约为多维数组
- 张量并不保存真正的数字,它保存的是如何得到这些数字的计算过程。可以理解为引用
import tensorflow as tf
a = tf.constant([1.0, 2.0], name = "a")
b = tf.constant([2.0, 3.0], name = "b")
result = tf.add(a,b,name="add")
print result
输出:
Tensro("add:0", shape(2,),dtype=float32)
命名可以通过"node:src_output"形式来给出,node为节点名称,src_output表示当前张量来自节点地第几个输出
- 张量三个特性:
-
name:遵守上述规范,不仅仅名字,同样也是给出如何计算出来
-
shape:描述一个张量的维度信息。比如shape(2,)说明是一个一维数组.
-
type:每个张量都有一个唯一的类型.tensorflow会对所有参与运算的张量进行类型检查
-
2.2 张量的使用
-
对中间计算结果的引用,使张量可以大大提高可读性,也方便获取中间结果.
-
当计算图构造完成后,张量可以用来获取计算结果,也是得到真实的数字。
3 TensorFlow运行模型--会话
- 明确调用会话生成函数及关闭函数。
sess = tf.Session()
sess.run(...)
sess.close()
避免异常退出时,导致资源不能释放.
- 利用python上下文管理器来使用会话。
with tf.Session() as sess:
sess.run(...)
- Tensorflow 提供一种交互式环境直接构建会话的函数--tf.InteractiveSession.可通过ConfigProto来配置需要生成的会话。
config = tf.ConfigProto(allow_soft_placement=True,log_device_placement=True)
sess1 = tf.InteractiveSession(config=config)
sess2 = tf.Sess(config=config)
注:allow_soft_palcement 为True表示GPU运算可以当在CPU上进行。log_device_placement将会记录每个节点(node)被安排在了哪个设备上以方便调试。
4 TensorFlow实现神经网络
4.1 TensorFlow 游乐园
- 地址:http://playground.tensorflow.org
- 在机器学习中,所有用于描述实体的数字的组合就是实体的向量特征。通过提取特征,就可以将实际问题中实体转化为空间的点
- 游乐园中,每一条变代表神经网络中的一个参数,它可以是任意实数
- 神经网络就是通过对参数合理设置来解决分类或者回归问题
4.2 前向传播算法介绍
---------持续更新-----------
网友评论