torch.clip() 函数用于将张量的数值裁剪到指定范围,小于min的数值裁剪为min,大于max的数值裁剪为max,多用于图像数据处理,用于剔除模型生成图像的异常值。
import torch
# Define a tensor
tensor = torch.tensor([-1, 0, 1, 2, 3, 4, 5])
# Clip the values of the tensor to be between 0 and 3
clipped_tensor = torch.clip(tensor, min=0, max=3)
print(clipped_tensor) # Output: tensor([0, 0, 1, 2, 3, 3, 3])