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 tensorx
at position 0, and assigns the result to the tensory
print(y)
: prints the tensory
Helpful links
More of Python Pytorch
- How can I use Yolov5 with PyTorch?
- How do I uninstall Python PyTorch?
- How can I use Python and PyTorch to create a U-Net architecture?
- How can I use Python and PyTorch to parse XML files?
- How do I remove PyTorch from my Python environment?
- How do I use Pytorch with Python 3.11 on Windows?
- How can I use Python and PyTorch on Windows?
- How can I use Python PyTorch with CUDA?
- How do I check the version of Python and PyTorch I am using?
- How do I update PyTorch using Python?
See more codes...