pytorch I don't know how to define multiple models

Question:

I want to use two different models in pytorch. Therefore, I executed the following code, but I cannot successfully run the second model. How can I do this?

class Model(nn.Module):
    def __init__(self):
        super(Model, self).__init__()
        self.linear1 = nn.Linear(2, 64)
        self.linear2 = nn.Linear(64, 3)

    def forward(self, x):   
        x = self.linear1(x)
        x = torch.sigmoid(x)  
        x = self.linear2(x)

        return x
                
class Model2(nn.Module):
    def __init__(self):
        super(Model, self).__init__()
        self.linear1 = nn.Linear(2, 64)
        self.linear2 = nn.Linear(64, 1)

    def forward(self, x):   
        x = self.linear1(x)
        x = torch.sigmoid(x)  
        x = self.linear2(x)

        return x
                
net = Model()
net2 = Model2()

erorr

TypeError Traceback (most recent call last)

/tmp/ipykernel_477/2280223066.py in <module>
     26 
     27 net = Model()
---> 28 net2 = Model2()

/tmp/ipykernel_477/2280223066.py in __init__(self)
     14 class Model2(nn.Module):
     15     def __init__(self):
---> 16         super(Model, self).__init__()
     17         self.linear1 = nn.Linear(2, 64)
     18         self.linear2 = nn.Linear(64, 1)

TypeError: super(type, obj): obj must be an instance or subtype of type

Asked By: asdfe

||

Answers:

It’s because you are calling super(Model, self).init() in line 16 instead of super(Model2, self).init(). You have to change the name of the model to match the name of the current class every time. Line 3 runs because Model is actually the name of the class in that case.

Answered By: James Lee