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 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
|
""" @author: zj @file: mnist.py @time: 2019-12-10 """
import time
import torch import torch.nn as nn import torch.optim as optim
import torchvision.transforms as transforms from torch.utils.data import DataLoader import torchvision.datasets as datasets
root = './data' bsize = 256 shuffle = True num_work = 8
learning_rate = 1e-3 moment = 0.9 epoches = 30
classes = range(10)
def load_mnist(transform, root, bsize, shuffle, num_work): train_dataset = datasets.MNIST(root, train=True, download=True, transform=transform) train_loader = DataLoader(train_dataset, batch_size=bsize, shuffle=shuffle, num_workers=num_work)
test_dataset = datasets.MNIST(root, train=False, download=True, transform=transform) test_loader = DataLoader(test_dataset, batch_size=bsize, shuffle=shuffle, num_workers=num_work)
return train_loader, test_loader
def load_fashion_mnist(transform, root, bsize, shuffle, num_work): train_dataset = datasets.FashionMNIST(root, train=True, download=True, transform=transform) train_loader = DataLoader(train_dataset, batch_size=bsize, shuffle=shuffle, num_workers=num_work)
test_dataset = datasets.FashionMNIST(root, train=False, download=True, transform=transform) test_loader = DataLoader(test_dataset, batch_size=bsize, shuffle=shuffle, num_workers=num_work)
return train_loader, test_loader
def compute_accuracy(loader, net, device): total_accu = 0.0 num = 0
for i, data in enumerate(loader, 0): inputs, labels = data[0].to(device), data[1].to(device)
outputs = net.forward(inputs) predicted = torch.argmax(outputs, dim=1) total_accu += torch.mean((predicted == labels).float()).item() num += 1 return total_accu / num
class AlexNet(nn.Module):
def __init__(self, num_channels=3, num_classes=1000): super(AlexNet, self).__init__() self.features = nn.Sequential( nn.Conv2d(num_channels, 64, kernel_size=11, stride=4, padding=2), nn.ReLU(inplace=True), nn.MaxPool2d(kernel_size=3, stride=2), nn.Conv2d(64, 192, kernel_size=5, padding=2), nn.ReLU(inplace=True), nn.MaxPool2d(kernel_size=3, stride=2), nn.Conv2d(192, 384, kernel_size=3, padding=1), nn.ReLU(inplace=True), nn.Conv2d(384, 256, kernel_size=3, padding=1), nn.ReLU(inplace=True), nn.Conv2d(256, 256, kernel_size=3, padding=1), nn.ReLU(inplace=True), nn.MaxPool2d(kernel_size=3, stride=2), ) self.avgpool = nn.AdaptiveAvgPool2d((6, 6)) self.classifier = nn.Sequential( nn.Dropout(), nn.Linear(256 * 6 * 6, 4096), nn.ReLU(inplace=True), nn.Dropout(), nn.Linear(4096, 4096), nn.ReLU(inplace=True), nn.Linear(4096, num_classes), )
def forward(self, x): x = self.features(x) x = self.avgpool(x) x = torch.flatten(x, 1) x = self.classifier(x) return x
if __name__ == '__main__': transform = transforms.Compose([ transforms.Resize((227, 227)), transforms.ToTensor(), transforms.Normalize(mean=(0.5,), std=(0.5,)) ]) train_loader, test_loader = load_mnist(transform, root, bsize, shuffle, num_work) # train_loader, test_loader = load_fashion_mnist(transform, root, bsize, shuffle, num_work)
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") net = AlexNet(num_channels=1, num_classes=10).to(device) criterion = nn.CrossEntropyLoss().to(device) optimer = optim.SGD(net.parameters(), lr=learning_rate, momentum=0.9, nesterov=True)
train_accu_list = list() test_accu_list = list() loss_list = list()
for epoch in range(epoches): num = 0 total_loss = 0.0 start = time.time() for i, data in enumerate(train_loader, 0): inputs, labels = data[0].to(device), data[1].to(device)
optimer.zero_grad()
outputs = net(inputs) loss = criterion(outputs, labels) loss.backward() optimer.step()
total_loss += loss.item() num += 1 end = time.time()
avg_loss = total_loss / num print('[%d] loss: %.5f, time: %.3f' % (epoch + 1, avg_loss, end - start)) loss_list.append(avg_loss)
train_accu = compute_accuracy(train_loader, net, device) test_accu = compute_accuracy(test_loader, net, device) print('train: %.3f, test: %.3f' % (train_accu, test_accu)) train_accu_list.append(train_accu) test_accu_list.append(test_accu)
print(loss_list) print(train_accu_list) print(test_accu_list)
|