Convert signed features to magnitudes
Data preprocessing
PyTorch · Function
Computes the absolute value of every element in a tensor and returns the resulting tensor. An optional output tensor can receive the result.
torch.abs applies the absolute-value operation independently to every element of the input tensor and returns the resulting tensor. You can optionally provide an out tensor to receive the result.
torch.abs(input: Tensor, *, out: Tensor | None = None) → Tensor| Name | Type | Description |
|---|---|---|
input | Tensor | Input tensor whose elements are transformed. |
out | Tensor | None | Optional output tensor that receives the result. |
A Tensor containing the elementwise absolute values of input.
import torch
x = torch.tensor([-1.0, 0.0, 2.5])
y = torch.abs(x)
print(y) # tensor([1.0000, 0.0000, 2.5000])Creates a tensor containing negative, zero, and positive values, then returns their elementwise absolute values.
Data preprocessing
Loss and metric preparation
Complex-valued tensors
torch.abs computes the absolute value of every element in a Tensor and returns a Tensor containing those results. For an element input_i, the result is |input_i|.
Follow-up: How would you apply the same operation to several tensors efficiently? Use torch.foreach.abs or the corresponding foreach operation, which applies torch.abs independently at each list position.
The input parameter is a Tensor, and the function accepts an optional keyword-only out Tensor. The returned value is the resulting Tensor.
Follow-up: What is the in-place alternative? torch.abs_ is the in-place version of torch.abs and modifies the input rather than producing a separate result.
For torch.tensor([-1, -2, 3]), torch.abs returns tensor([1, 2, 3]). The operation is pointwise, so tensor shape and element positions are preserved.
Follow-up: Is there an alias? Yes. torch.absolute is documented as an alias for torch.abs.
torch.absolutetorch.abs_torch.foreach.abs