5.3. 多层感知机的简洁实现¶
本节将介绍通过高级API更简洁地实现多层感知机。
import mlx.core as mx
import mlx.nn as nn
import mlx.optimizers as optim
from d2l import mlx as d2l
5.3.1. 模型¶
与softmax回归的简洁实现( 4.7节)相比, 唯一的区别是我们添加了2个全连接层(之前我们只添加了1个全连接层)。 第一层是隐藏层,它包含256个隐藏单元,并使用了ReLU激活函数。 第二层是输出层。
class MLP(nn.Module):
def __init__(self):
super().__init__()
self.layers = nn.Sequential(
nn.Sequential(d2l.Flatten()),
nn.Linear(784, 256),
nn.ReLU(),
nn.Linear(256, 10)
)
def init_fn(array):
if array.ndim > 1:
array = nn.init.normal(mean=0.0, std=0.01)(array)
else:
array = nn.init.constant(0.0)(array)
return array
for module in self.modules():
if isinstance(module, nn.Linear):
module.apply(init_fn)
def __call__(self, x):
return self.layers(x)
net = MLP()
params = net.parameters()
训练过程的实现与我们实现softmax回归时完全相同, 这种模块化设计使我们能够将与模型架构有关的内容独立出来。
batch_size, lr, num_epochs = 256, 0.1, 10
loss = nn.losses.cross_entropy
trainer = optim.SGD(learning_rate=lr)
train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size)
d2l.train_ch3(net, train_iter, test_iter, loss, num_epochs, trainer, batch_size, params)
5.3.2. 小结¶
我们可以使用高级API更简洁地实现多层感知机。
对于相同的分类问题,多层感知机的实现与softmax回归的实现相同,只是多层感知机的实现里增加了带有激活函数的隐藏层。
5.3.3. 练习¶
尝试添加不同数量的隐藏层(也可以修改学习率),怎么样设置效果最好?
尝试不同的激活函数,哪个效果最好?
尝试不同的方案来初始化权重,什么方法效果最好?