張量的操作主要包括張量的結構操作和張量的數學運算。
張量結構操作諸如:張量創建,索引切片,維度變換,合並分割。
張量數學運算主要有:標量運算,向量運算,矩陣運算。另外我們會介紹張量運算的廣播機制。
本篇我們介紹張量的數學運算。
一,標量運算
張量的數學運算符可以分為標量運算符、向量運算符、以及矩陣運算符。
加減乘除乘方,以及三角函數,指數,對數等常見函數,邏輯比較運算符等都是標量運算符。
標量運算符的特點是對張量實施逐元素運算。
有些標量運算符對常用的數學運算符進行了重載。並且支持類似numpy的廣播特性。
許多標量運算符都在 tf.math模塊下。
import tensorflow as tf import numpy as np a = tf.constant([[1.0,2],[-3,4.0]]) b = tf.constant([[5.0,6],[7.0,8.0]]) a+b #運算符重載
<tf.Tensor: shape=(2, 2), dtype=float32, numpy=
array([[ 6., 8.],
[ 4., 12.]], dtype=float32)>
a-b
<tf.Tensor: shape=(2, 2), dtype=float32, numpy=
array([[ -4., -4.],
[-10., -4.]], dtype=float32)>
a*b
<tf.Tensor: shape=(2, 2), dtype=float32, numpy=
array([[ 5., 12.],
[-21., 32.]], dtype=float32)>
a/b
<tf.Tensor: shape=(2, 2), dtype=float32, numpy=
array([[ 0.2 , 0.33333334],
[-0.42857143, 0.5 ]], dtype=float32)>
a**2
<tf.Tensor: shape=(2, 2), dtype=float32, numpy=
array([[ 1., 4.],
[ 9., 16.]], dtype=float32)>
a**(0.5)
<tf.Tensor: shape=(2, 2), dtype=float32, numpy=
array([[1. , 1.4142135],
[ nan, 2. ]], dtype=float32)>
a%3 #mod的運算符重載,等價於m = tf.math.mod(a,3)
<tf.Tensor: shape=(3,), dtype=int32, numpy=array([1, 2, 0], dtype=int32)>
a//3 #地板除法
<tf.Tensor: shape=(2, 2), dtype=float32, numpy=
array([[ 0., 0.],
[-1., 1.]], dtype=float32)>
(a>=2)
<tf.Tensor: shape=(2, 2), dtype=bool, numpy=
array([[False, True],
[False, True]])>
(a>=2)&(a<=3)
<tf.Tensor: shape=(2, 2), dtype=bool, numpy=
array([[False, True],
[False, False]])>
(a>=2)|(a<=3)
<tf.Tensor: shape=(2, 2), dtype=bool, numpy=
array([[ True, True],
[ True, True]])>
a==5 #tf.equal(a,5)
<tf.Tensor: shape=(3,), dtype=bool, numpy=array([False, False, False])>
tf.sqrt(a)
<tf.Tensor: shape=(2, 2), dtype=float32, numpy=
array([[1. , 1.4142135],
[ nan, 2. ]], dtype=float32)>
a = tf.constant([1.0,8.0]) b = tf.constant([5.0,6.0]) c = tf.constant([6.0,7.0]) tf.add_n([a,b,c])
<tf.Tensor: shape=(2,), dtype=float32, numpy=array([12., 21.], dtype=float32)>
tf.print(tf.maximum(a,b))
[5 8]
tf.print(tf.minimum(a,b))
[1 6]
二,向量運算
向量運算符只在一個特定軸上運算,將一個向量映射到一個標量或者另外一個向量。 許多向量運算符都以reduce開頭。
# 向量reduce a = tf.range(1,10) tf.print(tf.reduce_sum(a)) tf.print(tf.reduce_mean(a)) tf.print(tf.reduce_max(a)) tf.print(tf.reduce_min(a)) tf.print(tf.reduce_prod(a))
45
5
9
1
362880
# 張量指定維度進行reduce b = tf.reshape(a,(3,3)) tf.print(tf.reduce_sum(b, axis=1, keepdims=True)) tf.print(tf.reduce_sum(b, axis=0, keepdims=True))
[[6]
[15]
[24]]
[[12 15 18]]
# bool類型的reduce p = tf.constant([True,False,False]) q = tf.constant([False,False,True]) tf.print(tf.reduce_all(p)) tf.print(tf.reduce_any(q))
0
1
# 利用tf.foldr實現tf.reduce_sum s = tf.foldr(lambda a,b:a+b,tf.range(10)) tf.print(s)
45
# cum掃描累積 a = tf.range(1,10) tf.print(tf.math.cumsum(a)) tf.print(tf.math.cumprod(a))
[1 3 6 ... 28 36 45]
[1 2 6 ... 5040 40320 362880]
# arg最大最小值索引 a = tf.range(1,10) tf.print(tf.argmax(a)) tf.print(tf.argmin(a))
8
0
# tf.math.top_k可以用於對張量排序 a = tf.constant([1,3,7,5,4,8]) values,indices = tf.math.top_k(a,3,sorted=True) tf.print(values) tf.print(indices) # 利用tf.math.top_k可以在TensorFlow中實現KNN算法
[8 7 5]
[5 2 3]
三,矩陣運算
矩陣必須是二維的。類似tf.constant([1,2,3])這樣的不是矩陣。
矩陣運算包括:矩陣乘法,矩陣轉置,矩陣逆,矩陣求跡,矩陣范數,矩陣行列式,矩陣求特征值,矩陣分解等運算。
除了一些常用的運算外,大部分和矩陣有關的運算都在tf.linalg子包中。
# 矩陣乘法 a = tf.constant([[1,2],[3,4]]) b = tf.constant([[2,0],[0,2]]) a@b #等價於tf.matmul(a,b)
<tf.Tensor: shape=(2, 2), dtype=int32, numpy=
array([[2, 4],
[6, 8]], dtype=int32)>
# 矩陣轉置 a = tf.constant([[1.0,2],[3,4]]) tf.transpose(a)
<tf.Tensor: shape=(2, 2), dtype=float32, numpy=
array([[1., 3.],
[2., 4.]], dtype=float32)>
# 矩陣逆,必須為tf.float32或tf.double類型 a = tf.constant([[1.0,2],[3.0,4]],dtype = tf.float32) tf.linalg.inv(a)
<tf.Tensor: shape=(2, 2), dtype=float32, numpy=
array([[-2.0000002 , 1.0000001 ],
[ 1.5000001 , -0.50000006]], dtype=float32)>
# 矩陣求trace a = tf.constant([[1.0,2],[3,4]]) tf.linalg.trace(a)
<tf.Tensor: shape=(), dtype=float32, numpy=5.0>
# 矩陣求范數 a = tf.constant([[1.0,2],[3,4]]) tf.linalg.norm(a)
<tf.Tensor: shape=(), dtype=float32, numpy=5.477226>
# 矩陣行列式 a = tf.constant([[1.0,2],[3,4]]) tf.linalg.det(a)
<tf.Tensor: shape=(), dtype=float32, numpy=-2.0>
# 矩陣特征值 tf.linalg.eigvalsh(a)
<tf.Tensor: shape=(2,), dtype=float32, numpy=array([-0.8541021, 5.854102 ], dtype=float32)>
# 矩陣qr分解 a = tf.constant([[1.0,2.0],[3.0,4.0]],dtype = tf.float32) q,r = tf.linalg.qr(a) tf.print(q) tf.print(r) tf.print(q@r)
[[-0.316227794 -0.948683321]
[-0.948683321 0.316227734]]
[[-3.1622777 -4.4271884]
[0 -0.632455349]]
[[1.00000012 1.99999976]
[3 4]]
# 矩陣svd分解 a = tf.constant([[1.0,2.0],[3.0,4.0]],dtype = tf.float32) v,s,d = tf.linalg.svd(a) tf.matmul(tf.matmul(s,tf.linalg.diag(v)),d) # 利用svd分解可以在TensorFlow中實現主成分分析降維
<tf.Tensor: shape=(2, 2), dtype=float32, numpy=
array([[0.9999996, 1.9999996],
[2.9999998, 4. ]], dtype=float32)>
四,廣播機制
TensorFlow的廣播規則和numpy是一樣的:
- 1、如果張量的維度不同,將維度較小的張量進行擴展,直到兩個張量的維度都一樣。
- 2、如果兩個張量在某個維度上的長度是相同的,或者其中一個張量在該維度上的長度為1,那么我們就說這兩個張量在該維度上是相容的。
- 3、如果兩個張量在所有維度上都是相容的,它們就能使用廣播。
- 4、廣播之后,每個維度的長度將取兩個張量在該維度長度的較大值。
- 5、在任何一個維度上,如果一個張量的長度為1,另一個張量長度大於1,那么在該維度上,就好像是對第一個張量進行了復制。
tf.broadcast_to 以顯式的方式按照廣播機制擴展張量的維度。
# 矩陣svd分解 a = tf.constant([[1.0,2.0],[3.0,4.0]],dtype = tf.float32) v,s,d = tf.linalg.svd(a) tf.matmul(tf.matmul(s,tf.linalg.diag(v)),d) # 利用svd分解可以在TensorFlow中實現主成分分析降維
<tf.Tensor: shape=(3, 3), dtype=int32, numpy=
array([[1, 2, 3],
[2, 3, 4],
[3, 4, 5]], dtype=int32)>
tf.broadcast_to(a,b.shape)
<tf.Tensor: shape=(3, 3), dtype=int32, numpy=
array([[1, 2, 3],
[1, 2, 3],
[1, 2, 3]], dtype=int32)>
# 計算廣播后計算結果的形狀,靜態形狀,TensorShape類型參數 tf.broadcast_static_shape(a.shape,b.shape)
TensorShape([3, 3])
# 計算廣播后計算結果的形狀,動態形狀,Tensor類型參數 c = tf.constant([1,2,3]) d = tf.constant([[1],[2],[3]]) tf.broadcast_dynamic_shape(tf.shape(c),tf.shape(d))
<tf.Tensor: shape=(2,), dtype=int32, numpy=array([3, 3], dtype=int32)>
# 廣播效果 c+d #等價於 tf.broadcast_to(c,[3,3]) + tf.broadcast_to(d,[3,3])
<tf.Tensor: shape=(2, 2), dtype=float32, numpy=
array([[6.5760484, 7.8174157],
[6.8174157, 6.4239516]], dtype=float32)>
參考:
開源電子書地址:https://lyhue1991.github.io/eat_tensorflow2_in_30_days/
GitHub 項目地址:https://github.com/lyhue1991/eat_tensorflow2_in_30_days