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, memory_format=torch.contiguous_format)
- size (int…): It is a sequence of integers defining the shape of the output tensor.
- out (Tensor, optional): The output tensor.
- dtype (torch.dtype, optional): The desired data type of the returned tensor. Default: If none, use a global default.
- layout (torch.layout, optional): The desired layout of the returned tensor. Default: torch.strided.
- device (torch.device, optional): The desired device of the returned tensor. Default: If None, use the current device for the default tensor type.
- requires_grad (bool, optional): If autograd should record operations on the returned tensor. Default: False.
- 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) print(tensor)
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) print(tensor1)
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) print(tensor2)
tensor([[0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 0., 0.]], dtype=torch.float64)