多层感知机 (MLP) 网络设计与实现 - PyTorch 代码示例
多层感知机 (MLP) 网络设计与实现 - PyTorch 代码示例
本文介绍了使用 PyTorch 设计一个多层感知机 (MLP) 网络的步骤,并提供了详细的代码示例。该网络将 32x32 的灰度图像拉伸为 1x1024 向量,并通过三个全连接层进行特征提取,最后输出 20 维特征。代码中包含了权重初始化、激活函数等关键细节,并展示了网络输出形状和权重、偏差的统计信息。
网络架构:
- 将输入 32x32 的灰度图像拉伸为 1x1024 向量。
- 将拉伸后的数据传入第一个隐藏层,该隐藏层为全连接层,包含 2048 个隐藏单元,并使用 Sigmoid 激活函数。
- 将第一个隐藏层的输出传入第二个隐藏层,第二个隐藏层为全连接层,包含 512 个隐藏单元,使用 ReLU 激活函数。
- 将第二个隐藏层的输出传入最后一层,最后一层也为全连接层,输出 20 维特征,不使用激活函数。
权重初始化:
- 全连接层权重服从 [0,1] 区间上的均匀分布 (uniform)。
- 全连接层偏差为常值 0。
代码实现:
import torch
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(-1, 32*32)
x = self.fc1(x)
x = self.sigmoid(x)
x = self.fc2(x)
x = self.relu(x)
x = self.fc3(x)
return x
# 测试网络
model = MLP()
x = torch.randn(1, 1, 32, 32)
y = model(x)
print('Flatten output shape: ', x.view(1, -1).shape)
print('Linear output shape: ', model.fc1(x.view(-1, 32*32)).shape)
print(' Linear weight's mean: ', model.fc1.weight.mean())
print(' Linear bias's mean: ', model.fc1.bias.mean())
print('Sigmoid output shape: ', model.sigmoid(model.fc1(x.view(-1, 32*32))).shape)
print('Linear output shape: ', model.fc2(model.sigmoid(model.fc1(x.view(-1, 32*32)))).shape)
print(' Linear weight's mean: ', model.fc2.weight.mean())
print(' Linear bias's mean: ', model.fc2.bias.mean())
print('ReLU output shape: ', model.relu(model.fc2(model.sigmoid(model.fc1(x.view(-1, 32*32))))).shape)
print('Linear output shape: ', model.fc3(model.relu(model.fc2(model.sigmoid(model.fc1(x.view(-1, 32*32)))))).shape)
print(' Linear weight's mean: ', model.fc3.weight.mean())
print(' Linear bias's mean: ', model.fc3.bias.mean())
输出结果:
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.)
总结:
本文详细介绍了使用 PyTorch 设计和实现一个简单的 MLP 网络,并提供了代码示例和输出结果。该示例展示了如何使用 PyTorch 的模块进行网络构建,如何进行权重初始化,以及如何测试网络输出形状和统计信息。希望本文能够帮助您理解 MLP 网络的基本结构和实现步骤。
原文地址: https://www.cveoy.top/t/topic/nYWP 著作权归作者所有。请勿转载和采集!