RuntimeError: stack expects each tensor to be equal size, but got [4] at entry 0 and [3] at entry 1 error occurs when you “try to stack tensors that have different shapes using torch.stack() method.” In PyTorch, all tensors to be stacked must have the same shape.
Reproduce the error
import torch
tensor_a = torch.Tensor([1, 2, 3, 4])
tensor_b = torch.Tensor([5, 6, 7])
stacked_tensor = torch.stack((tensor_a, tensor_b), dim=0)
print(stacked_tensor)
Output
RuntimeError: stack expects each tensor to be equal size,
but got [4] at entry 0 and [3] at entry 1
Since their shapes are not equal, attempting to stack them will result in the RuntimeError.
How to fix the error
Here are the three ways to fix the error:
- Equalize the Shapes
- Using the torch.cat() method for Different Shapes
- Pad to Match Shapes
Solution 1: Equalize the shapes
Make sure all tensors have the same shape before stacking them.
import torch
tensor_a = torch.Tensor([1, 2, 3])
tensor_b = torch.Tensor([4, 5, 6])
stacked_tensor = torch.stack((tensor_a, tensor_b), dim=0)
print(stacked_tensor)
Output
tensor([[1., 2., 3.],
[4., 5., 6.]])
Solution 2: Using the torch.cat() method for Different Shapes
If you want to concatenate tensors of different shapes, you can use the torch.cat() instead of torch.stack(). However, they must still match in dimensions other than the one you’re concatenating along.
import torch
tensor_a = torch.Tensor([1, 2, 3, 4])
tensor_b = torch.Tensor([5, 6, 7])
concatenated_tensor = torch.cat((tensor_a, tensor_b), dim=0)
print(concatenated_tensor)
Output
tensor([1., 2., 3., 4., 5., 6., 7.])
Solution 3: Pad to Match Shapes
In some scenarios, you might want to pad smaller tensors to make their shapes match before stacking.
import torch
tensor_a = torch.Tensor([1, 2, 3, 4])
tensor_b = torch.Tensor([5, 6, 7])
tensor_b_padded = torch.cat((tensor_b, torch.Tensor([0])), dim=0)
stacked_tensor = torch.stack((tensor_a, tensor_b_padded), dim=0)
print(stacked_tensor)
Output
tensor([[1., 2., 3., 4.],
[5., 6., 7., 0.]])
Choose the best approach based on your specific use case.

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Machine Learning frameworks like PyTorch and Tensorflow is a testament to his versatility and commitment to the craft.