程序 = 数据结构+算法。
TensorFlow程序 = 张量数据结构 + 计算图算法语言
张量和计算图是 TensorFlow的核心概念。
Tensorflow的基本数据结构是张量Tensor,张量即多维数组。Tensorflow的张量和numpy中的array很类似。从行为特性来看,有两种类型的张量,常量constant和变量Variable。
- 常量的值在计算图中不可以被重新赋值。
- 变量可以在计算图中用assign等算子重新赋值。
一、常量张量
张量的数据类型和numpy.array基本一一对应。tf.constant()
定义常量张量。
# 定义常量张量
i = tf.constant(1) # tf.int32 类型常量
l = tf.constant(1, dtype=tf.int64) # tf.int64 类型常量
f = tf.constant(1.23) # tf.float32 类型常量
d = tf.constant(3.14, dtype=tf.double) # tf.double 类型常量
s = tf.constant("hello world") # tf.string类型常量
b = tf.constant(True) # tf.bool类型常量
print(tf.int64 == np.int64) # 等价
print(tf.bool == np.bool) # 等价
print(tf.double == np.float64) # 等价
print(tf.string == np.unicode) # tf.string类型和np.unicode类型不等价
标量为0维张量,向量为1维张量,矩阵为2维张量。
彩色图像有rgb三个通道,可以表示为3维张量。视频还有时间维,可以表示为4维张量。
可以简单地总结为:有几层中括号,就是多少维的张量。可以用numpy()
方法将tensorflow中的张量转化成numpy中的张量。
scalar = tf.constant(True) # 标量,0维张量
print(tf.rank(scalar))
print(scalar.numpy().ndim) # tf.rank的作用和numpy的ndim方法相同,输出0
输出
tf.Tensor(0, shape=(), dtype=int32)
0
备注:tf.rank()
用来返回张量的秩。需要注意的是,张量的秩与矩阵的秩不一样。张量的秩是唯一选择张量的每个元素所需的索引的数量。(例如,3维张量,选择某个元素 )秩也被称为 “order”,“degree” 或 “ndims”。这里张量的秩,可以直接理解维度,就是说这个张量是几维的,它不是矩阵的秩也不是数组的shape,可以简单的理解成’['的深度,即中括号的层数。
a = tf.constant([1])
b = tf.constant([3, 2, 1])
c = tf.constant([[4, 3], [2, 1]])
#x = tf.add(a, b)
with tf.Session() as sess:
print(tf.rank(a))
print(tf.rank(b))
print(tf.rank(c))
输出
Tensor("Rank:0", shape=(), dtype=int32)
Tensor("Rank_1:0", shape=(), dtype=int32)
Tensor("Rank_2:0", shape=(), dtype=int32)
可以用tf.cast()
改变张量的数据类型。
i = tf.constant([123,456], dtype=tf.int32)
f = tf.cast(i, tf.float32)
print(i.dtype, f.dtype)
输出
<dtype: 'int32'> <dtype: 'float32'>
可以用tf.shape()
方法查看张量的尺寸。
i = tf.constant([123,456], dtype=tf.int32)
print(tf.shape(i))
输出
tf.Tensor([2], shape=(1,), dtype=int32)
二、变量张量
模型中需要被训练的参数一般被设置成变量。
# 常量值不可以改变,常量的重新赋值相当于创造新的内存空间
c = tf.constant([1.0,2.0])
print(c)
print(id(c))
c = c + tf.constant([1.0,1.0])
print(c)
print(id(c))
输出
tf.Tensor([1. 2.], shape=(2,), dtype=float32)
140292310359208
tf.Tensor([2. 3.], shape=(2,), dtype=float32)
140292310358680
变量的值可以改变,可以通过assign(),
assign_add()
等方法给变量重新赋值
# 变量的值可以改变,可以通过assign, assign_add等方法给变量重新赋值
v = tf.Variable([1.0,2.0],name = "v")
print(v)
print(id(v))
v.assign_add([1.0,1.0])
print(v)
print(id(v))
v.assign([1.0,2.0])
print(v)
print(id(v))
输出
<tf.Variable 'v:0' shape=(2,) dtype=float32, numpy=array([1., 2.], dtype=float32)>
140292193929872
<tf.Variable 'v:0' shape=(2,) dtype=float32, numpy=array([2., 3.], dtype=float32)>
140292193929872
<tf.Variable 'v:0' shape=(2,) dtype=float32, numpy=array([1., 2.], dtype=float32)>
140292193929872