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

《动手学深度学习pytorch》部分学习笔记,仅用作自己复习。

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

import torch
import numpy as np
import sys
sys.path.append("..")
import d2lzh_pytorch as d2l

 获取和读取数据

# 我们将使⽤多层感知机对图像进⾏分类。
batch_size = 256 # 设置批量大小为256
# 这里继续使⽤Fashion-MNIST数据集。
train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size)

定义模型参数

# Fashion-MNIST数据集中图像形状为 28x28,类别数为10。
# 本节中我们依然使⽤长度为 28x28=784的向量表示每一张图像。
# 因此,输⼊个数为784,输出个数为10。实验中,我们设超参数隐藏单元个数为256。
num_inputs, num_outputs, num_hiddens = 784, 10, 256
W1 = torch.tensor(np.random.normal(0, 0.01, (num_inputs,num_hiddens)), dtype=torch.float)
b1 = torch.zeros(num_hiddens, dtype=torch.float)
W2 = torch.tensor(np.random.normal(0, 0.01, (num_hiddens,num_outputs)), dtype=torch.float)
b2 = torch.zeros(num_outputs, dtype=torch.float)
params = [W1, b1, W2, b2]
for param in params:
  param.requires_grad_(requires_grad=True)

定义激活函数

这⾥我们使用基础的 max 函数来实现ReLU,⽽非直接调⽤ relu 函数。

def relu(X):
  return torch.max(input=X, other=torch.tensor(0.0))

定义模型

def net(X):
  # 通过 view 函数将每张原始图像改成⻓度为 num_inputs 的向量。
  X = X.view((-1, num_inputs))
  # 实现上⼀节中多层感知机的计算表达式。
  H = relu(torch.matmul(X, W1) + b1)
  return torch.matmul(H, W2) + b2

定义损失函数

# 为了得到更好的数值稳定性,我们直接使⽤PyTorch提供的包括softmax运算和交叉熵损失计算的函数。
loss = torch.nn.CrossEntropyLoss() 

 训练模型

# 设超参数迭代周期数为5,学习率为100.0。
num_epochs, lr = 5, 100.0
d2l.train_ch3(net, train_iter, test_iter, loss, num_epochs,batch_size, params, lr)

输出:

epoch 1, loss 0.0030, train acc 0.714, test acc 0.753
epoch 2, loss 0.0019, train acc 0.821, test acc 0.777
epoch 3, loss 0.0017, train acc 0.842, test acc 0.834
epoch 4, loss 0.0015, train acc 0.857, test acc 0.839
epoch 5, loss 0.0014, train acc 0.865, test acc 0.845

小结

  • 可以通过⼿动定义模型及其参数来实现简单的多层感知机。
  • 当多层感知机的层数较多时,本节的实现方法会显得较烦琐,例如在定义模型参数的时候。

猜你喜欢

转载自blog.csdn.net/dujuancao11/article/details/108388567