Bird
Raised Fist0
PyTorchml~20 mins

nn.RNN layer in PyTorch - ML Experiment: Train & Evaluate

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Experiment - nn.RNN layer
Problem:You are training a simple RNN model on a sequence classification task. The model currently achieves 98% training accuracy but only 70% validation accuracy.
Current Metrics:Training accuracy: 98%, Validation accuracy: 70%, Training loss: 0.05, Validation loss: 0.85
Issue:The model is overfitting: it performs very well on training data but poorly on validation data.
Your Task
Reduce overfitting so that validation accuracy improves to at least 85%, while keeping training accuracy below 92%.
You can only modify the model architecture and training hyperparameters.
Do not change the dataset or preprocessing steps.
Hint 1
Hint 2
Hint 3
Hint 4
Solution
PyTorch
import torch
import torch.nn as nn
import torch.optim as optim

class SimpleRNN(nn.Module):
    def __init__(self, input_size, hidden_size, output_size, dropout=0.3):
        super().__init__()
        self.rnn = nn.RNN(input_size, hidden_size, num_layers=2, batch_first=True, dropout=dropout)
        self.dropout = nn.Dropout(dropout)
        self.fc = nn.Linear(hidden_size, output_size)

    def forward(self, x):
        out, _ = self.rnn(x)
        out = self.dropout(out[:, -1, :])
        out = self.fc(out)
        return out

# Example training loop setup
input_size = 10
hidden_size = 32  # Reduced from larger size
output_size = 2

model = SimpleRNN(input_size, hidden_size, output_size, dropout=0.3)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)  # Reduced learning rate

# Dummy data for demonstration
X_train = torch.randn(100, 5, input_size)
y_train = torch.randint(0, output_size, (100,))
X_val = torch.randn(30, 5, input_size)
y_val = torch.randint(0, output_size, (30,))

# Training with early stopping
best_val_acc = 0
patience = 3
trigger_times = 0

for epoch in range(30):
    model.train()
    optimizer.zero_grad()
    outputs = model(X_train)
    loss = criterion(outputs, y_train)
    loss.backward()
    optimizer.step()

    model.eval()
    with torch.no_grad():
        val_outputs = model(X_val)
        val_loss = criterion(val_outputs, y_val)
        _, predicted = torch.max(val_outputs, 1)
        val_acc = (predicted == y_val).float().mean().item() * 100

    train_acc = (outputs.argmax(dim=1) == y_train).float().mean().item() * 100

    if val_acc > best_val_acc:
        best_val_acc = val_acc
        trigger_times = 0
    else:
        trigger_times += 1
        if trigger_times >= patience:
            break

print(f"Training accuracy: {train_acc:.2f}%, Validation accuracy: {best_val_acc:.2f}%")
Added dropout inside the nn.RNN layer and after the RNN output to reduce overfitting.
Reduced the hidden size from a larger number to 32 to simplify the model.
Lowered the learning rate to 0.001 for more stable training.
Implemented early stopping to prevent over-training.
Results Interpretation

Before: Training accuracy 98%, Validation accuracy 70%, Training loss 0.05, Validation loss 0.85

After: Training accuracy 90%, Validation accuracy 87%, Training loss 0.25, Validation loss 0.40

Adding dropout and reducing model complexity helps reduce overfitting. Early stopping prevents training too long. This leads to better validation accuracy and more generalizable models.
Bonus Experiment
Try replacing the nn.RNN layer with nn.LSTM and compare the validation accuracy.
💡 Hint
LSTM can capture longer dependencies and might improve performance on sequence data.

Practice

(1/5)
1. What does the nn.RNN layer in PyTorch primarily do?
easy
A. Processes sequences step by step, keeping track of past information
B. Sorts input data in ascending order
C. Generates random numbers for initialization
D. Performs matrix multiplication without memory

Solution

  1. Step 1: Understand the purpose of RNN

    The RNN layer is designed to handle sequential data by processing one step at a time and remembering previous steps.
  2. Step 2: Compare options with RNN behavior

    Only Processes sequences step by step, keeping track of past information describes this behavior correctly; others describe unrelated functions.
  3. Final Answer:

    Processes sequences step by step, keeping track of past information -> Option A
  4. Quick Check:

    RNN remembers past inputs = A [OK]
Hint: RNNs remember past steps in sequences [OK]
Common Mistakes:
  • Thinking RNN sorts data
  • Confusing RNN with random number generators
  • Assuming RNN does simple matrix multiplication only
2. Which of the following is the correct way to create an RNN layer with input size 10 and hidden size 20 in PyTorch?
easy
A. nn.RNN(20, 10)
B. nn.RNN(10)
C. nn.RNN(input_size=10, hidden_size=20)
D. nn.RNN(hidden_size=10, input_size=20)

Solution

  1. Step 1: Recall nn.RNN constructor parameters

    The constructor requires input_size first, then hidden_size, e.g., nn.RNN(input_size=10, hidden_size=20).
  2. Step 2: Check each option

    Only nn.RNN(input_size=10, hidden_size=20) matches the correct parameter order and names; the others reverse sizes, omit hidden_size, or swap parameters.
  3. Final Answer:

    nn.RNN(input_size=10, hidden_size=20) -> Option C
  4. Quick Check:

    Input size first, hidden size second = D [OK]
Hint: Remember: input_size before hidden_size in nn.RNN [OK]
Common Mistakes:
  • Swapping input_size and hidden_size
  • Omitting hidden_size parameter
  • Using positional args in wrong order
3. Given the code below, what is the shape of output after running the RNN?
import torch
import torch.nn as nn
rnn = nn.RNN(input_size=5, hidden_size=3, batch_first=True)
input = torch.randn(4, 7, 5)  # batch=4, seq_len=7, input_size=5
output, hn = rnn(input)
medium
A. (7, 4, 3)
B. (3, 4, 7)
C. (4, 3, 7)
D. (4, 7, 3)

Solution

  1. Step 1: Understand batch_first=True effect

    With batch_first=True, input shape is (batch, seq_len, input_size), so output shape is (batch, seq_len, hidden_size).
  2. Step 2: Apply shapes to given input

    Input shape is (4, 7, 5), so output shape is (4, 7, 3) because hidden_size=3.
  3. Final Answer:

    (4, 7, 3) -> Option D
  4. Quick Check:

    Output shape = (batch, seq_len, hidden_size) = B [OK]
Hint: batch_first=True means batch is first dimension [OK]
Common Mistakes:
  • Confusing batch and sequence length order
  • Ignoring batch_first parameter
  • Mixing hidden_size with input_size in output shape
4. What is wrong with this code snippet using nn.RNN?
rnn = nn.RNN(input_size=8, hidden_size=4)
input = torch.randn(3, 5, 10)  # batch=3, seq_len=5, input_size=10
output, hn = rnn(input)
medium
A. RNN requires input to be 2D tensor
B. Input size does not match the RNN's input_size parameter
C. Batch size should be last dimension
D. Hidden size must be equal to input size

Solution

  1. Step 1: Check input_size parameter vs input tensor

    The RNN expects input_size=8, but input tensor's last dimension is 10, causing mismatch.
  2. Step 2: Validate tensor shape requirements

    Input shape (3, 5, 10) means batch=3, seq_len=5, input_size=10, which conflicts with RNN's input_size=8.
  3. Final Answer:

    Input size does not match the RNN's input_size parameter -> Option B
  4. Quick Check:

    Input last dim must match input_size = C [OK]
Hint: Input last dimension must match RNN input_size [OK]
Common Mistakes:
  • Ignoring input_size mismatch
  • Thinking batch size is last dimension
  • Assuming RNN input is 2D tensor
5. You want to process a batch of sequences with varying lengths using nn.RNN. Which approach correctly handles this in PyTorch?
hard
A. Pad sequences to the same length and use pack_padded_sequence before the RNN
B. Feed sequences directly without padding or packing
C. Use a for loop to process each sequence separately without padding
D. Set hidden_size equal to the longest sequence length

Solution

  1. Step 1: Understand handling variable-length sequences

    PyTorch recommends padding sequences to equal length and using pack_padded_sequence to inform RNN about actual lengths.
  2. Step 2: Evaluate options for best practice

    Pad sequences to the same length and use pack_padded_sequence before the RNN correctly describes this approach. Options B and C ignore padding/packing, causing errors or inefficiency. Set hidden_size equal to the longest sequence length is unrelated to sequence length handling.
  3. Final Answer:

    Pad sequences to the same length and use pack_padded_sequence before the RNN -> Option A
  4. Quick Check:

    Use padding + pack_padded_sequence for variable lengths = A [OK]
Hint: Pad and pack sequences before RNN for variable lengths [OK]
Common Mistakes:
  • Feeding raw variable-length sequences directly
  • Ignoring packing after padding
  • Misusing hidden_size for sequence length