Bird
Raised Fist0
PyTorchml~20 mins

nn.LSTM layer in PyTorch - Practice Problems & Coding Challenges

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
Challenge - 5 Problems
🎖️
LSTM Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output shape of nn.LSTM with batch_first=True
Consider the following PyTorch code snippet using nn.LSTM with batch_first=True. What is the shape of the output tensor `out`?
PyTorch
import torch
import torch.nn as nn

lstm = nn.LSTM(input_size=10, hidden_size=20, num_layers=2, batch_first=True)
input_tensor = torch.randn(5, 7, 10)  # batch=5, seq_len=7, input_size=10
out, (h_n, c_n) = lstm(input_tensor)
print(out.shape)
Atorch.Size([7, 5, 20])
Btorch.Size([5, 20, 7])
Ctorch.Size([7, 20, 5])
Dtorch.Size([5, 7, 20])
Attempts:
2 left
💡 Hint
Remember that batch_first=True means the batch dimension is the first dimension in the input and output.
Model Choice
intermediate
2:00remaining
Choosing LSTM parameters for sequence classification
You want to build an LSTM model to classify sequences of length 15 with 8 features each into 3 classes. Which nn.LSTM configuration is correct to output a tensor suitable for classification after processing the entire sequence?
Ann.LSTM(input_size=3, hidden_size=8, num_layers=2, batch_first=True)
Bnn.LSTM(input_size=15, hidden_size=3, num_layers=1, batch_first=False)
Cnn.LSTM(input_size=8, hidden_size=16, num_layers=1, batch_first=True)
Dnn.LSTM(input_size=8, hidden_size=15, num_layers=3, batch_first=False)
Attempts:
2 left
💡 Hint
Input size should match the feature dimension per time step.
Hyperparameter
advanced
2:00remaining
Effect of increasing num_layers in nn.LSTM
What is the main effect of increasing the num_layers parameter in nn.LSTM from 1 to 3?
AThe LSTM will have 3 stacked layers, allowing it to learn more complex temporal patterns.
BThe input size of the LSTM will automatically triple.
CThe output tensor shape will change from 3D to 2D.
DThe LSTM will process sequences in reverse order.
Attempts:
2 left
💡 Hint
Think about what stacking layers means in neural networks.
🔧 Debug
advanced
2:00remaining
Identifying error in LSTM input shape
What error will this code raise when running the LSTM forward pass?
PyTorch
import torch
import torch.nn as nn

lstm = nn.LSTM(input_size=5, hidden_size=10, batch_first=True)
input_tensor = torch.randn(4, 6, 4)  # batch=4, seq_len=6, input_size=4
out, (h_n, c_n) = lstm(input_tensor)
ARuntimeError: input size mismatch. Expected input_size=5 but got 4.
BTypeError: LSTM input must be 2D tensor.
CValueError: batch_first must be False for this input shape.
DNo error, code runs successfully.
Attempts:
2 left
💡 Hint
Check the input tensor's last dimension against the LSTM's input_size.
Metrics
expert
2:00remaining
Interpreting LSTM hidden state shapes after forward pass
After running an nn.LSTM with num_layers=2, hidden_size=8, batch_first=True on input of shape (3, 10, 6), what is the shape of the hidden state tensor h_n?
Atorch.Size([10, 3, 8])
Btorch.Size([2, 3, 8])
Ctorch.Size([3, 10, 8])
Dtorch.Size([3, 2, 8])
Attempts:
2 left
💡 Hint
Hidden state shape is (num_layers, batch_size, hidden_size).

Practice

(1/5)
1. What is the primary purpose of the nn.LSTM layer in PyTorch?
easy
A. To process and remember information from sequences over time
B. To perform image classification using convolution
C. To reduce the dimensionality of data using PCA
D. To generate random numbers for initialization

Solution

  1. Step 1: Understand the role of LSTM

    LSTM stands for Long Short-Term Memory, a type of recurrent neural network layer designed to handle sequence data and remember information over time.
  2. Step 2: Match purpose with options

    Among the options, only processing and remembering sequence information matches the LSTM's purpose.
  3. Final Answer:

    To process and remember information from sequences over time -> Option A
  4. Quick Check:

    LSTM purpose = sequence memory [OK]
Hint: LSTM = sequence memory layer, not image or random [OK]
Common Mistakes:
  • Confusing LSTM with convolutional layers
  • Thinking LSTM reduces data dimension like PCA
  • Assuming LSTM generates random numbers
2. Which of the following is the correct way to create an LSTM layer in PyTorch with input size 10 and hidden size 20?
easy
A. nn.LSTM(input=10, hidden=20)
B. nn.LSTM(20, 10)
C. nn.LSTM(10, 20)
D. nn.LSTM(hidden_size=10, input_size=20)

Solution

  1. Step 1: Recall nn.LSTM constructor parameters

    The first argument is input_size (features per input), the second is hidden_size (features in hidden state).
  2. Step 2: Match correct syntax

    nn.LSTM(10, 20) uses nn.LSTM(10, 20) which correctly sets input_size=10 and hidden_size=20.
  3. Final Answer:

    nn.LSTM(10, 20) -> Option C
  4. Quick Check:

    Constructor order = input_size, hidden_size [OK]
Hint: First arg input size, second hidden size in nn.LSTM() [OK]
Common Mistakes:
  • Swapping input_size and hidden_size
  • Using wrong keyword arguments
  • Confusing parameter names
3. Given the code below, what is the shape of output after running the LSTM?
import torch
import torch.nn as nn
lstm = nn.LSTM(input_size=5, hidden_size=3, num_layers=1)
inputs = torch.randn(4, 2, 5)  # seq_len=4, batch=2, input_size=5
output, (hn, cn) = lstm(inputs)
medium
A. (4, 2, 3)
B. (2, 4, 3)
C. (4, 3, 2)
D. (2, 3, 4)

Solution

  1. Step 1: Understand LSTM input and output shapes

    The input shape is (seq_len, batch, input_size). The output shape is (seq_len, batch, hidden_size).
  2. Step 2: Apply given dimensions

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

    (4, 2, 3) -> Option A
  4. Quick Check:

    Output shape = (seq_len, batch, hidden_size) [OK]
Hint: Output shape matches (seq_len, batch, hidden_size) [OK]
Common Mistakes:
  • Mixing batch and sequence dimensions
  • Confusing input_size with hidden_size
  • Assuming output shape swaps batch and seq_len
4. What is wrong with this code snippet that tries to create an LSTM layer?
import torch.nn as nn
lstm = nn.LSTM(10)
medium
A. The input size must be a tuple, not an integer
B. It misses the hidden_size argument, causing an error
C. LSTM requires a batch size argument at creation
D. The code is correct and runs without error

Solution

  1. Step 1: Check nn.LSTM constructor requirements

    nn.LSTM requires at least two positional arguments: input_size and hidden_size.
  2. Step 2: Identify missing argument

    The code only provides input_size=10, missing hidden_size, so it will raise a TypeError.
  3. Final Answer:

    It misses the hidden_size argument, causing an error -> Option B
  4. Quick Check:

    nn.LSTM needs input_size and hidden_size [OK]
Hint: nn.LSTM needs two sizes: input and hidden [OK]
Common Mistakes:
  • Thinking batch size is needed at layer creation
  • Assuming input_size can be a tuple
  • Believing code runs without error
5. You want to build a model that processes sequences of length 6 with 8 features each. You want the LSTM to output a sequence with 12 features per time step. Which of the following LSTM layer initializations is correct to achieve this?
hard
A. nn.LSTM(input_size=12, hidden_size=8)
B. nn.LSTM(input_size=8, hidden_size=6)
C. nn.LSTM(input_size=6, hidden_size=8)
D. nn.LSTM(input_size=8, hidden_size=12)

Solution

  1. Step 1: Identify input_size and hidden_size meanings

    input_size is the number of features per time step in the input sequence. hidden_size is the number of features in the output per time step.
  2. Step 2: Match given sequence and desired output

    Input sequences have 8 features, so input_size=8. Desired output features per time step is 12, so hidden_size=12.
  3. Final Answer:

    nn.LSTM(input_size=8, hidden_size=12) -> Option D
  4. Quick Check:

    Input features = 8, output features = 12 [OK]
Hint: Input size = input features, hidden size = output features [OK]
Common Mistakes:
  • Confusing sequence length with input_size
  • Swapping input_size and hidden_size
  • Using sequence length as hidden_size