PyTorch中Linear全连接层

在 PyTorch 中,torch.nn.Linear 是一个实现全连接层(线性变换)的模块,用于神经网络中的线性变换操作。它的数学表达式为:

其中:

  • x是输入数据

  • W是权重矩阵

  • b是偏置项

  • y是输出数据

基本用法

复制代码
import torch
import torch.nn as nn

# 创建一个线性层,输入特征数为5,输出特征数为3
linear_layer = nn.Linear(in_features=5, out_features=3)

# 创建一个随机输入张量(batch_size=2, 特征数=5)
input_tensor = torch.randn(2, 5)

# 前向传播
output = linear_layer(input_tensor)
print(output.shape)  # 输出 torch.Size([2, 3])

主要参数

  1. in_features - 输入特征的数量

  2. out_features - 输出特征的数量

  3. bias - 是否使用偏置项(默认为True)

重要属性

  1. weight - 可学习的权重参数(形状为out_features, in_features

  2. bias - 可学习的偏置参数(形状为out_features

示例:构建简单神经网络

复制代码
class SimpleNet(nn.Module):
    def __init__(self):
        super(SimpleNet, self).__init__()
        self.fc1 = nn.Linear(10, 20)  # 输入10维,输出20维
        self.fc2 = nn.Linear(20, 2)   # 输入20维,输出2维
        
    def forward(self, x):
        x = torch.relu(self.fc1(x))
        x = self.fc2(x)
        return x

model = SimpleNet()
input_data = torch.randn(5, 10)  # batch_size=5
output = model(input_data)
print(output.shape)  # torch.Size([5, 2])

初始化权重

复制代码
# 自定义权重初始化
nn.init.xavier_uniform_(linear_layer.weight)
nn.init.zeros_(linear_layer.bias)

# 或者使用PyTorch内置初始化
linear_layer = nn.Linear(5, 3)
torch.nn.init.kaiming_normal_(linear_layer.weight, mode='fan_out')

注意事项

  1. 输入数据的最后一维必须等于in_features

  2. 线性层通常与激活函数配合使用(如ReLU)

  3. 在GPU上使用时,确保数据和模型都在同一设备上。

相关推荐
程序猿追6 小时前
那个右下角的小数字怎么“卡”住我打字——我用 HarmonyOS 自己写了一个字数限制输入框
pytorch·华为·harmonyos
闵孚龙8 小时前
《PyTorch 深度修炼》Dataset 和 DataLoader:数据如何喂给模型
人工智能·pytorch·python
bryant_meng14 小时前
【VAE】From Pixels to Faces: Building a VAE from Scratch
pytorch·vae·log-sigma2·重参数
装不满的克莱因瓶15 小时前
了解多标签图像分类方法——从Sigmoid输出到真实世界复杂视觉理解
人工智能·pytorch·python·深度学习·机器学习·分类·数据挖掘
冷小鱼15 小时前
TensorFlow 2.21 进阶实战:从训练优化到生产部署的完整指南
人工智能·pytorch·python·tensorflow
冷小鱼16 小时前
PyTorch 2.12 完全指南:从动态图到编译优化的深度学习框架演进
人工智能·pytorch·深度学习
IRevers16 小时前
【大模型】Gemma4在ROCm和vLLM部署
人工智能·pytorch·深度学习·大模型·datawhale·vllm·amdev
盼小辉丶16 小时前
PyTorch强化学习实战(14)——优先经验回放机制
pytorch·python·深度学习·强化学习
装不满的克莱因瓶16 小时前
【工业领域】了解目标检测评估指标——从mAP到IoU的完整评价体系解析
人工智能·pytorch·python·深度学习·目标检测·计算机视觉·目标跟踪
闵孚龙1 天前
动态图机制:为什么 PyTorch 调试起来更舒服
人工智能·pytorch·python