In PyTorch, a tensor is a multi-dimensional array used for storing and manipulating numeric data. To create a tensor in PyTorch, we can use the ‘torch.Tensor()‘ constructor, which takes a sequence of data as input and creates a tensor out of it. Here’s an example to create a tensor of rank 2 (a matrix) with dimensions 3x2:
import torch
my_tensor = torch.Tensor([[1, 2], [3, 4], [5, 6]])
print(my_tensor)
Output:
tensor([[1., 2.],
[3., 4.],
[5., 6.]])
In this example, we first import the PyTorch library using ‘import torch‘. We then create a 2D tensor of size 3x2 by passing a list of lists containing the data to the ‘torch.Tensor()‘ constructor. We assign the resulting tensor to the variable ‘my_tensor‘. Finally, we use the ‘print()‘ function to display the tensor on the screen.
There are other ways to create tensors in PyTorch, such as using ‘torch.zeros()‘, ‘torch.ones()‘, ‘torch.arange()‘, and so on. These functions provide convenient ways to create tensors with specific values or dimensions. Additionally, we can also create tensors from existing data, such as NumPy arrays, using the ‘torch.from_numpy()‘ method or convert tensors to NumPy arrays using the ‘.numpy()‘ method.