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 152 153 154 155 156
|
import torch import torch.nn as nn import torch.optim as optim from torch.utils.data import DataLoader import torchvision.transforms as transforms import torchvision.datasets as datasets
import time
batch_size = 256
epochs = 300
lr = 1e-2
class AlexNet(nn.Module):
def __init__(self, num_classes=1000): super(AlexNet, self).__init__() self.features = nn.Sequential( nn.Conv2d(3, 96, kernel_size=11, stride=4, padding=0), nn.ReLU(inplace=True), nn.MaxPool2d(kernel_size=3, stride=2), nn.Conv2d(96, 256, kernel_size=5, stride=1, padding=2), nn.ReLU(inplace=True), nn.MaxPool2d(kernel_size=3, stride=2), nn.Conv2d(256, 384, kernel_size=3, stride=1, padding=1), nn.ReLU(inplace=True), nn.Conv2d(384, 384, kernel_size=3, stride=1, padding=1), nn.ReLU(inplace=True), nn.Conv2d(384, 256, kernel_size=3, stride=1, padding=1), nn.ReLU(inplace=True), nn.MaxPool2d(kernel_size=3, stride=2), ) 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.Dropout(),
nn.Linear(4096, num_classes), )
def forward(self, x): x = self.features(x) x = x.view(x.size(0), 256 * 6 * 6) x = self.classifier(x) return x
class AlexNet_v2(nn.Module): ...
def load_cifar_10_data(batch_size=128, shuffle=False): data_dir = '/home/lab305/Documents/data/cifar_10/' # data_dir = '/home/zj/zj/data/cifar_10/'
transform = transforms.Compose([ transforms.Resize((227, 227)), transforms.ToTensor(), transforms.Normalize(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5)) ])
train_data_set = datasets.CIFAR10(root=data_dir, train=True, download=True, transform=transform) test_data_set = datasets.CIFAR10(root=data_dir, train=False, download=True, transform=transform)
train_loader = DataLoader(train_data_set, batch_size=batch_size, shuffle=shuffle, num_workers=8) test_loader = DataLoader(test_data_set, batch_size=batch_size, shuffle=shuffle, num_workers=8)
return train_loader, test_loader
def compute_accuracy(loader, net, device): total_accuracy = 0 num = 0 for item in loader: data, labels = item data = data.to(device) labels = labels.to(device)
scores = net.forward(data) predicted = torch.argmax(scores, dim=1) total_accuracy += torch.mean((predicted == labels).float()).item() num += 1 return total_accuracy / num
if __name__ == '__main__': train_loader, test_loader = load_cifar_10_data(batch_size=batch_size, shuffle=True)
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") # device = torch.device("cpu")
# net = AlexNet(num_classes=10).to(device) net = AlexNet_v2(num_classes=10).to(device) criterion = nn.CrossEntropyLoss().to(device) optimer = optim.SGD(net.parameters(), lr=lr, momentum=0.9, nesterov=True)
best_train_accuracy = 0.995 best_test_accuracy = 0
loss_list = [] train_list = [] for i in range(epochs): num = 0 total_loss = 0 start = time.time() net.train() for j, item in enumerate(train_loader, 0): data, labels = item data = data.to(device) labels = labels.to(device)
scores = net.forward(data) loss = criterion.forward(scores, labels) total_loss += loss.item()
optimer.zero_grad() loss.backward() optimer.step() num += 1 end = time.time()
avg_loss = total_loss / num loss_list.append(float('%.8f' % avg_loss)) print('epoch: %d time: %.2f loss: %.8f' % (i + 1, end - start, avg_loss))
if i % 20 == 19: # 计算训练数据集检测精度 net.eval() train_accuracy = compute_accuracy(train_loader, net, device) train_list.append(float('%.4f' % train_accuracy)) if best_train_accuracy < train_accuracy: best_train_accuracy = train_accuracy
test_accuracy = compute_accuracy(test_loader, net, device) if best_test_accuracy < test_accuracy: best_test_accuracy = test_accuracy
print('best train accuracy: %.2f %% best test accuracy: %.2f %%' % ( best_train_accuracy * 100, best_test_accuracy * 100)) print(loss_list) print(train_list)
|