We use the Sequential model shortcut to quickly build a simple chain of layers in a neural network without writing extra code for each step.
Sequential model shortcut in PyTorch
import torch.nn as nn model = nn.Sequential( nn.Linear(input_size, hidden_size), nn.ReLU(), nn.Linear(hidden_size, output_size) )
The layers are passed as arguments inside nn.Sequential in the order they connect.
This shortcut works well for simple feed-forward networks.
model = nn.Sequential(
nn.Linear(10, 5),
nn.ReLU(),
nn.Linear(5, 2)
)model = nn.Sequential(
nn.Conv2d(1, 16, 3),
nn.ReLU(),
nn.Flatten(),
nn.Linear(16*26*26, 10)
)This code builds a simple Sequential model with two linear layers and ReLU in between. It runs a forward pass on sample data, calculates mean squared error loss, and performs one optimization step.
import torch import torch.nn as nn import torch.optim as optim # Create a simple Sequential model model = nn.Sequential( nn.Linear(4, 3), nn.ReLU(), nn.Linear(3, 2) ) # Sample input tensor (batch size 2, features 4) x = torch.tensor([[1.0, 2.0, 3.0, 4.0], [4.0, 3.0, 2.0, 1.0]]) # Forward pass output = model(x) # Print output print("Model output:") print(output) # Define dummy target and loss target = torch.tensor([[0.0, 1.0], [1.0, 0.0]]) criterion = nn.MSELoss() loss = criterion(output, target) print(f"Loss: {loss.item():.4f}") # Backward pass optimizer = optim.SGD(model.parameters(), lr=0.01) optimizer.zero_grad() loss.backward() optimizer.step()
Sequential models are easy to build but not flexible for complex architectures like multiple inputs or outputs.
Use nn.Sequential only when the data flows straight through layers.
Sequential shortcut helps build simple neural networks fast.
It stacks layers in order without extra code.
Good for beginners and quick experiments.
Practice
torch.nn.Sequential in PyTorch?Solution
Step 1: Understand what Sequential does
torch.nn.Sequentialstacks layers in order and handles the forward pass automatically.Step 2: Compare other options
Hyperparameter tuning, visualization, and replacing the loss function are not features of Sequential.Final Answer:
It allows stacking layers quickly without writing a forward method. -> Option AQuick Check:
Sequential = quick layer stacking [OK]
- Thinking Sequential tunes hyperparameters
- Confusing Sequential with visualization tools
- Assuming Sequential replaces loss functions
torch.nn.Sequential?Solution
Step 1: Check correct syntax for Sequential
nn.Sequentialtakes layers as separate arguments, separated by commas and enclosed in parentheses.Step 2: Identify syntax errors in other options
A misses commas between layers causing a syntax error, B uses a list which is invalid here, C uses curly braces which is wrong.Final Answer:
model = nn.Sequential(nn.Linear(10, 5), nn.ReLU(), nn.Linear(5, 2)) -> Option CQuick Check:
Sequential layers separated by commas in parentheses [OK]
- Using square brackets inside Sequential
- Using curly braces instead of parentheses
- Forgetting commas between layers
output?
import torch
import torch.nn as nn
model = nn.Sequential(
nn.Linear(4, 3),
nn.ReLU(),
nn.Linear(3, 2)
)
input = torch.randn(5, 4)
output = model(input)
print(output.shape)Solution
Step 1: Analyze input and first layer
Input shape is (5,4). First Linear layer maps 4 features to 3, so output shape becomes (5,3).Step 2: Analyze second Linear layer output
Second Linear layer maps 3 features to 2, so final output shape is (5,2).Final Answer:
torch.Size([5, 2]) -> Option DQuick Check:
Input batch 5, final features 2 [OK]
- Confusing input and output feature sizes
- Ignoring batch dimension
- Assuming ReLU changes shape
import torch.nn as nn
model = nn.Sequential(
nn.Linear(10, 5),
nn.ReLU,
nn.Linear(5, 2)
)Solution
Step 1: Check usage of nn.ReLU
nn.ReLU is a class; it must be called with parentheses to create an instance.Step 2: Verify other options
Linear layers sizes are compatible, Sequential supports activations, and subclassing is optional.Final Answer:
Missing parentheses after nn.ReLU causing a type error. -> Option AQuick Check:
Activation needs parentheses () [OK]
- Forgetting () after activation functions
- Thinking Sequential disallows activations
- Believing subclassing is mandatory
nn.Sequential model correctly implements this?Solution
Step 1: Check layer order and activations
Dropout should come after the first Linear layer and before ReLU to randomly drop activations during training.Step 2: Verify correct usage of activations and dropout
nn.Sequential(nn.Linear(8,4), nn.Dropout(0.5), nn.ReLU(), nn.Linear(4,1)) correctly uses nn.ReLU() with parentheses and places dropout before ReLU. Other options either miss parentheses or misplace dropout.Final Answer:
nn.Sequential(nn.Linear(8,4), nn.Dropout(0.5), nn.ReLU(), nn.Linear(4,1)) -> Option BQuick Check:
Dropout after Linear, before ReLU, with () [OK]
- Placing dropout after output layer
- Forgetting parentheses on ReLU
- Putting dropout before first Linear layer
Ready to prove it?
Pass the test and this pattern moves unknown
