整理自:《动手学深度学习》
在softmax的基础上加入了一个隐藏层,使得函数更加复杂,能够拟合一些非线性的数据。
隐藏层后紧跟着一层激活函数,是为了防止多层模型退化为线性模型。
此章的数据集获取、训练函数继承自上一章:softmax回归的简洁实现【动手学深度学习】_九羽-的博客-CSDN博客
1. 获取数据集
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. 定义模型
net = nn.Sequential(
nn.Flatten(),
nn.Linear(784, 256), nn.ReLU(),
nn.Linear(256,10)
)
def init_weight(m):
if type(m)==nn.Linear:
nn.init.normal_(m.weight, std=0.01)
net.apply(init_weight)
3. 损失函数,优化算法
loss = nn.CrossEntropyLoss(reduction='none')
trainer = torch.optim.SGD(net.parameters(), lr=0.1)
4. 训练
num_epochs = 10
d2l.train_ch3(net, train_iter, test_iter, loss, num_epochs, trainer)