PyTorch torch.randn() method **“returns a tensor filled with random numbers from a normal distribution with mean 0 and variance 1.”**

**Syntax**

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

**Parameters**

**size (int…)**: A sequence of integers defining the shape of the output tensor.

**out (Tensor, optional)**: It is 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.

**Example 1: How to Use the torch.randn() method**

```
import torch
rand_tensor = torch.randn(3, 3)
print(rand_tensor)
```

**Output**

```
tensor([[ 0.2211, 0.1781, 0.3264],
[ 0.3594, -0.3114, -0.8456],
[-1.6676, -0.2437, -0.3796]])
```

**Example 2: Generating a 3D tensor**

In this example, we’ll generate a 3D tensor with a shape (2, 2, 3).

```
import torch
rand_tensor_3d = torch.randn(2, 2, 3)
print(rand_tensor_3d)
```

**Output**

**Example 3: Using dtype and device parameters**

Here, we’ll generate a tensor of shape (4, 4) with data type as **torch.float64** (double precision) and place it on the cuda device (assuming you have a GPU).

```
import torch
# Check if CUDA is available, if not, use CPU
device = 'cuda' if torch.cuda.is_available() else 'cpu'
rand_tensor_double_on_cuda = torch.randn(4, 4, dtype=torch.float64, device=device)
print(rand_tensor_double_on_cuda)
```

**Output**

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.