PyTorch torch.full_like() Method

PyTorch torch.full_like() method returns a tensor the same size as input filled with fill_value. The torch.full_like(input, fill_value) is equivalent to torch.full(input.size(), fill_value, dtype=input.dtype, layout=input.layout, device=input.device) method.

Syntax

torch.full_like(input, fill_value, \*, dtype=None, layout=torch.strided, 
                device=None, requires_grad=False, 
                memory_format=torch.preserve_format)

Parameters

  1. input (Tensor): The input tensor whose shape will be used to define the shape of the output tensor.
  2. fill_value (scalar): The value to fill the output tensor with.
  3. dtype (torch.dtype, optional): The desired data type of the output tensor.
  4. layout (torch.layout, optional): The desired layout of the output tensor.
  5. device (torch.device, optional): The desired device of the output tensor.
  6. requires_grad (bool, optional): If True, the resulting tensor will require a gradient.
  7. memory_format (torch.memory_format, optional): Specifies the memory format of the produced tensor.

Example 1: Basic usage of the torch.full_like()

import torch

# Create a tensor
tensor_a = torch.tensor([[1, 2], [3, 4], [5, 6]])

full_tensor_a = torch.full_like(tensor_a, 7)

print("Original Tensor:")
print(tensor_a)
print("\nTensor Filled with 7:")
print(full_tensor_a)

Output

Basic usage of the torch.full_like()

Example 2: Using additional parameters with a torch.full_like()

import torch

# Create a tensor of float type
tensor_b = torch.tensor([[1.1, 2.2], [3.3, 4.4]], dtype=torch.float32)

full_tensor_b = torch.full_like(tensor_b, 8.8, dtype=torch.int64)

print("Original Tensor:")
print(tensor_b)
print("\nTensor Filled with 8 and Dtype int64:")
print(full_tensor_b)

Output

Using additional parameters with a torch.full_like()

Conclusion

PyTorch torch.full_like() method is used to create a new tensor with the same shape as the input tensor but filled with a specified value.

Related posts

torch.empty_like()

torch.empty()

Leave a Comment