PyTorch 中的 Clamp() 函数 – 完整指南

那么,各位程序员,你们还好吗?因此,在本教程中,我们将尝试使用PyTorch lamp() 函数我们将从理论和实践两个角度来看待它。

让我们开始吧。


Python PyTorch中clamp()简介

Clip () 函数用于将值限制在指定范围内。这意味着什么?

首先,让我们弄清楚这一点。

假设您得到了从60 到 110的数字范围,并且您正在寻找数字85因此,clamp() 函数将其值限制为 85。在这种情况下,85 介于 60 和 110 之间,因此计算起来很简单。

但是,如果您选择35,则将超出范围。在这种情况下,它被限制为 60,因为它最接近下限而不是范围的中间。

同样,如果您输入大于 110 的数字,例如132,它将返回 110,因为 132 接近最大限制,即 110。


在PyTorch中实现clamp()函数

让我们开始在PyTorch 中实现clamp() 函数。

使用clamp()函数

Python 钳制功能未内置于该语言中,但可以使用以下代码定义:

1
2
3
4
5
6
def clamp_fucntion (no , min_no , max_no ):
        n = max(min(no, max_no), min_no)
        return n
print( "Find 10 in 20 to 30 : ", clamp_fucntion(10 ,20 ,30) )
print( "Find 25 in 20 to 30 : ", clamp_fucntion(25 ,20 ,30 ) )
print( "Find 115  in 20 to 30 : ",  clamp_fucntion(115 ,20 ,30 ) )
Find 10 in 20 to 30 :  20
Find 25 in 20 to 30 :  25
Find 115  in 20 to 30 :  30

还有一些其他方法可以实现钳位功能让我们在下面的部分中看看其中的一些。

Pytorch 夹具()

然而,虽然这个函数在核心 Python 中并不经常使用,但它在许多 Python 库中被广泛使用,例如 Pytorch 和 Wand ImageMagick 库。

此外,该函数已包含在这些库中。您只需导入它并根据需要使用它即可。

让我们继续看一些例子。

1
2
3
4
5
6
7
import torch
 
T = torch.FloatTensor([3,12,15,18,21])
print("Input Tensor: ", T)
 
output = torch.clamp(T,min=10,max=20)
print("Output Tensor: ",output)
Input Tensor:  tensor([ 3., 12., 15., 18., 21.])
Output Tensor:  tensor([10., 12., 15., 18., 20.])

结论

恭喜!您刚刚了解了 Clamp 函数及其在 Python 中的实现。希望你喜欢它!😇

喜欢该教程吗?无论如何,我建议您查看下面提到的教程:

  1. Numpyaverage() 函数——简要概述
  2. Pandas isin() 函数 – 完整指南
  3. Python 中 4 个你必须知道的激活函数!
  4. Python 中的损失函数概述

感谢您抽出宝贵时间!希望你学到新东西!😄