1、全连接
import torch as t
from torch.autograd import Variable as V
from torch import nn
class Linear(nn.Module):
def __init__(self, in_features, out_features):
super(Linear, self).__init__()
self.w = nn.Parameter(t.randn(in_features, out_features))
self.b = nn.Parameter(t.randn(out_features))
def forward(self, x):
x = x.mm(self.w)
return x + self.b.expand_as(x)
if __name__ == '__main__':
layer = Linear(4, 3)
input = V(t.randn(2, 4))
output = layer(input)
print(output)
out:
tensor([[ 0.1976, -2.5591, 1.7264],
[-1.3980, -1.9007, 2.3434]], grad_fn=<AddBackward0>)
(1) 自定义层Linear必须继承nn.Module, super(Linear, self).__init__()等价与nn.Module.__init__(self).
(2)在构造函数__init__中必须自己定义可学习的参数,并封装成Parameter, Parameter是一种特殊的Variable, 其默认是自动求导的。
(3)forward函数实现前向传播,
(4)无需写反向传播函数,因为前向传播都是对variable进行操作。
(5)Module中学习的参数可以通过named_parameters()或者parameters()返回迭代器,
2、前馈网络的两种简化方式--ModuleList和Sequential
(1)Sequential的三种写法
# 方式1 net1 = nn.Sequential() net1.add_module('conv', nn.Conv2d(3, 3, 3)) net1.add_module('batchnorm', nn.BatchNorm2d(3)) net1.add_module('activation_layer', nn.ReLU()) # 方式2 net2 = nn.Sequential( nn.Conv2d(3, 3, 3), nn.BatchNorm2d(3), nn.ReLU() ) # 方式3 from collections import OrderedDict net3 = nn.Sequential(OrderedDict([ ('conv', nn.Conv2d(3, 3, 3)), ('bn1', nn.BatchNorm2d(3)), ('relu1', nn.ReLU()) ]))
(2) ModuleList
nn.ModuleList([nn.Linear(3, 4), nn.ReLU(), nn.Linear(4, 2)])
3、 优化器
from torch import optim
4、nn.functional
与nn.Module会自动提取可学习的参数,而nn.functional 中的函数更像是纯函数。何时使用,如果模型有可学习的参数,最好用nn.Module,否则两者都可使用。
5、初始化策略
from torch.nn import init
如果不支持初始化,也可以自己进行初始化。