Pytorch 常用函數


1. torch.renorm(inputpdimmaxnormout=None) → Tensor

Returns a tensor where each sub-tensor of input along dimension dim is normalized such that the p-norm of the sub-tensor is lower than the value maxnorm。

解釋:返回一個張量,包含規范化后的各個子張量,使得沿着dim維划分的各子張量的p范數小於maxnorm

>>> x = torch.Tensor([[1,2,3]])
>>> torch.renorm(x,2,0,1) tensor([[ 0.2673, 0.5345, 0.8018]])

 

2. torch. scatter_(dimindexsrc) → Tensor

src中的所有值按照index確定的索引寫入本tensor中。其中索引是根據給定的dimension,dim按照gather()描述的規則來確定。

注意,index的值必須是在0(self.size(dim)-1)之間,

參數:

  • input (Tensor)-源tensor
  • dim (int)-索引的軸向
  • index (LongTensor)-散射元素的索引指數
  • src (Tensor or float)-散射的源元素
 1 >>> x = torch.rand(2, 5)
 2 >>> x
 3  0.4319  0.6500  0.4080  0.8760  0.2355
 4  0.2609  0.4711  0.8486  0.8573  0.1029
 5 [torch.FloatTensor of size 2x5]
6 >>> torch.zeros(3, 5).scatter_(0, torch.LongTensor([[0, 1, 2, 0, 0], [2, 0, 0, 1, 2]]), x) #將 x 按照格式寫入新的Tensor里 7 0.4319 0.4711 0.8486 0.8760 0.2355 8 0.0000 0.6500 0.0000 0.8573 0.0000 9 0.2609 0.0000 0.4080 0.0000 0.1029 10 [torch.FloatTensor of size 3x5]
11 >>> z = torch.zeros(2, 4).scatter_(1, torch.LongTensor([[2], [3]]), 1.23) 12 >>> z 13 0.0000 0.0000 1.2300 0.0000 14 0.0000 0.0000 0.0000 1.2300 15 [torch.FloatTensor of size 2x4]

 

3.  torch.gather(input, dim, index, out=None) Tensor

沿給定軸dim,將輸入索引張量index指定位置的值進行聚合。

參數:

  • input (Tensor) – 源張量
  • dim (int) – 索引的軸
  • index (LongTensor) – 聚合元素的下標
  • out (Tensor, optional) – 目標張量
>>> t = torch.Tensor([[1,2],[3,4]])
>>> torch.gather(t, 1, torch.LongTensor([[0,0],[1,0]]))
 1  1
 4  3
[torch.FloatTensor of size 2x2]

 or:

>>> s=torch.randn(3,6)
>>> s
tensor([[-0.4857, -0.0982, -0.6532, -1.0273, -0.9205, -0.7440],
        [-0.6890, -0.3474, -1.4337, -0.3511, -0.2443, -0.6398],
        [ 1.2902,  1.1210,  1.7374,  0.0902, -0.4524, -0.6898]])
>>> s.gather(1,torch.LongTensor([[1,2,1],[1,2,3],[1,2,3]]))
tensor([[-0.0982, -0.6532, -0.0982],
        [-0.3474, -1.4337, -0.3511],
        [ 1.1210,  1.7374,  0.0902]])

 

4. pytorch改變維度的操作

Pytorch Tensor維度變換


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM