TensorDictBase.clamp#
- TensorDictBase.clamp(min: TensorDictBase | Tensor | float | None = None, max: TensorDictBase | Tensor | float | None = None, *, out=None) Self#
Returns a new tensordict with every leaf clamped into the range
[min, max].\[y_i = \min(\max(x_i, \text{min}_i), \text{max}_i)\]Where
minis greater thanmax, the result ismax, as withtorch.clamp(). At least one ofminandmaxmust be given; with only one bound,clampcallsclamp_min()orclamp_max().- Parameters:
min (TensorDictBase, Tensor, Number or None, optional) – the lower bound. A tensordict is paired with the tensordict key by key.
minandmaxmust both be tensordicts, or neither. Defaults toNone, which sets no lower bound.max (TensorDictBase, Tensor, Number or None, optional) – the upper bound.
minandmaxmust both be tensordicts, or neither. Defaults toNone, which sets no upper bound.
- Keyword Arguments:
out (TensorDictBase, optional) – the tensordict to write the result into, and the one returned. The result is copied into its leaves, so
outmust have the keys, shapes and dtypes of the result. Defaults toNone.- Raises:
ValueError – if one of
minandmaxis a tensordict and the other is not, or ifoutis given and bothminandmaxareNone.KeyError – if
outdoes not have the keys of the result.RuntimeError – if a leaf of
outdoes not have the dtype of the result, as withtorch.clamp().
Examples
>>> import torch >>> from tensordict import TensorDict >>> td = TensorDict(x=torch.tensor([-2.0, 0.5, 3.0]), batch_size=[3]) >>> td.clamp(0.0, 1.0)["x"] tensor([0.0000, 0.5000, 1.0000]) >>> td.clamp(max=0.0)["x"] tensor([-2., 0., 0.])
Every tensordict class and every tensorclass has this method. For the other methods, see Methods by task.