霜庭小筑

4.2-4.3 多层感知机的实现

4.2-4.3 多层感知机的实现

  • 导入包
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)
  • 初始化模型参数
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]
  • 激活函数
def relu(X):
a = torch.zeros_like(X)
return torch.max(X, a)
  • 模型
def net(X):
X = X.reshape(-1, num_inputs) # X形状为(256, 784)
H = relu(X @ W1 + b1) # W1形状为(784, 256),H形状为(256, 256)
return (H @ W2 + b2) # W2形状为(256, 10)
# “@”代表矩阵乘法

loss = nn.CrossEntropyLoss()

  • 训练

依旧库里没有train_ch3,不管了。

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)
#

多层感知机的简洁实现

什么?!刚刚的竟然不是简洁实现?

import torch
from torch import nn
from d2l import torch as d2l
net = nn.Sequential(nn.Flatten(),
nn.Linear(784, 256),
nn.ReLU(),
nn.Linear(256, 10))
def init_weights(m):
if type(m) == nn.Linear:
nn.init.normal_(m.weight, std=0.01);
net.apply(init_weights)
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(net, train_iter, test_iter, loss, num_epochs, trainer)
本文由 kaikaikk 原创,发布于 ; 转载请保留原文链接: https://kaikaikk.com/posts/d2l-4-2-mlp/