How is the torch.clamp() function used in Python?

The torch.clamp() function is used to restrict the elements in the input tensor to a specific range.

The syntax of the function is as follows:

torch.clamp(input, min, max, out=None)

Description of parameters:

  1. tensor input.
  2. Minimum: Elements smaller than this value will be replaced with it.
  3. Max: The maximum value that elements exceeding it will be replaced by.
  4. out: tensor used for storing output results.

Example of use:

import torch

x = torch.randn(5)  # 创建一个包含5个随机数的张量
print(x)  # 打印原始张量

# 使用clamp函数将张量的元素限制在-0.5到0.5之间
y = torch.clamp(x, -0.5, 0.5)
print(y)  # 打印限制后的张量

Sample output:

tensor([ 0.0849, -0.2706,  0.7244,  0.0921,  0.6237])
tensor([ 0.0849, -0.2706,  0.5000,  0.0921,  0.5000])

In the example above, a tensor x containing 5 random numbers is first created. The clamp function is then used to restrict the elements of the tensor to be between -0.5 and 0.5, and the results are stored in a new tensor y. Finally, the original tensor and the restricted tensor are printed out. It can be seen that all elements in tensor y have been constrained to be between -0.5 and 0.5.

bannerAds