Python – PyTorch clamp() method

PyTorch torch.clamp() method clamps all the input elements into the range [ min, max ] and return a resulting tensor.
Clamp method

Syntax: torch.clamp(inp, min, max, out=None)

Arguments

  • inp: This is input tensor.
  • min: This is a number and specifies the lower-bound of the range to which input to be clamped.
  • max: This is a number and specifies the upper-bound of the range to which input to be clamped.
  • out: The output tensor.

Return: It returns a Tensor.

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



filter_none

edit
close

play_arrow

link
brightness_4
code

# Importing the PyTorch library 
import torch 
    
# A constant tensor of size n
a = torch.randn(6)
print(a)
  
# Applying the clamp function and 
# storing the result in 'out'
out = torch.clamp(a, min = 0.5, max = 0.9)
print(out)

chevron_right


Output:

 -0.9214
-0.1268
 1.1570
-0.2753
-0.0746
 0.7957
[torch.FloatTensor of size 6]
 0.5000
 0.5000
 0.9000
 0.5000
 0.5000
 0.7957
[torch.FloatTensor of size 6]

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Importing the PyTorch library 
import torch 
    
# A constant tensor of size n
a = torch.FloatTensor([1, 4, 6, 8, 10, 14])
print(a)
  
# Applying the clamp function and 
# storing the result in 'out'
out = torch.clamp(a, min = 5, max = 10)
print(out) 

chevron_right


Output:

 1
  4
  6
  8
 10
 14
[torch.FloatTensor of size 6]
  5
  5
  6
  8
 10
 10
[torch.FloatTensor of size 6]?
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.