Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PyTorch torch.arange function

PyTorch torch.arange function


PyTorch torch reference manual 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:

Return Value:


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

)

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

)

print

(

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

)

print

(

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

)

print

(

x

)

The output is:

tensor([10,  8,  6,  4,  2])


PyTorch torch reference manual PyTorch torch reference manual