Pytorch Tensor 常用操作


https://pytorch.org/docs/stable/tensors.html

dtype: tessor的數據類型,總共有8種數據類型,其中默認的類型是torch.FloatTensor,而且這種類型的別名也可以寫作torch.Tensor

 

device: 這個參數表示了tensor將會在哪個設備上分配內存。它包含了設備的類型(cpucuda)和可選設備序號。如果這個值是缺省的,那么默認為當前的活動設備類型。

require_grad: 這個標志表明這個tensor的操作是否會被pytorch的自動微分系統(Autograd)記錄其操作過程,以便后續自動求導。

layout: 表示了tensor的內存分布方式。目前,pytorch支持torch.strided方式以及實驗性質地支持torch.sparse_coo。前者是目前普遍的使用方式。每一個strided tensor都關聯一個torch.storage以保存其數據。

 

創建

典型的tensor構建方法:

torch.tensor(data, dtype=None, device=None, requires_grad=False)

從其他形式轉換而來:

torch.as_tensor(data, dtype=None, device=None)

torch.from_numpy(ndarray)

創建特殊值組成的tensor:

torch.zeros(*sizes, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False)

torch.zeros_like(input, dtype=None, layout=None, device=None, requires_grad=False)

torch.ones(*sizes, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False)

torch.ones_like(input, dtype=None, layout=None, device=None, requires_grad=False)

torch.eye(n, m=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False)

torch.empty(*sizes, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False)

torch.empty_like(input, dtype=None, layout=None, device=None, requires_grad=False)

torch.full(size, fill_value, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False)

torch.full_like(input, fill_value, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False)

按照步長或者區間創建tensor:

torch.arange(start=0, end, step=1, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False)

torch.range(start=0, end, step=1, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False)

torch.linspace(start, end, steps=100, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False)

torch.logspace(start, end, steps=100, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False)

索引,分塊,組合,變形

組合--拼接

torch.cat(seq, dim=0, out=None):按照已經存在的維度進行concatenate。

在指定的維度dim上對序列seq進行連接操作。例如:

參數:

seq (sequence of Tensors) - Python序列或相同類型的張量序列

dim (int, optional) - 沿着此維度連接張量

out (Tensor, optional) - 輸出參數

x = torch.randn(2, 3)

x

-0.5866 -0.3784 -0.1705

-1.0125 0.7406 -1.2073

[torch.FloatTensor of size 2x3]

torch.cat((x, x, x), 0)

-0.5866 -0.3784 -0.1705

-1.0125 0.7406 -1.2073

-0.5866 -0.3784 -0.1705

-1.0125 0.7406 -1.2073

-0.5866 -0.3784 -0.1705

-1.0125 0.7406 -1.2073

[torch.FloatTensor of size 6x3]

torch.cat((x, x, x), 1)

-0.5866 -0.3784 -0.1705 -0.5866 -0.3784 -0.1705 -0.5866 -0.3784 -0.1705

-1.0125 0.7406 -1.2073 -1.0125 0.7406 -1.2073 -1.0125 0.7406 -1.2073

[torch.FloatTensor of size 2x9]

torch.stack(seq, dim=0, out=None):按照新的維度進行concatenate。

在指定的維度dim上對序列seq進行連接操作。例如:

a = torch.IntTensor([[1,2,3],[11,22,33]])

b = torch.IntTensor([[4,5,6],[44,55,66]])

c = torch.stack([a,b],0)

d = torch.stack([a,b],1)

e = torch.stack([a,b],2)

c :tensor([[[ 1,  2,  3],

         [11, 22, 33]],

        [[ 4,  5,  6],

         [44, 55, 66]]], dtype=torch.int32)

d :tensor([[[ 1,  2,  3],

         [ 4,  5,  6]],

        [[11, 22, 33],

         [44, 55, 66]]], dtype=torch.int32)

e :tensor([[[ 1,  4],

         [ 2,  5],

         [ 3,  6]],

        [[11, 44],

         [22, 55],

         [33, 66]]], dtype=torch.int32)

c, dim = 0時

c = [ a, b]

d, dim =1 時

d = [ [a[0] , b[0] ] , [a[1], b[1] ] ]

e, dim = 2 時

e=[[[a[0][0],b[0][0]],[a[0][1],b[0][1]],[a[0][2],b[0][2]]],[[a[1][0],b[1][0]],[a[1][1],b[0][1]],[a[1][2],b[1][2]]]]

分塊

torch.chunk(tensor, chunks, dim=0):按照某個維度平均分塊(最后一個可能小於平均值)

torch.split(tensor, split_size_or_sections, dim=0):按照某個維度依照第二個參數給出的list或者int進行分割tensor。

索引

torch.gather(input, dim, index, out=None):沿給定軸 dim ,將輸入索引張量 index 指定位置的值進行聚合輸出tensor。輸入與輸出大小一致。

例如:

對一個 3 維張量,輸出可以定義為:

out[i][j][k] = input[index[i][j][k]][j][k]  # if dim == 0

out[i][j][k] = input[i][index[i][j][k]][k]  # if dim == 1

out[i][j][k] = input[i][j][index[i][j][k]]  # if dim == 2

  • input (Tensor) – 源張量
  • dim (int) – 索引的軸
  • index (LongTensor) – 聚合元素的下標(index需要是torch.longTensor類型)
  • out (Tensor, optional) – 目標張量

dim = 1

a = torch.randint(0, 30, (2, 3, 5))

print(a)

'''

tensor([[[ 18.,   5.,   7.,   1.,   1.],

         [  3.,  26.,   9.,   7.,   9.],

         [ 10.,  28.,  22.,  27.,   0.]],

        [[ 26.,  10.,  20.,  29.,  18.],

         [  5.,  24.,  26.,  21.,   3.],

         [ 10.,  29.,  10.,   0.,  22.]]])

'''

index = torch.LongTensor([[[0,1,2,0,2],

                          [0,0,0,0,0],

                          [1,1,1,1,1]],

                        [[1,2,2,2,2],

                         [0,0,0,0,0],

                         [2,2,2,2,2]]])

print(a.size()==index.size())

b = torch.gather(a, 1,index)

print(b)

'''

True

tensor([[[ 18.,  26.,  22.,   1.,   0.],

         [ 18.,   5.,   7.,   1.,   1.],

         [  3.,  26.,   9.,   7.,   9.]],

        [[  5.,  29.,  10.,   0.,  22.],

         [ 26.,  10.,  20.,  29.,  18.],

         [ 10.,  29.,  10.,   0.,  22.]]])

可以看到沿着dim=1,也就是列的時候。輸出tensor第一頁內容,

第一行分別是 按照index指定的,

input tensor的第一頁

第一列的下標為0的元素 第二列的下標為1元素 第三列的下標為2的元素,第四列下標為0元素,第五列下標為2元素

index-->0,1,2,0,2    output--> 18.,  26.,  22.,   1.,   0.

'''

dim =2

c = torch.gather(a, 2,index)

print(c)

'''

tensor([[[ 18.,   5.,   7.,  18.,   7.],

         [  3.,   3.,   3.,   3.,   3.],

         [ 28.,  28.,  28.,  28.,  28.]],

        [[ 10.,  20.,  20.,  20.,  20.],

         [  5.,   5.,   5.,   5.,   5.],

         [ 10.,  10.,  10.,  10.,  10.]]])

dim = 2的時候就安裝 行 聚合了。參照上面的舉一反三。

'''

dim = 0

index2 = torch.LongTensor([[[0,1,1,0,1],

                          [0,1,1,1,1],

                          [1,1,1,1,1]],

                        [[1,0,0,0,0],

                         [0,0,0,0,0],

                         [1,1,0,0,0]]])

d = torch.gather(a, 0,index2)

print(d)

'''

tensor([[[ 18.,  10.,  20.,   1.,  18.],

         [  3.,  24.,  26.,  21.,   3.],

         [ 10.,  29.,  10.,   0.,  22.]],

        [[ 26.,   5.,   7.,   1.,   1.],

         [  3.,  26.,   9.,   7.,   9.],

         [ 10.,  29.,  22.,  27.,   0.]]])

這個有點特殊,dim = 0的時候(三維情況下),是從不同的頁收集元素的。

這里舉的例子只有兩頁。所有index在0,1兩個之間選擇。

輸出的矩陣元素也是按照index的指定。分別在第一頁和第二頁之間跳着選的。

index [0,1,1,0,1]的意思就是。

在第一頁選這個位置的元素,在第二頁選這個位置的元素,在第二頁選,第一頁選,第二頁選。

'''

 torch.index_select(input, dim, index, out=None):選出一維度的一些slice組合成新的tensor。指定維度的大小與index大小一致。

torch.masked_select(input, mask, out=None):按照mask輸出一個一維的tensor。

torch.take(input, indices):將輸入看成1D tensor,按照索引得到輸出。輸出大小與index大小一致。

torch.nonzero(input, out=None):輸出非0元素的坐標。

torch.where(condition, x, y):按照條件從x和y中選出滿足條件的元素組成新的tensor。

變形

torch.reshape(input, shape)

torch.t(input):只針對2D tensor轉置

torch.transpose(input, dim0, dim1):交換兩個維度

torch.squeeze(input, dim=None, out=None):去除那些維度大小為1的維度,如果輸入張量的形狀為(A×1×B×C×1×D),那么輸出張量的形狀為(A×B×C×D)

torch.unbind(tensor, dim=0):去除某個維度

torch.unsqueeze(input, dim, out=None):在指定位置添加維度

數學運算

Pointwise Ops 逐點操作

torch.addcdiv(tensor, value=1, tensor1, tensor2, out=None)

 

torch.addcmul(tensor, value=1, tensor1, tensor2, out=None)

 

torch.ceil(input, out=None)

 

torch.clamp(input, min, max, out=None)max或者min可以用*代替,表示沒有該項限制

 

torch.erf(tensor, out=None)

 

torch.fmod(input, divisor, out=None): 計算余數

torch.frac(tensor, out=None)

 

torch.lerp(start, end, weight, out=None)

 

torch.neg(input, out=None)

 

torch.pow(base, input, out=None)

 

torch.reciprocal(input, out=None)

 

torch.remainder(input, divisor, out=None)計算余數

torch.rsqrt(input, out=None)

 

torch.sign(input, out=None)取符號

torch.trunc(input, out=None):截取整數部分

Reduction Ops 歸約操作

torch.dist(input, other, p=2) 計算p范數

torch.norm() 計算2范數

torch.prod() 計算所有元素的積

torch.unique(input, sorted=False, return_inverse=False) 以1D向量保存張量中不同的元素。

Comparison Ops 比較操作

torch.isfinite(tensor)/torch.isinf(tensor)/torch.isnan(tensor)返回一個標記元素是否為 finite/inf/nan 的mask 張量。

torch.kthvalue(input, k, dim=None, keepdim=False, out=None) -> (Tensor, LongTensor):返回最小的第k個元素,如果為指定維度,則默認為最后一個維度。

torch.sort(input, dim=None, descending=False, out=None):沿着某一維度對張量進行升序排列。

torch.topk(input, k, dim=None, largest=True, sorted=True, out=None):返回最大的k個元素。

Other Operations 其他操作

torch.bincount(self, weights=None, minlength=0):返回每個值得頻數。

torch.cross(input, other, dim=-1, out=None):按照維度計算叉積。

torch.diag(input, diagonal=0, out=None):如果輸入時1D,則返回一個相應的對角矩陣;如果輸入時2D,則返回相應對角線的元素。

torch.flip(input, dims):按照給定維度翻轉張量

torch.histc(input, bins=100, min=0, max=0, out=None):計算張量的直方圖。

torch.meshgrid(seq):生成網格(可以生成坐標)。

查看張量單個元素的字節數

torch.Tensor.element_size() → int

查看某類型張量單個元素的字節數。

例如:

torch.FloatTensor().element_size()

4

 


免責聲明!

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



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