Skip to content

Commit 6311447

Browse files
committed
(Type what you did)
1 parent 95f0e9a commit 6311447

File tree

1 file changed

+62
-0
lines changed
  • content/pytorch/concepts/tensor-operations/terms/sign

1 file changed

+62
-0
lines changed
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
---
2+
Title: '.sign()'
3+
Description: 'Returns a tensor with the sign of each element, indicating whether it is negative, zero, or positive.'
4+
Subjects:
5+
- 'Computer Science'
6+
- 'Data Science'
7+
Tags:
8+
- 'Deep Learning'
9+
- 'Methods'
10+
- 'Programming'
11+
- 'PyTorch'
12+
CatalogContent:
13+
- 'intro-to-py-torch-and-neural-networks'
14+
- 'paths/data-science'
15+
---
16+
17+
The **`.sign()`** method in PyTorch returns a new [tensor](https://www.codecademy.com/resources/docs/pytorch/tensors) with the sign of each element from the input tensor. It returns -1 for negative values, 0 for zero, and 1 for positive values. This method is commonly used in gradient-based optimization, activation functions, and mathematical operations where the direction or polarity of values matters.
18+
19+
## Syntax
20+
21+
```pseudo
22+
torch.sign(input, *, out=None)
23+
```
24+
25+
**Parameters:**
26+
27+
- `input` (Tensor): The input tensor whose signs are to be computed.
28+
- `out` (optional): A tensor to store the output. Must have the same shape as `input`.
29+
30+
**Return value:**
31+
32+
The `.sign()` method returns a new tensor containing the sign of each element in the `input` tensor. Unless the `out` parameter is specified, the result is a new tensor.
33+
34+
## Example
35+
36+
This example demonstrates how to use the `.sign()` method on a tensor containing positive, negative, and zero values:
37+
38+
```py
39+
import torch
40+
41+
# Create a tensor with mixed values
42+
x = torch.tensor([1.5, -2.3, 0.0, 3.7, -0.5])
43+
44+
# Compute the sign of each element
45+
y = torch.sign(x)
46+
47+
print(f"Original tensor: {x}")
48+
print(f"Sign tensor: {y}")
49+
```
50+
51+
This example results in the following output:
52+
53+
```shell
54+
Original tensor: tensor([ 1.5000, -2.3000, 0.0000, 3.7000, -0.5000])
55+
Sign tensor: tensor([ 1., -1., 0., 1., -1.])
56+
```
57+
58+
In this example:
59+
60+
- Positive values (1.5, 3.7) return 1.
61+
- Negative values (-2.3, -0.5) return -1.
62+
- Zero (0.0) returns 0.

0 commit comments

Comments
 (0)