PyTorch .view()
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
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn PyTorch on Codecademy
- Machine Learning Data Scientists solve problems at scale, make predictions, find patterns, and more! They use Python, SQL, and algorithms.
- Includes 27 Courses
- With Professional Certification
- Beginner Friendly.95 hours
- Learn how to use PyTorch to build, train, and test artificial neural networks in this course.
- Intermediate.3 hours