Python Pytorch arange() method

PyTorch is an open-source machine learning library developed by Facebook. It is used for deep neural network and natural language processing purposes.

The function torch.arange() returns a 1-D tensor of size  \left\lceil \frac{\text{end} - \text{start}}{\text{step}} \right\rceil
with values from the interval  [start, end) taken with common difference step beginning from start.

 out_{i+1} = out_i + step

Syntax: torch.arange(start=0, end, step=1, out=None)

Parameters:
start: the starting value for the set of points. Default: 0.
end: the ending value for the set of points
step: the gap between each pair of adjacent points. Default: 1.
out(Tensor, optional): the output tensor



Return type: A tensor

Code #1:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Importing the PyTorch library
import torch
  
  
# Applying the arange function and
# storing the resulting tensor in 't'
a = torch.arange(3)
print("a = ", a)
  
b = torch.arange(1, 6)
print("b = ", b)
  
c = torch.arange(1, 5, 0.5)
print("c = ", c)

chevron_right


Output:

a =  tensor([0, 1, 2])
b =  tensor([1, 2, 3, 4, 5])
c =  tensor([1.0000, 1.5000, 2.0000, 2.5000, 3.0000, 3.5000, 4.0000, 4.5000])

 

Note that the non-integer step is subject to floating-point rounding errors when comparing against end; to avoid inconsistency, we advise adding a small epsilon to the end in such cases.

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.