The torch.sign() method returns a new tensor with the sign of each element in the input tensor. For a given element ( x ), the output is defined as:
- 1 if x > 0
- 0 if x = 0
- -1 if x < 0
If input is complex, the sign is defined as input / |input|.
It is an element-wise operation, so the output tensor preserves the shape of the input tensor.
Syntax
torch.sign(input, out=None)
Parameters
Argument | Description |
input (Tensor) |
It represents an input tensor of any numerical data type, such as torch.float32 and torch.int64. |
out (Tensor, optional) |
It represents an optional output tensor to store the result. If you don’t provide, it will create a new tensor. |
Basic usage with floating-point tensors
Let’s define the 1D tensor and compute the sign of elements in a floating-point tensor.
import torch tensor = torch.tensor([-2.1, 0.0, 1.9, -1.1]) signed_tensor = torch.sign(tensor) print(signed_tensor) # Output: tensor([-1., 0., 1., -1.])
From the above code, you can see that it replaces – (negative) value with -1, a + (positive) value with 1, and 0 with 0.
Integer tensors

In the above section, we saw a floating-point tensor; now, we will define a 2D integer tensor and apply the sign() method on it.
import torch tensor_2d = torch.tensor([[-11, 0], [19, -21]]) signed_2d_tensor = torch.sign(tensor_2d) print(signed_2d_tensor) # Output: # tensor([[-1, 0], # [ 1, -1]])
GPU Support
You can also run the torch.sign() method on a CUDA-enabled GPU like this:
import torch if torch.cuda.is_available(): x = torch.tensor([-1.5, 0.0, 2.3]).cuda() result = torch.sign(x) print(result) # Output: tensor([-1., 0., 1.], device='cuda:0')

Combining with torch.where() for conditional logic
We can use torch.sign() method with torch.where() to implement conditional transformations. We will conditionally replace negative values with -10 and positive or zero values with 10.
import torch tensor = torch.tensor([-1.0, 0.0, 5.0]) # Replace positive values with 10, others with -10 output_tensor = torch.where(torch.sign(tensor) > 0, torch.tensor(10.0), torch.tensor(-10.0)) print(output_tensor) # Output: tensor([-10., -10., 10.])That’s all!