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
- What is the most compatible version of Python to use with PyTorch?
- How can I use Python and PyTorch to parse XML files?
- How do I use Pytorch with Python 3.11 on Windows?
- How can I use Python PyTorch with CUDA?
- How do I use PyTorch with Python version 3.11?
- How can I compare Python PyTorch and Torch for software development?
- How can I use Python and PyTorch to create a Unity game?
- How can I use Python and PyTorch with ROCm?
- How can I use Python Torch to create a Tensor?
- How can I compare the performance of PyTorch Python and C++ for software development?
See more codes...