一、从0实现多层感知机
1、导包以及加载数据,使用的是Fashion-MNIST图像分类数据集
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)
2、初始化模型参数 Fashion-MNIST中的每个图像由 28 × 28 = 784个灰度像素值组成,所有图像共分为10个类别。忽略像素之间的空间结构,我们可以将每个图像视为具有784个输?特征和10个类的简单分类数据集。创建隐藏层为1有256个隐藏单元的感知机
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]
3、激活函数 自己实现的Relu激活函数,也可以调用内置的激活函数
def relu(X):
a = torch.zeros_like(X)
return torch.max(X, a)
4、模型 由于忽略了空间结构,所以我们使?reshape将每个?维图像转换为?个?度为num_inputs的向量。
def net(X):
X = X.reshape((-1, num_inputs))
H = relu(X@W1 + b1)
return (H@W2 + b2)。
5、损失函数使用内置的损失函数
loss = nn.CrossEntropyLoss(reduction='none')
6、进行训练
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)
结果为:
进行test
d2l.predict_ch3(net, test_iter)
结果为:
二、简洁实现多层感知机
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(reduction='none')
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)
|