PyTorch torch.arange function
PyTorch torch reference manual
torch.arange is a function in PyTorch used to create a tensor containing an arithmetic sequence. It creates a one-dimensional tensor with values progressing from a start value to an end value.
In deep learning this is often used to create indices, range arrays, or generate sequences in loops.
Function definition
torch.arange(start=0, end, step=1, dtype=None, device=None, requires_grad=False)
Parameters:
start(float, optional): The start value of the sequence; defaults to 0.end(float): The end value of the sequence (exclusive).step(float, optional): The step size; defaults to 1.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: From 0 to 5
Example
import
torch
Create an arithmetic sequence from 0 to 4
x
=
torch.
arange
(
5
)
(
x
)
The output is:
tensor([0, 1, 2, 3, 4])
Example 2: Specify the start and end values
Example
import
torch
Create an arithmetic sequence from 2 to 8
x
=
torch.
arange
(
2
,
9
)
(
x
)
The output is:
tensor([2, 3, 4, 5, 6, 7, 8])
Example 3: Specify the step size
Example
import
torch
Create an arithmetic sequence from 0 to 10 with a step of 2
x
=
torch.
arange
(
0
,
11
,
2
)
(
x
)
The output is:
tensor([0, 2, 4, 6, 8, 10])
Example 4: Negative step
Example
import
torch
Create an arithmetic sequence from 10 to 0 with a step of -2
x
=
torch.
arange
(
10
,
0
,
2
)
(
x
)
The output is:
tensor([10, 8, 6, 4, 2])