Sprint Chase Technologies
  • Home
  • About
    • Why Choose Us
    • Contact Us
    • Team Members
    • Testimonials
  • Services
    • Web Development
    • Web Application Development
    • Mobile Application Development
    • Web Design
    • UI/UX Design
    • Social Media Marketing
    • Projects
  • Blog
    • PyTorch
    • Python
    • JavaScript
  • IT Institute
menu
close

Need Help? Talk to an Expert

+91 8000107255
Sprint Chase Technologies
  • Home
  • About
    • Why Choose Us
    • Contact Us
    • Team Members
    • Testimonials
  • Services
    • Web Development
    • Web Application Development
    • Mobile Application Development
    • Web Design
    • UI/UX Design
    • Social Media Marketing
    • Projects
  • Blog
    • PyTorch
    • Python
    • JavaScript
  • IT Institute

Need Help? Talk to an Expert

+91 8000107255

torch.randn(): Generating a Tensor from Normal Distribution

Home torch.randn(): Generating a Tensor from Normal Distribution
PyTorch torch.randn() Function
  • Written by krunallathiya21
  • April 21, 2025
  • 0 Com
PyTorch

The torch.randn() is a PyTorch factory function that generates a tensor with random numbers from a standard normal distribution (mean = 0, standard deviation = 1, variance = 1).

torch.randn() method overview

It can create synthetic data, initialize neural weights, or simulate noise for testing and prototyping where sampling is required.

The torch.randn() method returns a tensor of the specified shape with values sampled independently from a normal distribution.

Function Signature

torch.randn(*sizes, 
            out=None, 
            dtype=None, 
            layout=torch.strided, 
            device=None, 
            requires_grad=False) → Tensor

Arguments

Name Value
*sizes (int) It determines the shape of the output tensor.
generator (torch.Generator, optional) It defines a pseudorandom number generator for sampling.
out (Tensor, optional) It is an output tensor into which we can write the results. It is an optional argument. The default is None.
dtype (torch.dtype, optional) It determines the output tensor’s data type. By default, it is float.
layout (torch.layout, optional) By default, it is torch.strided. It is a memory layout of the tensor.
device (torch.device, optional) By default, it is a CPU. But you can change it to “cuda:0” using this argument.
requires_grad (bool, optional) By default, it is False. If you set it to True, it will calculate the gradient for this tensor.
pin_memory (bool, optional) By default, it is False. If set to True, the returned tensor would be allocated in the pinned memory.

Basic random tensor generation

Let’s generate a random 2×3 tensor with standard normal values:
import torch

random_normal_tensor = torch.randn(2, 3)

print(random_normal_tensor)

# Output:
# tensor([[-0.3586, -0.4133,  1.1282],
#         [ 0.4028, -0.2565,  0.3398]])

Reproducibility with seed

You can control the randomness for deterministic results using torch.manual_seed() method.

import torch

torch.manual_seed(42)

random_normal_tensor = torch.randn(2, 3)

print(random_normal_tensor)

# Output:
# tensor([[ 0.3367,  0.1288,  0.2345],
#         [ 0.2303, -1.1229, -0.1863]])

# tensor([[ 0.3367,  0.1288,  0.2345],
#         [ 0.2303, -1.1229, -0.1863]])

# tensor([[ 0.3367,  0.1288,  0.2345],
#         [ 0.2303, -1.1229, -0.1863]])

You can see that I have executed multiple times, and each time it gives the same output. That means we can generate the exact same random numbers again and again.

Specifying Shape (*sizes)

You can pass the required shape either as integers or in a tuple or list format. Passing a tuple as a shape Let’s pass a tuple of sizes:
import torch

# Size passed a single tuple
random_normal_tensor = torch.randn((2, 3))

print(random_normal_tensor)

# Output:
# tensor([[ 1.4117,  0.2920,  1.8470],
#         [-0.2951,  0.1401,  0.0999]])
Let’s pass a list of sizes:
import torch

# Size passed a single tuple
random_normal_tensor = torch.randn([2, 3])

print(random_normal_tensor)

# Output:
# tensor([[ 1.4117,  0.2920,  1.8470],
#         [-0.2951,  0.1401,  0.0999]])

Writing into an existing tensor using “out” argument

From function arguments, we can use the “out” argument to write the result in a pre-allocated tensor.

For that, you have to create an empty tensor first using torch.empty() method:
import torch

pre_allocated = torch.empty(3, 2)

print(pre_allocated)
# Output:
# tensor([[0., 0.],
#         [0., 0.],
#         [0., 0.]])


torch.randn(3, 2, out=pre_allocated)

print(pre_allocated)
# Output:
# tensor([[-0.1070, -0.8163],
#         [-0.5375, -0.1606],
#         [ 0.1432,  0.4633]])

You can see that we did not write a new variable to assign the output tensor. Instead, we wrote the values into an existing tensor, which is “pre-allocated”.

One thing to make sure of is that the “out” tensor should have the same shape as the tensor you are randomly generating.

Changing dtype

Changing the dtype of torch.randn() method

You can control the output tensor’s type from the default torch.float32 to torch.float64 and torch.float16.

import torch

tensor64 = torch.randn(2, 2, dtype=torch.float64)

print(tensor64)
# Output:
# tensor([[0.6040, 1.1112],
#         [1.0618, 1.9945]], dtype=torch.float64)

tensor16 = torch.randn(2, 2, dtype=torch.float16)

print(tensor16)
# Output:
# tensor([[-0.3452,  0.0709],
#         [-0.5215, -0.4639]], dtype=torch.float16)

Non‑floating dtypes (e.g. torch.int32) are not supported and will raise RuntimeError: “normal_kernel_cpu” not implemented for ‘Long’:

import torch

tensorint64 = torch.randn(2, 2, dtype=torch.int64)

print(tensorint64)

# Output: RuntimeError: "normal_kernel_cpu" not implemented for 'Long'

Specifying device

You can generate directly on the GPU by specifying device = “cuda:0”.
import torch

cpu_tensor = torch.randn(4, 4, device="cpu")

print(cpu_tensor.device)
# Output: cpu

# On GPU (if available)
if torch.cuda.is_available():
    gpu_tensor = torch.randn(4, 4, device="cuda:0")
    print(gpu_tensor.device)  # → cuda:0

Tracking Gradients by requires_grad

You can control that the output tensor is a part of an autograd tensor by passing requires_grad = True.
import torch

# With gradient tracking
t2 = torch.randn(3, 3, requires_grad=True)

print(t2)
# Output:
# tensor([[-2.3310,  0.7982,  0.7574],
#         [ 0.1524, -0.2317,  0.6158],
#         [-0.3591, -1.5899,  0.2003]], requires_grad=True)

print(t2.requires_grad)
# Output: True

Batch Processing

Let’s generate a batch of 15 samples, each with 25 features:
import torch

batch_size = 15

features = 25

batch_data = torch.randn(batch_size, features)

print(batch_data.shape)

# Output: torch.Size([15, 25])
That’s all!
Post Views: 16
LEAVE A COMMENT Cancel reply
Please Enter Your Comments *

krunallathiya21

All Categories
  • JavaScript
  • Python
  • PyTorch
site logo

Address:  TwinStar, South Block – 1202, 150 Ft Ring Road, Nr. Nana Mauva Circle, Rajkot(360005), Gujarat, India

sprintchasetechnologies@gmail.com

(+91) 8000107255.

ABOUT US
  • About
  • Team Members
  • Testimonials
  • Contact

Copyright by @SprintChase  All Rights Reserved

  • PRIVACY
  • TERMS & CONDITIONS