PyTorch .copysign()
PyTorch’s .copysign() function creates a new tensor by combining the magnitude of the first input with the sign of the second input, element-wise.
Note: If the first input contains booleans, they are cast to floats (
Truebecomes1.0,Falsebecomes0.0).-0.0or-0in the second input is treated as a negative sign, while0.0or0is treated as positive, and these signs are preserved when copied.
Syntax
torch.copysign(input, other, *, out=None)
Parameters:
input(Tensor): The input tensor providing magnitudes.other(Tensor): The tensor whose sign will be copied to input. Must be broadcastable to the shape ofinput.out(Tensor, optional): The tensor to store the output. Must have the same shape as the broadcasted result.
Note: The tensors must be broadcastable in order to perform the operation. Otherwise, this will result in a
RuntimeError.
Return value:
A tensor where each element has the absolute value of the corresponding element in input and the sign of the corresponding element in other.
Example 1
This example shows how to copy signs from the signs tensor to the magnitudes tensor using .copysign():
import torch# Initializing tensorsmagnitudes = torch.tensor([-5.0, True, -8.0])signs = torch.tensor([-0.0, 0.0, 3.0])# Using torch.copysign to copy the sign from 'signs' to 'magnitudes'result = torch.copysign(magnitudes, signs)print(result)
The output of this code is:
tensor([-5., 1., 8.])
Example 2
This example shows how to copy the sign from a one-dimensional signs tensor to a two-dimensional magnitudes tensor using broadcasting. Each row of magnitudes is aligned with the corresponding value in signs, and the sign is applied column-wise:
import torchtorch.manual_seed(0)# Create a 3x3 tensor of magnitudesmagnitudes = torch.rand(3, 3)print("Magnitudes:\n", magnitudes)# 1D tensor whose signs will be broadcast across rowssigns = torch.tensor([0.6323, 0.3489, -0.4017])# Apply copysign with broadcastingresult = torch.copysign(magnitudes, signs)print("\nResult:\n", result)
The output of this code is:
Magnitudes:tensor([[0.4963, 0.7682, 0.0885],[0.1320, 0.3074, 0.6341],[0.4901, 0.8964, 0.4556]])Result:tensor([[ 0.4963, 0.7682, -0.0885],[ 0.1320, 0.3074, -0.6341],[ 0.4901, 0.8964, -0.4556]])
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn PyTorch on Codecademy
- Machine Learning Data Scientists solve problems at scale, make predictions, find patterns, and more! They use Python, SQL, and algorithms.
- Includes 27 Courses
- With Professional Certification
- Beginner Friendly.95 hours