PyTorch torch.clip 函数
torch.clip 是 PyTorch 中用于将张量中的值裁剪到指定范围内的函数。
函数定义
torch.clip(input, min, max, out=None)
使用示例
实例
import torch
# 创建张量
x = torch.tensor([1.0, 2.0, 3.0, 4.0, 5.0])
# 将值裁剪到 [2, 4] 范围
y = torch.clip(x, 2, 4)
print(y)
# 创建张量
x = torch.tensor([1.0, 2.0, 3.0, 4.0, 5.0])
# 将值裁剪到 [2, 4] 范围
y = torch.clip(x, 2, 4)
print(y)
输出结果为:
tensor([2., 2., 3., 4., 4.])

Pytorch torch 参考手册