-
Notifications
You must be signed in to change notification settings - Fork 3
/
main_naive.py
85 lines (62 loc) · 2.99 KB
/
main_naive.py
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
import torch
from torchvision.datasets.cifar import CIFAR100
from cl_dataset_tools import NCProtocol, NCProtocolIterator
from torchvision.models.resnet import resnet18
from torch.utils.data import DataLoader
from torch.utils.data import Dataset
import torchvision.transforms as transforms
from cl_metrics_tools import get_accuracy
tasks = 10
n_epochs = 1
top_k_accuracies = [1, 5]
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
transform = transforms.Compose([
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),
])
transform_test = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),
])
def main():
protocol = NCProtocol(CIFAR100('./data/cifar100', train=True, download=True, transform=transform),
CIFAR100('./data/cifar100', train=False, download=True, transform=transform_test),
n_tasks=tasks, shuffle=True, seed=1234)
model = resnet18(pretrained=False, num_classes=100).to(device)
train_dataset: Dataset
task_info: NCProtocolIterator
for task_idx, (train_dataset, task_info) in enumerate(protocol):
print('Classes in this batch:', task_info.classes_in_this_task)
train_loader = DataLoader(train_dataset, batch_size=128, shuffle=True, num_workers=4)
optimizer = torch.optim.Adam(model.parameters())
criterion = torch.nn.CrossEntropyLoss()
# Sets model in train mode
model.train()
for epoch in range(n_epochs):
for patterns, labels in train_loader:
# Clear grad
model.zero_grad()
# Send data to device
patterns = patterns.to(device)
labels = labels.to(device)
# Forward
output = model(patterns)
# Loss
loss = criterion(output, labels)
# Backward
loss.backward()
# Update step
optimizer.step()
print('Task', task_idx, 'ended')
top_train_accuracies, _, _ = get_accuracy(model,
task_info.swap_transformations().get_current_training_set(),
device=device, required_top_k=top_k_accuracies, batch_size=128)
for top_k_idx, top_k_acc in enumerate(top_k_accuracies):
print('Top', top_k_acc, 'train accuracy', top_train_accuracies[top_k_idx].item())
top_test_accuracies, _, _ = get_accuracy(model, task_info.get_cumulative_test_set(), device=device,
required_top_k=top_k_accuracies, batch_size=128)
for top_k_idx, top_k_acc in enumerate(top_k_accuracies):
print('Top', top_k_acc, 'test accuracy', top_test_accuracies[top_k_idx].item())
if __name__ == '__main__':
main()