How do you create tensors in PyTorch?
There are multiple ways to create tensors in PyTorch, with the most common methods including:
- Create a tensor by passing a list or array into the torch.tensor() function.
import torch
tensor = torch.tensor([1, 2, 3, 4, 5])
- Create a tensor containing all ones or all zeroes using the torch.ones() or torch.zeros() function.
import torch
ones_tensor = torch.ones(2, 3)
zeros_tensor = torch.zeros(3, 2)
- Create a random tensor following a normal distribution using the torch.randn() function.
import torch
random_tensor = torch.randn(2, 3)
- Create a tensor with an arithmetic sequence or evenly spaced values using torch.arange() function or torch.linspace() function.
import torch
arange_tensor = torch.arange(1, 10, 2)
linspace_tensor = torch.linspace(1, 10, 5)
In addition to the methods mentioned above, you can also create tensors according to your own needs using other methods, such as using the torch.eye() function to create an identity matrix tensor.