How To Unsqueeze A Torch Tensor?

This beginner-friendly Pytorch code shows you how to unsqueeze a torch tensor using the torch.unsqueeze() function.

Objective: How To Unsqueeze A Torch Tensor?

This PyTorch code example will teach you how to unsqueeze a torch tensor using the ‘torch.unsqueeze()’ function for a PyTorch tensor. 

How To Unsqueeze A Torch Tensor?

You can unsqueeze a torch tensor using the torch.unsqueeze() function, which will return a new tensor with a dimension of size one inserted at the specified position, and the returned tensor shares the same underlying data with this tensor. 

The syntax for the torch.unsqueeze() is-

torch.unsqueeze(input, dim)

where,

  • input - This is the input tensor.

  • dim - This is the index where you need the singleton dimension to be inserted.

How Do torch.unsqueeze() And torch.squeeze() Differ?

The difference between torch.unsqueeze() and torch.squeeze() is that torch.unsqueeze() adds a new dimension of size 1 to a tensor at the specified position, whereas torch.squeeze() removes dimensions of size 1 from a tensor.

When Do You Unsqueeze A Torch Tensor?

Unsqueezing can be done for several purposes, such as-

  • Preparing tensors for certain operations, such as broadcasting and matrix multiplication.

  • Changing the shape of tensors to match the required input shape of a model.

  • Adding dummy dimensions to tensors to make them compatible with other tensors or operations.

Steps Showing How To Unsqueeze A Torch Tensor

The following steps will show you how to unsqueeze a torch tensor using the torch.unsqueeze() function in an easy-to-understand PyTorch tensor example.

Step 1 - Import Library

First, you must import the required libraries.

import torch

Step 2 - Take Sample Data

The next step is to take sample data for your example.

Sample_data = torch.tensor([12, 13, 14, 15])

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

Step 3 - Unsqueeze The Torch Tensor

As shown in the code below, you must use the torch.unsqueeze() method to unsqueeze the tensor at dimension 0 and dimension 1, respectively. The results will be stored in the variables unsqueeze and unsqueeze_2.

unsqueeze = torch.unsqueeze(Sample_data, 0)

unsqueeze_2 = torch.unsqueeze(Sample_data, 1)

print("This is the unsqueeze data with dimension 0:","\n",unsqueeze, "\n")

print("-----------------------------------------------------------------")

print("This is the unsqueeze data with dimension 1:","\n",unsqueeze_2)

The output of the above code is-

This is the unsqueeze data with dimension 0: 

 tensor([[12, 13, 14, 15]]) 

-----------------------------------------------------------------

This is the unsqueeze data with dimension 1: 

 tensor([[12],

        [13],

        [14],

        [15]])

Learn How To Unsqueeze Torch Tensor With ProjectPro

This PyTorch code example is a comprehensive guide on unsqueezing a torch tensor, which is crucial for reshaping tensors for different mathematical operations or model requirements. We have covered the steps for effectively unsqueezing tensors along specific dimensions to expand their shape. You can further deepen your PyTorch expertise and apply it to real-world data science and machine learning projects by exploring PyTorch projects offered by ProjectPro. By engaging in these enterprise-grade projects from the ProjectPro repository, you can build the skills and confidence needed to excel in data science and machine learning.

What Users are saying..

profile image

Ed Godalle

Director Data Analytics at EY / EY Tech
linkedin profile url

I am the Director of Data Analytics with over 10+ years of IT experience. I have a background in SQL, Python, and Big Data working with Accenture, IBM, and Infosys. I am looking to enhance my skills... Read More

Relevant Projects

Loan Default Prediction Project using Explainable AI ML Models
Loan Default Prediction Project that employs sophisticated machine learning models, such as XGBoost and Random Forest and delves deep into the realm of Explainable AI, ensuring every prediction is transparent and understandable.

NLP Project for Beginners on Text Processing and Classification
This Project Explains the Basic Text Preprocessing and How to Build a Classification Model in Python

End-to-End ML Model Monitoring using Airflow and Docker
In this MLOps Project, you will learn to build an end to end pipeline to monitor any changes in the predictive power of model or degradation of data.

Learn Hyperparameter Tuning for Neural Networks with PyTorch
In this Deep Learning Project, you will learn how to optimally tune the hyperparameters (learning rate, epochs, dropout, early stopping) of a neural network model in PyTorch to improve model performance.

LLM Project to Build and Fine Tune a Large Language Model
In this LLM project for beginners, you will learn to build a knowledge-grounded chatbot using LLM's and learn how to fine tune it.

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 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.

CycleGAN Implementation for Image-To-Image Translation
In this GAN Deep Learning Project, you will learn how to build an image to image translation model in PyTorch with Cycle GAN.

Build CI/CD Pipeline for Machine Learning Projects using Jenkins
In this project, you will learn how to create a CI/CD pipeline for a search engine application using Jenkins.

Learn Object Tracking (SOT, MOT) using OpenCV and Python
Get Started with Object Tracking using OpenCV and Python - Learn to implement Multiple Instance Learning Tracker (MIL) algorithm, Generic Object Tracking Using Regression Networks Tracker (GOTURN) algorithm, Kernelized Correlation Filters Tracker (KCF) algorithm, Tracking, Learning, Detection Tracker (TLD) algorithm for single and multiple object tracking from various video clips.