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

相关推荐
九章云极AladdinEdu7 小时前
存算一体芯片生态评估:从三星PIM到知存科技WTM2101
人工智能·pytorch·科技·架构·开源·gpu算力
F_D_Z11 小时前
【PyTorch】单对象分割
人工智能·pytorch·python·深度学习·机器学习
浊酒南街11 小时前
Pytorch基础入门4
人工智能·pytorch·python
nju_spy11 小时前
南京大学 LLM开发基础(一)前向反向传播搭建
人工智能·pytorch·深度学习·大语言模型·梯度·梯度下降·反向传播
HUIMU_12 小时前
YOLOv5实战-GPU版本的pytorch虚拟环境配置
人工智能·pytorch·深度学习·yolo
1373i12 小时前
【Python】pytorch数据操作
开发语言·pytorch·python
luoganttcc17 小时前
PyTorch 中nn.Embedding
pytorch·深度学习·embedding
九章云极AladdinEdu17 小时前
绿色算力技术栈:AI集群功耗建模与动态调频系统
人工智能·pytorch·深度学习·unity·游戏引擎·transformer·gpu算力
Dfreedom.19 小时前
在Windows上搭建GPU版本PyTorch运行环境的详细步骤
c++·人工智能·pytorch·python·深度学习
深耕AI21 小时前
PyTorch自定义模型结构详解:从基础到高级实践
人工智能·pytorch·python