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
- input (Tensor): The input tensor whose shape will be used to define the shape of the output tensor.
- fill_value (scalar): The value to fill the output tensor with.
- dtype (torch.dtype, optional): The desired data type of the output tensor.
- layout (torch.layout, optional): The desired layout of the output tensor.
- device (torch.device, optional): The desired device of the output tensor.
- requires_grad (bool, optional): If True, the resulting tensor will require a gradient.
- 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
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
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

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Machine Learning frameworks like PyTorch and Tensorflow is a testament to his versatility and commitment to the craft.