1.基础运算
加减乘除四个最基本的数学运算,在TensorFlow中分别通过 tf.add, tf.subtract, tf.multiply, tf.divide 函数实现,TensorFlow 已经重载了+ ,−,∗,/运算符,一般为了方便,都是直接使用的运算符即可。
另外,整除和余除也是常见的运算之一,分别通过//和%运算符实现。
a = tf.constant([1, 3])
b = tf.constant([2, 4])
print("a+b: ", a + b)
print("a-b: ", a - b)
print("a*b: ", a * b)
print("a/b: ", a / b)
a+b: tf.Tensor([3 7], shape=(2,), dtype=int32)
a-b: tf.Tensor([-1 -1], shape=(2,), dtype=int32)
a*b: tf.Tensor([ 2 12], shape=(2,), dtype=int32)
a/b: tf.Tensor([0.5 0.75], shape=(2,), dtype=float64)
a = tf.range(5)
b = tf.constant(2)
print("a//b:", a//b)
print("a%b:", a%b)
a//b: tf.Tensor([0 0 1 1 2], shape=(5,), dtype=int32)
a%b: tf.Tensor([0 1 0 1 0], shape=(5,), dtype=int32)
2.乘方
通过 tf.pow(x, a)可以方便地完成𝑦 = 𝑥𝑎乘方运算,也可以通过运算符**实现𝑥 ∗∗ 𝑎运 算。
x = tf.range(4)
tf.pow(x, 3)
<tf.Tensor: id=92, shape=(4,), dtype=int32, numpy=array([ 0, 1, 8, 27])>
x = tf.range(4)
x ** 3
<tf.Tensor: id=98, shape=(4,), dtype=int32, numpy=array([ 0, 1, 8, 27])>
上面两种形式效果是等价的。
平方和平方根运算,可以使用 tf.square(x)和 tf.sqrt(x)实现。
x = tf.range(5)
x = tf.square(x)
x
<tf.Tensor: id=108, shape=(5,), dtype=int32, numpy=array([ 0, 1, 4, 9, 16])>
x = tf.range(5)
x = tf.cast(x, dtype=tf.float32)
x = tf.square(x)
x = tf.sqrt(x)
x
<tf.Tensor: id=167, shape=(5,), dtype=float32, numpy=array([0., 1., 2., 3., 4.], dtype=float32)>
3.指数和对数
通过 tf.pow(a, x)或者运算符可以方便实现指数运算ax。
x = tf.constant([1., 2., 3.])
2**x
<tf.Tensor: id=170, shape=(3,), dtype=float32, numpy=array([2., 4., 8.], dtype=float32)>
特别地,对于自然指数e**x,可以通过 tf.exp(x)实现。
x = tf.constant([1., 2., 3.])
tf.exp(1.)
<tf.Tensor: id=173, shape=(), dtype=float32, numpy=2.7182817>
自然对数logex可以通过 tf.math.log(x)实现。
x = tf.exp(3.)
tf.math.log(x)
<tf.Tensor: id=178, shape=(), dtype=float32, numpy=3.0>
如果希望计算其他底数的对数,可以根据对数的换底公式间接的通过 tf.math.log(x)实现。
x = tf.constant([1., 2.])
x = 10**x
tf.math.log(x)/tf.math.log(10.)
<tf.Tensor: id=188, shape=(2,), dtype=float32, numpy=array([1., 2.], dtype=float32)>
意思就是如今的TensorFlow只能够直接计算底为e的对数,以其他的数为底的对数的计算都需要间接地计算。
4.矩阵相乘
根据矩阵相乘的定义,a 和 b 能够矩阵相乘的条件是,a 的倒数第一个维度长度(列)和 b 的倒第二个维度长度(行)必须相等。
矩阵相乘可以通过@运算符实现,也可以通过tf.matmul()函数来实现。
a = tf.random.normal([4,3,23,32])
b = tf.random.normal([4,3,32,2])
a@b
<tf.Tensor: id=201, shape=(4, 3, 23, 2), dtype=float32, numpy=
array([[[[-1.57544804e+00, 1.28373241e+00],
[ 2.98329115e+00, 4.73872280e+00],
[-5.12334061e+00, -5.49857855e-01],
[ 3.33070755e-03, -5.75717926e-01],
......
a = tf.random.normal([4,3,23,32])
b = tf.random.normal([4,3,32,2])
tf.matmul(a, b)
<tf.Tensor: id=240, shape=(4, 3, 23, 2), dtype=float32, numpy=
array([[[[ -8.949667 , 6.5417395 ],
[ 3.9623122 , 1.3060207 ],
[ -3.9331567 , -3.33784 ],
[ -0.649312 , -3.0009353 ],
矩阵相乘函数支持自动 Broadcasting 机制。