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

**Syntax**

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

**Parameters**

**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)
```

**Output**

```
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)
```

**Output**

```
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)
```

**Output**

```
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**

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.