pythonsequentialpytorch

How do I write a PyTorch sequential model?


How do I write a sequential model in PyTorch, just like what we can do with Keras? I tried:

import torch
import torch.nn as nn

net = nn.Sequential()
net.add(nn.Linear(3, 4))
net.add(nn.Sigmoid())
net.add(nn.Linear(4, 1))
net.add(nn.Sigmoid())
net.float()

But I get the error:

AttributeError: 'Sequential' object has no attribute 'add'


Solution

  • As described by the correct answer, this is what it would look as a sequence of arguments:

    device = torch.device('cpu')
    if torch.cuda.is_available():
        device = torch.device('cuda')
     
    net = nn.Sequential(
          nn.Linear(3, 4),
          nn.Sigmoid(),
          nn.Linear(4, 1),
          nn.Sigmoid()
          ).to(device)
    
    print(net)
    
    Sequential(
      (0): Linear(in_features=3, out_features=4, bias=True)
      (1): Sigmoid()
      (2): Linear(in_features=4, out_features=1, bias=True)
      (3): Sigmoid()
      )