什么是Tensorflow
TensorFlow 是一个基于 数据流编程(dataflow programming)的符号数学系统,被广泛应用于各类机器学习(machine learning)算法的编程实现,其前身是谷歌的神经网络算法库DistBelief。
简单说,tensorflow 是广泛使用在 机器学习 等 大量数学运算的算法库之一。
注:本文使用 python 语言来理解学习Tensorflow以及机器学习的知识。
(Tensorflow 也支持 截至版本1.12.0,绑定完成并支持版本兼容运行的语言为C和Python,
其它(试验性)绑定完成的语言为JavaScript、C++、Java、Go和Swift。)
张量(Tensor)
Tensorflow 内部计算基本都是基于张量来运算的,张量一术语起源于力学,在物理和数学中都有重要的作用。
在Tensorflow中,tensor代表多维数组,对应神经网络计算中的高纬矩阵。
tensor可以有任意纬度,每个维度也可以有任意长度。特别来说:
一维tensor就是向量,是普通的一维数组, 二维tensor是矩阵。
Tensorflow 中一般都使用4维 tensorflow表示一个mini-batch的图片,四个维度分别代表着 批大小 像素行数 像素列数 通道数 [batch, height,width, channels]
tensor中的dtype 可以是任意内置类型,常用有: int32, int64, float32, float64, 等。其中float32 相对于神经网络来说 是最为常用的。
tensor中的shape 可以理解为多位数组中每个维度的数组中元素的个数。
3 # 这个 0 阶张量就是标量,shape=[]
[1., 2., 3.] # 这个 1 阶张量就是向量,shape=[3]
[[1., 2., 3.], [4., 5., 6.]] # 这个 2 阶张量就是二维数组,shape=[2, 3]
[[[1., 2., 3.]], [[7., 8., 9.]]] # 这个 3 阶张量就是三维数组,shape=[2, 1, 3]
声明变量:
-
引入 tensorflow 模块
import tensorflow as tf
-
声明一个常量
# 创建 整型常量 cont = tf.constant(3, dtype=tf.int32) # 创建 浮点型数组 一阶tensor cont1 = tf.constant([3.0, 2.0, 1.0], dtype=tf.float32) # 创建 字符串2*2数组 二阶tensor cont2 = tf.constant([['tensor1_1, tnesor1_2'], ['tensor2_1', 'tensor2_2']], dtype=tf.string) # 输出tensor print(cont, cont1, cont2) #cont : Tensor(shape=(),dtype=int32) #cont1 : Tensor(shape=(3,),dtype=float32) #cont2 : Tensor(shape=(2,2),dtype=string)
-
声明一个变量
最常见的创建变量方式是使用Variable()构造函数import tensorflow as tf # 创建变量w,为一个array w = tf.Variable([1,2,3], name='w') # 输出w 结果: <tf.Variable 'w:0' shape=(3,) dtype=int32_ref> print w # 初始化一个形状为[2]的张量, 里面的元素值全部为0. b = tf.Variable(tf.zeros[2], name='b') # 输出b 结果:<tf.Variable 'b:0' shape=(2,) dtype=float32_ref> print b
类似的函数还有tf.eye, tf.ones 等。
创建变量还可以调用 tf.get_variable 函数。此函数要求您指定变量的名称。此名称将被其他副本用来访问同一变量,以及在检验和导出模型时命名此变量的值。tf.get_variable 还允许您重用先前创建的同名变量,从而轻松定义重用层的模型。
要使用 tf.get_variable 创建变量,只需提供名称和形状即可# 这将创建一个名为“my_variable”的变量,该变量是形状为 [1, 2, 3] 的三维张量。 my_variable = tf.get_variable("my_variable", [1, 2, 3])
Session 会话
Session 是驱动Tensorflow 系统执行计算交互的入口。Session 负责完成多计算设备或集群分布式的节点布置和数据传输节点的添加, 并负责将子图分配给相应的执行器单元来运行。
触发计算图的执行通过 Run 接口,特就是Python的 tf.Session.run() 方法。通过这个接口,可以将数据带入模型,执行结算,并得到执行结果。 训练过程由客户端的循环来控制,一般情况下,都会在一个会话中通过Run接口执行成千上万的计算。
import tensorflow as tf
num1 = tf.constant(3.2)
num2 = tf.constant(4.8)
num = num1 + num2
print(num)
# 结果:Tensor("add:0", shape=(), dtype=float32)
with tf.Session as sess:
# 变量初始化
init = tf.global_variables_initializer()
sess.run(init)
print(sess.run(num))
# 结果:8.0
上面使用tf.constant()创建的 Tensor 都是常量,一旦创建后其中的值就不能改变了。有时我们还会需要从外部输入数据,这时可以用tf.placeholder 创建占位 Tensor,占位 Tensor 的值可以在运行的时候输入。如下就是创建占位 Tensor 的例子:
import tensorflow as tf
num_1 = tf.placeholder(tf.float32)
num_2 = tf.placeholder(tf.float32)
num_add = num_1 + num_2
print(num_1) # Tensor("Placeholder:0", dtype=float32)
print(num_2) # Tensor("Placeholder_1:0", dtype=float32)
print(num_add) # Tensor("add:0", dtype=float32)
with tf.Session() as sess:
print sess.run(num_add, {num_1:3, num_2:4}) # 7.0
end