Skip to content

[Solved][PyTorch] LSTM RuntimeError: input must have 3 dimensions, got 2

Today, when I using PyTorch to build a LSTM model, I got an error occured:

LSTM RuntimeError: input must have 3 dimensions, got 2

This is unexpected for me. I use this model structure again, but the last time I didn’t get the error message. But I print the input tensor size, I finally understood what was wrong.

My input tensor dimension is mismatch.

The input dimension need to be (batch_size, seq_len, input_size). But my data just have (batch_size, input_size).

After adjustment, it can run normally.

It should be noted that PyTorch’s nn.LSTM () has a parameter of “batch_first”. If True, the input format “batch_size” is the first one. If “batch_first” is False, the “batch_size” and “seq_len” positions are swapped.

Leave a Reply