In this tutorial, we will introduce how to use torch.linspace() function with some examples.
Syntax
torch.linspace() is defined as:
torch.linspace(start, end, steps, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False)
It will creates a one-dimensional tensor of size steps whose values are evenly spaced from start to end, inclusive.
It means we will get a one-dimensional tensor with values in
How to use torch.linspace() ?
Here we will use some example to show you how to use it.
For example:
import torch x = torch.linspace(3, 10, steps=5) print(x) print(x.shape)
Run this code, we will see:
tensor([ 3.0000, 4.7500, 6.5000, 8.2500, 10.0000]) torch.Size([5])
The shape of x = step
Meanwhile, the start and end value (3 and 10) are also included in tensor x.
If step = 2
x = torch.linspace(3, 10, steps=2) print(x) print(x.shape)
We will get:
tensor([ 3., 10.]) torch.Size([2])
If step = 1
x = torch.linspace(3, 10, steps=1) print(x) print(x.shape)
We will get:
tensor([3.]) torch.Size([1])