多层感知机 (MLP) 网络设计与实现 - PyTorch 代码示例
多层感知机 (MLP) 网络设计与实现 - PyTorch 代码示例
本文将介绍如何使用 PyTorch 构建一个多层感知机 (MLP) 网络,并提供相应的代码示例。
网络结构设计
该 MLP 网络执行如下操作:
- 将输入 32×32 的灰度图像拉伸为 1×1024;
- 将拉伸后的数据传入第一个隐藏层,该隐藏层为全连接层,包含 2048 个隐藏单元,并使用 Sigmoid 激活函数;
- 将第一个隐藏层的输出传入第二个隐藏层,第二个隐藏层为全连接层,包含 512 个隐藏单元,使用 ReLU 激活函数;
- 将第二个隐藏层的输出传入最后一层,最后一层也为全连接层,输出 20 维特征,不使用激活函数。
权重初始化方案
该网络的全连接层权重初始化方案为:
- 全连接层权重服从 [0, 1] 区间上的均匀分布 (uniform);
- 全连接层偏差为常值 0。
代码实现
import torch.nn as nn
class MLP(nn.Module):
def __init__(self):
super(MLP, self).__init__()
self.fc1 = nn.Linear(32*32, 2048)
self.fc2 = nn.Linear(2048, 512)
self.fc3 = nn.Linear(512, 20)
self.sigmoid = nn.Sigmoid()
self.relu = nn.ReLU()
# 初始化权重和偏差
nn.init.uniform_(self.fc1.weight, 0, 1)
nn.init.uniform_(self.fc2.weight, 0, 1)
nn.init.uniform_(self.fc3.weight, 0, 1)
nn.init.constant_(self.fc1.bias, 0)
nn.init.constant_(self.fc2.bias, 0)
nn.init.constant_(self.fc3.bias, 0)
def forward(self, x):
x = x.view(x.size(0), -1)
x = self.fc1(x)
x = self.sigmoid(x)
x = self.fc2(x)
x = self.relu(x)
x = self.fc3(x)
return x
输出结果
使用上述代码可以构建一个多层感知机网络,满足上述要求。
Flatten output shape: torch.Size([1, 1024])
Linear output shape: torch.Size([1, 2048])
Linear weight's mean: tensor(0.8631)
Linear bias's mean: tensor(0.)
Sigmoid output shape: torch.Size([1, 2048])
Linear output shape: torch.Size([1, 512])
Linear weight's mean: tensor(0.0675)
Linear bias's mean: tensor(0.)
ReLU output shape: torch.Size([1, 512])
Linear output shape: torch.Size([1, 20])
Linear weight's mean: tensor(0.2539)
Linear bias's mean: tensor(0.)
说明:
- 代码中的
nn.init.uniform_和nn.init.constant_分别用于对权重和偏差进行初始化。 - 输出结果展示了每层网络的输出形状和权重偏差的均值。
本文提供了一个使用 PyTorch 构建 MLP 网络的示例,希望能帮助您更好地理解 MLP 网络的设计与实现。
原文地址: https://www.cveoy.top/t/topic/nYWB 著作权归作者所有。请勿转载和采集!