- 环境:python3、torch1.2.0(torch1.5.0也可以)、torchvision0.4.0

- 代码:(注:DOWNLOAD_MNIST = False第一次应该设为True,原因在代码注释里)
1import torch
2from torch.autograd import Variable
3import torch.utils.data as Data
4import torchvision # 数据库模块
5import torch.nn as nn
6import matplotlib.pyplot as plt
7
8
9LR = 0.001 # 学习率
10BATCH_SIZE = 50 # 表示每次选取50个样本作训练
11EPOCH = 1 # epoch表示整个数据集重复训练次数
12DOWNLOAD_MNIST = False # 是否下载MNIST,第一次需要设置为True,下载完数据集,以后不需要下载,设置为False就可以了。
13
14train_data = torchvision.datasets.MNIST(root='./mnist',
15 train=True, # 表示这是训练集
16 transform=torchvision.transforms.ToTensor(), # 原始数据是array数组,转换为tensor,同时进行归一化
17 download=DOWNLOAD_MNIST)
18
19# 打印图片
20print(train_data.data.size()) # 打印训练集的大小
21print(train_data.targets.size()) # 打印训练集标签的大小
22# 使用imshow()函数加载训练集中的图片
23plt.imshow(train_data.data[0].numpy(), cmap='gray')
24plt.title('%i' % train_data.targets[0])
25plt.show()
26
27# 训练
28train_loader = Data.DataLoader(dataset=train_data, batch_size=BATCH_SIZE,
29 shuffle=True, num_workers=2) # 批量化(包装)处理数据集
30
31test_data = torchvision.datasets.MNIST(root='./mnist', train=False)
32
33'''#测试集shape from (2000, 28, 28) to (2000, 1, 28, 28), value in range(0,1)
34test_x = torch.unsqueeze(test_data.data, dim=[:2000].type(torch.FloatTensor).cuda()/255.
35
36'''#这里使用cuda()表示使用调用GPU加速跑测试集/训练集
37# test_y = test_data.targets[:2000].cuda()
38# test_x = Variable(torch.unsqueeze(test_data.test_data, dim=1), volatile=True).type(torch.FloatTensor)[:2000]/255
39with torch.no_grad():
40 test_x = Variable(torch.unsqueeze(test_data.data, dim=1)).type(torch.FloatTensor)[:2000]/255.# 这行代码中的volatile=True在torch1.5版本以上就不支持了(包括1.5版本)
41
42test_y = test_data.targets[:2000]
43
44# 搭建CNN网络
45if __name__ == '__main__':
46 class CNN(torch.nn.Module): # 定义一个神经网络层
47 def __init__(self): # 定义初始化
48 super(CNN, self).__init__() # 继承初始层
49 self.conv1 = torch.nn.Sequential(
50 nn.Conv2d(in_channels=1,
51 out_channels=16, # 卷积核个数
52 kernel_size=5, # 卷积核大小
53 stride=1, # 卷积核移动步长
54 padding=2, # 填充数目
55 ), #-->卷积后的图片形状大小(28,28,16)
56 nn.ReLU(),
57 nn.MaxPool2d(kernel_size=2), #-->池化后的图片形状大小(14,14,16)
58 )
59 self.conv2 = nn.Sequential(
60 nn.Conv2d(16, 32, 5, 1, 2), #-->第二次卷积后的图片形状大小(14,14,32)
61 nn.ReLU(),
62 nn.MaxPool2d(kernel_size=2) #-->第二次池化后的图片形状大小(7,7,32)
63 )
64 self.out = nn.Linear(32*7*7, 10) # 全连接层
65
66 def forward(self, x):
67 x = self.conv1(x)
68 x = self.conv2(x)
69 x = x.view(x.size(0), -1) # 数据展平为多维后的图片形状大小(batch size,7,7,32)
70 output = self.out(x)
71 return output
72
73 cnn = CNN()
74 print(cnn) # 打印CNN网络
75 # cnn.cuda() # CNN模型使用GPU加速
76
77 optimizer = torch.optim.Adam(cnn.parameters(), lr=LR, betas=(0.9, 0.99)) # Adam优化器
78 loss_func = nn.CrossEntropyLoss() # 损失函数
79
80 # 训练模型
81 for epoch in range(EPOCH):
82 for step, (b_x, b_y) in enumerate(train_loader):
83 # output = cnn(b_x.cuda()) # CNN预测输出
84 output = cnn(b_x) # CNN预测输出
85 # loss = loss_func(output, b_y.cuda())
86 loss = loss_func(output, b_y)
87 optimizer.zero_grad()
88 loss.backward()
89 optimizer.step()
90
91 if step % 50 == 0:
92 # test_output = cnn(test_x.cuda())
93 test_output = cnn(test_x)
94 # test_pred = torch.max(test_output, 1)[1].cuda().data
95 test_pred = torch.max(test_output, 1)[1].data
96 test_accuracy = float((test_pred == test_y).sum().item()) / float(test_y.size(0))
97 print('Epoch:', epoch, 'Train loss:', loss.data.cpu().numpy(), 'Test Accuracy:', test_accuracy)
98
99 # 观察前20个数据误差
100 test_output = cnn(test_x[:20])
101 # pred_y = torch.max(test_output, 1)[1].cuda().data
102 pred_y = torch.max(test_output, 1)[1].data
103 print(pred_y.cpu().numpy(), 'prediction number')
104 print(test_y[:20].cpu().numpy(), 'real number')
- 代码执行结果:

- 关掉显示窗口后程序继续执行
