多层感知机的从零开始实现

In [2]:
import torch
from torch import nn
from d2l import torch as d2l

batch_size = 256
train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size)

实现一个具有单隐藏层的多层感知机,它包含256个隐藏单元

In [3]:
num_inputs, num_outputs, num_hiddens = 784, 10, 256

W1 = nn.Parameter(
    torch.randn(num_inputs, num_hiddens, requires_grad=True) * 0.01)
b1 = nn.Parameter(torch.zeros(num_hiddens, requires_grad=True))
W2 = nn.Parameter(
    torch.randn(num_hiddens, num_outputs, requires_grad=True) * 0.01)
b2 = nn.Parameter(torch.zeros(num_outputs, requires_grad=True))

params = [W1, b1, W2, b2]

实现ReLU激活函数

In [4]:
def relu(X):
    a = torch.zeros_like(X)
    return torch.max(X, a)

实现我们的模型

In [6]:
def net(X):
    X = X.reshape((-1, num_inputs))
    H = relu(X @ W1 + b1)
    return (H @ W2 + b2)

loss = nn.CrossEntropyLoss()

多层感知机的训练过程与softmax回归的训练过程完全相同

In [7]:
num_epochs, lr = 10, 0.1
updater = torch.optim.SGD(params, lr=lr)
d2l.train_ch3(net, train_iter, test_iter, loss, num_epochs, updater)
2021-05-15T04:08:43.380505 image/svg+xml Matplotlib v3.3.4, https://matplotlib.org/

在一些测试数据上应用这个模型

In [8]:
d2l.predict_ch3(net, test_iter)
2021-05-15T04:08:43.777081 image/svg+xml Matplotlib v3.3.4, https://matplotlib.org/