python-pytorchHow do I add a dimension to a PyTorch tensor?
Adding a dimension to a PyTorch tensor is done using the unsqueeze() method. This method adds a single-dimensional entry to the tensor at a given position. For example:
import torch
x = torch.tensor([1, 2, 3])
# Add a dimension at position 0
y = x.unsqueeze(0)
print(y)
Output example
tensor([[1, 2, 3]])
The code above creates a new tensor y with an additional dimension at position 0.
The unsqueeze() method takes one argument, the position of the new dimension. This argument is optional; if no argument is provided, the new dimension will be added at the end.
Code explanation
import torch: imports the PyTorch library into the current environmentx = torch.tensor([1, 2, 3]): creates a PyTorch tensor with the values 1, 2, and 3y = x.unsqueeze(0): adds a single-dimensional entry to the tensorxat position 0, and assigns the result to the tensoryprint(y): prints the tensory
Helpful links
More of Python Pytorch
- How do I update PyTorch using Python?
- How can I use Python, PyTorch, and YOLOv5 to build an object detection model?
- How can I use PyTorch with Python 3.10?
- How do I install a Python PyTorch .whl file?
- How can I use PyTorch with Python 3.11?
- How can I use Python PyTorch without CUDA?
- What is the best version of Python to use with PyTorch?
- How can I use Python and PyTorch to parse XML files?
- How do I install PyTorch on Ubuntu using Python?
- How can I use Python and PyTorch with ROCm?
See more codes...