TensorFlow2.0(二):数学运算

  • 2019 年 10 月 3 日
  • 笔记

 

1 基本运算:(+、-、*、/、//、%)

 

基本运算中所有实例都以下面的张量a、b为例进行:

In [1]:
import tensorflow as tf  a = tf.random.uniform([2, 3], minval=1, maxval=6,dtype=tf.int32)  b = tf.random.uniform([2, 3], minval=1, maxval=6,dtype=tf.int32)  

In [3]:
a  

Out[3]:
<tf.Tensor: id=3, shape=(2, 3), dtype=int32, numpy=  array([[1, 4, 5],         [5, 1, 4]])>

In [4]:
b  

Out[4]:
<tf.Tensor: id=7, shape=(2, 3), dtype=int32, numpy=  array([[1, 3, 5],         [3, 5, 2]])>

 

(1)加(+)

In [6]:
tf.add(a,b)  # 通过add方法执行加操作  

Out[6]:
<tf.Tensor: id=12, shape=(2, 3), dtype=int32, numpy=  array([[ 2,  7, 10],         [ 8,  6,  6]])>

In [8]:
a + b  # 也可以通过操作符进行  

Out[8]:
<tf.Tensor: id=16, shape=(2, 3), dtype=int32, numpy=  array([[ 2,  7, 10],         [ 8,  6,  6]])>

 

(2)减(-)

In [10]:
tf.subtract(a,b)  

Out[10]:
<tf.Tensor: id=18, shape=(2, 3), dtype=int32, numpy=  array([[ 0,  1,  0],         [ 2, -4,  2]])>

In [11]:
a - b  

Out[11]:
<tf.Tensor: id=20, shape=(2, 3), dtype=int32, numpy=  array([[ 0,  1,  0],         [ 2, -4,  2]])>

 

(3)乘法(*)

In [12]:
tf.multiply(a,b)  

Out[12]:
<tf.Tensor: id=22, shape=(2, 3), dtype=int32, numpy=  array([[ 1, 12, 25],         [15,  5,  8]])>

In [13]:
a * b  

Out[13]:
<tf.Tensor: id=24, shape=(2, 3), dtype=int32, numpy=  array([[ 1, 12, 25],         [15,  5,  8]])>

 

(4)除法(/)

In [15]:
tf.divide(a,b)  

Out[15]:
<tf.Tensor: id=28, shape=(2, 3), dtype=float64, numpy=  array([[1.        , 1.33333333, 1.        ],         [1.66666667, 0.2       , 2.        ]])>

In [16]:
a/b  

Out[16]:
<tf.Tensor: id=32, shape=(2, 3), dtype=float64, numpy=  array([[1.        , 1.33333333, 1.        ],         [1.66666667, 0.2       , 2.        ]])>

 

(5)地板除法(//)

In [17]:
tf.floor_div(a,b)  

Out[17]:
<tf.Tensor: id=34, shape=(2, 3), dtype=int32, numpy=  array([[1, 1, 1],         [1, 0, 2]])>

In [19]:
a // b  

Out[19]:
<tf.Tensor: id=38, shape=(2, 3), dtype=int32, numpy=  array([[1, 1, 1],         [1, 0, 2]])>

 

(6)取余(%)

In [54]:
tf.mod(b,a)  

Out[54]:
<tf.Tensor: id=115, shape=(2, 2, 3), dtype=int32, numpy=  array([[[0, 1, 2],          [0, 0, 2]],           [[0, 1, 2],          [0, 0, 2]]])>

In [55]:
b % a  

Out[55]:
<tf.Tensor: id=117, shape=(2, 2, 3), dtype=int32, numpy=  array([[[0, 1, 2],          [0, 0, 2]],           [[0, 1, 2],          [0, 0, 2]]])>

 

可以看出,对于基本运算加(+)、减(-)、点乘(*)、除(/)、地板除法(//)、取余(%),都是对应元素进行运算。

 

2 指数、开方、对数

 

(1)对数运算

 

TensorFlow提供tf.math.log()方法来求对数,当然,求的是以自然常数$e$为底的对数:

In [22]:
e = 2.71828183  a = tf.constant([e, e*e, e*e*e])  tf.math.log(a)  

Out[22]:
<tf.Tensor: id=41, shape=(3,), dtype=float32, numpy=array([0.99999994, 2.        , 3.        ], dtype=float32)>

In [23]:
c = tf.fill([2,2],1.)  tf.math.log(c)  

Out[23]:
<tf.Tensor: id=46, shape=(2, 2), dtype=float32, numpy=  array([[0., 0.],         [0., 0.]], dtype=float32)>

 

注意:TensorFlow中没有提供函数实现以其他数值为底的对数运算,例如$lo{g_2}8$, $lg100$。不过,我们可以通过其他方式来求取,记得下面这个高中时学过的公式吗:

 
$$lo{g_a}b = frac{{lo{g_c}b}}{{lo{g_c}a}}$$

 

所以有:

In [24]:
f = tf.constant([[1., 9.], [16., 100.]])  g = tf.constant([[2., 3.], [2., 10.]])  

In [25]:
tf.math.log(f) / tf.math.log(g)  

Out[25]:
<tf.Tensor: id=52, shape=(2, 2), dtype=float32, numpy=  array([[0., 2.],         [4., 2.]], dtype=float32)>

 

(2)指数运算

In [30]:
g = tf.constant([[2, 3], [2, 10]])  

In [31]:
tf.pow(g, 2)  

Out[31]:
<tf.Tensor: id=66, shape=(2, 2), dtype=int32, numpy=  array([[  4,   9],         [  4, 100]])>

 

也可以直接通过运算符来完成:

In [27]:
g ** 2  

Out[27]:
<tf.Tensor: id=59, shape=(2, 2), dtype=int32, numpy=  array([[  4,   9],         [  4, 100]])>

 

(3)开方

In [32]:
f = tf.constant([[1., 9.], [16., 100.]])  

In [33]:
tf.sqrt(f)  

Out[33]:
<tf.Tensor: id=69, shape=(2, 2), dtype=float32, numpy=  array([[ 1.,  3.],         [ 4., 10.]], dtype=float32)>

 

自然常数$e$的指数运算:

In [34]:
d = tf.constant([[1.,2.],[3.,4.]])  

In [35]:
tf.exp(d)  

Out[35]:
<tf.Tensor: id=72, shape=(2, 2), dtype=float32, numpy=  array([[ 2.7182817,  7.389056 ],         [20.085537 , 54.598152 ]], dtype=float32)>

 

注意:对数运算函数log()与指数运算函数在不同的模块中。

在我看来,上面提到的指数运算与对数运算不在通知模块以及没有提供以其他自然数为底的对数运算,应该应该是TensorFlow中的遗留问题,希望能够在正式版中得到修正。

 

3 矩阵相乘

In [36]:
import numpy as np  a = tf.constant(np.arange(6),shape=(2,3))  b = tf.constant(np.arange(6),shape=(3,2))  

In [37]:
a  

Out[37]:
<tf.Tensor: id=76, shape=(2, 3), dtype=int32, numpy=  array([[0, 1, 2],         [3, 4, 5]])>

In [38]:
b  

Out[38]:
<tf.Tensor: id=79, shape=(3, 2), dtype=int32, numpy=  array([[0, 1],         [2, 3],         [4, 5]])>

In [39]:
tf.matmul(a,b)  

Out[39]:
<tf.Tensor: id=82, shape=(2, 2), dtype=int32, numpy=  array([[10, 13],         [28, 40]])>

 

矩阵相乘也可以通过符号来操作进行,用“@”表示:

In [41]:
a @ b  

Out[41]:
<tf.Tensor: id=86, shape=(2, 2), dtype=int32, numpy=  array([[10, 13],         [28, 40]])>

 

这里的张量a和b都是二维的,但在实际应用中,数据往往高于二维,这时候怎么应算呢?

In [42]:
a = tf.constant(np.arange(12),shape=(2,2,3))  b = tf.constant(np.arange(12),shape=(2,3,2))  

In [43]:
a  

Out[43]:
<tf.Tensor: id=90, shape=(2, 2, 3), dtype=int32, numpy=  array([[[ 0,  1,  2],          [ 3,  4,  5]],           [[ 6,  7,  8],          [ 9, 10, 11]]])>

In [44]:
b  

Out[44]:
<tf.Tensor: id=93, shape=(2, 3, 2), dtype=int32, numpy=  array([[[ 0,  1],          [ 2,  3],          [ 4,  5]],           [[ 6,  7],          [ 8,  9],          [10, 11]]])>

In [45]:
a @ b  

Out[45]:
<tf.Tensor: id=96, shape=(2, 2, 2), dtype=int32, numpy=  array([[[ 10,  13],          [ 28,  40]],           [[172, 193],          [244, 274]]])>

 

可以看到,当高于二维的张量进行矩阵相乘时,最终的实现还是二维矩阵相乘,只不过分成了多个二维矩阵,四维张量也是一样的:

In [46]:
a = tf.constant(np.arange(24),shape=(2,2,2,3))  b = tf.constant(np.arange(24),shape=(2,2,3,2))  

In [47]:
a @ b  

Out[47]:
<tf.Tensor: id=104, shape=(2, 2, 2, 2), dtype=int32, numpy=  array([[[[  10,   13],           [  28,   40]],            [[ 172,  193],           [ 244,  274]]],             [[[ 550,  589],           [ 676,  724]],            [[1144, 1201],           [1324, 1390]]]])>

 

4 Broadcasting机制

 

上面的所有实例中所用到的张量都是在维度数和形状相同情况下进行,那么,当两个张量维度数或者形状不一样时能不能进行运算呢?

In [48]:
a = tf.constant([1,2,3])  b = tf.constant(np.arange(12),shape=(2,2,3))  

In [49]:
b  

Out[49]:
<tf.Tensor: id=109, shape=(2, 2, 3), dtype=int32, numpy=  array([[[ 0,  1,  2],          [ 3,  4,  5]],           [[ 6,  7,  8],          [ 9, 10, 11]]])>

In [50]:
a + b  

Out[50]:
<tf.Tensor: id=111, shape=(2, 2, 3), dtype=int32, numpy=  array([[[ 1,  3,  5],          [ 4,  6,  8]],           [[ 7,  9, 11],          [10, 12, 14]]])>

In [51]:
a * b  

Out[51]:
<tf.Tensor: id=113, shape=(2, 2, 3), dtype=int32, numpy=  array([[[ 0,  2,  6],          [ 3,  8, 15]],           [[ 6, 14, 24],          [ 9, 20, 33]]])>

 

可以看到,一个一维的张量与一个三维张量进行运算是完全没有问题的,从运算结果上可以看出,相当于是三维张量中的每一行数据与张量a进行运算,为什么可以这样运输呢?这就得益于TensorFlow中的Broadcasting机制。

Broadcasting机制解除了只能维度数和形状相同的张量才能进行运算的限制,当两个数组进行算术运算时,TensorFlow的Broadcasting机制首先对维度较低的张量形状数组填充1,从后向前,逐元素比较两个数组的形状,当逐个比较的元素值(注意,这个元素值是指描述张量形状数组的值,不是张量的值)满足以下条件时,认为满足 Broadcasting 的条件:

(1)相等

(2)其中一个张量形状数组元素值为1。

当不满足时进行运算则会抛出 ValueError: frames are not aligne 异常。算术运算的结果的形状的每一元素,是两个数组形状逐元素比较时的最大值。

回到上面张量a与b相乘的例子,a的形状是(3,),b的形状是(2, 2, 3),在Broadcasting机制工作时,首先比较维度数,因为a的维度为1,小于b的维度3,所以填充1,a的形状就变成了(1,1,3),然后从最后端的形状数组元素依次往前比较,先是就是3与3比,结果是相等,接着1与2相比,因为其中一个为1,所以a的形状变成了(1,2,3),继续1与2比较,因为其中一个为1,所以a的形状变成了(2,2,3),a中的数据每一行都填充a原来的数据,也就是[1,2,3],然后在与b进行运算。

当然,在TensorFlow的Broadcasting机制运行过程中,上述操作只是理论的,并不会真正的将a的形状变成(2,2,3,),更不会将每一行填充[1,2,3],只是虚拟进行操作,真正计算时,依旧是使用原来的张量a。这么做的好处是运算效率更高,也更节省内存。

再举一些例子加深理解:

 
  • [ ] A:(2d array): 5 x 4
  • [ ] B:(1d array): 1
  • [ ] Result:(2d array): 5 x 4

  • [ ] A:(2d array): 5 x 4
  • [ ] B:(1d array): 4
  • [ ] Result:(2d array): 5 x 4

  • [ ] A:(3d array): 15 x 3 x 5
  • [ ] B:(3d array): 15 x 1 x 5
  • [ ] Result:(3d array): 15 x 3 x 5

  • [ ] A:(3d array): 15 x 3 x 5
  • [ ] B:(2d array): 3 x 5
  • [ ] Result:(3d array): 15 x 3 x 5

  • [ ] A:(3d array): 15 x 3 x 5
  • [ ] B:(2d array): 3 x 1
  • [ ] Result:(3d array): 15 x 3 x 5

 

一些反例(不满足 Broadcasting 规则 ):

 
  • [ ] A (1d array): 3
  • [ ] B (1d array): 4

  • [ ] A (2d array): 2 x 1
  • [ ] B (3d array): 8 x 4 x 3

 

5 范数

 

范数是泛函分析中的概念,指的是一种更宽泛的长度(距离)概念,只要满足非负、自反、三角不等式就可以称之为距离。向量$v$的$p$范数可以使用下面公式进行计算: $$|v|{|_p} = {left[ {sumlimits_{k = 1}^N {|{v_k}|p} } right]^{1/p}}$$ 当$p = 1,2$时分别叫做1范数,2范数。除此以外,还有无穷范数: $$|v|{|_{ + infty }} = max (|v(i)|)$$ $$|v|{|_{ – infty }} = min (|v(i)|)$$

In [1]:
import tensorflow as tf  

In [2]:
a = tf.constant([[1.,2.],[1.,2.]])  

In [3]:
tf.norm(a, ord=1)  # 1范数  

Out[3]:
<tf.Tensor: id=4, shape=(), dtype=float32, numpy=6.0>

In [4]:
tf.norm(a, ord=2)  # 2范数  

Out[4]:
<tf.Tensor: id=10, shape=(), dtype=float32, numpy=3.1622777>

In [5]:
tf.norm(a)  # ord不指定时,默认是2  

Out[5]:
<tf.Tensor: id=16, shape=(), dtype=float32, numpy=3.1622777>

 

我们也可以全手动地实现范数:

In [6]:
tf.sqrt(tf.reduce_sum(tf.square(a)))  

Out[6]:
<tf.Tensor: id=21, shape=(), dtype=float32, numpy=3.1622777>

 

指定维度求范数:

In [7]:
tf.norm(a, ord=2, axis=0)  

Out[7]:
<tf.Tensor: id=27, shape=(2,), dtype=float32, numpy=array([1.4142135, 2.828427 ], dtype=float32)>

In [8]:
tf.norm(a, ord=2, axis=1)  

Out[8]:
<tf.Tensor: id=33, shape=(2,), dtype=float32, numpy=array([2.236068, 2.236068], dtype=float32)>

 

参考