pytorch 模塊


pytorch的中文手冊:https://github.com/zergtant/pytorch-handbook

 

一、定義/初始化張量Define tensors

tensor,即“張量”。實際上跟numpy數組、向量、矩陣的格式基本一樣。但是是專門針對GPU來設計的,可以運行在GPU上來加快計算效率。

PyTorch中定義tensor,就跟numpy定義矩陣、向量差不多,例如定義一個5×3的tensor,每一項都是0的張量:
x = torch.zeros(5,3)

如果想查看某個tensor的形狀的話,使用:
z.size(),或者z.shape,但是前者更常用。

下面列舉一些常用的定義tensor的方法:

常數初始化:

  • torch.empty(size)返回形狀為size的空tensor
  • torch.zeros(size)全部是0的tensor
  • torch.zeros_like(input)返回跟input的tensor一個size的全零tensor
  • torch.ones(size)全部是1的tensor
  • torch.ones_like(input)返回跟input的tensor一個size的全一tensor
  • torch.arange(start=0, end, step=1)返回一個從start到end的序列,可以只輸入一個end參數,就跟python的range()一樣了。實際上PyTorch也有range(),但是這個要被廢掉了,替換成arange了
  • torch.full(size, fill_value)這個有時候比較方便,把fill_value這個數字變成size形狀的張量

隨機抽樣(隨機初始化):

  • torch.rand(size) [0,1)內的均勻分布隨機數
  • torch.rand_like(input)返回跟input的tensor一樣size的0-1隨機數
  • torch.randn(size)返回標准正太分布N(0,1)的隨機數
  • torch.normal(mean, std, out=None)正態分布。這里注意,mean和std都是tensor,返回的形狀由mean和std的形狀決定,一般要求兩者形狀一樣。如果,mean缺失,則默認為均值0,如果std缺失,則默認標准差為1.

更多的隨機抽樣方法,參見鏈接:
https://pytorch.org/docs/stable/torch.html#random-sampling


二、基本操作、運算 Basic operations

1.tensor的切片、合並、變形、抽取操作

(Indexing, Slicing, Joining, Mutating)

這里我就簡單總結一些重要的tensor基本操作:

  • torch.cat(seq, dim=0, out=None),把一堆tensor丟進去,按照dim指定的維度拼接、堆疊在一起.
    比如:
In [70]: x = torch.tensor([[1,2,3]])
In [71]: x
Out[71]: tensor([[1, 2, 3]])

 #按第0維度堆疊,對於矩陣,相當於“豎着”堆
In [72]: print(torch.cat((x,x,x),0))
tensor([[1, 2, 3],
        [1, 2, 3],
        [1, 2, 3]])

 #按第1維度堆疊,對於矩陣,相當於“橫着”拼
In [73]: print(torch.cat((x,x,x),1)) 
tensor([[1, 2, 3, 1, 2, 3, 1, 2, 3]])
  • torch.chunk(tensor, chunks, dim=0)把tensor切成塊,數量由chunks指定。
    例如:
In [74]: a = torch.arange(10)
In [75]: a
Out[75]: tensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

In [76]: torch.chunk(a,4)
Out[76]: (tensor([0, 1, 2]), tensor([3, 4, 5]), tensor([6, 7, 8]), tensor([9]))
  • 切塊還有torch.split(tensor, split_size_or_sections, dim=0)具體區別大家自行查閱文檔
  • 按index選擇:torch.index_select(input, dim, index, out=None)
  • 按mask選擇:torch.masked_select(input, mask, out=None)
  • 經常會使用的“壓扁”函數:torch.squeeze(input),壓縮成1維。注意,壓縮后的tensor和原來的tensor共享地址
  • 改變形狀:torch.reshape(input, shape)以及tensor.view(shape).前者是把tensor作為函數的輸入,后者是任何tensor的函數。實際上,二者的返回值,都只是讓我們從另一種視角看某個tensor,所以不會改變本來的形狀,除非你把結果又賦值給原來的tensor。下面給一個例子對比二者的用法:
In [82]: a Out[82]: tensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) # 單純的調用view函數: In [83]: a.view(2,5) Out[83]: tensor([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]) # a的形狀並不會變化 In [84]: print(a) tensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) # 試試reshape函數: In [86]: torch.reshape(a,[5,2]) Out[86]: tensor([[0, 1], [2, 3], [4, 5], [6, 7], [8, 9]]) # a的形狀依然不會變化: In [87]: a Out[87]: tensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) 

要想讓a的形狀變化,比如把結果賦值給a,比如a = a.view(2,5)

還有好多有意思的操作,自己去發掘吧:
https://pytorch.org/docs/stable/torch.html#indexing-slicing-joining-mutating-ops

2.基本數學操作

  • 加法直接加:x+y
    或者用torch.add(x,y).
    實際上,.add()可以接受三個參數:torch.add(input, value, out=None)
    out怎么用呢?一般,如果直接torch.add(x,y),那么x,y本身都不會變化的。但是如果設置out=x,那么x就變變成加和后的值。

特別的,若想進行in-place操作,就比方說y加上x,y的值就改變了,就可以用y.add_(x)這樣y就直接被改變了。Torch里面所有帶"_"的操作,都是in-place的。例如x.copy_(y)

  • 乘法:torch.mul(input, other, out=None)用input乘以other
  • 除法:torch.div(input, other, out=None)用input除以other
  • 指數:torch.pow(input, exponent, out=None)
  • 開根號:torch.sqrt(input, out=None)
  • 四舍五入到整數:torch.round(input, out=None)
  • argmax函數torch.argmax(input, dim=None, keepdim=False)返回指定維度最大值的序號,dim給定的定義是:the demention to reduce.也就是把dim這個維度的,變成這個維度的最大值的index。例如:
     
    argmax
  • sigmoid函數:torch.sigmoid(input, out=None)
  • tanh函數:torch.tanh(input, out=None)
  • torch.abs(input, out=None)取絕對值
  • torch.ceil(input, out=None)向上取整,等於向下取整+1
  • torch.clamp(input, min, max, out=None)刀削函數,把輸入數據規范在min-max區間,超過范圍的用min、max代替

太多了,基本上,numpy里面有的數學函數這里都有,能想到的的基本都有。所以更詳細的內容,還是去查看文檔吧哈哈:
https://pytorch.org/docs/stable/torch.html#math-operations

三、Torch Tensor與Numpy的互相轉換

  • Tensor-->Numpy
    直接用.numpy()即可。但是注意,轉換后,numpy的變量和原來的tensor會共用底層內存地址,所以如果原來的tensor改變了,numpy變量也會隨之改變。參見下面的例子:
In [11]: a = torch.ones(2,4) In [12]: a Out[12]: tensor([[1., 1., 1., 1.], [1., 1., 1., 1.]]) In [13]: b = a.numpy() In [14]: b Out[14]: array([[1., 1., 1., 1.], [1., 1., 1., 1.]], dtype=float32) In [15]: a.add_(1) Out[15]: tensor([[2., 2., 2., 2.], [2., 2., 2., 2.]]) In [16]: b Out[16]: array([[2., 2., 2., 2.], [2., 2., 2., 2.]], dtype=float32) 
  • Numpy-->Tensor
    torch.from_numpy()來轉換。參見下面例子:
import numpy as np a = np.ones(5) b = torch.from_numpy(a) np.add(a, 1, out=a) print(a) print(b) 

輸出:

[2. 2. 2. 2. 2.] tensor([2., 2., 2., 2., 2.], dtype=torch.float64) 

同樣,兩者會共用內存地址。



作者:Stack_empty
鏈接: https://www.jianshu.com/p/7dbfc7076e5a
來源:簡書
著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請注明出處。


免責聲明!

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



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