pytorch常用函數(shù)定義是怎樣的
Admin 2022-08-12 群英技術(shù)資訊 885 次瀏覽
關(guān)于“pytorch常用函數(shù)定義是怎樣的”的知識有一些人不是很理解,對此小編給大家總結(jié)了相關(guān)內(nèi)容,具有一定的參考借鑒價值,而且易于學(xué)習(xí)與理解,希望能對大家有所幫助,有這個方面學(xué)習(xí)需要的朋友就繼續(xù)往下看吧。import torch
from torch import nn
class MyLinear(nn.Module):
def __init__(self, in_features, out_features):
super().__init__()
self.weight = nn.Parameter(torch.randn(in_features, out_features))
self.bias = nn.Parameter(torch.randn(out_features))
def forward(self, input):
return (input @ self.weight) + self.bias
一個有序的容器,神經(jīng)網(wǎng)絡(luò)模塊將按照在傳入構(gòu)造器的順序依次被添加到計算圖中執(zhí)行,同時以神經(jīng)網(wǎng)絡(luò)模塊為元素的有序字典也可以作為傳入?yún)?shù)。Sequential適用于快速驗證結(jié)果,簡單易讀,但使用Sequential也會使得模型定義喪失靈活性,比如需要在模型中間加入一個外部輸入時就不適合用Sequential的方式實現(xiàn)。
net = nn.Sequential(
('fc1',MyLinear(4, 3)),
('act',nn.ReLU()),
('fc2',MyLinear(3, 1))
)
ModuleList 接收一個子模塊(或?qū)?,需屬于nn.Module類)的列表作為輸入,然后也可以類似List那樣進(jìn)行append和extend操作。同時,子模塊或?qū)拥臋?quán)重也會自動添加到網(wǎng)絡(luò)中來。
net = nn.ModuleList([nn.Linear(784, 256), nn.ReLU()]) net.append(nn.Linear(256, 10)) # # 類似List的append操作 print(net[-1]) # 類似List的索引訪問 print(net)
Linear(in_features=256, out_features=10, bias=True) ModuleList( (0): Linear(in_features=784, out_features=256, bias=True) (1): ReLU() (2): Linear(in_features=256, out_features=10, bias=True) )
要特別注意的是,nn.ModuleList 并沒有定義一個網(wǎng)絡(luò),它只是將不同的模塊儲存在一起。
ModuleList中元素的先后順序并不代表其在網(wǎng)絡(luò)中的真實位置順序,需要經(jīng)過forward函數(shù)指定各個層的先后順序后才算完成了模型的定義。
具體實現(xiàn)時用for循環(huán)即可完成:
class model(nn.Module):
def __init__(self, ...):
super().__init__()
self.modulelist = ...
...
def forward(self, x):
for layer in self.modulelist:
x = layer(x)
return x
ModuleDict和ModuleList的作用類似,只是ModuleDict能夠更方便地為神經(jīng)網(wǎng)絡(luò)的層添加名稱。
net = nn.ModuleDict({
'linear': nn.Linear(784, 256),
'act': nn.ReLU(),
})
net['output'] = nn.Linear(256, 10) # 添加
print(net['linear']) # 訪問
print(net.output)
print(net)
Linear(in_features=784, out_features=256, bias=True) Linear(in_features=256, out_features=10, bias=True) ModuleDict( (act): ReLU() (linear): Linear(in_features=784, out_features=256, bias=True) (output): Linear(in_features=256, out_features=10, bias=True) )
ModuleList和ModuleDict在某個完全相同的層需要重復(fù)出現(xiàn)多次時,非常方便實現(xiàn),可以”一行頂多行“;當(dāng)我們需要之前層的信息的時候,比如 ResNets 中的殘差計算,當(dāng)前層的結(jié)果需要和之前層中的結(jié)果進(jìn)行融合,一般使用 ModuleList/ModuleDict 比較方便。
展平輸入的張量: 28x28 -> 784
input = torch.randn(32, 1, 5, 5)
m = nn.Sequential(
nn.Conv2d(1, 32, 5, 1, 1),
nn.Flatten()
)
output = m(input)
output.size()
有了上面的一些常用方法,我們可以修改現(xiàn)有的一些開源模型,這里通過介紹修改模型層、添加額外輸入的案例來幫助我們更好地理解。
以pytorch官方視覺庫torchvision預(yù)定義好的模型ResNet50為例,探索如何修改模型的某一層或者某幾層。
我們先看看模型的定義:
import torchvision.models as models net = models.resnet50() print(net)
ResNet(
(conv1): Conv2d(3, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False)
(bn1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(relu): ReLU(inplace=True)
(maxpool): MaxPool2d(kernel_size=3, stride=2, padding=1, dilation=1, ceil_mode=False)
(layer1): Sequential(
(0): Bottleneck(
(conv1): Conv2d(64, 64, kernel_size=(1, 1), stride=(1, 1), bias=False)
..............
(avgpool): AdaptiveAvgPool2d(output_size=(1, 1))
(fc): Linear(in_features=2048, out_features=1000, bias=True)
)
為了適配ImageNet,fc層輸出是1000,若需要用這個resnet模型去做一個10分類的問題,就應(yīng)該修改模型的fc層,將其輸出節(jié)點數(shù)替換為10。另外,我們覺得一層全連接層可能太少了,想再加一層。
可以做如下修改:
from collections import OrderedDict
classifier = nn.Sequential(OrderedDict([('fc1', nn.Linear(2048, 128)),
('relu1', nn.ReLU()),
('dropout1',nn.Dropout(0.5)),
('fc2', nn.Linear(128, 10)),
('output', nn.Softmax(dim=1))
]))
net.fc = classifier # 將模型(net)最后名稱為“fc”的層替換成了我們自己定義的名稱為“classifier”的結(jié)構(gòu)
有時候在模型訓(xùn)練中,除了已有模型的輸入之外,還需要輸入額外的信息。比如在CNN網(wǎng)絡(luò)中,我們除了輸入圖像,還需要同時輸入圖像對應(yīng)的其他信息,這時候就需要在已有的CNN網(wǎng)絡(luò)中添加額外的輸入變量。
基本思路是:將原模型添加輸入位置前的部分作為一個整體,同時在forward中定義好原模型不變的部分、添加的輸入和后續(xù)層之間的連接關(guān)系,從而完成模型的修改。
我們以torchvision的resnet50模型為基礎(chǔ),任務(wù)還是10分類任務(wù)。不同點在于,我們希望利用已有的模型結(jié)構(gòu),在倒數(shù)第二層增加一個額外的輸入變量add_variable來輔助預(yù)測。
具體實現(xiàn)如下:
class Model(nn.Module):
def __init__(self, net):
super(Model, self).__init__()
self.net = net
self.relu = nn.ReLU()
self.dropout = nn.Dropout(0.5)
self.fc_add = nn.Linear(1001, 10, bias=True)
self.output = nn.Softmax(dim=1)
def forward(self, x, add_variable):
x = self.net(x)
# add_variable (batch_size, )->(batch_size, 1)
x = torch.cat((self.dropout(self.relu(x)), add_variable.unsqueeze(1)),1)
x = self.fc_add(x)
x = self.output(x)
return x
修改好的模型結(jié)構(gòu)進(jìn)行實例化,就可以使用
import torchvision.models as models net = models.resnet50() model = Model(net).cuda() # 使用時輸入兩個inputs outputs = model(inputs, add_var)
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:[email protected]進(jìn)行舉報,并提供相關(guān)證據(jù),查實之后,將立刻刪除涉嫌侵權(quán)內(nèi)容。
猜你喜歡
這篇文章主要介紹了解決Django?cors跨域問題,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
這篇文章主要為大家介紹了Caffe卷積神經(jīng)網(wǎng)絡(luò)數(shù)據(jù)層及參數(shù)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
本文給大家分享的是python中排序的方法,簡單介紹了冒泡排序、選擇排序、插入排序、快速排序、希爾排序、歸并排序。有這方面學(xué)習(xí)需要的朋友可以參考參考。
這篇文章主要介紹了Python函數(shù)使用的相關(guān)練習(xí)題分享,文章基于python函數(shù)內(nèi)容展開其相關(guān)例題,具有一定的參考價值,需要的小伙伴可以參考一下
ord()?函數(shù)是?chr()?函數(shù)(對于?8?位的?ASCII?字符串)的配對函數(shù),它以一個字符串(Unicode?字符)作為參數(shù),返回對應(yīng)的?ASCII?數(shù)值,或者?Unicode?數(shù)值,這篇文章主要介紹了python?中內(nèi)置函數(shù)ord()返回字符串的ASCII數(shù)值,需要的朋友可以參考下
推薦內(nèi)容
成為群英會員,開啟智能安全云計算之旅
立即注冊關(guān)注或聯(lián)系群英網(wǎng)絡(luò)
7x24小時售前:400-678-4567
7x24小時售后:0668-2555666
24小時QQ客服
群英微信公眾號
CNNIC域名投訴舉報處理平臺
服務(wù)電話:010-58813000
服務(wù)郵箱:[email protected]
投訴與建議:0668-2555555
Copyright ? QY Network Company Ltd. All Rights Reserved. 2003-2020 群英 版權(quán)所有
增值電信經(jīng)營許可證 : B1.B2-20140078 ICP核準(zhǔn)(ICP備案)粵ICP備09006778號 域名注冊商資質(zhì) 粵 D3.1-20240008