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上使用时,确保数据和模型都在同一设备上。

相关推荐
慕婉030712 小时前
Tensor自动微分
人工智能·pytorch·python
槑槑紫1 天前
深度学习pytorch整体流程
人工智能·pytorch·深度学习
IT古董1 天前
【第三章:神经网络原理详解与Pytorch入门】02.深度学习框架PyTorch入门-(5)PyTorch 实战——使用 RNN 进行人名分类
pytorch·深度学习·神经网络
机器学习之心1 天前
小波增强型KAN网络 + SHAP可解释性分析(Pytorch实现)
人工智能·pytorch·python·kan网络
Green1Leaves2 天前
pytorch学习-11卷积神经网络(高级篇)
pytorch·学习·cnn
灵智工坊LingzhiAI2 天前
人体坐姿检测系统项目教程(YOLO11+PyTorch+可视化)
人工智能·pytorch·python
William.csj2 天前
Pytorch/CUDA——flash-attn 库编译的 gcc 版本问题
pytorch·cuda
Green1Leaves3 天前
pytorch学习-9.多分类问题
人工智能·pytorch·学习
摸爬滚打李上进3 天前
重生学AI第十六集:线性层nn.Linear
人工智能·pytorch·python·神经网络·机器学习
HuashuiMu花水木3 天前
PyTorch笔记1----------Tensor(张量):基本概念、创建、属性、算数运算
人工智能·pytorch·笔记