nn.functional与nn作用基本相同的,一般来说用nn即可,但是有特殊情况,比如说参数共享,就需要用nn.functional 了。
例如:
有这么一种情况, 我想行为不同,但参数矩阵相同的两个 layer 共享参数, 该怎么做呢?如果行为相同那就简单了,直接多次调用 nn 里面的 Module 就好了。行为不同咋搞呢,比如说,我想让两个 dilation 不同但 kernel 相同的 Conv2d 层共享参数,此时 nn.functional 就派上用场了:
import torch
import torch.nn as nn
import torch.nn.functional as F
class Model(nn.Module):
def __init__(self):
super(Model, self).__init__()
self.weight = nn.Parameter(torch.Tensor(10,10,3,3))
def forward(self, x):
x_1 = F.conv2d(x, self.weight,dilation=1, padding=1)
x_2 = F.conv2d(x, self.weight,dilation=2, padding=2)
return x_1 + x_2
这个操作很像 MXNet 里共享参数的做法。 pytorch 的 nn 模块则可以大大方便相同行为层的参数共享。这个操作会有用的,尤其是做 detection 和 segmentation 的同学。