神经网络的典型处理如下所示:
class FeatureL2Norm(torch.nn.Module):
def init(self):
super(FeatureL2Norm, self).init()
def forward(self, feature):
epsilon = 1e-6
norm = torch.pow(torch.sum(torch.pow(feature,2),1)+epsilon,0.5).unsqueeze(1).expand_as(feature)
return torch.div(feature,norm)
class FeatureRegression(nn.Module):
def init(self, output_dim=6, use_cuda=True):
super(FeatureRegression, self).init()
self.conv = nn.Sequential(
nn.Conv2d(225, 128, kernel_size=7, padding=0),
nn.BatchNorm2d(128),
nn.ReLU(inplace=True),
nn.Conv2d(128, 64, kernel_size=5, padding=0),
nn.BatchNorm2d(64),
nn.ReLU(inplace=True),
)
self.linear = nn.Linear(64 * 5 * 5, output_dim)
if use_cuda:
self.conv.cuda()
self.linear.cuda()
def forward(self, x):
x = self.conv(x)
x = x.view(x.size(0), -1)
x = self.linear(x)
return x
由上例代码可以看到,不论是在定义网络结构还是定义网络层的操作(Op),均需要定义forward函数,下面看一下PyTorch官网对PyTorch的forward方法的描述:
那么调用forward方法的具体流程是什么样的呢?具体流程是这样的:
以一个Module为例:
def call(self, *input, **kwargs):
result = self.forward(*input, **kwargs)
for hook in self._forward_hooks.values():
#将注册的hook拿出来用
hook_result = hook(self, input, result)
…
return result
可以看到,当执行model(x)的时候,底层自动调用forward方法计算结果。具体示例如下:
class LeNet(nn.Module):
def init(self):
super(LeNet, self).init()
layer1 = nn.Sequential()
layer1.add_module('conv1', nn.Conv(1, 6, 3, padding=1))
layer1.add_moudle('pool1', nn.MaxPool2d(2, 2))
self.layer1 = layer1
layer2 = nn.Sequential()
layer2.add_module('conv2', nn.Conv(6, 16, 5))
layer2.add_moudle('pool2', nn.MaxPool2d(2, 2))
self.layer2 = layer2
layer3 = nn.Sequential()
layer3.add_module('fc1', nn.Linear(400, 120))
layer3.add_moudle('fc2', nn.Linear(120, 84))
layer3.add_moudle('fc3', nn.Linear(84, 10))
self.layer3 = layer3
def forward(self, x):
x = self.layer1(x)
x = self.layer2(x)
x = x.view(x.size(0), -1)
x = self.layer3(x)
return x
model = LeNet()
y = model(x)
如上则调用网络模型定义的forward方法。