1、tensorflow数据模型——张量
在tensorflow中所有的数据都通过张量的形式表示。
张量可以简单理解为多维数组:
- 标量是零维数组(零阶张量)。例如,
\'Howdy\'
或5
- 矢量或向量是一维数组(一阶张量)。例如,
[2, 3, 5, 7, 11]
或[5]
- 矩阵是二维数组(二阶张量)。例如,
[[3.1, 8.2, 5.9][4.3, -2.7, 6.5]]
张量可以作为常量或变量存储在图中。您可能已经猜到,常量存储的是值不会发生更改的张量,而变量存储的是值会发生更改的张量。不过,您可能没有猜到的是,常量和变量都只是图中的一种指令。常量是始终会返回同一张量值的指令。变量是会返回分配给它的任何张量的指令。
要定义常量,请使用 tf.constant
指令,并传入它的值。例如:
x = tf.constant([5]) tf.constant('Hello, world!')
同样,您可以创建如下变量:
y = tf.Variable([5])
2、计算模型——计算图
TensorFlow 图(也称为计算图或数据流图)是一种图数据结构。很多 TensorFlow 程序由单个图构成,但是 TensorFlow 程序可以选择创建多个图。图的节点是指令;图的边是张量。张量流经图,在每个节点由一个指令操控。一个指令的输出张量通常会变成后续指令的输入张量。TensorFlow 会实现延迟执行模型,意味着系统仅会根据相关节点的需求在需要时计算节点。
tensorflow 的所有的计算都会转化成计算图上的节点
图必须在 TensorFlow 会话中运行,会话存储了它所运行的图的状态:
将 tf.Session() 作为会话:
initialization = tf.global_variables_initializer()
print y.eval()
3、运行模型——会话
会话拥有并管理Tensorflow程序运行时的所有资源,会话来执行之前定义好的运算。
总结
TensorFlow 编程本质上是一个两步流程:
- 将常量、变量和指令整合到一个图中。
- 在一个会话中评估这些常量、变量和指令。
实例:
import tensorflow as tf
# Create a graph.
g = tf.Graph()
# Establish the graph as the "default" graph.
with g.as_default():
# Assemble a graph consisting of the following three operations:
# * Two tf.constant operations to create the operands.
# * One tf.add operation to add the two operands.
x = tf.constant(8, name="x_const")
y = tf.constant(5, name="y_const")
sum = tf.add(x, y, name="x_y_sum")
# Now create a session.
# The session will run the default graph.
with tf.Session() as sess:
print sum.eval()
参考:谷歌机器学习速成课程 TensorFlow书籍