多层感知机的简洁实现

一、前言

1、和softmax实现一样,唯一的区别是我们模型含有两个全连接层

2、直接通过高级API更简洁实现多层感知机

3、对于相同的分类问题,多层感知机的实现和softmax回归的实现完全相同,只是多层感知机的实现增加了带有激活函数的隐藏层

二、模型

1、第一层是隐藏层,包含256个隐藏单元,并使用ReLU激活函数

2、第二层是输出层

# 因为图片是一个3D的东西,然后使用nn.Flatten()为二维
# nn.Linear(784, 256)线性层,输入为784,输出为256
# nn.Linear(256, 10)线性层,输入为256,输出为10
net = nn.Sequential(nn.Flatten(), nn.Linear(784, 256), nn.ReLU(),
                    nn.Linear(256, 10))

def init_weights(m):
    if type(m) == nn.Linear:
        #从给定均值和标准差的正态分布(mean, std)中生成值,填充输入的张量或变量
        nn.init.normal_(m.weight, std=0.01)

# net.apply:会先遍历子线性层,再遍历父线性层
net.apply(init_weights);

 

三、训练过程

# num_epochs:表示跑多少轮
batch_size, lr, num_epochs = 256, 0.1, 10
loss = nn.CrossEntropyLoss()# 损失函数

# 更新数据
trainer = torch.optim.SGD(net.parameters(), lr=lr)
# 下载测试数据集和训练数据集
train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size)

# 直接调用d2l包的train_ch3函数
d2l.train_ch3(net, train_iter, test_iter, loss, num_epochs, trainer)

原文地址:https://www.cnblogs.com/xiaoqing-ing/p/15069608.html