
上QQ阅读APP看书,第一时间看更新
3.3 张量
3.3.1 张量的创建
我们在第2章中已经介绍了PyTorch中张量的定义。TensorFlow里,我们同样可以定义任意阶数的张量。

上面的代码中,我们定义了c0、c1、c2三种张量,它们都是常量。注意,TensorFlow中可以使用name参数对张量指定名称,这样做的好处是方便在TensorBoard里查看张量。关于TensorBoard,我们后面将会介绍。下面,使用print语句把这些张量打印出来。
>>> print(c0) Tensor(″c0:0″, shape=(), dtype=int32) >>> print(c1) Tensor(″c1:0″, shape=(3,), dtype=int32) >>> print(c2) Tensor(″c2:0″, shape=(2, 2), dtype=int32)
我们发现,使用print语句打印一个张量只能打印出它的属性定义,并不能打印出它的值,要想查看一个张量的值还需要经过会话(Session)的运行,这正是TensorFlow的独特之处。关于会话,后面将会详细介绍。
3.3.2 张量的数学运算
TensorFlow中的张量同样可以进行常规的数学运算,请看下面几个例子。
>>> a = tf.constant([[1, 2], [3, 4]], name=′a′) >>> b = tf.constant([[5, 6], [7, 8]], name=′b′) # 加法 add >>> tf.add(a, b, name=′add′) <tf.Tensor ′add:0′ shape=(2, 2) dtype=int32> # 减法 sub >>> tf.subtract(a, b, name=′sub′) <tf.Tensor ′sub:0′ shape=(2, 2) dtype=int32>
# 对应元素相乘 multiply >>> tf.multiply(a, b, name=′multiply′) <tf.Tensor ′multiply:0′ shape=(2, 2) dtype=int32>
# 矩阵相乘 matmul >>> tf.matmul(a, b, name=′matmul′) <tf.Tensor ′matmul:0′ shape=(2, 2) dtype=int32>
通过name参数的设置,除了可以给张量命名之外,还可以给运算类型命名。TensorFlow中,张量的数学运算和普通计算是不同的,保存的不是数值而是计算过程,需要在会话中计算结果。