Skip to content
Related Articles

Related Articles

Improve Article

Python – PyTorch abs() method

  • Last Updated : 26 May, 2020

PyTorch torch.abs() method computes the element-wise absolute value of the given input tensor.

Syntax: torch.abs(inp, out=None) ? Tensor

Arguments

  • inp: This is input tensor.
  • out: This is optional parameter and is the output tensor.

Return: It returns a Tensor having absolute value of input inp.

Let’s see this concept with the help of few examples:
Example 1:






# Importing the PyTorch library 
import torch 
    
# A constant tensor of size 1 
a = torch.FloatTensor([-15]) 
print(a) 
    
# Applying the abs function and 
# storing the result in 'b' 
b = torch.abs(a) 
print(b) 

Output:

-15
[torch.FloatTensor of size 1]
 15
[torch.FloatTensor of size 1]

Example 2:




# Importing the PyTorch library 
import torch 
    
# A constant tensor of size n 
a = torch.FloatTensor([15, -5, 3, -2]) 
print(a) 
    
# Applying the abs function and 
# storing the result in 'b' 
b = torch.abs(a) 
print(b) 

Output:

 15
 -5
  3
 -2
[torch.FloatTensor of size 4]
 15
  5
  3
  2
[torch.FloatTensor of size 4]

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :