Containers(容器):
class torch.nn.Module
所有网络的基类。
你的模型也应该继承这个类。
Modules也可以包含其它Modules,允许使用树结构嵌入他们。你可以将子模块赋值给模型属性。
import torch.nn as nnimport torch.nn.functional as Fclass Model(nn.Module): def init(self): super(Model, self).init() self.conv1 = nn.Conv2d(1, 20, 5)# submodule: Conv2d self.conv2 = nn.Conv2d(20, 20, 5) def forward(self, x): x = F.relu(self.conv1(x)) return F.relu(self.conv2(x))
通过上面方式赋值的submodule会被注册。当调用 .cuda() 的时候,submodule的参数也会转换为cuda Tensor。
add_module(name, module)
将一个 child module 添加到当前 modle。 被添加的module可以通过 name属性来获取。 例:
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) 和上面这个增加module的方式等价model = Model()print(model.conv)
输出:
Conv2d(10, 20, kernel_size=(4, 4), stride=(1, 1))
children()
Returns an iterator over immediate children modules. 返回当前模型 子模块的迭代器。
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.add_module("conv1", nn.Conv2d(20 ,10, 4))model = Model()for sub_module in model.children(): print(sub_module)
Conv2d(10, 20, kernel_size=(4, 4), stride=(1, 1))Conv2d(20, 10, kernel_size=(4, 4), stride=(1, 1))
cpu(device_id=None)
将所有的模型参数(parameters)和buffers复制到CPU
NOTE:官方文档用的move,但我觉着copy更合理。
cuda(device_id=None)
将所有的模型参数(parameters)和buffers赋值GPU
参数说明:
- device_id (int, optional) – 如果指定的话,所有的模型参数都会复制到指定的设备上。
double()
将parameters和buffers的数据类型转换成double。
eval()
将模型设置成evaluation模式
仅仅当模型中有Dropout和BatchNorm是才会有影响。
float()
将parameters和buffers的数据类型转换成float。
forward(* input)
定义了每次执行的 计算步骤。 在所有的子类中都需要重写这个函数。
half()
将parameters和buffers的数据类型转换成half。
load_state_dict(state_dict)
将state_dict中的parameters和buffers复制到此module和它的后代中。state_dict中的key必须和 model.state_dict()返回的key一致。 NOTE:用来加载模型参数。
参数说明:
- state_dict (dict) – 保存parameters和persistent buffers的字典。
modules()
返回一个包含 当前模型 所有模块的迭代器。
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.add_module("conv1", nn.Conv2d(20 ,10, 4))model = Model()for module in model.modules(): print(module)
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))
可以看出,modules()返回的iterator不止包含 子模块。这是和children()的不同。
NOTE: 重复的模块只被返回一次(children()也是)。 在下面的例子中, submodule 只会被返回一次:
import torch.nn as nnclass Model(nn.Module): def init(self): super(Model, self).init() submodule = nn.Conv2d(10, 20, 4) self.add_module("conv", submodule) self.add_module("conv1", submodule)model = Model()for module in model.modules(): print(module)
Model ( (conv): Conv2d(10, 20, kernel_size=(4, 4), stride=(1, 1)) (conv1): Conv2d(10, 20, kernel_size=(4, 4), stride=(1, 1)))Conv2d(10, 20, kernel_size=(4, 4), stride=(1, 1))
named_children()
返回 包含 模型当前子模块 的迭代器,yield 模块名字和模块本身。
例子:
for name, module in model.named_children(): if name in ['conv4', 'conv5']: print(module)
named_modules(memo=None, prefix='')[source]
返回包含网络中所有模块的迭代器, yielding 模块名和模块本身。
注意:
重复的模块只被返回一次(children()也是)。 在下面的例子中, submodule 只会被返回一次。
parameters(memo=None)
返回一个 包含模型所有参数 的迭代器。
一般用来当作optimizer的参数。
例子:
for param in model.parameters(): print(type(param.data), param.size())<class 'torch.FloatTensor'> (20L,)<class 'torch.FloatTensor'> (20L, 1L, 5L, 5L)
register_backward_hook(hook)
在module上注册一个bachward hook。
每次计算module的inputs的梯度的时候,这个hook会被调用。hook应该拥有下面的signature。
hook(module, grad_input, grad_output) -> Variable or None
如果module有多个输入输出的话,那么grad_input grad_output将会是个tuple。 hook不应该修改它的arguments,但是它可以选择性的返回关于输入的梯度,这个返回的梯度在后续的计算中会替代grad_input。
这个函数返回一个 句柄(handle)。它有一个方法 handle.remove(),可以用这个方法将hook从module移除。
register_buffer(name, tensor)
给module添加一个persistent buffer。
persistent buffer通常被用在这么一种情况:我们需要保存一个状态,但是这个状态不能看作成为模型参数。 例如:, BatchNorm’s running_mean 不是一个 parameter, 但是它也是需要保存的状态之一。
Buffers可以通过注册时候的name获取。
NOTE:我们可以用 buffer 保存 moving average
例子:
self.register_buffer('running_mean', torch.zeros(num_features))self.running_mean
register_forward_hook(hook)
在module上注册一个forward hook。 每次调用forward()计算输出的时候,这个hook就会被调用。它应该拥有以下签名:
hook(module, input, output) -> None
hook不应该修改 input和output的值。 这个函数返回一个 句柄(handle)。它有一个方法 handle.remove(),可以用这个方法将hook从module移除。
register_parameter(name, param)
向module添加 parameter
parameter可以通过注册时候的name获取。
state_dict(destination=None, prefix='')[source]
返回一个字典,保存着module的所有状态(state)。
parameters和persistent buffers都会包含在字典中,字典的key就是parameter和buffer的 names。
例子:
import torchfrom torch.autograd import Variableimport torch.nn as nnclass Model(nn.Module): def init(self): super(Model, self).init() self.conv2 = nn.Linear(1, 2) self.vari = Variable(torch.rand([1])) self.par = nn.Parameter(torch.rand([1])) self.register_buffer("buffer", torch.randn([2,3]))model = Model()print(model.state_dict().keys())
odict_keys(['par', 'buffer', 'conv2.weight', 'conv2.bias'])
train(mode=True)
将module设置为 training mode。
仅仅当模型中有Dropout和BatchNorm是才会有影响。
zero_grad()
将module中的所有模型参数的梯度设置为0.
class torch.nn.Sequential(* args)
一个时序容器。Modules 会以他们传入的顺序被添加到容器中。当然,也可以传入一个OrderedDict。
为了更容易的理解如何使用Sequential, 下面给出了一个例子:
Example of using Sequentialmodel = nn.Sequential( nn.Conv2d(1,20,5), nn.ReLU(), nn.Conv2d(20,64,5), nn.ReLU() )# Example of using Sequential with OrderedDictmodel = nn.Sequential(OrderedDict([ ('conv1', nn.Conv2d(1,20,5)), ('relu1', nn.ReLU()), ('conv2', nn.Conv2d(20,64,5)), ('relu2', nn.ReLU()) ]))
class torch.nn.ModuleList(modules=None)[source]
将submodules保存在一个list中。
ModuleList可以像一般的Python list一样被索引。而且ModuleList中包含的modules已经被正确的注册,对所有的module method可见。
参数说明:
- modules (list, optional) – 将要被添加到MuduleList中的 modules 列表
例子:
class 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 ints for i, l in enumerate(self.linears): x = self.linearsi // 2 + l(x) return x
append(module)[source]
等价于 list 的 append()
参数说明:
- module (nn.Module) – 要 append 的module
extend(modules)[source]
等价于 list 的 extend() 方法
参数说明:
- modules (list) – list of modules to append
class torch.nn.ParameterList(parameters=None)
将submodules保存在一个list中。
ParameterList可以像一般的Python list一样被索引。而且ParameterList中包含的parameters已经被正确的注册,对所有的module method可见。
参数说明:
- modules (list, optional) – a list of nn.Parameter
例子:
class 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 ints for i, p in enumerate(self.params): x = self.params[i // 2].mm(x) + p.mm(x) return x
append(parameter)[source]
等价于python list 的 append 方法。
参数说明:
- parameter (nn.Parameter) – parameter to append
extend(parameters)[source]
等价于python list 的 extend 方法。
参数说明:
- parameters (list) – list of parameters to append