Pytorch Torch Subtract
## PyTorch: torch.subtract
`torch.subtract` is a PyTorch function used to perform element-wise subtraction on tensors. It is fully alias-compatible and identical in functionality to `torch.sub`.
---
### Function Definition
```python
torch.subtract(input, other, *, alpha=1, out=None) -> Tensor
```
### Parameters
* **`input` (Tensor)**: The input tensor (the minuend).
* **`other` (Tensor or Scalar)**: The tensor or scalar value to be subtracted from `input` (the subtrahend).
* **`alpha` (Scalar, optional)**: A scaling factor for `other`. The operation performed is $\text{input} - \text{alpha} \times \text{other}$. The default value is `1`.
* **`out` (Tensor, optional)**: The output tensor where the result will be stored.
---
## Usage Examples
### 1. Basic Element-Wise Subtraction
Subtract one 1D tensor from another of the same shape.
```python
import torch
# Define two 1D tensors
x = torch.tensor([5.0, 6.0, 7.0])
y = torch.tensor([1.0, 2.0, 3.0])
# Perform element-wise subtraction
result = torch.subtract(x, y)
print("Result of subtraction:")
print(result)
# Output: tensor([4., 4., 4.])
```
### 2. Subtraction with a Scalar
Subtract a constant scalar value from all elements of a tensor.
```python
import torch
x = torch.tensor([[10.0, 20.0], [30.0, 40.0]])
# Subtract a scalar value of 5
result = torch.subtract(x, 5)
print("Result of subtracting a scalar:")
print(result)
# Output:
# tensor([[ 5., 15.],
# [25., 35.]])
```
### 3. Using the `alpha` Parameter
Multiply the subtrahend (`other`) by a multiplier (`alpha`) before performing the subtraction.
```python
import torch
x = torch.tensor([10.0, 20.0, 30.0])
y = torch.tensor([1.0, 2.0, 3.0])
# Computes: x - 2 * y
result = torch.subtract(x, y, alpha=2)
print("Result with alpha=2:")
print(result)
# Output: tensor([ 8., 16., 24.])
```
### 4. Broad-casting Subtraction
PyTorch supports broadcasting when the shapes of the two tensors are different but compatible.
```python
import torch
# Shape (2, 3)
x = torch.tensor([[10, 20, 30],
[40, 50, 60]])
# Shape (1, 3)
y = torch.tensor([[1, 2, 3]])
# y is broadcasted to match the shape of x
result = torch.subtract(x, y)
print("Result of broadcasting subtraction:")
print(result)
# Output:
# tensor([[ 9, 18, 27],
# [39, 48, 57]])
```
---
## Key Considerations
1. **In-place Subtraction**: If you want to perform the subtraction in-place (modifying the original tensor directly to save memory), use `input.subtract_(other)` or `input.sub_(other)`.
2. **Data Type Promotion**: If `input` and `other` have different data types (e.g., `float32` and `int64`), PyTorch will automatically promote the resulting tensor to a common, more precise data type.
3. **Alias**: `torch.subtract` is a direct alias for `torch.sub`. Both can be used interchangeably depending on your preference for code readability.
YouTip