Function Differences with torch.clamp
torch.clamp
torch.clamp(
input,
min,
max,
out=None
)
For more information, see torch.clamp.
mindspore.ops.clip_by_value
mindspore.ops.clip_by_value(
x,
clip_value_min,
clip_value_max
)
For more information, see mindspore.ops.clip_by_value.
Differences
PyTorch: Clamps all elements in input into the range [ min, max ] and return a resulting tensor. Supports specifying one of two parameters ‘min’, ‘max’.
MindSpore:Limits the value of ‘x’ to a range, whose lower limit is ‘clip_value_min’ and upper limit is ‘clip_value_max’. The two parameters ‘clip_value_min’, ‘clip_value_max’ are required.
Code Example
import mindspore as ms
import mindspore.ops as ops
import torch
import numpy as np
min_value = ms.Tensor(5, ms.float32)
max_value = ms.Tensor(20, ms.float32)
x = ms.Tensor(np.array([[1., 25., 5., 7.], [4., 11., 6., 21.]]), ms.float32)
output = ops.clip_by_value(x, min_value, max_value)
print(output)
# Out:
# [[ 5. 20. 5. 7.]
# [ 5. 11. 6. 20.]]
a = torch.randn(4)
print(a)
# Out:
#tensor([-1.7120, 0.1734, -0.0478, -0.0922])
print(torch.clamp(a, min=-0.5, max=0.5))
# Out:
# tensor([-0.5000, 0.1734, -0.0478, -0.0922])
a = torch.randn(4)
print(a)
# Out:
# tensor([-0.0299, -2.3184, 2.1593, -0.8883])
print(torch.clamp(a, min=0.5))
# Out:
# tensor([ 0.5000, 0.5000, 2.1593, 0.5000])
a = torch.randn(4)
print(a)
# Out:
# tensor([ 0.7753, -0.4702, -0.4599, 1.1899])
print(torch.clamp(a, max=0.5))
# Out:
# tensor([ 0.5000, -0.4702, -0.4599, 0.5000])