What Does Torch Full Do?

This beginner-friendly Pytorch code shows you how to implement the torch.full() function

Objective: What Does Torch Full Do?

This PyTorch code example will teach you to use the ‘torch.full()’ function for a PyTorch tensor. 

What Does PyTorch Torch.Full() Do?

The torch.full() function in PyTorch returns a tensor ‘size’ of a given size filled with the given value ‘fill_value’. The torch.full() is a useful function for initializing tensors with specific values. For example, you can use it to initialize a tensor of weights for a neural network or to initialize a tensor of zeros to use as a mask.

The syntax for the torch.full() function is-

torch.full(size, fill_value, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False)

There are various parameters in the above syntax, which are as follows-

  • size - This will define the shape of the output tensor, which can be a list, tuple, or tensor.size of the integers.

  • fill_value - This is the value that is to be filled the output tensor with.

  • out - This is the output tensor.

  • dtype(torch.dtype) - It is the desired data type of the returned tensor. By default, if None, then uses a global default.

  • layout (torch.layout) - The desired layout of the returned tensor by default, which is torch.strided.

  • device(torch.device) - The desired device of the returned tensor. By default, if the value is None, then it uses the current device for the default tensor type (see torch.set_default_tensor_type()). device will be the CPU for CPU tensor types and the current CUDA device for CUDA tensor types.

  • requires_grad - If autograd should record operations on the returned tensor. By default, it is False.

Steps Showing How To Use PyTorch Tensor.Full()

The following steps will show you how to use the torch.full() function to disable the gradient calculation in an easy-to-understand PyTorch tensor example.

Step 1 - Import Library For Using torch.full()

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 - Using ‘torch.full()’ in PyTorch

As shown in the code below, you will create a tensor called task_torch using the torch.full() function. The torch.full() function creates a tensor of size 4x4 filled with the specified value 1.5678.

task_torch = torch.full((4,4), 1.5678)

print("This is the output of following task:","\n",task_torch)

The output of the above code is-

tensor([[1.5678, 1.5678, 1.5678, 1.5678],

        [1.5678, 1.5678, 1.5678, 1.5678],

        [1.5678, 1.5678, 1.5678, 1.5678],

        [1.5678, 1.5678, 1.5678, 1.5678]])

How To Use Torch.Full() To Filter Out Tensor Elements?

You can use the torch.full() function to create a mask to filter out elements of a tensor. For example, you can create a mask to filter out elements of a tensor that are less than 0, as shown in the below code-

import torch

# Create a tensor with random values

tensor = torch.randn(10)

# Create a mask to filter out elements of the tensor that are less than 0

mask = torch.full(tensor.size(), False)

mask[tensor >= 0] = True

# Apply the mask to the tensor

filtered_tensor = tensor[mask]

Explore The Real-World Implementations of Torch.Full() With ProjectPro

This PyTorch code example helps you gain a solid understanding of the torch.full() function in PyTorch, which is useful for creating tensors with constant values. We have explored how to use it to generate tensors of specified shapes and how to apply it to filter or mask out elements in existing tensors efficiently. 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

Anand Kumpatla

Sr Data Scientist @ Doubleslash Software Solutions Pvt Ltd
linkedin profile url

ProjectPro is a unique platform and helps many people in the industry to solve real-life problems with a step-by-step walkthrough of projects. A platform with some fantastic resources to gain... Read More

Relevant Projects

Ola Bike Rides Request Demand Forecast
Given big data at taxi service (ride-hailing) i.e. OLA, you will learn multi-step time series forecasting and clustering with Mini-Batch K-means Algorithm on geospatial data to predict future ride requests for a particular region at a given time.

Build OCR from Scratch Python using YOLO and Tesseract
In this deep learning project, you will learn how to build your custom OCR (optical character recognition) from scratch by using Google Tesseract and YOLO to read the text from any images.

Learn to Build a Neural network from Scratch using NumPy
In this deep learning project, you will learn to build a neural network from scratch using NumPy

Text Classification with Transformers-RoBERTa and XLNet Model
In this machine learning project, you will learn how to load, fine tune and evaluate various transformer models for text classification tasks.

Avocado Machine Learning Project Python for Price Prediction
In this ML Project, you will use the Avocado dataset to build a machine learning model to predict the average price of avocado which is continuous in nature based on region and varieties of avocado.

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.

NLP Project on LDA Topic Modelling Python using RACE Dataset
Use the RACE dataset to extract a dominant topic from each document and perform LDA topic modeling in python.

Build a Multi Touch Attribution Machine Learning Model in Python
Identifying the ROI on marketing campaigns is an essential KPI for any business. In this ML project, you will learn to build a Multi Touch Attribution Model in Python to identify the ROI of various marketing efforts and their impact on conversions or sales..

MLOps AWS Project on Topic Modeling using Gunicorn Flask
In this project we will see the end-to-end machine learning development process to design, build and manage reproducible, testable, and evolvable machine learning models by using AWS

Credit Card Default Prediction using Machine learning techniques
In this data science project, you will predict borrowers chance of defaulting on credit loans by building a credit score prediction model.