[nn.MaxPool2d(kernel_size,stride)与nn.functional.max_pool2d(t,kernel_size,stride)之间有什么区别?
我在模块中定义的第一个,在正向功能中定义的第二个?
谢谢
它们本质上是相同的。区别在于torch.nn.MaxPool2d
是显式的nn.Module
,它通过其自己的torch.nn.functional.max_pool2d()
方法调用forward()
。
您可以在此处查看torch.nn.MaxPool2d
的来源并亲自查看通话:https://pytorch.org/docs/stable/_modules/torch/nn/modules/pooling.html#MaxPool2d
转载如下:
def forward(self, input):
return F.max_pool2d(input, self.kernel_size, self.stride,
self.padding, self.dilation, self.ceil_mode,
self.return_indices)
为什么对同一任务有两种方法?我想它适合可能使用PyTorch的许多人的编码风格。一些人喜欢有状态的方法,而另一些人则更喜欢功能性的方法。
例如,具有torch.nn.MaxPool2d
意味着我们可以很容易地将其放入nn.Sequential
块中。
model = nn.Sequential(
nn.Conv2d(1,3,3),
nn.ReLU(),
nn.MaxPool2d((2, 2))
)