PyTorch torch.arange Function
Pytorch torch Reference Manual
torch.arangeis a function in PyTorch used to create arithmetic progression tensors. It creates a one-dimensional tensor containing an arithmetic sequence from the start value to the end value.
This is often used in deep learning 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 starting 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 to compute gradients.
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)
print(x)
# Create an arithmetic sequence from 0 to 4
x = torch.arange(5)
print(x)
The output result is:
tensor([0, 1, 2, 3, 4])
Example 2: Specify Start and End Values
Example
import torch
# Create an arithmetic sequence from 2 to 8
x = torch.arange(2, 9)
print(x)
# Create an arithmetic sequence from 2 to 8
x = torch.arange(2, 9)
print(x)
The output result is:
tensor([2, 3, 4, 5, 6, 7, 8])
Example 3: Specify Step Size
Example
import torch
# Create an arithmetic sequence from 0 to 10 with step size 2
x = torch.arange(0, 11, 2)
print(x)
# Create an arithmetic sequence from 0 to 10 with step size 2
x = torch.arange(0, 11, 2)
print(x)
The output result is:
tensor([0, 2, 4, 6, 8, 10])
Example 4: Negative Step Size
Example
import torch
# Create an arithmetic sequence from 10 to 0 with step size -2
x = torch.arange(10, 0, -2)
print(x)
# Create an arithmetic sequence from 10 to 0 with step size -2
x = torch.arange(10, 0, -2)
print(x)
The output result is:
tensor([10, 8, 6, 4, 2])
Other Extensions