Pytorch Tensor基本操作

創建Tensor

  • 從numpy引入 torch.from_numpy()
   a = np.array([2,3])
   torch.from_numpy(a)
  • 使用list導入,不用numpy作爲載體
   torch.tensor([2,3.3]) #具體的數據作爲參數
   torch.Tensor(2,3) #size作爲參數
  • torch.tensor()與torch.Tensor()
    torch.tensor()生成的Tensor會根據括號裏邊的參數類型而自動修改類型, 而FloatTensor,IntTensor,DoubleTensor則一開始就定義好了參數類型。

  • 隨機初始化生成Tensor rand/rand_like/randint/randn

   a = torch.rand(2,3) #rand生成0-1之間的數
   b = torch.rand_like(a) #生成一個與a形狀相同的Tensor
   c = torch.randint(1,10,[3,3]) #生成一個1到10(不包括10)之間的[3,3]的Tensor
   d = torch.randn(3,3) #生成0到1之間的[3,3]的Tensor           
  • 賦值生成Tensor
    torch.full([2,3],7) #生成兩行三列每個值爲7的Tensor
  • arange/range
    torch.arange(0,10) #[0,1,2,3,4,5,6,7,8,9]
    torch.arange(0,10,2) #[0,2,4,6,8]
  • linspace/logspace
    torch.linspace(0,10,4) #生成0-10之間的四個等分數
    torch.logspace(0,10,4) #生成log0-log10之間的四個等分數
  • Ones/zeros/eye
    torch.ones(3,3)
    torch.zeros(3,3)
    torch.eye(3) #對角矩陣
  • randperm隨機打散
    torch.randperm(10) #生成0-10之間隨機打亂的Tensor

索引與切片

  • 最常見的索引
    a = torch.rand(4,3,28,28) #4張圖片3個通道28*28的圖片
    a[0,0,2,4] #第1張圖第1個通道,第2行第4列
  • 取連續片段
    a = torch.rand(4,3,28,28)
    a[:2].shape #第0張和第1張圖片的所有數據,[2,3,28,28]
    a[:2,:1,:,:] #[2,1,28,28]
    a[:,:,0:28:2,0:28:2]
    a[:,:,::2,::2]
  • index_select()

    a.index_select(0,torch.tensor([0,2])).shape

    a = torch.rand(4,3,28,28)
    a.index_select(0,torch.tensor([0,2])).shape
    #0表示第0個維度,

維度變換

  • view()
    a = torch.rand(2,3)
    #tensor([[0.6165, 0.5740, 0.5052],
    #        [0.8733, 0.4058, 0.8350]])
    a.view(1,2*3)
    #tensor([[0.6165, 0.5740, 0.5052, 0.8733, 0.4058, 0.8350]])
  • unsqueeze()展開,插入一個維度
  a = torch.rand(4,1,28,28)
  a.unsqueeze(0).shape #[1,4,1,28,28]
  a.unsqueeze(-1).shape #[4,1,28,28,1]
  a.unsqueeze(4).shape #[4,1,28,28,1]
  a.unsqueeze(-4).shape #[4,1,1,28,28]
  • squeeze()維度刪減
    刪除維度爲1的數據
    a = torch.arand(1,32,1,1)
    a.squeeze().shape #[32]
    a.squeeze(1).shape #[1,32,1,1]
    a.squeeze(-1).shape #[1,32,1]
  • expand() 維度擴展
    b = torch.rand(1,32,1,1)
    b.expand(4,32,14,14) #[4,32,14,14]
    b.expand(-1,32,-1,-1) #[1,32,1,1]
  • repeat() 複製
    b = torch.rand(1,32,1,1)
    b.repeat(4,32,1,1) #[4,1024,1,1]
    b.repeat(4,1,1,1) #[4,32,1,1]
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章