TensorFlow 张量

1. Tensor三要素

Tensor包括三部分:名字、形状、数据类型,直接用 print就可以查看

1
2
3
4
5
6
a = tf.constant(1)
b = tf.constant([1, 2])
c = tf.constant([[1, 2], [3, 4], [5, 6]])
print(a) # Tensor("Const:0", shape=(), dtype=int32) name中冒号之前是op类型,冒号之后的0是无意义的
print(b) # Tensor("Const_1:0", shape=(2,), dtype=int32)
print(c) # Tensor("Const_2:0", shape=(3, 2), dtype=int32)

2. Tensor的阶

Tensor底层是对Numpy的ndarray的封装。ndarray中叫维度,到了Tensor这里就叫阶。数学中更习惯用阶这个概念

数学实例 Python 例子
0 纯量 (只有大小) s = 483
1 向量 (大小和方向) v = [1.1, 2.2, 3.3]
2 矩阵 (数据表) m = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
3 3阶张量 (数据立体) t = [[[2], [4], [6]], [[8], [10], [12]], [[14], [16], [18]]]
n n阶 (自己想想看) ….

3. Tensor数据类型

张量的数据类型可以是以下数据类型中的任意一种

数据类型 Python 类型 描述
DT_FLOAT tf.float32 32 位浮点数
DT_DOUBLE tf.float64 64 位浮点数
DT_INT64 tf.int64 64 位有符号整型
DT_INT32 tf.int32 32 位有符号整型
DT_INT16 tf.int16 16 位有符号整型
DT_INT8 tf.int8 8 位有符号整型
DT_UINT8 tf.uint8 8 位无符号整型
DT_STRING tf.string 可变长度的字节数组.每一个张量元素都是一个字节数组
DT_BOOL tf.bool 布尔型
DT_COMPLEX64 tf.complex64 由两个32位浮点数组成的复数:实数和虚数
DT_QINT32 tf.qint32 用于量化Ops的32位有符号整型
DT_QINT8 tf.qint8 用于量化Ops的8位有符号整型
DT_QUINT8 tf.quint8 用于量化Ops的8位无符号整型

4. Tensor的属性

1
2
3
4
5
6
7
8
9
10
tensor = tf.constant(1)

print(tensor.graph) # 所属的图
print(tensor.dtype) # 数据类型
print(tensor.name) # 名称
print(tensor.op) # 操作名
print(tensor.shape) # 形状

with tf.Session() as sess:
print(tensor.eval()) # 值

5. Tensor动态形状和静态形状

动态形状:生成新的张量
静态形状:不会生成新的张量

5.1. 静态形状

一旦张量形状固定了,就无法再修改静态形状

1
2
3
4
5
6
7
8
p = tf.placeholder(tf.float32)
print(p.shape) # <unknown>, placeholder一开始没有形状

p.set_shape([3, 2])
print(p.shape) # (3, 2)

p.set_shape([4, 2]) # ValueError,静态形状一旦被设置,就无法再修改
print(p.shape)

5.2. 动态形状

tf.reshape() 返回修改某个tensor形状的副本,不会影响原tensor的形状。修改形状时,注意元素个数必须匹配

1
2
3
4
5
p = tf.placeholder(tf.float32, [6, 2])
print(p.shape)

p1 = tf.reshape(p, [4, 3])
p2 = tf.reshape(p, [2, 6])
panchaoxin wechat
关注我的公众号
支持一下