TensorFlow 与 MXNet、PyTorch 很相似,上手速度很快(相比于 TensorFlow1.x)。
TensorFlow 拆开来看,就是 Tensor 与 Flow,即数据流程图,也是有向无环图(DAG)。在 TensorFlow 中以 Tensor(张量)表示数据,即 DAG 的(实线)边,而虚线的边用来表示流程的控制关系。DAG 的节点表示数学操作符(即数学运算)。
1 张量 tf.Tensor
张量是由 tf.Tensor 对象表示的具有统一类型(称为 dtype)的多维数组。您可以在 tf.dtypes.DType 中查看所有支持的 dtypes。就像 Python 数值和字符串一样,所有张量都是不可变的:永远无法更新张量的内容,只能创建新的张量。
编写 TensorFlow 程序时,主要操纵和传递的对象是 tf.Tensor。tf.Tensor 具有以下属性:
单一数据类型 (比如,float32,int32或字符串)
a shape
TensorFlow 支持 eager 执行和 graph 执行。eager 执行时,将立即执行运算。在 graph 中执行时,构造一个计算图为以后运算。TensorFlow 默认 eager 执行。在以下示例中,立即计算矩阵乘法结果。其中 tf.constant 是张量的一种。
# 使用 Tensor 计算一些值
c = tf.constant([[1.0, 2.0], [3.0, 4.0]]) # 常量
d = tf.constant([[1.0, 1.0], [0.0, 1.0]])
e = tf.matmul(c, d) # 矩阵乘法
print(e)
输出:
tf.Tensor(
[[1. 3.]
[3. 7.]], shape=(2, 2), dtype=float32)
请注意,在 eager 执行过程中,您可能会发现您的 Tensors 实际上是类型为“EagerTensor”。这是内部细节,但确实可以给您访问有用的函数 numpy():
在 TensorFlow 中,tf.function 是定义 graph 执行的常用方法。张量的 shape(即张量的 rank 和每个维度的大小)可能并不总是完全已知的。在 tf.function 定义中,shape 可能仅是部分已知的。
如果也可以完全知道其输入的形状,则大多数操作都会生成形状已知的张量,但是在某些情况下,只有在执行时才能找到张量的形状。
有许多专用的张量:参见 tf.constant, tf.sparse.SparseTensor, 和 tf.RaggedTensor。
1.1 常量 tf.constant
def constant(value, dtype=None, shape=None, name="Const"):
从 tensor-like 的对象创建恒定张量,即常量。
注意:所有 eager 的 tf.Tensor 值都是不可变的(与 tf.Variable 相反)。从 tf.constant 返回的值没有特别常数。此功能与 tf.convert_to_tensor 基本上没有区别。名称 tf.constant 来自符号API(例如 tf.data或 tf.keras functional models),其中 value 嵌入在 tf.Graph 的 Const 节点中。tf.constant 可用于断言该值可以通过这种方式嵌入。
我们来创建一些基本张量。
下面是一个“标量”(或称“0 秩”张量)。标量包含单个值,但没有“轴”。
rank_0_tensor = tf.constant(4)
print(rank_0_tensor)
输出:
tf.Tensor(4, shape=(), dtype=int32)
“向量”(或称“1 秩”张量)就像一个值的列表。向量有 1 个轴:
rank_1_tensor = tf.constant([2.0, 3.0, 4.0])
print(rank_1_tensor)
输出:
tf.Tensor([2. 3. 4.], shape=(3,), dtype=float32)
“矩阵”(或称“2 秩”张量)有 2 个轴:
rank_2_tensor = tf.constant([[1, 2],
[3, 4],
[5, 6]], dtype=tf.float16)
print(rank_2_tensor)
输出:
tf.Tensor(
[[1. 2.]
[3. 4.]
[5. 6.]], shape=(3, 2), dtype=float16)
张量的轴可能更多,下面是一个包含 3 个轴的张量:
rank_3_tensor = tf.constant([
[[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9]],
[[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19]],
[[20, 21, 22, 23, 24],
[25, 26, 27, 28, 29]],])
print(rank_3_tensor)
输出:
tf.Tensor(
[[[ 0 1 2 3 4]
[ 5 6 7 8 9]]
[[10 11 12 13 14]
[15 16 17 18 19]]
[[20 21 22 23 24]
[25 26 27 28 29]]], shape=(3, 2, 5), dtype=int32)
对于包含 2 个以上的轴的张量ÿ