PyTorch torch.empty() Method

PyTorch torch.empty() method returns a tensor filled with uninitialized data. The variable argument size defines the shape of the tensor.


torch.empty(*size, *, out=None, dtype=None, layout=torch.strided, 
            device=None, requires_grad=False, pin_memory=False, 


  1. size (int…): It is a sequence of integers defining the shape of the output tensor.
  2. out (Tensor, optional): The output tensor.
  3. dtype (torch.dtype, optional): The desired data type of the returned tensor. Default: If none, use a global default.
  4. layout (torch.layout, optional): The desired layout of the returned tensor. Default: torch.strided.
  5. device (torch.device, optional): The desired device of the returned tensor. Default: If None, use the current device for the default tensor type.
  6. requires_grad (bool, optional): If autograd should record operations on the returned tensor. Default: False.
  7. pin_memory (bool, optional): The returned tensor would be allocated in the pinned memory if set. Works only for CUDA tensors. Default: False.

Example 1: Basic example to demonstrate how to use a torch.empty()

import torch

# Create a 2x3 uninitialized tensor
tensor = torch.empty(2, 3)



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

Example 2: Creating a 3D Uninitialized Tensor

import torch

# Create a 2x2x3 uninitialized tensor
tensor1 = torch.empty(2, 2, 3)


tensor([[[0., 0., 0.],
         [0., 0., 0.]],

        [[0., 0., 0.],
         [0., 0., 0.]]])

Example 3: Uninitialized Tensor with Specific Data Type and Device

Generate a 4×4 uninitialized tensor of type float64 on the CPU.

import torch

# Create a 4x4 uninitialized tensor with dtype set to float64

tensor2 = torch.empty(4, 4, dtype=torch.float64)


tensor([[0., 0., 0., 0.],
        [0., 0., 0., 0.],
        [0., 0., 0., 0.],
        [0., 0., 0., 0.]], dtype=torch.float64)

That’s it!

Related posts





Leave a Comment