This blog will explain the method to use the “clamp()” method in PyTorch.
How to Use the “clamp()” Method in PyTorch?
To use the “clamp()” method in PyTorch, look at the provided steps:
- Import PyTorch library
- Create a desired tensor
- Clamp the tensor’s elements using the “clamp()” method
- Display clamped values tensor
The basic syntax of “clamp()” is:
Here, “min” is the lower bound value, and “max” is the upper bound value.
Let explore the steps:
Step 1: Import PyTorch Library
First, import the “torch” library to use the “clamp()” method in PyTorch:
Step 2: Create a Tensor
Then, create a desired tensor using the “torch.tensor()” function and print its elements. Here, we are creating the following “Tens” tensor from a list:
print(Tens)
The below output shows the created tensor:
Step 3: Clamp Tensor Elements
Now, use the “clamp()” function and provide the input tensor and specific range (lower bound and upper bound) as arguments. Here, we are clamping the elements of the “Tens” tensor and setting the min value “5” and max value “10”. This will replace any values in the tensor that are less than 5 with “5” and any values greater than 10 with “10”:
Step 4: Display Clamped Values Tensor
Finally, display the tensor with clamped values and view its elements:
In the below output, it can be observed that the values that were less than 5 and greater than 10 have been replaced with “5” and “10” respectively. This indicates that the “clamp()” method has been applied successfully:
Similarly, if we specify different min and max values in the “clamp()” function, the output will be changed:
print(Clamp_tens)
The below output shows that the values less than 7 and greater than 13 have been successfully replaced with “7” and “13” respectively.
We have efficiently explained the use of the “clamp()” method in PyTorch.
Note: You can access our Google Colab Notebook at this link.
Conclusion
To use the “clamp()” method in PyTorch, first, import the torch library. Then, create the desired tensor and view its elements. Next, use the “clamp()” method to clamp elements of the input tensor. It is required to provide the input tensor and specific range (lower bound and upper bound) as arguments. Finally, display the tensor with clamped values and view its elements. This write-up has explained the method to use the “clamp()” method in PyTorch.