Search code examples
pythondeep-learningpytorch

Unusual Error When Using nn.Sequential in Model Class in PyTorch


Just creating a simple neural network here to try out nn.Sequential, for some reason i'm getting this error

Here is the code:

# Create Model

class Net(nn.Module):
    def __init__(self):
        super().__init__()

        # Define Network

        self.stack = nn.Sequential(
            nn.Linear(in_features=3, out_features=8),

            nn.ReLU(),

            nn.Linear(in_features=8, out_features=8),

            nn.ReLU(),

            nn.Linear(in_features=8, out_features=1),

            nn.Sigmoid(),
        )

    def forward(self, x):
        # Define Forward Pass

        return self.stack(x)


# Instance Of Model

model = Net(X_train[:5])

Error Here:

TypeError                                 Traceback (most recent call last)
<ipython-input-32-f947c74336f3> in <cell line: 31>()
     29 # Instance Of Model
     30 
---> 31 model = Net(X_train[0])

TypeError: Net.__init__() takes 1 positional argument but 2 were given

Here I tried to test if my model worked by inputting the first 5 values of my training data, instead of getting 5 numbers between 0 and 1, ex. [0.1, 0.2, 0.43, 0.67, .78] I get the error above.


Solution

  • You are passing your input to the model constructor. You need to instantiate the model before calling the forward method.

    model = Net()
    out = model(torch.randn(8, 3))