PyTorch torch.arange() Method

PyTorch torch.arange() method is “used to create a 1-dimensional tensor with a sequence of numbers.” This method is similar to Python’s built-in range() but returns a tensor.

Syntax

torch.arange(start=0, end, step=1, *, out=None, dtype=None, 
             layout=torch.strided, device=None, requires_grad=False)

Parameters

  1. start (Number): It is the starting value for the set of points. Default: 0.
  2. end (Number): It is the ending value for the set of points
  3. step (Number): It is the gap between each pair of adjacent points. Default: 1.
  4. out: An output tensor.
  5. dtype: The desired data type of the tensor. Default is inferred.
  6. layout: Memory layout of the tensor. The default is the torch.strided.
  7. device: The desired device for the tensor. Default is the current default device.
  8. requires_grad: If set to True, the tensor will be created with gradient tracking enabled. The default is False.

Example 1: Creating a Tensor with Numbers from 0 to 4

import torch

tensor1 = torch.arange(5)

print(tensor1)

Output

tensor([0, 1, 2, 3, 4])

Example 2: Creating a Tensor with Numbers from 2 to 8 in Steps 2

import torch

tensor2 = torch.arange(2, 10, 2)

print(tensor2)

Output

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

Example 3: Creating a Tensor with Numbers from 0 to 1 in Steps of 0.1

import torch

tensor3 = torch.arange(0, 1.1, 0.1)

print(tensor3)

Output

tensor([0.0000, 0.1000, 0.2000, 0.3000, 0.4000, 0.5000, 0.6000, 0.7000, 0.8000,
        0.9000, 1.0000])

Related posts

torch.ones_like()

torch_ones()

torch_zeros_like()

torch.zeros()

Leave a Comment