1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim

import torchvision
import torchvision.transforms as transforms
import numpy as np
import matplotlib.pyplot as plt

torch.set_printoptions(linewidth=120)
torch.set_grad_enabled(True) # 启用梯度跟踪

def get_num_correct(preds, labels):
return preds.argmax(dim=1).eq(labels).int().sum().item()

class Network(nn.Module): # line 1
def __init__(self):
super(Network, self).__init__()
self.conv1 = nn.Conv2d(in_channels=1, out_channels=6, kernel_size=5)
self.conv2 = nn.Conv2d(in_channels=6, out_channels=12, kernel_size=5)

self.fc1 = nn.Linear(in_features=12 * 4 * 4, out_features=120)
self.fc2 = nn.Linear(in_features=120, out_features=60)
self.out = nn.Linear(in_features=60, out_features=10)

def forward(self, t):
t = F.relu(self.conv1(t)) # 激活操作
t = F.max_pool2d(t, kernel_size=2, stride=2) # 池化操作

t = F.relu(self.conv2(t))
t = F.max_pool2d(t, kernel_size=2, stride=2)

t = F.relu(self.fc1(t.reshape(-1, 12 * 4 * 4)))
t = F.relu(self.fc2(t))
t = self.out(t)

return t

train_set = torchvision.datasets.FashionMNIST(
root='./data/FashionMNIST'
,train=True
,download=True
,transform=transforms.Compose([
transforms.ToTensor()
])
)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
network = Network()

train_loader = torch.utils.data.DataLoader(train_set, batch_size=100)
optimizer = optim.Adam(network.parameters(), lr=0.01)

for epoch in range(5):
total_loss = 0
total_correct = 0

for batch in train_loader: # Get Batch
images, labels = batch
preds = network(images)
loss = F.cross_entropy(preds, labels)
optimizer.zero_grad()
loss.backward()
optimizer.step()
total_loss += loss.item()
total_correct += get_num_correct(preds, labels)

print('eopch:', epoch, "total_correct:", total_correct, "loss:", total_loss)