torch.clamp、torch.div用法

torch.clamp(input,min,max)

  • 对输入的 input 张量中每个值做截断操作

截断方式如下
y i = { m i n if  x i <min x i if min <=  x i  <= max m a x if  x i  > max y_i= \left\{\begin{array}{ll} min & \textrm{if $x_i$<min}\\ x_i & \textrm{if min <= $x_i$ <= max}\\ max & \textrm{if $x_i$ > max} \end{array}\right. yi=minximaxif xi<minif min <= xi <= maxif xi > max

  • input(Tensor),输入张量;
  • min(Number) ,截断范围最小值;
  • max(Number),截断范围最大值;

例子如下

>>> a = torch.randn(4)
>>> a
tensor([-1.7120,  0.1734, -0.0478, -0.0922])
>>> torch.clamp(a, min=-0.5, max=0.5)
tensor([-0.5000,  0.1734, -0.0478, -0.0922])

torch.div(input,other)

  • input 张量中值除以other 张量中对应的元素值,other 可为张量也可为 标量,转换方式如下

o u t i = i n p u t i o t h e r i out_i = \frac{input_i}{other_i} outi=otheriinputi

参数解析

  • input(Tensor) ,输入张量,作为被除数;
  • other(Tensor or Number) ,作除数的张量或标量;

代码实例:

>>> a = torch.randn(5)
>>> a
tensor([ 0.3810,  1.2774, -0.2972, -0.3719,  0.4637])
>>> torch.div(a, 0.5)
tensor([ 0.7620,  2.5548, -0.5944, -0.7439,  0.9275])
>>> a = torch.randn(4, 4)
>>> a
tensor([[-0.3711, -1.9353, -0.4605, -0.2917],
        [ 0.1815, -1.0111,  0.9805, -1.5923],
        [ 0.1062,  1.4581,  0.7759, -1.2344],
        [-0.1830, -0.0313,  1.1908, -1.4757]])
>>> b = torch.randn(4)
>>> b
tensor([ 0.8032,  0.2930, -0.8113, -0.2308])
>>> torch.div(a, b)
tensor([[-0.4620, -6.6051,  0.5676,  1.2637],
        [ 0.2260, -3.4507, -1.2086,  6.8988],
        [ 0.1322,  4.9764, -0.9564,  5.3480],
        [-0.2278, -0.1068, -1.4678,  6.3936]])

猜你喜欢

转载自blog.csdn.net/weixin_42512684/article/details/110789526