-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsemantic_gan.py
148 lines (122 loc) · 5.3 KB
/
semantic_gan.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
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
from torch.utils.data import DataLoader
from torch import nn
import argparse
from few_shot.datasets import OmniglotDataset, MiniImageNet
from few_shot.core import BasicSampler, create_nshot_task_label, EvaluateFewShot, prepare_nshot_task
from few_shot.callbacks import *
from few_shot.utils import setup_dirs
from few_shot.train import fit, gradient_step
from config import PATH
import numpy as np
from few_shot.semantic_gan import SemanticBinaryEncoder, SemanticBinaryDecoder, SemanticBinaryDiscriminator, SemanticBinaryClassifierLatentSpace, fit_gan_few_shot
import torch
import matplotlib.pyplot as plt
setup_dirs()
assert torch.cuda.is_available()
device = torch.device('cuda')
torch.backends.cudnn.benchmark = True
if __name__ == '__main__':
torch.multiprocessing.freeze_support()
##############
# Parameters #
##############
parser = argparse.ArgumentParser()
parser.add_argument('--n', default=1, type=int)
parser.add_argument('--k', default=5, type=int)
parser.add_argument('--epochs', default=50, type=int)
parser.add_argument('--size-binary-layer', default=10, type=int)
parser.add_argument('--size-continue-layer', default=10, type=int)
parser.add_argument('--stochastic', action='store_true')
parser.add_argument('--simplified', action='store_true')
# parser.add_argument('--eval-batches', default=20, type=int)
# parser.add_argument('--inner-train-steps', default=1, type=int)
# parser.add_argument('--inner-val-steps', default=3, type=int)
args = parser.parse_args()
dataset_class = OmniglotDataset
fc_layer_size = 64
num_input_channels = 1
dataset = 'Omniglot'
param_str = str(dataset) + '__n=' + str(args.n) + '_k=' + str(args.k) \
+ '_epochs=' + str(args.epochs) + '__lr=' + '__size_binary_layer=' \
+ str(args.size_binary_layer) + '__size_continue_layer=' + str(args.size_continue_layer) \
+ ('__stochastic' if args.stochastic else '__deterministic')\
+ ('__simplified' if args.simplified else '')
# f'train_steps={args.inner_train_steps}_val_steps={args.inner_val_steps}'
###################
# Create datasets #
###################
validation_split = .2
split = int(np.floor(validation_split * args.n))
background = dataset_class('background')
classes = np.random.choice(background.df['class_id'].unique(), size=args.k)
for i in classes:
background.df[background.df['class_id'] == i] = background.df[background.df['class_id'] == i].sample(frac=1)
train_dataloader = DataLoader(
background,
batch_sampler=BasicSampler(background, validation_split, True, classes, n=args.n),
num_workers=8
)
eval_dataloader = DataLoader(
background,
batch_sampler=BasicSampler(background, validation_split, False, classes, n=args.n),
num_workers=8
)
# evaluation = dataset_class('evaluation')
# evaluation_taskloader = DataLoader(
# evaluation,
# batch_sampler=NShotTaskSampler(evaluation, args.eval_batches, n=args.n, k=args.k),
# num_workers=8
# )
############
# Training #
############
print('Training semantic GAN on ' + str(dataset) + '...')
classifier = SemanticBinaryClassifierLatentSpace(args.size_binary_layer, args.k).to(device, dtype=torch.double)
encoder = SemanticBinaryEncoder(num_input_channels, args.size_binary_layer, args.size_continue_layer,
stochastic=args.stochastic).to(device, dtype=torch.double)
discriminator = SemanticBinaryDiscriminator(num_input_channels, fc_layer_size).to(device, dtype=torch.double)
generator = SemanticBinaryDecoder(args.size_binary_layer, args.size_continue_layer).to(device, dtype=torch.double)
lr_fast = 0.0002
lr_slow = 0.0001
d_optimizer = torch.optim.Adam(discriminator.parameters(), lr=lr_slow)
g_optimizer = torch.optim.Adam(generator.parameters(), lr=lr_fast)
c_optimizer = torch.optim.Adam(classifier.parameters(), lr=lr_slow)
e_optimizer = torch.optim.Adam(encoder.parameters(), lr=lr_fast)
def prepare_batch(n, k):
def prepare_batch_(batch):
x, y = batch
x = x.double().cuda()
# Create dummy 0-(num_classes - 1) label
y = create_nshot_task_label(k, n).cuda()
# for e in x:
# plt.imshow(e.cpu().squeeze().numpy())
# plt.show()
return x, y
return prepare_batch_
evalmetrics = EvaluateMetrics(eval_dataloader)
callbacks = [
evalmetrics,
CSVLogger(os.path.join(PATH, 'logs', 'semantic_gan', str(param_str) + '.csv'))
]
fit_gan_few_shot(
encoder,
generator,
classifier,
discriminator,
train_dataloader,
param_str,
args.k,
args.n,
args.epochs,
prepare_batch(args.n, args.k),
args.size_continue_layer,
args.size_binary_layer,
device,
e_optimizer,
g_optimizer,
c_optimizer,
d_optimizer,
metrics=['categorical_accuracy'],
callbacks=callbacks,
is_complete=not args.simplified
)