How To Multiply PyTorch Tensors?

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

Objective: How To Multiply PyTorch Tensors?

This PyTorch code example will teach you to perform PyTorch multiply tensors as matrices using the ‘torch.matmul()’ function.

How To Multiply PyTorch Tensors?

You can multiply PyTorch tensors using the torch.matmul() function. This function takes two tensors as input and returns a new tensor that is the product of the two matrices. The input tensors must have compatible dimensions for the operation to succeed.

What Are Some Possible Cases of ‘PyTorch Multiply Tensors’?

There are various cases available for PyTorch tensor multiplication, which are as follows-

  • The dot product is returned if both the tensors are 1 dimensional.

  • The matrix product is returned if both the tensors are 2 dimensional.

  • If the first one is 1-dimensional and the second one is 2 - 2-dimensional, it means that 1 is prepended to its dimension for the purpose of the matrix multiplication, and after multiplication, the prepended dimension is removed.

  • The matrix-vector multiplication is returned when the first tensor is 2-dimensional and the second is 1-dimensional.

Steps Showing How To Multiply Two Tensors Together PyTorch

The following steps will show you how to multiply two PyTorch tensors using the torch.sum() function, which will return the matrix multiplications of the input tensors.

Step 1 - Import Library To Multiply Tensors PyTorch

First, you must import the required libraries.

import torch

Step 2 - Take Sample Tensors

The next step is to take any sample tensors.

tensor_1 = torch.tensor([[4],[8],[9]])
tensor_2 = torch.tensor([8])

Step 3 - Pytorch Multiply Tensors in One Dimension

The final step is to multiply two tensors PyTorch using the torch.matmul() function.

multi = torch.matmul(tensor_1, tensor_2)
print("Output of matrix multiplication is:",multi)

The output of the above code is-

Output of matrix multiplication is: tensor([32, 64, 72])

How To Perform PyTorch Multiply Tensors Elementwise?

PyTorch elementwise multiplication is a way to multiply the corresponding elements of two tensors together. You can perform elementwise multiplication in PyTorch using the torch.mul() function. This function takes two tensors as input and returns a new tensor with the corresponding elements multiplied together.

import torch

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

b = torch.tensor([4, 5, 6])

# Elementwise multiplication

c = torch.mul(a, b)

print(c)

The output of the above code is-

tensor([4, 10, 18])

How To Multiply 3D Tensors PyTorch?

The following code shows how to multiply two 3D tensors with the dimensions (batch_size, height, width)-

import torch

a = torch.tensor([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])

b = torch.tensor([[[10, 11, 12]], [[13, 14, 15]]])

# Matrix multiplication

c = torch.matmul(a, b)

print(c)

The output of the above code is-

tensor([[[140, 162, 184]], [[294, 330, 366]]])

How To Multiply Broadcast Two Tensors PyTorch?

In PyTorch, you can multiply tensors of different shapes using broadcasting. Broadcasting allows PyTorch to automatically expand smaller tensors to match the shape of larger tensors for element-wise operations.

Suppose you have two tensors, tensor1, and tensor2, and you want to multiply them element-wise-

import torch

# Create two tensors

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

tensor2 = torch.tensor([5])

# Multiply the tensors using broadcasting

result = tensor1 * tensor2

print(result)

The output of the above code will be-

[10, 15, 20]

Multiply PyTorch Tensors Like A Breeze With ProjectPro

This comprehensive PyTorch code tutorial has given you a solid understanding of performing element-wise multiplication between PyTorch tensors, including concepts like 3D tensors multiplication and broadcasting. Mastering these fundamental tensor operations is crucial for data manipulation and feature engineering in machine learning and data science projects. You can further deepen your knowledge and leverage PyTorch's capabilities for building real-world data science and machine learning solutions with ProjectPro. The PyTorch projects in the ProjectPro repository offer hands-on learning and expert guidance, helping you gain practical experience and proficiency in using PyTorch for solving complex data science challenges.

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 Speech-Text Transcriptor with Nvidia Quartznet Model
In this Deep Learning Project, you will leverage transfer learning from Nvidia QuartzNet pre-trained models to develop a speech-to-text transcriptor.

Customer Market Basket Analysis using Apriori and Fpgrowth algorithms
In this data science project, you will learn how to perform market basket analysis with the application of Apriori and FP growth algorithms based on the concept of association rule learning.

Build a Multi-Class Classification Model in Python on Saturn Cloud
In this machine learning classification project, you will build a multi-class classification model in Python on Saturn Cloud to predict the license status of a business.

Build a Collaborative Filtering Recommender System in Python
Use the Amazon Reviews/Ratings dataset of 2 Million records to build a recommender system using memory-based collaborative filtering in Python.

Hands-On Approach to Master PyTorch Tensors with Examples
In this deep learning project, you will learn how to perform various operations on the building block of PyTorch : Tensors.

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.

Learn How to Build PyTorch Neural Networks from Scratch
In this deep learning project, you will learn how to build PyTorch neural networks from scratch.

Build a Face Recognition System in Python using FaceNet
In this deep learning project, you will build your own face recognition system in Python using OpenCV and FaceNet by extracting features from an image of a person's face.

Build Piecewise and Spline Regression Models in Python
In this Regression Project, you will learn how to build a piecewise and spline regression model from scratch in Python to predict the points scored by a sports team.

Deep Learning Project for Text Detection in Images using Python
CV2 Text Detection Code for Images using Python -Build a CRNN deep learning model to predict the single-line text in a given image.