PyTorch torch.empty_like() Method

The torch.empty_like() method returns an uninitialized tensor the same size as input. torch.empty_like(input) is equivalent to torch.empty(input.size(), dtype=input.dtype, layout=input.layout, device=input.device).

Syntax

torch.empty_like(input*dtype=Nonelayout=Nonedevice=None                requires_grad=Falsememory_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. dtype (torch.dtype, optional): The desired data type of the output tensor.
  3. layout (torch.layout, optional): The desired layout of the output tensor.
  4. device (torch.device, optional): The desired device of the output tensor.
  5. requires_grad (bool, optional): If True, the resulting tensor will require a gradient.
  6. memory_format (torch.memory_format, optional): Specifies the memory format of the produced tensor.

Example 1: How to Use torch.empty_like() method

import torch

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

# Use empty_like to create a new tensor with the same shape
empty_tensor = torch.empty_like(tensor)

print(empty_tensor)

Output

tensor([[0, 0],
        [0, 0]])

This will produce a tensor with the same shape as the tensor but with uninitialized values.

Example 2: Basic usage of the torch.empty_like()

import torch

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

# Use empty_like to create a new tensor with the same shape
empty_tensor_1 = torch.empty_like(tensor_1)

print("Original Tensor:")
print(tensor_1)
print("\nEmpty Tensor with Same Shape:")
print(empty_tensor_1)

Output

Basic usage of the torch.empty_like()

Example 3: Using additional parameters with a torch.empty_like()

import torch

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

# Use empty_like to create a new tensor with the same shape but different dtype
empty_tensor_2 = torch.empty_like(tensor_2, dtype=torch.int64)

print("Original Tensor:")
print(tensor_2)
print("\nEmpty Tensor with Same Shape but Different Dtype:")
print(empty_tensor_2)

Output

Original Tensor:
tensor([[1.1000, 2.2000],
        [3.3000, 4.4000]])

Empty Tensor with Same Shape but Different Dtype:
tensor([[0, 0],
        [0, 0]])

Conclusion

PyTorch torch.empty_like() method is “used to create a new tensor with the same shape as the input tensor but without initializing the values.”

Related posts

torch.empty()

torch.ones()

torch.ones_like()

torch.zeros()

torch.zeros_like()

Leave a Comment