Clamp() Function in PyTorch – A Complete Guide

FeaImg Clamp Function

So, how are you doing, fellow coders? So, in this tutorial, we’ll try to get our hands on the PyTorch clamp() function. We will look at it from both theoretical and practical perspectives.

Let’s get started.

Introduction to clamp() in Python PyTorch

The clamp() function is used to constrain a value inside a specified range. What does this imply?

First, let’s get this straight.

Assume you’ve been given a range of numbers ranging from 60 to 110, and you’re seeking the number 85. As a result, the clamp() function restricts its value to 85. In this scenario, 85 falls between 60 and 110, making it simple to calculate.

However, if you choose 35, you will be outside of the range. In this situation, it is limited to 60 since it is closest to the lower limit rather than in the middle of the range.

Similarly, if you enter a number bigger than 110, such as 132, it will return 110 because 132 is near to the maximum limit, which is 110.

Implement the clamp() function in PyTorch

Let’s get into implementing the clamp() function in PyTorch.

Using the clamp() function

The Python clamp functionality is not built into the language, but it may be defined using the following code:

def clamp_fucntion (no , min_no , max_no ):
        n = max(min(no, max_no), min_no)
        return n
print( "Find 10 in 20 to 30 : ", clamp_fucntion(10 ,20 ,30) )
print( "Find 25 in 20 to 30 : ", clamp_fucntion(25 ,20 ,30 ) )
print( "Find 115  in 20 to 30 : ",  clamp_fucntion(115 ,20 ,30 ) )
Find 10 in 20 to 30 :  20
Find 25 in 20 to 30 :  25
Find 115  in 20 to 30 :  30

There are some other ways of implementing the clamp function. Let’s look at some of them in the section below.

Pytorch Clamp()

However, while this function is not frequently used in core Python, it is widely utilized in a number of Python libraries such as Pytorch and the Wand ImageMagick library.

Furthermore, this function is already included in these libraries. You just need to import it and utilize it as needed.

Let’s go ahead and look at some examples of them.

import torch

T = torch.FloatTensor([3,12,15,18,21])
print("Input Tensor: ", T)

output = torch.clamp(T,min=10,max=20)
print("Output Tensor: ",output)
Input Tensor:  tensor([ 3., 12., 15., 18., 21.])
Output Tensor:  tensor([10., 12., 15., 18., 20.])


Congratulations! You just learned about the Clamp function and its implementation in Python. Hope you enjoyed it! 😇

Liked the tutorial? In any case, I would recommend you to have a look at the tutorials mentioned below:

  1. Numpy average() Function – A Brief Overview
  2. Pandas isin() function – A Complete Guide
  3. 4 Activation Functions in Python to know!
  4. Overview of Loss Functions in Python

Thank you for taking your time out! Hope you learned something new!! 😄