.view()

Anonymous contributor's avatar
Anonymous contributor
Published Nov 9, 2024
Contribute to Docs

The .view() method in PyTorch reshapes a tensor without altering its underlying data, provided the total number of elements remains the same. This method is useful when preparing tensors for operations requiring specific dimensions, such as neural network inputs.

Syntax

tensor.view(shape)
  • shape: A tuple or list defining the desired dimensions. The total number of elements must match the original tensor.

The function returns a tensor with the specified shape, sharing the same data as the original tensor.

Example

This example reshapes a tensor from a shape of (2, 3) to (3, 2) using .view():

import torch
# Create a tensor of shape (2, 3)
original_tensor = torch.tensor([[1, 2, 3], [4, 5, 6]])
# Reshape the tensor to (3, 2)
reshaped_tensor = original_tensor.view(3, 2)
print(reshaped_tensor)

This example results in the following output:

tensor([[1, 2],
[3, 4],
[5, 6]])

In this example, .view() modifies the shape of original_tensor while preserving its data.

All contributors

Contribute to Docs

Learn PyTorch on Codecademy