1
2
3
import torch
from torch import nn
from d2l import torch as d2l
1
2
batch_size = 256
train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size)#先加载数据集并且分类为训练集和测试集

3.7.1 Initialize modelling parameters

1
2
3
4
5
6
7
8
9
10
11
#Softmax regression output layer is a fully connection layer. So to realize the model, we only
#need to add a 10-output fully connected layer in Sequential

#pytorch will not adjust shape of input implicitly
#so we define flatten layer before Linear layer to adjust the shape of network input.
net = nn.Sequential(nn.Flatten(), nn.Linear(784, 10))

def init_weights(m):
if type(m) == nn.Linear:
nn.init.normal_(m.weight, std=0.01)
net.apply(init_weights)
Sequential(
  (0): Flatten(start_dim=1, end_dim=-1)
  (1): Linear(in_features=784, out_features=10, bias=True)
)
1
loss = nn.CrossEntropyLoss(reduction='none')

3.7.3 优化算法

1
trainer = torch.optim.SGD(net.parameters(), lr = 0.1)

3.7.4 training

1
2
num_epochs = 10
d2l.train_ch3(net, train_iter, test_iter, loss, num_epochs, trainer)

svg