Clamp¶
- class pfhedge.nn.Clamp(*args, **kwargs)[source]¶
Clamp all elements in
input
into the range \([\min, \max]\).The bounds \(\min\) and \(\max\) can be tensors.
If \(\min \leq \max\):
\[\begin{split}\text{output} = \begin{cases} \min & \text{input} < \min \\ \text{input} & \min \leq \text{input} \leq \max \\ \max & \max < \text{input} \end{cases}\end{split}\]If \(\min > \max\):
\[\begin{split}\text{output} = \begin{cases} \frac12 (\min + \max) & \text{inverted_output} = \text{'mean'} \\ \max & \text{inverted_output} = \text{'max'} \\ \end{cases}\end{split}\]- Parameters
inverted_output ({'mean', ''max'}, default='mean') – Controls the output when \(\min > \max\). ‘max’ is consistent with
torch.clamp()
.
- Shape:
input: \((N, *)\) where \(*\) means any number of additional dimensions.
min: \((N, *)\) or any size broadcastable to
input
.max: \((N, *)\) or any size broadcastable to
input
.output: \((N, *)\), same shape as the input.
Examples
>>> import torch >>> from pfhedge.nn import Clamp >>> >>> m = Clamp() >>> input = torch.linspace(-2, 12, 15) * 0.1 >>> input tensor([-0.2000, -0.1000, 0.0000, 0.1000, 0.2000, 0.3000, 0.4000, 0.5000, 0.6000, 0.7000, 0.8000, 0.9000, 1.0000, 1.1000, 1.2000]) >>> m(input, 0.0, 1.0) tensor([0.0000, 0.0000, 0.0000, 0.1000, 0.2000, 0.3000, 0.4000, 0.5000, 0.6000, 0.7000, 0.8000, 0.9000, 1.0000, 1.0000, 1.0000])
When \(\min > \max\), returns the mean of \(\min\) and \(\max\).
>>> input = torch.tensor([1.0, 0.0]) >>> min = torch.tensor([0.0, 1.0]) >>> max = torch.tensor([0.0, 0.0]) >>> m(input, min, max) tensor([0.0000, 0.5000])
- forward(input, min=None, max=None)[source]¶
Clamp all elements in
input
into the range \([\min, \max]\).- Parameters
input (torch.Tensor) – The input tensor.
min (torch.Tensor, optional) – Lower-bound of the range to be clamped to.
max (torch.Tensor, optional) – Upper-bound of the range to be clamped to.
- Returns
torch.Tensor