PyTorch torch.linspace function
PyTorch torch reference manual
torch.linspace is a function in PyTorch used to create a tensor with evenly spaced values. It creates a one-dimensional tensor containing a sequence of evenly spaced numbers from a start value to an end value.
The difference between torch.arange in Vue 2,torch.linspace It specifies the number of elements rather than the step size, which is useful when you need precise control over the number of elements.
Function definition
torch.linspace(start, end, steps, dtype=None, device=None, requires_grad=False)
Parameters:
start(float): The starting value of the sequence.end(float): The ending value of the sequence (inclusive).steps(int): The number of elements in the sequence, which must be a positive integer.dtype(torch.dtype, optional): Specifies the data type of the tensor.device(torch.device, optional): Specifies the device on which the tensor is stored.requires_grad(bool, optional): Whether gradients need to be computed.
Return Value:
torch.Tensor: Returns a one-dimensional tensor.
Usage examples
Example 1: Create 5 evenly spaced points
Example
import
torch
Create an evenly spaced sequence from 0 to 10 with 5 points
x
=
torch.
linspace
(
0
,
10
,
5
)
(
x
)
The output is:
tensor([ 0.0000, 2.5000, 5.0000, 7.5000, 10.0000])
Example 2: Create 10 points
Example
import
torch
Create an evenly spaced sequence from -1 to 1 with 10 points
x
=
torch.
linspace
(
1
,
1
,
10
)
(
x
)
The output is:
tensor([-1.0000, -0.7778, -0.5556, -0.3333, -0.1111, 0.1111, 0.3333, 0.5556,
0.7778, 1.0000])
Example 3: Used for learning rate scheduling in neural networks
Example
import
torch
Simulate the learning rate gradually decreasing from 0.1 to 0.001
learning_rates
=
torch.
linspace
(
0.1
,
0.001
,
100
)
(
"Initial learning rate:"
,
learning_rates
[
0
]
.
item
(
)
)
(
"Final learning rate:"
,
learning_rates
[
1
]
.
item
(
)
)
The output is:
初始学习率: 0.10000000149011612
最终学习率: 0.0010000000474974513
In this example, we create a sequence of 100 learning rate values, which is often used for learning rate scheduling.
The difference between torch.arange and torch.linspace
torch.arange(start, end, step): Creates a sequence based on a step size, where the number of elements is determined by the range and the step size.torch.linspace(start, end, steps): Creates a sequence based on the number of elements, where the spacing is determined by the range and the number of elements.