Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Term Entry] PyTorch Tensor Operations: .abs() #6278

Merged
merged 8 commits into from
Mar 8, 2025
Prev Previous commit
Next Next commit
Add entry for abs tensor operation
  • Loading branch information
karishma-battina committed Mar 5, 2025
commit bd562d0936cf64b414f6d9cc033b65df373ceb1a
31 changes: 29 additions & 2 deletions content/pytorch/concepts/tensor-operations/terms/abs/abs.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
---
Title: '.abs()'
Description: 'Computes the adjoint of a 2D complex-valued tensor in PyTorch.'
Description: 'Computes the absolute value of each element in a PyTorch tensor. For complex numbers, returns their magnitude.'
Subjects:
- 'Computer Science'
- 'Data Science'
Expand All @@ -13,22 +13,49 @@ CatalogContent:
- 'paths/data-science'
---

The **`.abs()`** method in PyTorch
The **`.abs()`** method in PyTorch calculates the absolute value (magnitude) of each element in a tensor. For real numbers, this returns their non-negative value. For complex numbers, it computes the magnitude using the formula √(real² + imag²). This operation is widely used in data preprocessing, signal processing, and mathematical transformations.

## Syntax

```pseudo
tensor.abs()
```

The `.abs()` method returns a tensor where each element is the absolute value of the corresponding element in the input tensor.

## Example

This example shows how to use .abs() to compute absolute values for both real and complex tensors:

```py
import torch

# Define a tensor with real and complex numbers
tensor = torch.tensor([[-3.0, 2.5], [1 - 2j, 3 + 4j]])

# Compute absolute values
abs_tensor = tensor.abs()

print("Original Tensor:")
print(tensor)

print("\nAbsolute Values:")
print(abs_tensor)
```

This example results in the following output:

```shell
Original Tensor:
tensor([[-3.0000+0.j, 2.5000+0.j],
[1.0000-2.j, 3.0000+4.j]])

Absolute Values:
tensor([[3.0000, 2.5000],
[2.2361, 5.0000]])
```

In this example:

- **Real numbers**: -3.0 becomes 3.0, 2.5 remains 2.5.
- **Complex numbers**: 1 - 2j → √(1² + (-2)²) ≈ 2.2361; 3 + 4j → √(3² + 4²) = 5.0