TensorFlow程序使用一个tensor数据结构来代表所有数据。你可以认为一个TensorFlow的tensor是一个n维数组或者列表。一个tensor有一个静态类型和动态维度。只有tensor可以在计算图节点之间被传递。
Rank
在TensorFlow系统中,tensor可用被称为“秩”(rank)的维度单元描述。Tensor的秩与矩阵的秩不一样。Tensor的秩(有时也叫“序”(order)或者“度”(degree)又或者“n-维度”)是tensor维度的数量。例如,下面的tensor(定义为一个Python列表)的秩为2:
t =[[1,2,3],[4,5,6],[7,8,9]]
我们通常会把一个秩为2的tensor看作为一个矩阵,秩为1的是一个向量。对于秩为2的tensor,你可以用t[i,j]这样的语法来获取任意元素。而对于一个秩为3的tensor,你需要使用t[i,j,k]来获取一个元素。
Rank |
Math entity |
Python example |
---|
0 |
Scalar (magnitude only) |
s = 483 |
1 |
Vector (magnitude and direction) |
v = [1.1, 2.2, 3.3] |
2 |
Matrix (table of numbers) |
m = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] |
3 |
3-Tensor (cube of numbers) |
t = [[[2], [4], [6]], [[8], [10], [12]], [[14], [16], [18]]] |
n |
n-Tensor (you get the idea) |
.... |
形状
Tensorflow文档使用三种惯用标记来描述tensor的维度:秩、形状和维数。下表这些标记相互之间的对应关系:
Rank |
Shape |
Dimension number |
Example |
---|
0 |
[] |
0-D |
A 0-D tensor. A scalar. |
1 |
[D0] |
1-D |
A 1-D tensor with shape [5]. |
2 |
[D0, D1] |
2-D |
A 2-D tensor with shape [3, 4]. |
3 |
[D0, D1, D2] |
3-D |
A 3-D tensor with shape [1, 4, 3]. |
n |
[D0, D1, ... Dn-1] |
n-D |
A tensor with shape [D0, D1, ... Dn-1]. |
形状可以通过Python的整型列表、元组来表示,或者通过
tf.TensorShape
。
数据类型
除了维度外,tensor还有数据类型。你可以指定tensor属于下表中任何一种数据类型:
Data type |
Python type |
Description |
---|
DT_FLOAT |
tf.float32 |
32 bits floating point. |
DT_DOUBLE |
tf.float64 |
64 bits floating point. |
DT_INT8 |
tf.int8 |
8 bits signed integer. |
DT_INT16 |
tf.int16 |
16 bits signed integer. |
DT_INT32 |
tf.int32 |
32 bits signed integer. |
DT_INT64 |
tf.int64 |
64 bits signed integer. |
DT_UINT8 |
tf.uint8 |
8 bits unsigned integer. |
DT_UINT16 |
tf.uint16 |
16 bits unsigned integer. |
DT_STRING |
tf.string |
Variable length byte arrays. Each element of a Tensor is a byte array. |
DT_BOOL |
tf.bool |
Boolean. |
DT_COMPLEX64 |
tf.complex64 |
Complex number made of two 32 bits floating points: real and imaginary parts. |
DT_COMPLEX128 |
tf.complex128 |
Complex number made of two 64 bits floating points: real and imaginary parts. |
DT_QINT8 |
tf.qint8 |
8 bits signed integer used in quantized Ops. |
DT_QINT32 |
tf.qint32 |
32 bits signed integer used in quantized Ops. |
DT_QUINT8 |
tf.quint8 |
8 bits unsigned integer used in quantized Ops. |