Generating Tensor Data

Just like numpy, the Pytorch library offers a way to generate tensor such as torch.ones and torch.zeros. These can be used to generate constant arrays of desired dimensions, if and when needed.

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)
tensor([[1., 1., 1.], [1., 1., 1.]])

torch.zeros

The same can be done using torch.zeros and passing in the desired dimensions.

torch.zeros(1, 5)
tensor([[0., 0., 0., 0., 0.]])

torch.eye

The torch.eye(n) create an identify matrix of a given size $n$.

torch.eye(4)
tensor([[1., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., 1., 0.], [0., 0., 0., 1.]])

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 from_numpy. The example below demostrates this implementation:

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)
Numy Array: [1 2 3] Tensor from Array: tensor([1, 2, 3])

Numerical Ranges

Another useful utility method is the torch.arange(start, end) which generate a range of numbers from start to end.

a = torch.arange(1, 15)
a
tensor([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14])
# skipping 2 steps
torch.arange(1, 15, 2)
tensor([ 1, 3, 5, 7, 9, 11, 13])

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(n) generates a 1-d array with random $n$ random numbers between $0$ and $1$.

torch.rand(5)
tensor([0.6047, 0.7257, 0.3807, 0.2282, 0.5123])

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))
tensor([[0.8693, 0.3817, 0.4203], [0.9344, 0.6891, 0.7220]])

Random Integer Generation

The torch.randint() generates random integers within specified high and low range.

The example below with explicit arguments generates a tensor of $3x3$ with integers in the range of low=11 and high=21.

torch.randint(low=11, high=21, size=(3, 3))
tensor([[19, 14, 14], [17, 17, 14], [16, 20, 16]])