在使用numpy 對張量(數組)進行操做時,兩個形狀相同的張量進行加減等運算很容易理解,那麼不一樣形狀的張量之間的運算是經過廣播來實現的。廣播實際上很簡單,可是弄清楚是也花了不小功夫,這裏記錄一下。數組
廣播的目的是將兩個不一樣形狀的張量 變成兩個形狀相同的張量,即先對小的張量添加軸(使其ndim與較大的張量相同),在把較小的張量沿着新軸重複(使其shape與較大的相同)spa
廣播的的限制條件爲:兩個張量的 trailing dimension(從後往前算起的維度)的軸長相等 或 其中一個的長度爲1code
import numpy as np a=np.arange(0,12) a=a.reshape(3,4) b=np.arange(0,4) print(a) #[[ 0 1 2 3] # [ 4 5 6 7] # [ 8 9 10 11]] print(b) #[0 1 2 3] print(a.shape) #(3, 4) print(b.shape) #(4,) print(a.ndim) #2 print(b.ndim) #1 a+b #array([[ 0, 2, 4, 6], # [ 4, 6, 8, 10], # [ 8, 10, 12, 14]])
上述 a+b 的計算過程等價爲:blog
(1)先將b添加一個軸 即圖片
(2)在將b沿着 新加的軸進行重複 io
b.reshape(1,4) #array([[0, 1, 2, 3]]) c=np.array([b,b,b]) #array([[0, 1, 2, 3], # [0, 1, 2, 3], # [0, 1, 2, 3]]) a+c #array([[ 0, 2, 4, 6], # [ 4, 6, 8, 10], # [ 8, 10, 12, 14]])
其餘幾個例子class
x=np.arange(0,12) x=x.reshape(3,4,1) x y=np.arange(0,8) y=y.reshape(4,2) y q=x+y q.shape #(3,4,2)
x=np.arange(0,12) x=x.reshape(3,4,1) x z=np.arange(0,2) z=z.reshape(1,2) z q=x+z q.shape #(3,4,2)
x : y
z
x+y
x+z
import
最後放上幾個圖片便於理解numpy