<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          筆記 | PyTorch安裝及入門(mén)教程

          共 15892字,需瀏覽 32分鐘

           ·

          2021-08-10 18:40

          點(diǎn)擊上方小白學(xué)視覺(jué)”,選擇加"星標(biāo)"或“置頂

          重磅干貨,第一時(shí)間送達(dá)

          本文內(nèi)容概述如何安裝PyTorch以及PyTorch的一些簡(jiǎn)單操作

          本期筆記目錄:

                2.1 為何選擇PyTorch?

          PyTorch主要由4個(gè)包組成:

          1. torch:可以將張量轉(zhuǎn)換為torch.cuda.TensorFloat

          2. torch.autograd:自動(dòng)梯度

          3. torch.nn:具有共享層和損失函數(shù)的神經(jīng)網(wǎng)絡(luò)庫(kù)

          4. torch.optim:具有通用的優(yōu)化算法包(SGD、Adam)

            2.2 安裝Anaconda

          Anaconda官網(wǎng)地址

          https://www.anaconda.com/products/individual

                 


                 



                 



                 


          這里選擇All Users,一步一步操作即可

                


          安裝成功與否

                 



             


                 


                 


                 


          2.3 安裝Pytorch

          由于pytorch有不同的版本,為了方便使用不同的版本,我們新建不同的環(huán)境(類(lèi)比建造房屋,一個(gè)房屋放一個(gè)版本的pytorch),用來(lái)安裝現(xiàn)有版本的pytorch

          conda create –n pytorch python=3.7

                 

          選擇Y    

             

          conda info –envs

                 

          conda activate pytorch

                 


          安裝Pytorch

          Pytorch的官方網(wǎng)站:

          https://pytorch.org/

                 

          conda install pytorch torchvision cudatoolkit=10.2 -c pytorch

                 

          選擇y 

               

                 


               


                 


                 

                 


               


          2.4 Numpy 與 Tensor

          Numpy會(huì)把ndarray 放在CPU中運(yùn)行加速,而由Torch產(chǎn)生的Tensor會(huì)放在GPU中進(jìn)行加速運(yùn)算

          2.4.1 Tensor概述

          從接口的角度劃分:

          1. torch.function           torch.sum       torch.add
          2. tensor.function tensor.view tensor.add

          從修改方式的角度劃分:

          1. 不修改自身數(shù)據(jù),x.add(y),x數(shù)據(jù)不變,返回新的Tensor
          2. 修改自身數(shù)據(jù),x.add_(y),運(yùn)算結(jié)果存在x中,x被修改
          import torch
          x=torch.tensor([1,2])
          y=torch.tensor([3,4])
          z=x.add(y)
          print(z)
          print(x)
          x.add_(y)
          print(x)

          2.4.2 創(chuàng)建Tensor

          創(chuàng)建Tensor的常用方法

          * Tensor(*size)                          從參數(shù)構(gòu)建,List或者Numpy都行
          * eye(row,column) 指定行數(shù)和列數(shù)的二維Tensor
          * linspace(start,end,steps) 均勻分成
          * longspace(start,end,steps) 10^start到10^end,均勻分成
          * rand/randn(*size) 生成[0,1)均與分布,標(biāo)準(zhǔn)正態(tài)分布
          * ones(*size) 返回指定shape張量,元素為1
          * zeros(*size) 返回指定shape張量,元素為0
          * ones_like(t)
          * zeros_like(t)
          * arange(start,end,stop)
          * from_Numpy(ndarray)
          import torch

          print(torch.Tensor([1,2,3,4,5,6]))
          print(torch.Tensor(2,3))
          t = torch.Tensor([[1,2,3],[4,5,6]])
          print(t)
          print(t.size())
          t.shape
          torch.Tensor(t.size())

          torch.Tensor與torch.tensor的區(qū)別:

          1. torch.Tensor是torch.empty 和 torch.tensor 之間的混合。傳入數(shù)據(jù)時(shí),torch.Tensor使用全局默認(rèn)dtype(FloatTensor),而torch.tensor是從數(shù)據(jù)中推斷數(shù)據(jù)類(lèi)型

          2. torch.tensor(1)返回的是固定值1;torch.Tensor返回的是大小為1的張量

            import torch
            t1=torch.Tensor(1)
            t2=torch.tensor(1)
            print("t1的值{},t1的數(shù)據(jù)類(lèi)型{}".format(t1,t1.type()))
            print("t2的值{},t2的數(shù)據(jù)類(lèi)型{}".format(t2,t2.type()))
            # 輸出
            t1的值tensor([0.]),t1的數(shù)據(jù)類(lèi)型torch.FloatTensor
            t2的值1,t2的數(shù)據(jù)類(lèi)型torch.LongTensor
            import torch
            print(torch.eye(2,2))
            print(torch.zeros(2,3))
            print(torch.linspace(1,10,4))
            print(torch.rand(2,3))
            print(torch.randn(2,3))
            print(torch.zeros_like(torch.rand(2,3)))
            #輸出結(jié)果
            tensor([[1., 0.],
            [0., 1.]])
            tensor([[0., 0., 0.],
            [0., 0., 0.]])
            tensor([ 1., 4., 7., 10.])
            tensor([[0.5942, 0.1468, 0.3175],
            [0.2744, 0.9218, 0.7266]])
            tensor([[ 1.0187, -0.2809, 1.0421],
            [-0.1697, -0.0604, -1.6645]])
            tensor([[0., 0., 0.],
            [0., 0., 0.]])

            2.4.3 修改Tensor形狀

          常用的tensor修改形狀的函數(shù)

          * size()                         計(jì)算張量屬性值,與shape等價(jià)
          * numel(input) 計(jì)算張量的元素個(gè)數(shù)
          * view(*shape) 修改張量的shape,共享內(nèi)存,修改一個(gè)同時(shí)修改。
          * resize() 類(lèi)似于view
          * item 返回標(biāo)量
          * unsqueeze 在指定維度增加一個(gè)1
          * squeeze 在指定維度壓縮一個(gè)1
          import torch

          x = torch.randn(2,3)

          print(x.size())

          print("維度:" ,x.dim())

          print("這里把矩陣變?yōu)?x2的矩陣:",x.view(3,2))

          print("這里把x展為1維向量:", x.view(-1))

          y=x.view(-1)
          z=torch.unsqueeze(y,0)
          print("沒(méi)增加維度前:",y," 的維度",y.size())
          print("增加一個(gè)維度:", z)
          print("z的維度:", z.size())
          print("z的個(gè)數(shù):", z.numel())
          # 輸出結(jié)果
          torch.Size([2, 3])
          維度:2
          這里把矩陣變?yōu)?x2的矩陣:tensor([[ 1.3014, 1.0249],
          [ 0.8903, -0.4908],
          [-0.3393, 0.7987]])
          這里把x展為1維向量:tensor([ 1.3014, 1.0249, 0.8903, -0.4908, -0.3393, 0.7987])
          沒(méi)增加維度前:tensor([ 1.3014, 1.0249, 0.8903, -0.4908, -0.3393, 0.7987]) 的維度 torch.Size([6])
          增加一個(gè)維度: tensor([[ 1.3014, 1.0249, 0.8903, -0.4908, -0.3393, 0.7987]])
          z的維度:torch.Size([1, 6])
          z的個(gè)數(shù):6

          torch.view 與 torch.reshape 的異同

          1. reshape()可以由torch.reshape()或者torch.Tensor.reshape()調(diào)用;而view()只可以由torch.Tensor.view()調(diào)用

          2. 新的size必須與原來(lái)的size與stride兼容,否則,在view之前必須調(diào)用contiguous()方法

          3. 同樣返回?cái)?shù)據(jù)量相同的但形狀不同的Tensor,若滿(mǎn)足view條件,則不會(huì)copy,若不滿(mǎn)足,就copy

          4. 只想重塑,就使用torch.reshape,如果考慮內(nèi)存并共享,就用torch.view

            2.4.4 索引操作

          常用選擇操作的函數(shù)

          * index_select(input,dim,index)   在指定維度上選擇列或者行
          * nonzero(input) 獲取非0元素的下標(biāo)
          * masked_select(input,mask) 使用二元值進(jìn)行選擇
          * gather(input,dim,index) 指定維度選擇數(shù)據(jù),輸出形狀與index一致
          * scatter_(input,dim,index,src) gather的反操作,根據(jù)指定索引補(bǔ)充數(shù)據(jù)
          import torch# 設(shè)置一個(gè)隨機(jī)種子torch.manual_seed(100)# print(torch.manual_seed(100))x = torch.randn(2,3)
          print(x)# 索引獲取第一行所有數(shù)據(jù)x[0,:]
          print(x[0,:])# 獲取最后一列的數(shù)據(jù)x[:,-1]
          print(x[:,-1])# 生成是否大于0的張量mask=x>0print(mask)# 獲取大于0的值torch.masked_select(x,mask)
          print(torch.masked_select(x,mask))# 獲取非0下標(biāo),即行、列的索引torch.nonzero(mask)
          print(torch.nonzero(mask))# 獲取指定索引對(duì)應(yīng)的值,輸出根據(jù)以下規(guī)則得到# out[i][j] = input[index[i][j][j]] # 如果 if dim == 0# out[i][j] = input[i][index[i][j]] # 如果 if dim == 1index = torch.LongTensor([[0,1,1]])
          print(index)
          torch.gather(x,0,index)
          index=torch.LongTensor([[0,1,1],[1,1,1]])
          a = torch.gather(x,1,index)
          print("a: ",a)# 把a(bǔ)的值返回到2x3的0矩陣中z = torch.zeros(2,3)
          z.scatter_(1,index,a)# 輸出結(jié)果tensor([[ 0.3607, -0.2859, -0.3938],
          [ 0.2429, -1.3833, -2.3134]])
          tensor([ 0.3607, -0.2859, -0.3938])
          tensor([-0.3938, -2.3134])
          tensor([[ True, False, False],
          [ True, False, False]])
          tensor([0.3607, 0.2429])
          tensor([[0, 0],
          [1, 0]])
          tensor([[0, 1, 1]])
          a: tensor([[ 0.3607, -0.2859, -0.2859],
          [-1.3833, -1.3833, -1.3833]])
          Out[25]:
          tensor([[ 0.3607, -0.2859, 0.0000],
          [ 0.0000, -1.3833, 0.0000]])

          2.4.5 廣播機(jī)制

          import torch
          import numpy as np
          A = np.arange(0,40,10).reshape(4,1)
          B = np.arange(0,3)
          A1 = torch.from_numpy(A) #形狀4x1
          B1 = torch.from_numpy(B) #形狀3
          #自動(dòng)廣播
          C=A1+B1
          #也可以根據(jù)廣播機(jī)制手動(dòng)配置
          # B1要與A1看齊,變成(1,3)
          B2=B1.unsqueeze(0)
          A2=A1.expand(4,3)
          B3=B2.expand(4,3)
          C1=A2+B3
          print("A1:",A1)
          print("B1:",B1)
          print("C:",C)
          print("B2:",B2)
          print("A2:",A2)
          print("B3:",B3)
          print("C1:",C1)
          # 輸出結(jié)果
          A1: tensor([[ 0],
          [10],
          [20],
          [30]], dtype=torch.int32)
          B1: tensor([0, 1, 2], dtype=torch.int32)
          C: tensor([[ 0, 1, 2],
          [10, 11, 12],
          [20, 21, 22],
          [30, 31, 32]], dtype=torch.int32)
          B2: tensor([[0, 1, 2]], dtype=torch.int32)
          A2: tensor([[ 0, 0, 0],
          [10, 10, 10],
          [20, 20, 20],
          [30, 30, 30]], dtype=torch.int32)
          B3: tensor([[0, 1, 2],
          [0, 1, 2],
          [0, 1, 2],
          [0, 1, 2]], dtype=torch.int32)
          C1: tensor([[ 0, 1, 2],
          [10, 11, 12],
          [20, 21, 22],
          [30, 31, 32]], dtype=torch.int32)

          2.4.6 逐元素操作

          常見(jiàn)的逐元素操作

          * abs   add                                     絕對(duì)值,加法
          * addcdiv(t,v,t1,t2) t1與t2按元素除后,乘v加t
          * addcmul(t,v,t1,t2) t1與t2按元素乘后,乘v加t
          * ceil floor 向上取整;向下取整
          * clamp(t, min , max) 將張量元素限制在指定區(qū)間
          * exp log pow 指數(shù),對(duì)數(shù),冪
          * mul( 或 * ) neg 逐元素乘法,取反
          * sigmoid tanh softmax 激活函數(shù)
          * sign sqrt 取符號(hào),開(kāi)根號(hào)
          import torch
          t = torch.randn(1,3)
          t1 = torch.randn(3,1)
          t2 = torch.randn(1,3)
          # t+0.1*(t1/t2)
          a = torch.addcdiv(t, 0.1, t1, t2)
          #計(jì)算sigmoid
          b = torch.sigmoid(t)
          # 將t限制在【0,1】之間
          c = torch.clamp(t,0,1)
          #t+2進(jìn)行直接運(yùn)算
          t.add_(2)
          print("t: ",t)
          print("t1: ",t1)
          print("t2: ",t2)
          print("a: ",a)
          print("b: ",b)
          print("c: ",c)
          # 結(jié)果
          t: tensor([[1.7266, 2.0815, 3.4672]])
          t1: tensor([[0.2309],
          [0.3393],
          [1.3639]])
          t2: tensor([[-0.5414, -1.4628, -0.4191]])
          a: tensor([[-0.3161, 0.0657, 1.4121],
          [-0.3361, 0.0583, 1.3863],
          [-0.5254, -0.0117, 1.1418]])
          b: tensor([[0.4321, 0.5204, 0.8126]])
          c: tensor([[0.0000, 0.0815, 1.0000]])

          2.4.7 歸并操作

          常用的歸并操作

          * cumprod(t,axis)        在指定維度上對(duì)t進(jìn)行累積
          * cumsum 對(duì)指定維度進(jìn)行累加
          * dist(a,b,p=2) 返回a,b之間的p階范數(shù)
          * mean ; median 平均值,中位數(shù)
          * std var 標(biāo)準(zhǔn)差 方差
          * norm(t,p=2) 返回t的p階范數(shù)
          * prod(t) sum(t) 返回所有元素的積,和
          import torch
          a=torch.linspace(0,10,6)
          #使用view變?yōu)?x3矩陣
          a=a.view((2,3))
          print("a: ",a)
          # 沿著y軸方向累加,dim=0
          b=a.sum(dim=0)
          print("b: ",b)
          # 沿著y軸方向累加,dim=0,并保留含1的維度
          b=a.sum(dim=0,keepdim=True)
          print("b: ",b)
          # 結(jié)果
          a: tensor([[ 0., 2., 4.],
          [ 6., 8., 10.]])
          b: tensor([ 6., 10., 14.])
          b: tensor([[ 6., 10., 14.]])

          2.4.8 比較操作

          常用的比較函數(shù)

          * eq                                    是否相等
          * equal 是否相同的shape和值
          * ge / le / gt / lt 大于、小于、大于等于、小于等于
          * max / min (t,axis) 返回最值,指定axis返回下標(biāo)
          * topk(t,k,axis) 在指定維度上取最高的k個(gè)值
          import torch
          x=torch.linspace(0,10,6).view(2,3)
          print(torch.max(x))
          print(torch.max(x,dim=0))
          print(torch.topk(x,1,dim=0))
          # 結(jié)果
          tensor([[ 0., 2., 4.],
          [ 6., 8., 10.]])
          tensor(10.)
          torch.return_types.max(
          values=tensor([ 6., 8., 10.]),
          indices=tensor([1, 1, 1]))
          torch.return_types.topk(
          values=tensor([[ 6., 8., 10.]]),
          indices=tensor([[1, 1, 1]]))

          2.4.9 矩陣操作

          常用的矩陣函數(shù)

          * dot(t1,t2)                                                       計(jì)算內(nèi)積
          * mm(mat1,mat2) bmm(batch1,batch2) 計(jì)算矩陣乘積,3D矩陣
          * mv(t1,v1) 計(jì)算矩陣與向量乘法
          * t 轉(zhuǎn)置
          * svd(t) 計(jì)算SVD
          import torch
          a=torch.tensor([2,3])
          b=torch.tensor([3,4])
          print(torch.dot(a,b))
          x=torch.randint(10,(2,3))
          print(x)
          y=torch.randint(6,(3,4))
          print(y)
          print(torch.mm(x,y))
          x=torch.randint(10,(2,2,3))
          print(x)
          y=torch.randint(6,(2,3,4))
          print(y)
          print(torch.bmm(x,y))
          #結(jié)果
          tensor(18)
          tensor([[1, 1, 1],
          [3, 1, 9]])
          tensor([[1, 4, 4, 5],
          [1, 5, 2, 4],
          [2, 0, 3, 3]])
          tensor([[ 4, 9, 9, 12],
          [22, 17, 41, 46]])
          tensor([[[0, 9, 3],
          [7, 1, 4]],
          [[9, 6, 3],
          [2, 0, 1]]])
          tensor([[[0, 5, 1, 3],
          [2, 4, 3, 1],
          [5, 2, 1, 1]],
          [[4, 3, 0, 0],
          [4, 5, 0, 4],
          [0, 0, 3, 3]]])
          tensor([[[33, 42, 30, 12],
          [22, 47, 14, 26]],
          [[60, 57, 9, 33],
          [ 8, 6, 3, 3]]])

          2.4.10 PyTorch與Numpy比較

          PyTorch與Numpy函數(shù)對(duì)照表


          np.ndarry([3.2,4.3],dtype=np.float16)torch.tensor([3.2,4.3], dtype=torch.float16

          x.copy()x.clone()

          np.dottorch.mm

          x.ndimx.dim

          x.sizex.nelement()

          x.reshapex.reshape,x.view

          x.flattenx.view(-1)

          np.floor(x)torch.floor(x), x.floor()

          np.lessx.lt

          np.random.seedtorch.manual_seed

          2.5 Tensor與Autograd

          2.5.1 自動(dòng)求導(dǎo)的要點(diǎn)

          1. 創(chuàng)建葉子節(jié)點(diǎn)的Tensor,使用requires_grad指定是否需要對(duì)其進(jìn)行操作

          2. 可以利用requiresgrad()方法修改Tensor的requires_grad屬性??梢哉{(diào)用  .detach()或者 with torch.no_grad()

          3. 自動(dòng)賦予grad_fn屬性,表示梯度函數(shù)。

          4. 執(zhí)行backward()函數(shù)后,保存到grad屬性中了。計(jì)算完成,非葉子節(jié)點(diǎn)梯度會(huì)自動(dòng)釋放

          5. backward()函數(shù)接收參數(shù),維度相同。

          6. 反向傳播的中間緩存會(huì)被清空,如果需要多次反向傳播,需指定backward中的retain_graph=True  多次反向傳播時(shí),梯度累加

          7. 非葉子節(jié)點(diǎn)的梯度backward 調(diào)用后即被清空

          8. 用 torch.no_grad()包裹代碼塊形式阻止autograd去追蹤那些標(biāo)記為.requesgrad=True的張量歷史記錄

            2.5.2 計(jì)算圖

          表達(dá)式z=wx+b

          可以寫(xiě)成:y=wx    z=y+b

          x,w,b為變量;y,z是計(jì)算得到的變量,不是葉子節(jié)點(diǎn)

          根據(jù)鏈?zhǔn)椒▌t計(jì)算的

          • z對(duì)x求導(dǎo)為w

          • z對(duì)w求導(dǎo)為x

          • z對(duì)b求導(dǎo)為1

            2.5.3 標(biāo)量反向傳播

          主要步驟如下:

          1. 定義葉子節(jié)點(diǎn)及算子節(jié)點(diǎn)

          2. 查看葉子節(jié)點(diǎn)、非葉子節(jié)點(diǎn)的其他屬性

          3. 自動(dòng)求導(dǎo),實(shí)現(xiàn)梯度方向傳播,也就是梯度的反向傳播

          分步進(jìn)行展示

          (1)定義葉子節(jié)點(diǎn)及算子節(jié)點(diǎn)

          import torch
          # 定義輸入張量x
          x=torch.Tensor([2])
          # 初始化權(quán)重參數(shù)w,偏移量b,并設(shè)置require_grad屬性為T(mén)rue
          w=torch.randn(1,requires_grad=True)
          b=torch.randn(1,requires_grad=True)
          # 實(shí)現(xiàn)前向傳播
          y=torch.mul(w,x) # 等價(jià)于w*x
          z=torch.add(y,b) # 等價(jià)于y+b
          # 查看x,w,b葉子節(jié)點(diǎn)的requires_grad屬性
          print("x,w,b葉子節(jié)點(diǎn)的requires_grad屬性分別為:{},{},{}".format(x.requires_grad,w.requires_grad,b.requires_grad))

          運(yùn)行結(jié)果:

          x,w,b葉子節(jié)點(diǎn)的requires_grad屬性分別為:False,True,True

          (2)查看葉子節(jié)點(diǎn)、非葉子節(jié)點(diǎn)的其他屬性

          # 查看非葉子節(jié)點(diǎn)的requires_grad屬性
          print("y, z的requires_grad屬性分別為:{},{}".format(y.requires_grad,z.requires_grad))
          # 查看各節(jié)點(diǎn)是否為葉子節(jié)點(diǎn)
          print("x, w, b, y, z是否為葉子節(jié)點(diǎn):{},{},{},{},{}".format(x.is_leaf,w.is_leaf,b.is_leaf,y.is_leaf,z.is_leaf))
          # 查看葉子節(jié)點(diǎn)的grad_fn屬性
          print("x, w, b的 grad_fn屬性:{},{},{}".format(x.grad_fn,w.grad_fn,b.grad_fn))
          # 查看非葉子節(jié)點(diǎn)的grad_fn屬性
          print("y, z是否為葉子節(jié)點(diǎn):{},{}".format(y.grad_fn,z.grad_fn))

          運(yùn)行結(jié)果:

          y, z的requires_grad屬性分別為:True,True
          x, w, b, y, z是否為葉子節(jié)點(diǎn):True,True,True,F(xiàn)alse,F(xiàn)alse
          x, w, b的 grad_fn屬性:None,None,None
          y, z是否為葉子節(jié)點(diǎn):<MulBackward0 object at 0x00000295C920E948>,<AddBackward0 object at 0x00000295C920EA48>

          (3)自動(dòng)求導(dǎo),實(shí)現(xiàn)梯度方向傳播,也就是梯度的反向傳播

          # 基于張量z進(jìn)行求導(dǎo),執(zhí)行backward后計(jì)算圖會(huì)自動(dòng)清空
          z.backward()
          # 如果需要多次使用backward,需要修改參數(shù)為retain_graph=True,此時(shí)梯度累加
          # z.backward(retain_graph=True)
          # 查看葉子節(jié)點(diǎn)的梯度,x是葉子節(jié)點(diǎn)但是無(wú)需求導(dǎo),故梯度為None
          print("參數(shù)w, b,x的梯度分別為:{},{},{}".format(w.grad,b.grad,x.grad))
          # 非葉子節(jié)點(diǎn)的梯度,執(zhí)行backward后會(huì)自動(dòng)清空
          print("非葉子節(jié)點(diǎn)y, z的梯度分別為:{},{}".format(y.grad,z.grad))

          運(yùn)行結(jié)果:

          參數(shù)w, b,x的梯度分別為:tensor([2.]),tensor([1.]),None
          非葉子節(jié)點(diǎn)y, z的梯度分別為:None,None

          2.5.4 非標(biāo)量的反向傳播

          張量對(duì)張量的求導(dǎo)轉(zhuǎn)換成標(biāo)量對(duì)張量的求導(dǎo)

          backward函數(shù)的格式

          backward(gradient=None, retain_graph=None, create_graph=False)

          舉例:

          # (1)定義葉子節(jié)點(diǎn)及計(jì)算節(jié)點(diǎn)
          import torch
          # 定義葉子節(jié)點(diǎn)張量x,形狀為1x2
          x = torch.tensor([[2, 3]], dtype=torch.float, requires_grad=True)
          # 初始化雅可比矩陣
          J = torch.zeros(2,2)
          # 初始化目標(biāo)張量,形狀1x2
          y = torch.zeros(1,2)
          # 定義y與x之間的映射關(guān)系
          # y1=x1**2 + 3*x2, y2=x2**2 + 2*x1
          y[0, 0] = x[0, 0]**2+3*x[0, 1]
          y[0, 1] = x[0, 1]**2+2*x[0, 0]
          # 首先讓v=(1,0)得到y(tǒng)1對(duì)x的梯度
          # 然后讓v=(0,1)得到y(tǒng)2對(duì)x的梯度
          # 需要重復(fù)使用backward(),所以設(shè)置參數(shù)retain_graph=True
          # 生成y1對(duì)x的梯度
          y.backward(torch.Tensor([[1,0]]),retain_graph=True)
          J[0]=x.grad
          # 梯度是累加的,所以需要對(duì)x的梯度清零
          x.grad = torch.zeros_like(x.grad)
          # 生成y2對(duì)x的梯度
          y.backward(torch.Tensor([[0,1]]))
          J[1]=x.grad
          # 顯示雅克比矩陣的值
          print(J)

          運(yùn)行結(jié)果:

          tensor([[4., 3.],
          [2., 6.]])

          2.6 使用Numpy實(shí)現(xiàn)機(jī)器學(xué)習(xí)

          給出一個(gè)數(shù)組x,基于表達(dá)式y(tǒng)=3x^2+2,加上一些噪聲數(shù)據(jù)到達(dá)另一組數(shù)據(jù)y

          構(gòu)建一個(gè)機(jī)器學(xué)學(xué)模型,學(xué)習(xí)y=wx^2+b中的2個(gè)參數(shù),w和b,利用x,y數(shù)據(jù)為訓(xùn)練數(shù)據(jù)

          ## (1)導(dǎo)入所需要的庫(kù)
          # -*- coding : utf-8 -*-
          import numpy as np
          %matplotlib inline
          from matplotlib import pyplot as plt
          ## (2)生成隨機(jī)數(shù)據(jù)x及目標(biāo)y
          # 設(shè)置隨機(jī)種子,生成同一份數(shù)據(jù),方便多種方法比較
          np.random.seed(100)
          x = np.linspace(-1,1,100).reshape(100,1)
          y = 3*np.power(x,2) + 2 + 0.2*np.random.rand(x.size).reshape(100,1)
          ## (3)查看x,y數(shù)據(jù)分布情況
          plt.scatter(x,y)
          plt.show()
          ## (4)初始化權(quán)重參數(shù)
          w1 = np.random.rand(1,1)
          b1 = np.random.rand(1,1)
          ## (5)訓(xùn)練模型
          lr =0.001 # 學(xué)習(xí)率
          for i in range(800):
          # 前向傳播
          y_pred = np.power(x,2)*w1+b1
          # 定義損失函數(shù)
          loss = 0.5 * (y_pred - y) **2
          loss = loss.sum
          # 計(jì)算梯度
          grad_w = np.sum((y_pred - y)*np.power(x,2))
          grad_b = np.sum(y_pred - y)
          # 使用梯度下降法,使得loss最小
          w1 -= lr * grad_w
          b1 -= lr * grad_b
          ## 可視化結(jié)果
          plt.plot(x, y_pred, 'r-', label='predict')
          plt.scatter(x,y,color='blue',marker='o',label='true')
          plt.xlim(-1,1)
          plt.ylim(2,6)
          plt.legend()
          plt.show()
          print(w1,b1)


                 


          2.7 使用Tensor及Autograd實(shí)現(xiàn)機(jī)器學(xué)習(xí)

          # (1) 導(dǎo)入所需要的庫(kù)
          import torch as t
          %matplotlib inline
          from matplotlib import pyplot as plt
          # (2)生成訓(xùn)練數(shù)據(jù),并可視化數(shù)據(jù)分布情況
          t.manual_seed(100)
          dtype=t.float
          # 生成x坐標(biāo)數(shù)據(jù),x為tensor,需要把x的形狀轉(zhuǎn)換為100x1
          x = t.unsqueeze(t.linspace(-1,1,100),dim=1)
          # 生成y坐標(biāo)數(shù)據(jù),y為tensor,形狀為100x1,加上一些噪聲
          y = 3*x.pow(2)+ 2 + 0.2*t.rand(x.size())

          # 畫(huà)圖,將tensor數(shù)據(jù)轉(zhuǎn)換為numpy數(shù)據(jù)
          plt.scatter(x.numpy(),y.numpy())
          plt.show()
          # (3)初始化權(quán)重
          # 隨機(jī)初始化參數(shù),w,b需要學(xué)習(xí),所以設(shè)定requires_grad=True
          w = t.randn(1,1,dtype=dtype,requires_grad=True)
          b = t.zeros(1,1,dtype=dtype,requires_grad=True)
          # (4)訓(xùn)練模型
          lr = 0.001 # 學(xué)習(xí)率
          for ii in range(800):
          # 前向傳播,定義損失函數(shù)
          y_pred = x.pow(2).mm(w) + b
          loss = 0.5 * (y_pred - y) **2
          loss = loss.sum()

          # 自動(dòng)計(jì)算梯度
          loss.backward()

          # 手動(dòng)更新參數(shù),使用torch.no_grad(),使上下文切斷自動(dòng)求導(dǎo)計(jì)算
          with t.no_grad():
          w -= lr * w.grad
          b -= lr * b.grad

          # 梯度清零
          w.grad.zero_()
          b.grad.zero_()

          # (5)可視化訓(xùn)練結(jié)果
          plt.plot(x.numpy(), y_pred.detach().numpy(), 'r-', label='predict')
          plt.scatter(x.numpy(),y.numpy(),color='blue',marker='o',label='true')
          plt.xlim(-1,1)
          plt.ylim(2,6)
          plt.legend()
          plt.show()
          print(w,b)


                 


          下載1:OpenCV-Contrib擴(kuò)展模塊中文版教程
          在「小白學(xué)視覺(jué)」公眾號(hào)后臺(tái)回復(fù):擴(kuò)展模塊中文教程,即可下載全網(wǎng)第一份OpenCV擴(kuò)展模塊教程中文版,涵蓋擴(kuò)展模塊安裝、SFM算法、立體視覺(jué)、目標(biāo)跟蹤、生物視覺(jué)、超分辨率處理等二十多章內(nèi)容。

          下載2:Python視覺(jué)實(shí)戰(zhàn)項(xiàng)目52講
          小白學(xué)視覺(jué)公眾號(hào)后臺(tái)回復(fù):Python視覺(jué)實(shí)戰(zhàn)項(xiàng)目,即可下載包括圖像分割、口罩檢測(cè)、車(chē)道線(xiàn)檢測(cè)、車(chē)輛計(jì)數(shù)、添加眼線(xiàn)、車(chē)牌識(shí)別、字符識(shí)別、情緒檢測(cè)、文本內(nèi)容提取、面部識(shí)別等31個(gè)視覺(jué)實(shí)戰(zhàn)項(xiàng)目,助力快速學(xué)校計(jì)算機(jī)視覺(jué)。

          下載3:OpenCV實(shí)戰(zhàn)項(xiàng)目20講
          小白學(xué)視覺(jué)公眾號(hào)后臺(tái)回復(fù):OpenCV實(shí)戰(zhàn)項(xiàng)目20講,即可下載含有20個(gè)基于OpenCV實(shí)現(xiàn)20個(gè)實(shí)戰(zhàn)項(xiàng)目,實(shí)現(xiàn)OpenCV學(xué)習(xí)進(jìn)階。

          交流群


          歡迎加入公眾號(hào)讀者群一起和同行交流,目前有SLAM、三維視覺(jué)、傳感器、自動(dòng)駕駛、計(jì)算攝影、檢測(cè)、分割、識(shí)別、醫(yī)學(xué)影像、GAN、算法競(jìng)賽等微信群(以后會(huì)逐漸細(xì)分),請(qǐng)掃描下面微信號(hào)加群,備注:”昵稱(chēng)+學(xué)校/公司+研究方向“,例如:”張三 + 上海交大 + 視覺(jué)SLAM“。請(qǐng)按照格式備注,否則不予通過(guò)。添加成功后會(huì)根據(jù)研究方向邀請(qǐng)進(jìn)入相關(guān)微信群。請(qǐng)勿在群內(nèi)發(fā)送廣告,否則會(huì)請(qǐng)出群,謝謝理解~


          瀏覽 69
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          評(píng)論
          圖片
          表情
          推薦
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  堕落人妻5果冻传媒 | 在线的成人网站 | 中文字幕1页 | 亚洲视频在线观看高清无码 | 尾随搭讪酒店前台思妍 |