PyTorch torch.reshape() method “returns a tensor with the same data and number of elements as input but with the specified shape.” When possible, the returned tensor will be a view of input. Otherwise, it will be a copy.
In summary, the torch.reshape() function allows you to change the shape of a tensor without altering its data. It returns a tensor with the desired shape.
Syntax
torch.reshape(input, shape)
Parameters
- input (Tensor): The input tensor.
- shape (tuple of ints): The new shape of the tensor.
Example 1: Simple Reshaping
Suppose you have a tensor of shape (4, 5) and want to reshape it to (2, 10).
import torch
# Sample tensor
tensor = torch.arange(20).reshape(4, 5)
# Reshape the tensor
reshaped_tensor = torch.reshape(tensor, (2, 10))
print(reshaped_tensor)
Output
tensor([[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]])
Example 2: Using -1 for Inferencing Dimension Size
If one of the dimensions is -1, its size can be inferred. For instance, if you have a tensor of shape (4, 5) and want to reshape it to have 10 columns but don’t explicitly know how many rows it would result in, you can use -1.
import torch
# Sample tensor
tensor = torch.arange(20).reshape(4, 5)
# Reshape the tensor, let PyTorch infer the number of rows
reshaped_tensor = torch.reshape(tensor, (-1, 10))
print(reshaped_tensor)
Output
tensor([[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]])
That’s it!
Related posts

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.