Pytorch框架學習(2)——張量操作與線性迴歸

張量操作與線性迴歸

1. 張量的操作:拼接、切分、索引和變換

1.1 張量的拼接與切分

  • torch.cat()

  • 功能:將張量按維度dim進行拼接(不會擴充張量的維度)

    • tensors:張量序列
    • dim:要拼接的維度
  • torch.stack()

  • 功能:在新創建的維度dim上進行拼接(創建新的維度擴充張量)

    • tensors:張量序列
    • dim:要拼接的維度
  • torch.chunk()

  • 功能:將張量按維度dim進行平均切分

  • 返回值:張量列表

  • 注意:若不能整除,最後一份張量小於其他張量

    • input:要切分的張量
    • chunks:要切分的份數
    • dim:要切分的維度
  • torch.split()

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

  • 返回值:張量列表

    • tensor:要切分的張量
    • split_size_or_sections:爲int時,表示每一份的長度;爲list時,按list元素切分
    • dim:要切分的維度
t = torch.ones(2, 5)
list_of_tensors = torch.split(t, [2, 1, 2], dim=1)
for idx, t in enumerate(list_of_tensors):
	print('第{}個張量:{},shape is {}'.format(idx + 1, t, t.shape))

結果爲:

第1個張量:tensor([[1., 1.],
[1., 1.]]),shape is torch.Size([2, 2])
第2個張量:tensor([[1.],
[1.]]),shape is torch.Size([2, 1])
第3個張量:tensor([[1., 1.],
[1., 1.]]),shape is torch.Size([2, 2])

1.2 張量索引

  • torch.index_select()
  • 功能:在維度dim上,按index索引數據
  • 返回值:依index索引數據拼接的張量
    • input:要索引的張量
    • dim:要索引的維度
    • index:要索引數據的序號(tensor數據結構,tensor裏面的數據必須爲長整型,torch.long)
t = torch.randint(0, 9, size=(3, 3))
idx = torch.tensor([0, 2], dtype=torch.long)
t_select = torch.index_select(t, dim=0, index=idx)
print('t:\n{}\nt_select\n:{}'.format(t, t_select))

結果爲:

t:
tensor([[5, 8, 2],
        [1, 3, 0],
        [2, 1, 6]])
t_select
:tensor([[5, 8, 2],
        [2, 1, 6]])
  • torch.masked_select()
  • 功能:按mask中的True進行索引,通常用來篩選數據
  • 返回值:一維張量
    • input:要索引的張量
    • mask:與input同形狀的布爾類型張量
t = torch.randint(0, 9, size=(3, 3))
mask = t.ge(5) # ge is mean greater than or equal.  gt is mean greater than . 還有le和lt
t_select = torch.masked_select(t, mask)
print('t:\n{}\nt_select\n:{}'.format(t, t_select))

結果爲:

t:
tensor([[5, 7, 2],
        [1, 6, 6],
        [1, 1, 8]])
t_select
:tensor([5, 7, 6, 6, 8])

1.3 張量變換

  • torch.reshape()
  • 功能:變換張量形狀
  • 注意:當張量在內存中是連續時,新張量與input共享數據內存
    • input:要變換的張量
    • shape:新張量的形狀
        t = torch.randperm(8)
        t_reshape = torch.reshape(t, (2, 4))
        print('t:{}\nt_reshape:\n{}'.format(t, t_reshape))
        print('t.data內存地址:{}\nt_reshape.data內存地址:{}'.format(id(t.data), id(t_reshape.data)))

結果爲:

t:tensor([0, 4, 1, 3, 5, 7, 6, 2])
t_reshape:
tensor([[0, 4, 1, 3],
        [5, 7, 6, 2]])
t.data內存地址:2126059754696
t_reshape.data內存地址:2126059754696
  • torch.transpose()

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

    • input:要交換的張量
    • dim0:要交換的維度
    • dim1:要交換的維度
  • torch.t()

  • 功能:2維張量轉置,對矩陣而言,等價於torch.transpose(input, 0, 1)

  • torch.sequeeze()

  • 功能:壓縮長度爲1的維度(軸)

    • dim:若爲None,移除所有長度爲1的軸;若指定維度,當且僅當該軸長度爲1時,可以被移除。
  • torch.unsequeeze()

  • 功能:依據dim擴展維度

    • dim:擴展的維度
        t = torch.rand((1, 2, 3, 1))
        t_sq = torch.squeeze(t)
        t_0 = torch.squeeze(t, dim=0)
        t_1 = torch.squeeze(t, dim=1)
        print(t.shape)
        print(t_sq.shape)
        print(t_0.shape)
        print(t_1.shape)

結果爲:

torch.Size([1, 2, 3, 1])
torch.Size([2, 3])
torch.Size([2, 3, 1])
torch.Size([1, 2, 3, 1])

2.張量的數學運算

張量之間可以進行加減乘除,可以進行對數、指數、冪函數運算,可以進行三角函數運算
在這裏插入圖片描述
這裏簡單介紹加法運算

  • torch.add()
  • 功能:逐元素計算***input+alpha+other***
    • input:第一個張量
    • alpha:乘項因子
    • other:第二個張量

除此之外,還有兩個加法運算,一個是加法結合除法,另一個是加法結合乘法

  • torch.addcdiv() outi=inputi+value×tensor1itensor2iout_i = input_i + value \times \frac{tensor1_i}{tensor2_i}
  • torch.addcmul() intpui+value×tensor1i×tensor2iintpu_i + value \times tensor1_i \times tensor2_i

3.線性迴歸

線性迴歸是分析一個變量與另外一個(多)個變量之間關係的方法。

  • 因變量:y
  • 自變量:x
  • 關係:線性 y=wx+by = wx + b
  • 分析:求解w,b

3.1 求解步驟

  1. 確定模型:
    Model:y=wx+bModel : y = wx + b
  2. 選擇損失函數loss:
    一般選擇均方誤差MSE:1mi=1m(yiyi^)2\frac{1}{m} \sum_{i=1}^{m}(y_i -\hat{y_i})^2
  3. 求解梯度並更新w,b:
    w=wLRw.gradw = w - LR * w.grad(LR爲步長,學習率)
    b=bLRw.gradb = b - LR * w.grad

import torch
import matplotlib.pyplot as plt


def main():

    torch.manual_seed(10)

    # 學習率
    lr = 0.05

    # 創建訓練數據
    x = torch.rand(20, 1) * 10
    y = 2*x + (5 + torch.randn(20, 1)) # y值隨機加入擾動

    #構建線性迴歸模型
    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 = (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('Iteratiion:{}\nw:{} b:{}'.format(iteration, w.data.numpy(), b.data.numpy()))
            plt.pause(0.5)

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


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