How To Subtract PyTorch Tensors?

This beginner-friendly Pytorch code shows you how to subtract PyTorch tensors using the torch.sub() function.

Objective: How To Subtract PyTorch Tensors?

This PyTorch code example will teach you to perform PyTorch subtract two tensors using the ‘torch.sub()’ function. 

How To Subtract Tensors PyTorch?

You can subtract tensors in PyTorch using the torch.sub() method. This method takes two torch tensors as input and returns a new tensor with the result of the subtraction.

Syntax for torch.sub() function-

torch.sub(input, other, *, alpha=1, out=None) → Tensor

Here,

  • input - it is the input tensor.

  • other - it can be a tensor or a scalar, which will be subtracted from the input.

  • alpha - it is the scalar multiplier for others.

  • out - it is the output tensor, which is optional.

Steps Showing How To Subtract Two Tensors in PyTorch

The following steps will show you how to subtract two PyTorch tensors using the torch.sub() function that will return the difference between the two input tensors.

Step 1 - Import Library To Subtract Tensors PyTorch

First, you must import the required libraries.

import torch

Get Closer To Your Dream of Becoming a Data Scientist with Solved End-to-End PyTorch Projects

Step 2 - Take Sample Tensors

The next step is to take any sample tensors for subtraction.

tensor_1 = torch.tensor((56,78))

tensor_2 = torch.tensor((40, 31))

Step 3 - Subtract Two Tensors PyTorch

The final step is to subtract 2 tensors PyTorch using the torch.sub() function.

subtract = torch.sub(tensor_1, tensor_2, alpha=1)

print("This is the output for substraction:",subtract)

The output of the above code is-

This is the output for substraction: tensor([16, 47])

How To Subtract PyTorch Tensors With Different Shapes?

If you subtract PyTorch tensors with different shapes, broadcasting will be applied to ensure they have the same shape before the subtraction. Broadcasting means that the smaller tensor is expanded to have the same shape as the larger tensor by repeating its elements along the dimensions where it is smaller.

For example, if you subtract a 1D tensor from a 2D tensor, the 1D tensor will be expanded to have the same number of rows as the 2D tensor.

tensor1 = torch.tensor([1, 2, 3])

tensor2 = torch.tensor([[4, 5, 6], [7, 8, 9]])

# Broadcast the tensors to the same shape

tensor1 = torch.broadcast(tensor1, tensor2.shape)

# Subtract the tensors

subtracted_tensor = tensor1 - tensor2

print(subtracted_tensor)

The output of the above code is-

tensor([[3, 3, 3], [4, 4, 4]])

Learn How To Subtract Pytorch Tensors Like A Pro With ProjectPro

This step-by-step PyTorch code example has helped you gain a solid foundation in performing tensor subtraction with PyTorch, addressing the subtraction of tensors with matching shapes and those with differing shapes through broadcasting. Understanding these fundamental operations is essential for data preprocessing and model development in data science and machine learning. Furthermore, if you want to expand your proficiency in PyTorch and apply it to real-world data science and machine learning solutions, you must explore the ProjectPro platform. By engaging with over 270 end-to-end solved projects in the ProjectPro repository, you can gain the skills and expertise needed to excel in data science and machine learning.

What Users are saying..

profile image

Savvy Sahai

Data Science Intern, Capgemini
linkedin profile url

As a student looking to break into the field of data engineering and data science, one can get really confused as to which path to take. Very few ways to do it are Google, YouTube, etc. I was one of... Read More

Relevant Projects

Build a Churn Prediction Model using Ensemble Learning
Learn how to build ensemble machine learning models like Random Forest, Adaboost, and Gradient Boosting for Customer Churn Prediction using Python

Stock Price Prediction Project using LSTM and RNN
Learn how to predict stock prices using RNN and LSTM models. Understand deep learning concepts and apply them to real-world financial data for accurate forecasting.

Build CNN Image Classification Models for Real Time Prediction
Image Classification Project to build a CNN model in Python that can classify images into social security cards, driving licenses, and other key identity information.

Forecasting Business KPI's with Tensorflow and Python
In this machine learning project, you will use the video clip of an IPL match played between CSK and RCB to forecast key performance indicators like the number of appearances of a brand logo, the frames, and the shortest and longest area percentage in the video.

Build Time Series Models for Gaussian Processes in Python
Time Series Project - A hands-on approach to Gaussian Processes for Time Series Modelling in Python

Build a Text Generator Model using Amazon SageMaker
In this Deep Learning Project, you will train a Text Generator Model on Amazon Reviews Dataset using LSTM Algorithm in PyTorch and deploy it on Amazon SageMaker.

Build Deep Autoencoders Model for Anomaly Detection in Python
In this deep learning project , you will build and deploy a deep autoencoders model using Flask.

PyTorch Project to Build a LSTM Text Classification Model
In this PyTorch Project you will learn how to build an LSTM Text Classification model for Classifying the Reviews of an App .

NLP Project to Build a Resume Parser in Python using Spacy
Use the popular Spacy NLP python library for OCR and text classification to build a Resume Parser in Python.

Linear Regression Model Project in Python for Beginners Part 2
Machine Learning Linear Regression Project for Beginners in Python to Build a Multiple Linear Regression Model on Soccer Player Dataset.