Normally we use pytorch like the following code.
class MyNet(nn.Module):
def __init__(self):
super().__init__()
self.layer1 = nn.Conv2d(3, 32, 3)
self.layer2 = nn.Conv2d(32, 64, 3)
self.layer3 = nn.Conv2d(64, 2, 3)
def forward(self, x):
out = self.layer1(x)
out = self.layer2(out)
out = self.layer3(out)
return out
My question is:
Do I have to instantiate layers in init() function? Are the following 2 code segments also okay?
Code_1
class MyNet(nn.Module):
def __init__(self):
super().__init__()
self.layer1 = nn.Conv2d(3, 32, 3)
def forward(self, x):
out = self.layer1(x)
self.layer2 = nn.Conv2d(32, 64, 3)
self.layer3 = nn.Conv2d(64, 2, 3)
out = self.layer2(out)
out = self.layer3(out)
return out
Code_2
layer2 = nn.Conv2d(32, 64, 3)
layer3 = nn.Conv2d(64, 2, 3)
class MyNet(nn.Module):
def __init__(self):
super().__init__()
self.layer1 = nn.Conv2d(3, 32, 3)
def forward(self, x):
out = self.layer1(x)
out = layer2(out)
out = layer3(out)
return out