model_conversion.py 1.88 KB
Newer Older
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
import models
import torch
import torch.optim as optim
import argparse
import data
import models

device = torch.device('cuda')

parser = argparse.ArgumentParser()
parser.add_argument('--models', type=int, help='Number of models to use')
parser.add_argument('--epochs', type=int, help='Number of epochs to train for')
parser.add_argument('--dataset', choices=data.spatial_dataset_map.keys(), help='Dataset to use')
parser.add_argument('--batch_size', type=int, help='Batch size')
parser.add_argument('--data', help='Root folder for the dataset')
args = parser.parse_args()

spatial_accuracies = 0
jpeg_accuracies = 0
for m in range(args.models):
    print('Train spatial model {}/{}'.format(m, args.models))
    spatial_dataset = data.spatial_dataset_map[args.dataset](args.batch_size, args.data)
    dataset_info = data.dataset_info[args.dataset]
    spatial_model = models.SpatialResNet(dataset_info['channels'], dataset_info['classes']).to(device)
    optimizer = optim.Adam(spatial_model.parameters())

    for e in range(args.epochs):
        models.train(spatial_model, device, spatial_dataset[0], optimizer, e)
        models.test(spatial_model, device, spatial_dataset[1])

    acc = models.test(spatial_model, device, spatial_dataset[1])
    spatial_accuracies += acc

    print('Convert model to JPEG')
    jpeg_model = models.JpegResNetExact(spatial_model).to(device)

    print('Test JPEG model')
    jpeg_dataset = data.jpeg_dataset_map[args.dataset](args.batch_size, args.data)
    acc = models.test(jpeg_model, device, jpeg_dataset[1])
    jpeg_accuracies += acc

spatial_accuracies /= args.models
jpeg_accuracies /= args.models

print('Report')
print('======')
print('Number of Models: {}'.format(args.n_models))
print('Average Spatial Accuracy: {}'.format(spatial_accuracies))
print('Average JPEG Accuracy: {}'.format(jpeg_accuracies))
print('Deviation: {}'.format(spatial_accuracies - jpeg_accuracies))