In this tutorial, we will introdue how to create a pytorch tensor. There are some ways to create, we will introduce one by one.
Method 1: Use python data
We can use python list, tuple, float et al to create a pytorch tensor. Here is an example:
import torch import numpy as np # python data v1 = torch.tensor(1) print(v1) v2 = torch.tensor([1, 2]) print(v2) v2 = torch.tensor((2, 2)) print(v2)
Run this code, you will see:
tensor(1) tensor([1, 2]) tensor([2, 2])
Method 2: Use numpy data
We also can use numpy ndarray to create a pytorch tensor. For example:
v2 = torch.tensor(np.array([1, 2])) print(v2)
You will see:
tensor([1, 2])
You also can use torch.from_numpy() to convert a numpy data to pytorch tensor.
n = np.ones(5) v3 = torch.from_numpy(n) print(v3)
You will get a tensor:
tensor([1., 1., 1., 1., 1.], dtype=torch.float64)
Method 3: Use pytorch built-in methods
Pytorch has some built-in methods, we can use them to create a new tensor. These methods are:
torch.ones() torch.rand() torch.zeros()
et al.
For example:
b = torch.rand((2, 3), dtype=torch.float64) print(b, b.requires_grad)
We will get a new tensor:
tensor([[0.5199, 0.0872, 0.3165], [0.3257, 0.3458, 0.8638]], dtype=torch.float64) False
Method 4: Use an existing tensor to create a new tensor
We can use torch.ones_like() or torch.rand_like() to create a new tensor.
Here is an example:
c = torch.rand_like(b, dtype=torch.float32) print(c)
You will get:
tensor([[0.7924, 0.9788, 0.2649], [0.7819, 0.1700, 0.4190]])