๐ŸŽ“ A1Learner
๐Ÿ”

PyTorch Reshaping Tensors

Reshaping changes the shape of a tensor without changing its values. The new shape must hold the same number of values.

Turn a row into a table

reshape reads the values in order. It fills the new shape row by row.

values = torch.arange(12)
print(values.reshape(3, 4))

Let PyTorch work out one size

The values stay the same. Only the shape changes, and -1 marks the size to work out.

table = values.reshape(2, -1)
print(table.shape)
print(table)

Use view for the same job

view sets a new shape too. The value count must still match.

print(values.view(4, 3))

Example

import torch

values = torch.arange(1, 13)

print("Flat values:")
print(values)
print("Flat shape:", values.shape)

table = values.reshape(3, 4)
print("Table:")
print(table)
print("Table shape:", table.shape)

back = table.reshape(-1)
print("Back to flat:")
print(back)
print("Back shape:", back.shape)

Key points

  • Use reshape to give a tensor a new shape
  • The value count stays the same, so 12 values cannot fill a (3, 5) shape
  • Writing -1 for one size lets PyTorch work that size out
  • Use view to set a new shape in the same way

In this example, values holds the numbers 1 to 12 in one row. The first prints show the row and its shape, (12,). reshape(3, 4) then lays the same values out as three rows of four. The table prints with the shape (3, 4). reshape(-1) at the end flattens the table back into one row. The values come back in the same order.

Note

view needs the values laid out in a simple order, and reshape handles the other cases too

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Python Playground

Exercise

A tensor holds 12 values. Which shape can reshape give it?