PyTorch torch.full() Method

PytTorch torch.full() method is “used to create a tensor of size ‘size’ filled with fill_value”. The tensor’s dtype is inferred from fill_value.

Syntax

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

Parameters

  1. size (int…): It is a list, tuple, or torch.Size of integers defining the shape of the output tensor.
  2. fill_value (Scalar): The value to fill the output tensor with.
  3. out (Tensor, optional): It is the output tensor.
  4. dtype (torch.dtype, optional): It is the desired data type of the returned tensor.
  5. layout (torch.layout, optional): It is the desired layout of returned Tensor. Default: torch.strided.
  6. device (torch.device, optional): The desired device of the returned tensor.
  7. requires_grad (bool, optional): If autograd should record operations on the returned tensor.

Example 1: Create a 1D tensor filled with a specific value

import torch

# Create a 1D tensor of size 5 filled with the value 7
tensor1 = torch.full((5,), 7)
print("1D tensor filled with 7")
print(tensor1)

Output

1D tensor filled with 7

tensor([7, 7, 7, 7, 7])

Example 2: Create a 2D tensor filled with a particular value

import torch

# Create a 2D tensor of shape (3, 4) filled with the value -1
tensor2 = torch.full((3, 4), -1)
print("2D tensor of shape (3, 4) filled with -1")
print(tensor2)

Output

2D tensor of shape (3, 4) filled with -1

tensor([[-1, -1, -1, -1],
        [-1, -1, -1, -1],
        [-1, -1, -1, -1]])

Example 3: Create a tensor with a particular type of data

import torch

tensor3 = torch.full((2, 2), 0, dtype=torch.int)
print("2D tensor of shape (2, 2) filled with 0 and dtype set to int")
print(tensor3)

Output

2D tensor of shape (2, 2) filled with 0 and dtype set to int
              
tensor([[0, 0],
        [0, 0]], dtype=torch.int32)

That’s it!

Related posts

PyTorch torch.optim.Adam()

PyTorch torch.unsqueeze()

PyTorch torch.squeeze()

PyTorch torch.nn.Conv2d()

PyTorch torch.clone()

Leave a Comment