43_pytorch nn.Module,模型的创建,构建子模块,API介绍,Sequential(序号),ModuleList,ParameterList,案例等(学习笔记)
1.40.PyTorch nn.Module
1.40.1.模型的創(chuàng)建
1.40.2.構(gòu)建子模塊
1.40.3.nn.Module API介紹
1.40.3.1.核心功能
1.40.3.2.查看模塊
1.40.3.3.類型轉(zhuǎn)換
1.40.3.4.設(shè)置功能
1.40.3.5.注冊(cè)功能
1.40.3.6.Sequential(序號(hào))
1.40.3.7.ModuleList模型列表
1.40.3.8.ParameterList參數(shù)列表
1.40.4.nn.Module 其它API介紹
1.40.5.nn.Module介紹
1.40.6.nn.Module提供的便利
1.40.7.參考博文
1.40.PyTorch nn.Module
1.40.1.模型的創(chuàng)建
模型創(chuàng)建的步驟:
模型構(gòu)建的兩個(gè)要素:
1.構(gòu)建子模塊(構(gòu)建網(wǎng)絡(luò)層)
2.拼接子模塊(拼接網(wǎng)絡(luò)層)
1.40.2.構(gòu)建子模塊
以之前上傳的紙幣二分類代碼為例,對(duì)模型的構(gòu)建進(jìn)行講解。
在70行設(shè)置斷點(diǎn),查看如何構(gòu)建LeNet網(wǎng)絡(luò)。
net = LeNet(classes=2) net.initialize_weights()step into進(jìn)入
class LeNet(nn.Module):def __init__(self, classes):super(LeNet, self).__init__()self.conv1 = nn.Conv2d(3, 6, 5)self.conv2 = nn.Conv2d(6, 16, 5)self.fc1 = nn.Linear(16 * 5 * 5, 120)self.fc2 = nn.Linear(120, 84)self.fc3 = nn.Linear(84, classes)進(jìn)入到LeNet的__init__函數(shù)構(gòu)建子模塊,創(chuàng)建了兩個(gè)卷積層與三個(gè)全連接層。運(yùn)行完最后一個(gè)子模塊self.fc3就會(huì)跳出返回,模型的初始化便完成了。
net = LeNet(classes=2) net.initialize_weights()1.40.3.nn.Module API介紹
這是所有網(wǎng)絡(luò)的基類,Modules也可以包括其他Modules, 運(yùn)行使用樹結(jié)構(gòu)來嵌入,可以將子模塊給模型賦予屬性,從下列看出,self.conv1, self.conv2是模型的子模型。
1.40.3.1.核心功能
?add_module(name,module) 將子模塊加入當(dāng)前的模塊中,被添加的模塊可以name來獲取
# -*- coding: UTF-8 -*-import torch.nn as nnclass Model(nn.Module):def __init__(self):super(Model, self).__init__()self.add_module("conv", nn.Conv2d(10, 20, 4))# self.conv = nn.Conv2d(10, 20, 4) 和上面這個(gè)增加module的方式等價(jià)model = Model() print(model.conv) """ 輸出結(jié)果: Conv2d(10, 20, kernel_size=(4, 4), stride=(1, 1)) """?forward(*input) 每次運(yùn)行時(shí)都會(huì)執(zhí)行的步驟,所有自定義的module都要重寫這個(gè)函數(shù)
?state_dict(destination=None) 返回一個(gè)字典,保存module的所有狀態(tài)
?load_state_dict(state_dict): 用來加載模型參數(shù)
1.40.3.2.查看模塊
?parameters(memo=None): 返回一個(gè) 包含模型所有參數(shù) 的迭代器。一般用作optimizer參數(shù)
?children(): 返回當(dāng)前模型 子模塊的迭代器。
?name_children(): 返回 包含 模型當(dāng)前子模塊 的迭代器,yield 模塊名字和模塊本身。
?modules(): 返回一個(gè)包含 當(dāng)前模型 所有模塊的迭代器。
?named_modules(): 返回包含網(wǎng)絡(luò)中所有模塊的迭代器, yielding 模塊名和模塊本身。
輸出結(jié)果:
Model((conv): Conv2d(10, 20, kernel_size=(4, 4), stride=(1, 1))(conv1): Conv2d(20, 10, kernel_size=(4, 4), stride=(1, 1)) ) Conv2d(10, 20, kernel_size=(4, 4), stride=(1, 1)) Conv2d(20, 10, kernel_size=(4, 4), stride=(1, 1)) --------------------------------------------------- Conv2d(20, 10, kernel_size=(4, 4), stride=(1, 1)) Conv2d(20, 10, kernel_size=(4, 4), stride=(1, 1))1.40.3.3.類型轉(zhuǎn)換
?cpu(device_id=None):將所有的模型參數(shù)(parameters)和buffers復(fù)制到CPU
?cuda(device_id=None):將所有的模型參數(shù)(parameters)和buffers賦值GPU
?double() :將parameters和buffers的數(shù)據(jù)類型轉(zhuǎn)換成double
?float(): 將parameters和buffers的數(shù)據(jù)類型轉(zhuǎn)換成float。
?half():將parameters和buffers的數(shù)據(jù)類型轉(zhuǎn)換成half。
1.40.3.4.設(shè)置功能
?train(mode=True):將module設(shè)置為 training mode,只影響dropout和batchNorm
?eval(): 將模型設(shè)置成evaluation模式,只影響dropout和batchNorm
?zero_grad(): 將module中的所有模型的梯度設(shè)置為0
1.40.3.5.注冊(cè)功能
register_parameter(name, param):向module添加 parameter,可以通過name獲取
register_forward_hook(hook): 在module上注冊(cè)一個(gè)forward hook。每次調(diào)用forward()計(jì)算輸出的時(shí)候,這個(gè)hook就會(huì)被調(diào)用。
register_backward_hook(hook): 在module上注冊(cè)一個(gè)bachward hook。每次計(jì)算module的inputs的梯度的時(shí)候,這個(gè)hook會(huì)被調(diào)用
register_buffer(name, tensor): 給module添加一個(gè)persistent buffer,通常用來保存一個(gè)不需要看成模型參數(shù)的狀態(tài)。
1.40.3.6.Sequential(序號(hào))
class torch.nn.Sequential(*args)
當(dāng)你使用Sequential時(shí),Modules會(huì)以傳入的順序來添加layer到容器中,也可以傳入一個(gè)OrderedDict,下面是個(gè)簡單的例子
import torch.nn as nn# Example of using Sequential model = nn.Sequential(nn.Conv2d(1,20,5),nn.ReLU(),nn.Conv2d(20,64,5),nn.ReLU()) # Example of using Sequential with OrderedDict model = nn.Sequential(OrderedDict([('conv1', nn.Conv2d(1,20,5)),('relu1', nn.ReLU()),('conv2', nn.Conv2d(20,64,5)),('relu2', nn.ReLU())]))1.40.3.7.ModuleList模型列表
class torch.nn.ModuleList(modules=None)將你的字模型保存在一個(gè)list中,可以像python list一樣被索引,moduleList中包含的modules已經(jīng)被正確的注冊(cè),對(duì)所有module method可見
參數(shù)說明:
module(list, optional) – 將要被添加到ModuleList中的modules列表
方法:
append(module): 添加模型,等價(jià)于list的append
extend(modules): 等價(jià)于list的extend
例子:
import torch.nn as nnclass MyModule(nn.Module):def __init__(self):super(MyModule, self).__init__()self.linears = nn.ModuleList([nn.Linear(10, 10) for i in range(10)])def forward(self, x):# ModuleList can act as an iterable, or be indexed using intsfor i, l in enumerate(self.linears):x = self.linears[i // 2](x) + l(x)return x1.40.3.8.ParameterList參數(shù)列表
class torch.nn.ParameterList(parameters=None)
將submodules 保存在一個(gè)list中。ParameterList 可以像一般的Python list一樣被索引。而且 ParameterList 中包含的 parameters 已經(jīng)被正確的注冊(cè),對(duì)所有的 module method可見。
參數(shù)說明:
modules (list, optional) – a list of nn.Parameter
方法:
append(module): 添加模型,等價(jià)于list的append
extend(modules): 等價(jià)于list的extend
例子:
import torch import torch.nn as nnclass MyModule(nn.Module):def __init__(self):super(MyModule, self).__init__()self.params = nn.ParameterList([nn.Parameter(torch.randn(10, 10)) for i in range(10)])def forward(self, x):# ModuleList can act as an iterable, or be indexed using intsfor i, p in enumerate(self.params):x = self.params[i // 2].mm(x) + p.mm(x)卷積層:
class torch.nn.Conv1d() class torch.nn.Conv2d()1.40.4.nn.Module 其它API介紹
nn.Module在torch.nn下
nn.module通過八個(gè)有序字典來管理模型
?parameters: 存儲(chǔ)管理nn.Parameter類,如權(quán)值、偏置
?modules: 存儲(chǔ)管理nn.Module類,如卷積層,池化層
?buffers: 存儲(chǔ)管理緩沖屬性,如BN層中的running_mean
?***_hooks: 存儲(chǔ)管理鉤子函數(shù)
1.40.5.nn.Module介紹
nn.Module是所有網(wǎng)絡(luò)層的父類,pytorch提供的線性層、卷積層也是集成自這個(gè)類,包括:
- nn.Linear
- nn.BatchNorm2d
- nn.Conv2d
我們自己定義的網(wǎng)絡(luò)層時(shí)也要繼承這個(gè)類(nn.Module),并實(shí)現(xiàn)前饋函數(shù)forward。
1.40.6.nn.Module提供的便利
?nn.Module提供了大量的現(xiàn)成的計(jì)算模塊,比如以下:
Linear、Relu、Sigmoid、Con2d、ConvTransposed2d、Dropout等。
?nn.Sequential,模塊將按照構(gòu)造函數(shù)中傳遞的順序添加到模塊中。另外,也可以傳入一個(gè)有序模塊。
官網(wǎng)示例:
# Example of using Sequential model = nn.Sequential(nn.Conv2d(1, 20, 5),nn.ReLU(),nn.Conv2d(20, 64, 5),nn.ReLU())# Example of using Sequential with OrderedDict model = nn.Sequential(OrderedDict([('conv1', nn.Conv2d(1,20,5)),('relu1', nn.ReLU()),('conv2', nn.Conv2d(20,64,5)),('relu2', nn.ReLU())]))可以使用torch.nn.Sequential快速搭建神經(jīng)網(wǎng)絡(luò),為了方便比較,我們先用普通方法搭建一個(gè)神經(jīng)網(wǎng)絡(luò)。
class Net(torch.nn.Module):def __init__(self, n_feature, n_hidden, n_output):super(Net, self).__init__()self.hidden = torch.nn.Linear(n_feature, n_hidden)self.predict = torch.nn.Linear(n_hidden, n_output)def forward(self, x):x = F.relu(self.hidden(x))x = self.predict(x)return xnet1 = Net(1, 10, 1)上面class繼承了一個(gè)torch中的神經(jīng)網(wǎng)絡(luò)結(jié)構(gòu), 然后對(duì)其進(jìn)行了修改;接下來我們來使用torch.nn.Sequential來快速搭建一個(gè)神經(jīng)網(wǎng)絡(luò)。
net2 = torch.nn.Sequential(torch.nn.Linear(1, 10),torch.nn.ReLU(),torch.nn.Linear(10, 1) )(3)net.parameters():構(gòu)建好神經(jīng)網(wǎng)絡(luò)后,網(wǎng)絡(luò)的參數(shù)都保存在parameters()函數(shù)當(dāng)中。
import torch import torch.nn as nnnet = nn.Sequential(nn.Linear(4, 2), nn.Linear(3,2)) # 網(wǎng)絡(luò)的參數(shù)都保存在parameters()函數(shù)中 print(list(net.parameters())[0].shape) print(list(net.parameters())[0].shape) print(list(net.parameters())[0].shape) print(list(net.parameters())[0].shape)結(jié)果:
torch.Size([2, 4]) torch.Size([2]) torch.Size([2, 3]) torch.Size([2])(4)modules:modules: all nodes,children: direct children
import torch import torch.nn as nnclass BasicNet(nn.Module):def __init__(self):super(BasicNet, self).__init__()self.net = nn.Linear(4, 3)def forward(self, x):return self.net(x)class Net(nn.Module):def __init__(self):super(Net, self).__init__()self.net = nn.Sequential(BasicNet(), nn.ReLU(), nn.Linear(3, 2))def forward(self, x):return self.net(x)(5)更換數(shù)據(jù)存放位置:cpu --> cuda
device = torch.device('cuda') net = Net() net.to(device)(6)save and load: 保存和加載模型數(shù)據(jù)
device = torch.device('cuda') net = Net() net.to(device)net.load_state_dict(torch.load('ckpt.mdl'))# train...torch.save(net.state_dict(), 'ckpt.mdl')(7)train/test: 訓(xùn)練和測(cè)試階段的切換
device = torch.device('cuda') net = Net() net.to(device)# train net.train()# test net.eval()(8)Implement own layer
class Flatten(nn.Module):def __init__(self):super(Flatten, self).__init__()def forward(self, input):return input.view(input.size(0), -1)class TestNet(nn.Module):def __init__(self):super(TestNet, self).__init__()self.net = nn.Sequential(nn.Conv2d(1, 16, stride=1, padding=1),nn.MaxPool2d(2, 2),Flatten(),nn.Linear(1 * 14 * 14, 10))def forward(self, x):return self.net(x)1.40.7.參考博文
https://zhuanlan.zhihu.com/p/69526677
http://ddrv.cn/a/586531
總結(jié)
以上是生活随笔為你收集整理的43_pytorch nn.Module,模型的创建,构建子模块,API介绍,Sequential(序号),ModuleList,ParameterList,案例等(学习笔记)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。