pytorch api文档:torch.randn()生成标准正态分布随机张量 作者:马育民 • 2026-01-18 09:23 • 阅读:10001 # 介绍 `torch.randn()` 函数,是生成 **标准正态分布 随机张量** 的核心工具,也是深度学习中 **模型权重初始化 的 首选函数**(如线性层、卷积层) ### 作用 创建指定形状的张量,元素值 **随机采样自标准正态分布(Standard Normal Distribution)**——即均值`(μ)= 0`,方差`(σ²)= 1`,标准差 `(σ)= 1` 的正态分布,数值范围覆盖 `(-∞, +∞)`(实际绝大多数值落在 `[-3, 3]` 之间)。 在深度学习中最常用的随机初始化函数,对比同类随机函数: - `torch.rand()`:`[0,1)` 均匀分布(简单初始化); - `torch.randint()`:整数随机分布(生成索引/标签)。 # 语法 ``` torch.randn(*size, dtype=None, device=None, requires_grad=False) ``` #### 参数 | 参数 | 作用 | 常用场景 | |----------------|----------------------------------------------------------------------|--------------------------------------------------------------------------| | `*size` | 张量形状,可传单个整数、多个整数,或元组(如 `torch.randn((2,3))`)| 核心参数,必传;权重初始化时遵循“输出维度在前”(如线性层权重 `(out_dim, in_dim)`) | | `dtype` | 指定数据类型(`torch.float32`/`torch.float64`)| 默认 `torch.float32`,高精度场景设 `torch.float64` | | `device` | 指定存储设备(`cpu`/`cuda`)| 模型训练时需和模型同设备,如 `device="cuda:0"` | | `requires_grad`| 是否开启梯度计算 | 仅作为可训练权重初始化时设 `True`,普通随机数据设 `False`(默认)| # 例子 `size` 是唯一必传参数,支持一维/二维/高维张量,直接看代码更直观: ```python import torch # 示例1:一维标准正态分布张量(3个元素) randn_1d = torch.randn(3) print("一维随机张量:", randn_1d) # 输出示例:tensor([-0.2345, 1.5678, -0.8901])(均值≈0,方差≈1) print("形状:", randn_1d.shape) # torch.Size([3]) # 示例2:二维张量(2行3列,模拟权重矩阵) randn_2d = torch.randn(2, 3) print("二维随机张量:\n", randn_2d) # 输出示例: # tensor([[ 0.4567, -0.7890, 0.1234], # [-1.3456, 0.9876, -0.5678]]) print("均值:", randn_2d.mean().item()) # ≈0 print("方差:", randn_2d.var().item()) # ≈1 # 示例3:高维张量(批量场景,4个 2×3 的矩阵) randn_3d = torch.randn(4, 2, 3) print("三维张量形状:", randn_3d.shape) # torch.Size([4, 2, 3]) print("数值范围:", (randn_3d.min().item(), randn_3d.max().item())) # 多在 [-3, 3] 之间 ``` ### 参数示例 ```python # 示例1:指定数据类型(float64,更高精度) randn_float64 = torch.randn(2, 3, dtype=torch.float64) print("数据类型:", randn_float64.dtype) # torch.float64 print("数值:\n", randn_float64) # 示例2:指定GPU设备(需CUDA环境) if torch.cuda.is_available(): randn_cuda = torch.randn(2, 3, device="cuda") print("设备:", randn_cuda.device) # cuda:0 else: print("无CUDA环境,默认生成CPU张量") # 示例3:可求梯度的随机张量(初始化模型权重) randn_grad = torch.randn(2, 3, requires_grad=True) print("是否可求梯度:", randn_grad.requires_grad) # True ``` ### 随机种子(复现实验) `torch.randn()` 生成的是伪随机数,设置全局随机种子可固定结果,保证实验可复现: ```python # 设置全局随机种子(固定所有随机数生成结果) torch.manual_seed(42) print("固定种子结果1:", torch.randn(2)) # tensor([0.3367, 0.1288]) torch.manual_seed(42) print("固定种子结果2:", torch.randn(2)) # tensor([0.3367, 0.1288])(完全一致) ``` ### 自定义正态分布(非标准) 如果需要生成**均值为 μ、标准差为 σ** 的正态分布,可通过简单变换实现: ```python # 目标:生成均值=2,标准差=0.5 的正态分布 mu, sigma = 2.0, 0.5 randn_custom = mu + sigma * torch.randn(2, 3) print("自定义正态分布:\n", randn_custom) print("均值:{:.4f},标准差:{:.4f}".format(randn_custom.mean().item(), randn_custom.std().item())) # 输出:均值≈2.0,标准差≈0.5 ``` # 实战核心场景 ### 模型权重初始化(最常用) 深度学习中,线性层、卷积层的权重通常用正态分布初始化(PyTorch 官方默认也是类似逻辑): ```python import torch.nn as nn # 自定义线性层,用 randn 初始化权重 class MyLinear(nn.Module): def __init__(self, in_features, out_features): super().__init__() # 权重:标准正态分布 → 缩放(避免数值过大) self.weight = nn.Parameter(torch.randn(out_features, in_features) * 0.01) # 偏置:全零初始化(也可改用 randn 但通常没必要) self.bias = nn.Parameter(torch.zeros(out_features)) def forward(self, x): return x @ self.weight.T + self.bias # 初始化并验证 linear = MyLinear(in_features=5, out_features=3) print("线性层权重:\n", linear.weight) print("权重均值:{:.4f},方差:{:.4f}".format(linear.weight.mean().item(), linear.weight.var().item())) # 输出:均值≈0,方差≈0.0001(因乘以0.01缩放) ``` ### 添加高斯噪声(数据增强/正则化) 在输入数据中添加小幅度正态分布噪声,可提升模型泛化能力: ```python # 模拟输入数据(4个样本,5维特征) x = torch.randn(4, 5) # 添加高斯噪声(均值0,标准差0.01) noise = 0.01 * torch.randn_like(x) # 与x形状一致的标准正态分布 x_noisy = x + noise print("原始数据:\n", x) print("加噪后数据:\n", x_noisy) print("噪声幅度:", noise.std().item()) # ≈0.01 ``` ### 生成模拟测试数据 测试模型时,用 `torch.randn()` 生成符合正态分布的模拟输入(更贴近真实数据分布): ```python # 模拟:批量图像数据(batch=8, channel=3, H=28, W=28) batch_img = torch.randn(8, 3, 28, 28) print("模拟图像形状:", batch_img.shape) # torch.Size([8, 3, 28, 28]) print("像素值范围:", (batch_img.min().item(), batch_img.max().item())) # 多在 [-3, 3] 之间 ``` # 总结 1. `torch.randn(*size)` 生成**标准正态分布(μ=0, σ²=1)** 的随机张量,是深度学习权重初始化的核心工具。 2. 核心参数:`size` 定义形状,`device` 需与模型/数据一致;设置 `torch.manual_seed()` 可固定随机结果,方便复现。 3. 关键技巧:自定义正态分布用 `μ + σ * torch.randn()`;权重初始化时需缩放(如乘以0.01)避免数值过大。 4. 适用场景:模型权重初始化、添加高斯噪声、生成模拟测试数据(均匀分布用 `torch.rand()`)。 原文出处:http://malaoshi.top/show_1GW2c5isoUYi.html