导包
1 | import torch |
定义参数
1 | # Device configuration |
导入MNIST数据集,定义数据加载器
1 | # MNIST dataset |
定义网络
1 | # Convolutional neural network (two convolutional layers) |
定义损失函数和优化器
1 | criterion = nn.CrossEntropyLoss() |
训练模型
1 | total_step = len(train_loader) |
Epoch [1/5], Step [100/600], Loss: 0.1660
Epoch [1/5], Step [200/600], Loss: 0.1084
Epoch [1/5], Step [300/600], Loss: 0.1126
Epoch [1/5], Step [400/600], Loss: 0.1015
Epoch [1/5], Step [500/600], Loss: 0.0653
Epoch [1/5], Step [600/600], Loss: 0.0254
Epoch [2/5], Step [100/600], Loss: 0.0603
Epoch [2/5], Step [200/600], Loss: 0.0961
Epoch [2/5], Step [300/600], Loss: 0.0400
Epoch [2/5], Step [400/600], Loss: 0.0505
Epoch [2/5], Step [500/600], Loss: 0.0174
Epoch [2/5], Step [600/600], Loss: 0.0152
Epoch [3/5], Step [100/600], Loss: 0.0507
Epoch [3/5], Step [200/600], Loss: 0.0348
Epoch [3/5], Step [300/600], Loss: 0.0123
Epoch [3/5], Step [400/600], Loss: 0.0862
Epoch [3/5], Step [500/600], Loss: 0.0125
Epoch [3/5], Step [600/600], Loss: 0.0577
Epoch [4/5], Step [100/600], Loss: 0.0247
Epoch [4/5], Step [200/600], Loss: 0.0079
Epoch [4/5], Step [300/600], Loss: 0.0147
Epoch [4/5], Step [400/600], Loss: 0.0494
Epoch [4/5], Step [500/600], Loss: 0.0648
Epoch [4/5], Step [600/600], Loss: 0.0337
Epoch [5/5], Step [100/600], Loss: 0.0128
Epoch [5/5], Step [200/600], Loss: 0.0083
Epoch [5/5], Step [300/600], Loss: 0.0158
Epoch [5/5], Step [400/600], Loss: 0.0212
Epoch [5/5], Step [500/600], Loss: 0.0166
Epoch [5/5], Step [600/600], Loss: 0.0016
测试模型
1 | # eval mode (batchnorm uses moving mean/variance instead of mini-batch mean/variance) |
Test Accuracy of the model on the 10000 test images: 98.94 %