PyTorch torch.reshape() Method

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

  1. input (Tensor): The input tensor.
  2. 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

torch.randperm()

torch.randint()

torch.randn()

torch.stack()

torch.cat()

torch.matmul()

torch.split()

torch.unsqueeze()

Leave a Comment