现在位置: 首页 > PyTorch 教程 > 正文

PyTorch torch.randn 函数


Pytorch torch 参考手册 Pytorch torch 参考手册

torch.randn 是 PyTorch 中用于创建来自标准正态分布(均值为 0,方差为 1 的高斯分布)的随机张量的函数。

这在深度学习中常用于初始化权重、生成随机输入等场景。

函数定义

torch.randn(*size, dtype=None, device=None, requires_grad=False)

参数:

  • *size (int): 张量的形状。
  • dtype (torch.dtype, 可选): 数据类型,默认为 torch.float32
  • device (torch.device, 可选): 设备。
  • requires_grad (bool, 可选): 是否需要计算梯度。

返回值:

  • torch.Tensor: 返回包含随机数的张量。

使用示例

示例 1: 创建随机张量

实例

import torch

# 创建 3x4 的随机张量
x = torch.randn(3, 4)

print(x)

输出结果为:

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

示例 2: 神经网络权重初始化

实例

import torch
import torch.nn as nn

# 使用 randn 初始化神经网络权重
linear = nn.Linear(10, 5)

# 用随机值初始化权重
nn.init.randn_(linear.weight)
nn.init.zeros_(linear.bias)

print("权重形状:", linear.weight.shape)
print("权重均值:", linear.weight.mean().item())
print("权重标准差:", linear.weight.std().item())

Pytorch torch 参考手册 Pytorch torch 参考手册