YouTip LogoYouTip

Pytorch Torch Randn

# PyTorch torch.randn Function * * * [![Image 3: Pytorch torch Reference Manual]( Pytorch torch Reference Manual]( `torch.randn` is a function in PyTorch used to create random tensors from a standard normal distribution (Gaussian distribution with mean 0 and variance 1). This is commonly used in deep learning for initializing weights, generating random inputs, and other scenarios. ### Function Definition torch.randn(*size, dtype=None, device=None, requires_grad=False) **Parameters**: * `*size` (int): The shape of the tensor. * `dtype` (torch.dtype, optional): The data type, default is `torch.float32`. * `device` (torch.device, optional): The device. * `requires_grad` (bool, optional): Whether gradient computation is required. **Return Value**: * `torch.Tensor`: Returns a tensor containing random numbers. * * * ## Usage Examples ### Example 1: Creating a Random Tensor ## Example import torch # Create a 3x4 random tensor x = torch.randn(3,4) print(x) Output: tensor([[-0.2107, -0.6198, 0.2103, 0.4513], [-0.0124, -1.1746, 0.1844, -0.6199], [ 1.1729, -0.7669, 0.3034, -0.0808]]) ### Example 2: Neural Network Weight Initialization ## Example import torch import torch.nn as nn # Use randn to initialize neural network weights linear = nn.Linear(10,5) # Initialize weights with random values nn.init.randn_(linear.weight) nn.init.zeros_(linear.bias) print("Weight shape:", linear.weight.shape) print("Weight mean:", linear.weight.mean().item()) print("Weight std:", linear.weight.std().item()) * * * [![Image 4: Pytorch torch Reference Manual]( Pytorch torch Reference Manual](
← Pytorch Torch RavelPytorch Torch Quantized_Batch_ β†’