濮阳杆衣贸易有限公司

主頁 > 知識庫 > pytorch教程之網(wǎng)絡(luò)的構(gòu)建流程筆記

pytorch教程之網(wǎng)絡(luò)的構(gòu)建流程筆記

熱門標(biāo)簽:佛山防封外呼系統(tǒng)收費(fèi) 南昌辦理400電話怎么安裝 鄭州智能外呼系統(tǒng)運(yùn)營商 不錯的400電話辦理 湛江電銷防封卡 電話機(jī)器人適用業(yè)務(wù) 徐州天音防封電銷卡 哈爾濱外呼系統(tǒng)代理商 獲客智能電銷機(jī)器人

參考網(wǎng)址

構(gòu)建網(wǎng)絡(luò)

我們可以通過torch.nn包來構(gòu)建網(wǎng)絡(luò),現(xiàn)在你已經(jīng)看過了autograd,nn在autograd的基礎(chǔ)上定義模型和求微分。一個nn.Module包括很多層,forward方法返回output。

一個典型的訓(xùn)練過程包括這么幾步:
1.定義一個網(wǎng)絡(luò)結(jié)構(gòu)包含一些可訓(xùn)練的額參數(shù)
2.為數(shù)據(jù)集制定輸入iterata
3.通過網(wǎng)絡(luò)計(jì)算Output
4.計(jì)算loss
5.反向傳播計(jì)算梯度
6.更新權(quán)值

weight = weight - learning_rate * gradient

定義一個網(wǎng)絡(luò)

讓我們來定義一個網(wǎng)絡(luò)

import torch
import torch as nn
import torch.nn.functional as F
class Net(nn.Module):
    def __init__(self):
        super(Net,self).__init__(
        #1 input image channel ,6output image channel ,5*5convolytion kernel
        self.conv1 = nn.Conv2d(1,6,5)
        self.conv2 = nn.Conv2d(6,16,5)
        # an affine operation:y = Wx+b
        self.fc1 = nn.Linear(16*5*5,120)
        self.fc2 = nn.Linear(120,84)
        self.fc3 = nn.Linear(84,10)
    def forward(self,x):
        #max pooling
        x.F.max_pool2d(F.relu(self.conv1(x)),(2,2))
        #2   =    (2,2)
        x.F.max_pool2d(F.relu(self.con2(x)),2)
        x = x.view(-1,self.num_flat_features(x))
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3(x)
        return  x
    def num_flat_features(self,x):
        size = x.size()[1:]
        num_feature = 1
        for s in size:
            num_features *=s
        return num_features

net = Net()
print(net)      

out

Net(
  (conv1): Conv2d(1, 6, kernel_size=(5, 5), stride=(1, 1))
  (conv2): Conv2d(6, 16, kernel_size=(5, 5), stride=(1, 1))
  (fc1): Linear(in_features=400, out_features=120, bias=True)
  (fc2): Linear(in_features=120, out_features=84, bias=True)
  (fc3): Linear(in_features=84, out_features=10, bias=True)
)

我們只需定義forward和backward函數(shù),會自動求導(dǎo)通過你定義的函數(shù),你可以使用所有的Tensor操作在forward函數(shù)中。
我們使用net.parameters()函數(shù)返回可學(xué)習(xí)的參數(shù)

params = list(net.parameters())
print(len(params))
print(params[0].size())  # conv1's .weight

out

10
torch.Size([6, 1, 5, 5])

讓我們試試32*32的輸入節(jié)點(diǎn),因?yàn)閘enet網(wǎng)絡(luò)的輸入應(yīng)該是32*32,為了在MNIST數(shù)據(jù)集上使用lenet我們需要將圖片reshpe成32*32

input = torch.randn(1,1,32,32)
oyt = net(input)
print(out)

out

tensor([[-0.1346,  0.0581, -0.0396, -0.1136, -0.1128,  0.0180, -0.1226,
         -0.0419, -0.1150,  0.0278]])

零化導(dǎo)數(shù)buffers所有的參數(shù)都會隨機(jī)求導(dǎo)

net.zero_grad()
out.backward(torch.randn(1,10))

torch.nn只支持mini-batch,而不是單個的樣本
例如,nn.Conv2d輸入是一個4維tensors

nSamples * nChannels * Height * Width

如果你只有單個的樣本,使用input.unsqueeze(0)增加一個假的batch維度
在后處理之前,讓我們看看都學(xué)過什么類

Recap:

torch.Tensor - A multi-dimensional array with support for autograd operations like backward(). Also holds the gradient w.r.t. the tensor.
nn.Module - Neural network module. Convenient way of encapsulating parameters, with helpers for moving them to GPU, exporting, loading, etc.
nn.Parameter - A kind of Tensor, that is automatically registered as a parameter when assigned as an attribute to a Module.
autograd.Function - Implements forward and backward definitions of an autograd operation. Every Tensor operation, creates at least a single Function node, that connects to functions that created a Tensor and encodes its history.

目前,我們學(xué)習(xí)了:
1.定義一個神經(jīng)網(wǎng)絡(luò)
2.處理輸入和使用后向傳播
我們還需要學(xué)習(xí):
1.計(jì)算loss
2.更新權(quán)值

loss Function

Loss function接受(output traget)對作為輸入,計(jì)算一個反映到目標(biāo)距離的值。
在nn這個包里面有很多l(xiāng)oss function ,最簡單的是nn.MSELoss,就是那輸入與輸出的均方誤差。

舉個例子

output = net(input)
target = torch.arrange(1,11)
target = target.view(1m-1)
criterion = nn.MSELoss()
loss = criterion(output,target)
print(loss)

Out:

tensor(39.1076)

Backprop

為了反向傳播我們需要做的僅僅是進(jìn)行l(wèi)oss.backward(),我們需要清除現(xiàn)有的梯度

更新權(quán)值

最簡單常用的更新權(quán)值的方法就是SGD(Stochastic Gradient Descent )

weight = weight - learning_rata * gradiernt

我們可以通過簡單的代碼實(shí)現(xiàn)上面的公式:

learning_rata = 0.01
for f in net.parameters():
    f.data.sib_(f.grad.data *  learining_rata)

但是我們也可以使用不同的更新規(guī)則,像是 SGD, Nesterov-SGD, Adam, RMSProp, etc.
為了使用這些,我們需要torch.optim包,使用起來也很簡單。

import torch.optim as optim 
#creat you optimizer
optimizer = optim.SGD(net.parameters(),lr = 0.01)
#in your training loop:
optimizer.zero_grad()
output = net(input)
loss = criterion(output,target)
loss.backward()
optimizer.step()

注意gradient必須清零
現(xiàn)在我們調(diào)用loss.backward(),并且看看con1的bias的前后差別

ner.zero_grad()
print('conv1.bias.grad before backward')
loss.backward()
print('conv1.bias.grad after backward')
piint(net.conv1.bias.grad)

out

conv1.bias.grad before backward
tensor([ 0.,  0.,  0.,  0.,  0.,  0.])
conv1.bias.grad after backward
tensor([ 0.1178, -0.0404, -0.0810,  0.0363, -0.0631,  0.1423])

現(xiàn)在,我們看到了如何使用loss function
重要
torch包含很多的loss function和其他包,其余的文檔可以看這里
http://pytorch.org/docs/nn

以上就是pytorch教程之網(wǎng)絡(luò)的構(gòu)建流程筆記的詳細(xì)內(nèi)容,更多關(guān)于pytorch教程的資料請關(guān)注腳本之家其它相關(guān)文章!

您可能感興趣的文章:
  • pytorch構(gòu)建網(wǎng)絡(luò)模型的4種方法
  • PyTorch的深度學(xué)習(xí)入門教程之構(gòu)建神經(jīng)網(wǎng)絡(luò)
  • PyTorch如何搭建一個簡單的網(wǎng)絡(luò)
  • 關(guān)于pytorch中全連接神經(jīng)網(wǎng)絡(luò)搭建兩種模式詳解
  • Pytorch 神經(jīng)網(wǎng)絡(luò)—自定義數(shù)據(jù)集上實(shí)現(xiàn)教程
  • pytorch快速搭建神經(jīng)網(wǎng)絡(luò)_Sequential操作

標(biāo)簽:廣西 懷化 吉安 蘭州 紹興 蕪湖 呂梁 安康

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《pytorch教程之網(wǎng)絡(luò)的構(gòu)建流程筆記》,本文關(guān)鍵詞  pytorch,教程,之,網(wǎng)絡(luò),的,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 下面列出與本文章《pytorch教程之網(wǎng)絡(luò)的構(gòu)建流程筆記》相關(guān)的同類信息!
  • 本頁收集關(guān)于pytorch教程之網(wǎng)絡(luò)的構(gòu)建流程筆記的相關(guān)信息資訊供網(wǎng)民參考!
  • 推薦文章
    阳泉市| 宁远县| 泸溪县| 峨边| 从化市| 湖南省| 吴江市| 南皮县| 盐亭县| 宝山区| 阿巴嘎旗| 夹江县| 社会| 双辽市| 宁乡县| 油尖旺区| 翁源县| 图木舒克市| 黑水县| 汽车| 五家渠市| 潞城市| 天峻县| 贵南县| 抚松县| 西乌珠穆沁旗| 洮南市| 凌源市| 循化| 绵竹市| 巢湖市| 中方县| 松江区| 莎车县| 昭通市| 安阳县| 时尚| 固镇县| 柞水县| 军事| 华安县|