t.clamp(a,min=2,max=4)近似於tf.clip_by_value(A, min, max),修剪值域。
a = t.arange(0,6).view(2,3) print("a:",a) print("t.cos(a):",t.cos(a)) print("a % 3:",a % 3) # t.fmod(a, 3) print("a ** 2:",a ** 2) # t.pow(a, 2) print("t.clamp(a, min=2, max=4)",t.clamp(a,min=2,max=4))
a: 0 1 2 3 4 5 [torch.FloatTensor of size 2x3] t.cos(a): 1.0000 0.5403 -0.4161 -0.9900 -0.6536 0.2837 [torch.FloatTensor of size 2x3] a % 3: 0 1 2 0 1 2 [torch.FloatTensor of size 2x3] a ** 2: 0 1 4 9 16 25 [torch.FloatTensor of size 2x3] t.clamp(a, min=2, max=4) 2 2 2 3 4 4 [torch.FloatTensor of size 2x3]
b = t.ones(2,3) print("b.sum():",b.sum(dim=0,keepdim=True)) print("b.sum():",b.sum(dim=0,keepdim=False))
cumsum和cumprob(累加和累乘)屬於特殊的歸併,結果相對於輸入並無降維。python
以前有說過,t.max用法較爲特殊;而a.topk是個對於深度學習非常方便的函數。數組
a = t.linspace(0,15,6).view(2,3) print("a:",a) print("a.sort(2):\n",a.sort(dim=1)) # 在某個維度上排序 print("a.topk(2):\n",a.topk(2,dim=1)) # 在某個維度上尋找top-k print("t.max(a):\n",t.max(a)) # 不輸入dim的話就是普通的max print("t.max(a,dim=1):\n",t.max(a,dim=1)) # 輸入dim的話就會集成argmax的功能
a: 0 3 6 9 12 15 [torch.FloatTensor of size 2x3] a.sort(2): ( 0 3 6 9 12 15 [torch.FloatTensor of size 2x3] , 0 1 2 0 1 2 [torch.LongTensor of size 2x3] ) a.topk(2): ( 6 3 15 12 [torch.FloatTensor of size 2x2] , 2 1 2 1 [torch.LongTensor of size 2x2] ) t.max(a): 15.0 t.max(a,dim=1): ( 6 15 [torch.FloatTensor of size 2] , 2 2 [torch.LongTensor of size 2] )
import numpy as np # 數組和Tensor互換 a = t.ones(2,3) b = a.numpy() c = t.from_numpy(b) c[0,0] = 0 print(a)
0 1 1 1 1 1 [torch.FloatTensor of size 2x3]
# 廣播法則 # 1.全部數組向shape最長的數組看齊,不足的在前方補一 # 2.兩個數組要麼在某個維度長度一致,要麼一個爲一,不然不能計算 # 3.對長度爲一的維度,計算時複製元素擴充至和此維度最長數組一致 a = t.ones(3,2) b = t.ones(2,3,1) print(a + b) # 先a->(1,3,2)而後a,b->(2,3,2)
(0 ,.,.) = 2 2 2 2 2 2 (1 ,.,.) = 2 2 2 2 2 2 [torch.FloatTensor of size 2x3x2]
使用尺寸調整函數模擬廣播過程以下,函數
# 手工復現廣播過程 # expend能夠擴張維度的數字大小,repeat相似,可是expend不會複製數組內存,節約空間 # 被擴充維度起始必須是1才行 print(a.unsqueeze(0).expand(2,3,2) + b.expand(2,3,2)) print(a.view(1,3,2).expand(2,3,2) + b.expand(2,3,2))
(0 ,.,.) = 2 2 2 2 2 2 (1 ,.,.) = 2 2 2 2 2 2 [torch.FloatTensor of size 2x3x2] (0 ,.,.) = 2 2 2 2 2 2 (1 ,.,.) = 2 2 2 2 2 2 [torch.FloatTensor of size 2x3x2]
咱們來看看expand方法,它要求咱們的被擴展維度爲1才行(以下),若是不是1則擴展失敗。學習
expand方法不會複製數組,不會佔用額外空間,只有在須要時才進行擴展,很節約內存。spa
a = t.ones(1) print(a.shape) b = a.expand(6) a = 2 print(a)