Pytorch Torch Add
# PyTorch torch.add Function
* * Pytorch torch reference manual](#)
`torch.add` is a function in PyTorch used to perform element-wise addition. It adds two tensors or a tensor and a scalar.
This is one of the most basic mathematical operations, which will be used in various computational scenarios in deep learning.
### Function Definition
torch.add(input, other, alpha=1, out=None)
**Parameters**:
* `input` (Tensor): The first input tensor.
* `other` (Tensor or float): The second input tensor or scalar.
* `alpha` (float, optional): Scaling factor; `other` will be multiplied by this value before being added to `input`, default is 1.
* `out` (Tensor, optional): Output tensor.
**Return Value**:
* `torch.Tensor`: Returns the tensor after addition.
* * *
## Usage Examples
### Example 1: Adding Two Tensors
## Instance
import torch
# Create two tensors
a = torch.tensor([1,2,3])
b = torch.tensor([4,5,6])
# Add them together
c = torch.add(a, b)
print(c)
Output result:
tensor([5, 7, 9])
### Example 2: Tensor Plus Scalar
## Instance
import torch
# Create a tensor
a = torch.tensor([1,2,3])
# Add scalar
b = torch.add(a,10)
print(b)
Output result:
tensor([11, 12, 13])
### Example 3: Using the alpha Parameter
## Instance
import torch
# Create two tensors
a = torch.tensor([1.0,2.0,3.0])
b = torch.tensor([1.0,2.0,3.0])
# Calculate a + 2 * b
c = torch.add(a, b, alpha=2)
print(c)
Output result:
tensor([3., 6., 9.])
The `alpha` parameter is useful when implementing certain algorithms, such as computing `input + alpha * other`.
### Example 4: Broadcasting Mechanism
## Instance
import torch
# Add tensors of different shapes (broadcasting)
a = torch.tensor([[1,2,3],[4,5,6]])
b = torch.tensor([1,2,3])
c = torch.add(a, b)
print(c)
Output result:
tensor([[2, 4, 6], [5, 7, 9]])
PyTorch supports broadcasting mechanism, allowing operations on tensors of different shapes.
* * *
## Using the Plus Operator
Besides using the `torch.add()` function, you can also directly use the `+` operator, both have the same effect:
## Instance
import torch
a = torch.tensor([1,2,3])
b = torch.tensor([4,5,6])
# Both methods are equivalent
c1 = torch.add(a, b)
c2 = a + b
print(c1)
print(c2)
print(torch.equal(c1, c2))
* * Pytorch torch reference manual](#)
YouTip