Generating Tensor Data
Just like numpy, the Pytorch library offers a way to generate tensor such as
Below is an example of generating tensor data.
import torch
import numpy as np
torch.ones
Generating a tensor of $2x3$ dimensions with each element being of value $1$.
torch.ones(2, 3)
torch.zeros
The same can be done using
torch.zeros(1, 5)
torch.eye
The
torch.eye(4)
Tensors from Numpy Arrays
Another way to generate data is to convert numpy array into tensors. This can be accomplished with a built in
method
x_array = np.array([1, 2, 3])
x_tensor = torch.from_numpy(x_array)
print("Numy Array:", x_array, "\n"
"Tensor from Array:", x_tensor)
Numerical Ranges
Another useful utility method is the
a = torch.arange(1, 15)
a
# skipping 2 steps
torch.arange(1, 15, 2)
Generating Random Values
Much like numpy, we can generate random numbers from a distribution or particular constraints using torch tensors. Below are a few demostrations:
Random values between 0 and 1
The base
torch.rand(5)
Random values between 0 and 1 with dimensions
We can also pass tuple dimensions of the arrays and generate random numbers to fit the dimensions.
torch.rand((2, 3))
Random Integer Generation
The
The example below with explicit arguments generates a tensor of $3x3$ with integers in the range of
torch.randint(low=11, high=21, size=(3, 3))