How to perform element-wise subtraction on tensors in PyTorch?

How to perform element-wise subtraction on tensors in PyTorch?

In PyTorch, performing element-wise subtraction between tensors is straightforward and can be done using the - operator or the torch.sub() function. Here's a guide on how to do it:

Example: Element-wise Subtraction of Tensors

First, ensure you have PyTorch installed. If not, you can install it using pip:

pip install torch 

Now, let's create two tensors and perform element-wise subtraction:

Import PyTorch

import torch 

Create Tensors

# Example tensors tensor_a = torch.tensor([1, 2, 3, 4]) tensor_b = torch.tensor([4, 3, 2, 1]) 

Subtract Tensors

You can subtract tensors either directly using the - operator or by using the torch.sub() function.

Using the - Operator
result = tensor_a - tensor_b print(result) 
Using torch.sub()
result = torch.sub(tensor_a, tensor_b) print(result) 

Both methods will produce the same result:

tensor([-3, -1, 1, 3]) 

Notes

  • The tensors tensor_a and tensor_b should be of the same size or compatible sizes for broadcasting. PyTorch will throw an error if the tensors cannot be broadcasted to a common shape.
  • Broadcasting allows PyTorch to perform operations on tensors of different shapes in a way that makes them compatible. For instance, a scalar can be subtracted from a tensor, or a tensor of shape (n,) can be subtracted from a tensor of shape (m, n).

Example with Broadcasting

If you have tensors of different shapes, PyTorch can automatically apply broadcasting if the shapes are compatible:

tensor_c = torch.tensor([1, 2, 3]) tensor_d = torch.tensor([[1], [2], [3]]) result = tensor_c - tensor_d print(result) 

In this case, tensor_d is expanded to match the shape of tensor_c, resulting in a 2D tensor subtraction.

The output will be:

tensor([[ 0, 1, 2], [-1, 0, 1], [-2, -1, 0]]) 

This demonstrates the flexibility and power of PyTorch's broadcasting capabilities in tensor operations.


More Tags

xvfb dinktopdf information-extraction mapfragment zend-framework2 code-snippets rhel uniqueidentifier product ios-app-extension

More Programming Guides

Other Guides

More Programming Examples