YouTip LogoYouTip

Pytorch Torch Neg

## PyTorch torch.neg() Function The `torch.neg()` function in PyTorch is used to perform element-wise negation on an input tensor. It multiplies every element in the input tensor by $-1$, effectively flipping the sign of each numerical value. --- ### Function Definition ```python torch.neg(input, *, out=None) -> Tensor ``` Alternatively, you can use the alias `torch.negative()` or the in-place version `torch.neg_()`. ### Parameters | Parameter | Type | Description | | :--- | :--- | :--- | | `input` | Tensor | The input tensor containing the numerical values to be negated. | | `out` | Tensor (Optional) | The output tensor where the result will be written. Defaults to `None`. | ### Return Value * Returns a new tensor with the same shape and data type as `input`, where each element has its sign inverted. --- ## Usage Examples ### Example 1: Basic Element-Wise Negation This example demonstrates how to negate a 1D tensor containing positive floating-point numbers. ```python import torch # Create a 1D tensor x = torch.tensor([1.0, 2.0, 3.0]) # Perform element-wise negation result = torch.neg(x) print("Original Tensor:") print(x) print("\nNegated Tensor:") print(result) ``` **Output:** ```text Original Tensor: tensor([1., 2., 3.]) Negated Tensor: tensor([-1., -2., -3.]) ``` --- ### Example 2: Handling Mixed Signs and Zero `torch.neg()` correctly handles positive numbers, negative numbers, and zero. ```python import torch # Create a tensor with positive, negative, and zero values x = torch.tensor([-5, 0, 12], dtype=torch.int32) # Negate the tensor result = torch.neg(x) print("Original Tensor:", x) print("Negated Tensor: ", result) ``` **Output:** ```text Original Tensor: tensor([-5, 0, 12], dtype=torch.int32) Negated Tensor: tensor([ 5, 0, -12], dtype=torch.int32) ``` --- ### Example 3: In-Place Negation (`neg_`) and Operator Alias If you want to modify the tensor in-place without allocating new memory, you can use `neg_()`. You can also use the unary minus operator `-` as a shorthand. ```python import torch x = torch.tensor([[1.0, -2.0], [3.0, -4.0]]) # Method 1: Using the unary minus operator neg_operator = -x # Method 2: In-place negation x.neg_() print("Negated using operator (-x):") print(neg_operator) print("\nOriginal tensor modified in-place (x.neg_()):") print(x) ``` **Output:** ```text Negated using operator (-x): tensor([[-1., 2.], [-3., 4.]]) Original tensor modified in-place (x.neg_()): tensor([[-1., 2.], [-3., 4.]]) ``` --- ## Considerations 1. **Data Types**: `torch.neg()` supports integer, floating-point, and complex data types. For complex numbers, it negates both the real and imaginary parts. 2. **Boolean Tensors**: Attempting to use `torch.neg()` on a boolean (`torch.bool`) tensor is not supported in newer PyTorch versions and will raise a `RuntimeError`. For logical negation, use `torch.logical_not()` or the bitwise NOT operator `~` instead. 3. **Memory Efficiency**: For large tensors, using the in-place variant `input.neg_()` helps optimize memory usage by avoiding the allocation of a new tensor.
← Pytorch Torch NextafterPytorch Torch Narrow_Copy β†’