torch.nn.Linear()函数的理解

本文详细介绍了如何使用PyTorch实现线性层,包括输入数据的维度设定,线性层参数的形状以及输出结果的验证。通过具体代码示例,展示了线性层的前向传播过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

import torch

x = torch.randn(128, 20)  # 输入的维度是(128,20)
m = torch.nn.Linear(20, 30)  # 20,30是指维度
output = m(x)
print('m.weight.shape:\n ', m.weight.shape)
print('m.bias.shape:\n', m.bias.shape)
print('output.shape:\n', output.shape)

# ans = torch.mm(input,torch.t(m.weight))+m.bias 等价于下面的
ans = torch.mm(x, m.weight.t()) + m.bias   
print('ans.shape:\n', ans.shape)

print(torch.equal(ans, output))
 

 

m.weight.shape:
  torch.Size([30, 20])
m.bias.shape:
 torch.Size([30])
output.shape:
 torch.Size([128, 30])
ans.shape:
 torch.Size([128, 30])

 

 

 

 

<think>我们正在寻找`torch.nn.Linear`的函数原型定义。根据PyTorch官方文档,`torch.nn.Linear`是一个类,它的构造函数定义了参数。因此,我们关注其`__init__`方法的参数。 函数原型定义通常包括类名、参数及其类型和默认值。 根据官方文档和引用内容,`torch.nn.Linear`的构造函数如下: ```python torch.nn.Linear(in_features, out_features, bias=True, device=None, dtype=None) ``` 参数说明: - `in_features` (int): 每个输入样本的大小(即输入特征的数量)。 - `out_features` (int): 每个输出样本的大小(即输出特征的数量)。 - `bias` (bool, optional): 如果设置为`False`,则层不会学习附加偏置。默认值:`True`。 - `device` (torch.device, optional): 该层参数所在的设备。如果为`None`,则使用当前设备(例如GPU或CPU)。默认值:`None`。 - `dtype` (torch.dtype, optional): 该层参数的数据类型。默认值:`None`。 注意:在PyTorch中,当使用`device`和`dtype`参数时,它们将应用于该层创建的权重和偏置(如果存在)张量。 另外,引用[1]中提到了`torch.nn.Linear`的操作是$y = xA^T + b$,其中$x$是输入,$A$是权重矩阵,$b$是偏置。引用[2]则展示了使用`torch.nn.Linear`和`torch.nn.functional.linear`的示例,但我们的重点是函数原型。 因此,我们可以将`torch.nn.Linear`的函数原型定义总结如下:</think>### PyTorch `torch.nn.Linear` 函数原型定义 `torch.nn.Linear` 是 PyTorch 中实现全连接层的**类**(非函数),其构造函数定义如下: ```python torch.nn.Linear( in_features: int, out_features: int, bias: bool = True, device: Optional[Union[torch.device, str]] = None, dtype: Optional[torch.dtype] = None ) ``` #### 参数详解: | 参数名 | 类型 | 默认值 | 说明 | |--------|------|--------|------| | `in_features` | `int` | **必填** | 输入特征维度 $d_{\text{in}}$ | | `out_features` | `int` | **必填** | 输出特征维度 $d_{\text{out}}$ | | `bias` | `bool` | `True` | 是否包含可训练偏置项 $\mathbf{b}$ | | `device` | `torch.device` | `None` | 参数存储设备(CPU/GPU) | | `dtype` | `torch.dtype` | `None` | 参数数据类型(float32/float16等) | #### 数学运算: 执行线性变换: $$ \mathbf{y} = \mathbf{x}\mathbf{W}^\top + \mathbf{b} $$ 其中: - $\mathbf{x}$:输入张量(形状 `[*, in_features]`) - $\mathbf{W}$:权重矩阵(形状 `[out_features, in_features]`) - $\mathbf{b}$:偏置向量(形状 `[out_features]`) - $\mathbf{y}$:输出张量(形状 `[*, out_features]`) #### 示例用法: ```python import torch.nn as nn # 创建线性层:10输入特征 -> 5输出特征 linear_layer = nn.Linear( in_features=10, out_features=5, bias=True # 显式声明(可省略) ) # 检查参数形状 print(linear_layer.weight.shape) # torch.Size([5, 10]) print(linear_layer.bias.shape) # torch.Size([5]) ``` #### 关键特性: 1. **自动参数初始化**:权重 $\mathbf{W}$ 使用均匀分布 $U(-\sqrt{k}, \sqrt{k})$ 初始化,其中 $k=1/\text{in\_features}$[^1] 2. **设备感知**:自动匹配输入数据的设备(通过 `device` 参数可强制指定) 3. **动态计算图**:支持 PyTorch 的自动微分机制 4. **张量广播**:支持任意批次维度(如 `[batch_size, seq_len, in_features]`)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值