torch.clamp(input, min, max, out=None)
将输入input张量每个元素的范围限制到区间 [min,max],返回结果到一个新张量。
- input (Tensor) – 输入张量
- min (Number) – 限制范围下限
- max (Number) – 限制范围上限
- out (Tensor, optional) – 输出张量
举例
import torch
a = torch.arange(9).reshape(3, 3) # 创建3*3的tensor
b = torch.clamp(a, 3, 6) # 对a的值进行限幅,限制在[3, 6]
print('a:', a)
print('shape of a:', a.shape)
print('b:', b)
print('shape of b:', b.shape)
''' 输出结果 '''
a: tensor([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
shape of a: torch.Size([3, 3])
b: tensor([[3, 3, 3],
[3, 4, 5],
[6, 6, 6]])
shape of b: torch.Size([3, 3])