Pytorch系列:Pytorch的簡單操作(三) ---- 張量的基礎操作

一、張量的拼接與切分

1. torch.cat(tensor, dim=0, out=None)

功能: 將張量按維度dim進行拼接
參數:

  • tensors:張量序列
  • dim:要拼接的維度
>>> t = torch.ones((2, 3))
>>> torch.cat([t, t], dim=0)
tensor([[1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.]])
>>> torch.cat([t, t], dim=1)
tensor([[1., 1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1., 1.]])
2. torch.stack(tensors, dim=0, out=None)

功能: 在新創建的維度dim上進行拼接,如果維度已經存在,則將存在的維度向後移動。然後新建維度進行拼接。
參數:

  • tensors:張量序列
  • dim:要拼接的維度
>>> t = torch.ones((2, 3))
>>> t_stack = torch.stack([t, t], dim=2)
>>> t_stack
tensor([[[1., 1.],
         [1., 1.],
         [1., 1.]],

        [[1., 1.],
         [1., 1.],
         [1., 1.]]])
>>> t_stack.shape
torch.Size([2, 3, 2])
>>> t.shape
torch.Size([2, 3])
>>> t_stack = torch.stack([t, t], dim=0)
>>> t_stack.shape
torch.Size([2, 2, 3])
3. torch.chunk(input, chunks, dim=0)

功能: 將張量按維度dim進行平均切分
返回值: 張量列表
注意事項: 若不能整除,最後一份張量小於其他張量
參數:

  • input:要切分的張量
  • chunks:要切分的份數
  • dim:要切分的維度
>>> a = torch.ones((2, 5))
>>> list_of_tensors = torch.chunk(a, dim=1, chunks=2)
>>>> for idx, t in enumerate(list_of_tensors):
...     print("第{}個張量:{},shape is {}".format(idx+1, t, t.shape))
...
第1個張量:tensor([[1., 1., 1.],
        [1., 1., 1.]]),shape is torch.Size([2, 3])
第2個張量:tensor([[1., 1.],
        [1., 1.]]),shape is torch.Size([2, 2])
4. torch.split(tensor, split_size_or_sections, dim=0)

功能: 將張量按維度dim進行切分
參數:

  • tensor:要切分的張量
  • split_size_or_sections:爲int時,表示每一份的長度;爲list時,按list元素切分
  • dim:要切分的維度
>>> t = torch.ones((2, 5))
>>> torch.split(t, 2, dim=1)
(tensor([[1., 1.],
        [1., 1.]]), 
 tensor([[1., 1.],
        [1., 1.]]), 
 tensor([[1.],
        [1.]]))

>>> torch.split(t, [2, 1, 2], dim=1)
(tensor([[1., 1.],
        [1., 1.]]), tensor([[1.],
        [1.]]), tensor([[1., 1.],
        [1., 1.]]))

二、張量的索引

1. torch.index_select(input, dim, index, out=None)

功能: 在維度dim上,按index索引數據
返回值: 依index索引數據拼接的張量
參數:

  • input:要索引的張量
  • dim:要索引的維度
  • index:要索引數據的序號
>>> t = torch.randint(0, 9, size=(3, 3))
>>> idx = torch.tensor([0, 2], dtype=torch.long)
>>> torch.index_select(t, dim=0, index=idx)
tensor([[3, 0, 8],
        [5, 3, 4]])
>>> t
tensor([[3, 0, 8],
        [4, 3, 8],
        [5, 3, 4]])
2. torch.masked_select(input, mask, out=None)

功能: 按mask中的True進行索引
返回值: 一維張量
參數:

  • input:要索引的張量
  • mask:與input同形狀的布爾類型張量
>>> t = torch.randint(0, 9, size=(3, 3))
>>> mask = t.ge(5)
>>> torch.masked_select(t, mask)
tensor([7, 5, 6, 7, 5])
>>> mask
tensor([[1, 0, 1],
        [1, 1, 0],
        [0, 1, 0]], dtype=torch.uint8)
>>> t
tensor([[7, 3, 5],
        [6, 7, 2],
        [1, 5, 4]])

三、張量變換

1. torch.reshape(input, shape)

功能: 變換張量形狀
注意事項: 當張量在內存中是連續時,新張量與input共享數據內存
參數:

  • input:要變換的張量
  • shape:新張量的形狀
>>> t = torch.randperm(8)
>>> t
tensor([1, 7, 3, 6, 4, 5, 2, 0])
>>> torch.reshape(t, (2, 4))
tensor([[1, 7, 3, 6],
        [4, 5, 2, 0]])
2. torch.transpose(input, dim0, dim1)

功能: 交換張量的兩個維度
參數:

  • input:要變換的張量
  • dim0:要交換的維度
  • dim1:要交換的維度
>>> t = torch.rand((2, 3, 4))
>>> t0 = torch.transpose(t, dim0=1, dim1=2)
>>> t0.shape
torch.Size([2, 4, 3])
3. torch.t(input)

功能: 2維張量轉置。

4. torch.squeeze(input, dim=None, out=None)

功能: 壓縮長度爲1的維度
參數:

  • input:輸入的張量
  • dim:若爲None,移除所有長度爲1的軸;若指定維度,當且僅當該軸長度爲1時,可以被移除。
>>> t = torch.rand((1, 2, 3, 1))
>>> torch.squeeze(t).shape
torch.Size([2, 3])
>>> torch.squeeze(t, dim=0).shape
torch.Size([2, 3, 1])
>>> torch.squeeze(t, dim=1).shape
torch.Size([1, 2, 3, 1])
5. torch.unsqueeze(input, dim, out=None)

功能: 依據dim擴展維度
參數:

  • dim:擴展的維度

四、張量的數學運算

        張量的數學運算包括:加減乘除、對數、指數、冪函數和三角函數等。常用的函數如下:

  1. torch.add()
  2. torch.sub()
  3. torch.div()
  4. torch.mul()
  5. torch.log(input)
  6. torch.log10(input)
  7. torch.exp(input)
  8. torch.abs(input)
  9. torch.cos(input)

五、線性迴歸

import torch
import matplotlib.pyplot as plt
torch.manual_seed(10)

lr = 0.05  # 學習率    

# 創建訓練數據
x = torch.rand(20, 1) * 10  
y = 2*x + (5 + torch.randn(20, 1))  

# 構建線性迴歸參數
w = torch.randn((1), requires_grad=True)
b = torch.zeros((1), requires_grad=True)

for iteration in range(1000):

    # 前向傳播
    wx = torch.mul(w, x)
    y_pred = torch.add(wx, b)

    # 計算 MSE loss
    loss = (0.5 * (y - y_pred) ** 2).mean()

    # 反向傳播
    loss.backward()

    # 更新參數
    b.data.sub_(lr * b.grad)
    w.data.sub_(lr * w.grad)

    # 清零張量的梯度   20191015增加
    w.grad.zero_()
    b.grad.zero_()

    # 繪圖
    if iteration % 20 == 0:

        plt.scatter(x.data.numpy(), y.data.numpy())
        plt.plot(x.data.numpy(), y_pred.data.numpy(), 'r-', lw=5)
        plt.text(2, 20, 'Loss=%.4f' % loss.data.numpy(), fontdict={'size': 20, 'color':  'red'})
        plt.xlim(1.5, 10)
        plt.ylim(8, 28)
        plt.title("Iteration: {}\nw: {} b: {}".format(iteration, w.data.numpy(), b.data.numpy()))
        # plt.pause(0.5)
        plt.show()

        if loss.data.numpy() < 1:
            break

1

80

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章