torch.copysign

torch.copysign(x, y, *, out=None) Tensor

创建一个新浮点张量,其中每个元素的幅值来自input,符号来自other

$\text{out}_{i} = \begin{cases} -|\text{input}_{i}| & \text{if } \text{other}_{i} \leq -0.0 \\ |\text{input}_{i}| & \text{if } \text{other}_{i} \geq 0.0 \\ \end{cases}$

支持广播到公共形状,以及整数和浮点数的输入。

参数
  • 输入 (Tensor) – 模.magnitude。

    注:原文中的“magnitude”被翻译为中文的“模”,但后面又出现了英文的“magnitude”,为了避免混淆,可以将“magnitude”统一处理。如果需要更自然的表达,建议如下:

    输入 (Tensor) – 张量的幅值。

  • other (TensorNumber) – 包含其符号位将应用于input中数值幅度的值。

关键字参数

out (Tensor, 可选) – 指定输出张量。

示例:

>>> a = torch.randn(5)
>>> a
tensor([-1.2557, -0.0026, -0.5387,  0.4740, -0.9244])
>>> torch.copysign(a, 1)
tensor([1.2557, 0.0026, 0.5387, 0.4740, 0.9244])
>>> a = torch.randn(4, 4)
>>> a
tensor([[ 0.7079,  0.2778, -1.0249,  0.5719],
        [-0.0059, -0.2600, -0.4475, -1.3948],
        [ 0.3667, -0.9567, -2.5757, -0.1751],
        [ 0.2046, -0.0742,  0.2998, -0.1054]])
>>> b = torch.randn(4)
tensor([ 0.2373,  0.3120,  0.3190, -1.1128])
>>> torch.copysign(a, b)
tensor([[ 0.7079,  0.2778,  1.0249, -0.5719],
        [ 0.0059,  0.2600,  0.4475, -1.3948],
        [ 0.3667,  0.9567,  2.5757, -0.1751],
        [ 0.2046,  0.0742,  0.2998, -0.1054]])
>>> a = torch.tensor([1.])
>>> b = torch.tensor([-0.])
>>> torch.copysign(a, b)
tensor([-1.])

注意

copysign 函数处理带有符号的零。如果另一个参数是负零 (-0),那么对应的输出值也会是负零。

本页目录