对于一些常见模块或者算子,在pytorch的nn模块和nn.functional中都有实现,例如nn.ReLU()和F.relu(),nn.Conv2d和F.conv2d()等。
对于这二者都可以实现指定目的,但是二者有什么区别呢?
对于nn中实现的,它继承了nn.Module类,它是一个类,如果要使用需要先实例化创建一个对象才可以调用,而nn.functional中实现的它是一个函数,可以直接当作函数进行调用。
a = torch.randn(3, 4)
print(a)
relu = nn.ReLU()
print(relu(a))
print(F.relu(a))
tensor([[-0.4196, 0.6217, -1.2835, 2.2796],
[-1.2185, 0.5819, -1.0084, -1.0939],
[-1.3235, -0.6229, 0.2442, -1.0914]])
tensor([[0.0000, 0.6217, 0.0000, 2.2796],
[0.0000, 0.5819, 0.0000, 0.0000],
[0.0000, 0.0000, 0.2442, 0.0000]])
tensor([[0.0000, 0.6217, 0.0000, 2.2796],
[0.0000, 0.5819, 0.0000, 0.0000],
[0.0000, 0.0000, 0.2442, 0.0000]])
对于定义模型类时,一般我们把带有学习参数的层放在构造函数中,而将不带有学习参数的层放在forward中进行实现,例如:
class Net(nn.Module):
def __init__(self):
super().__init__
self.conv = nn.Conv2d(1, 6, 5)
self.fc = nn.Linear(10, 2)
def forward(self, x):
x = self.conv(x)
x = F.max_pool2d(x)
x = self.fc(x)
x = F.dropout(x)
x = F.sigmoid(x)
return x