PyTorch .full()

Anonymous contributor's avatar
Anonymous contributor
Published Oct 16, 2024
Contribute to Docs

The .full() function creates a tensor of a specified shape, filled with a constant value. This function is particularly useful in machine learning and data science for efficiently managing tensors, as it allows the creation of tensors with predefined values. Additionally, it accepts several parameters that allow users to specify the shape, fill value, and other optional attributes like data type and device allocation.

  • Learn how to use PyTorch to build, train, and test artificial neural networks in this course.
    • Intermediate.
      3 hours
  • Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
    • With Certificate
    • Beginner Friendly.
      24 hours

Syntax

torch.full(size, fill_value, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False)
  • size: A list or tuple that specifies the desired shape of the output tensor.
  • fill_value: A scalar value that fills the tensor.
  • out (optional): An existing tensor where the result will be stored, it must have the same shape as the output.
  • dtype (optional): The desired data type of the output tensor.
  • layout (optional): Desired layout of the returned tensor. Default value is torch.strided.
  • device (optional): The device on which the tensor is to be allocated.
  • requires_grad (optional): A boolean value that indicates whether to track the operations on the tensor for gradient computation. By default this is False.

Example

The below example code creates a 2x3 tensor where all elements are set to 5:

import torch
# Create a 2x3 tensor filled with the value 5
tensor = torch.full((2, 3), 5)
print(tensor)

The code above produces the following output:

tensor([[5, 5, 5],
[5, 5, 5]])

All contributors

Contribute to Docs

Learn PyTorch on Codecademy

  • Learn how to use PyTorch to build, train, and test artificial neural networks in this course.
    • Intermediate.
      3 hours
  • Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
    • With Certificate
    • Beginner Friendly.
      24 hours