-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgen.py
1844 lines (1690 loc) · 66.4 KB
/
gen.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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
This file defines generating processes for data using the environments defined
in the env module.
The first simple classification task should be the following : with a fixed
number of objects, train a model to recognise object configuration,
irrespective of object position.
"""
import os.path as op
import random
import pickle
import numpy as np
import cv2
import torch
from glob import glob
from tqdm import tqdm
from env import Env
from dataset import Dataset, PartsDataset
from utils import to_file, from_file
### quick testing ###
import matplotlib.pyplot as plt
from torch.utils.data import DataLoader
from dataset import collate_fn
N_SH = 3
DTYPE = torch.float32
class Resample(Exception):
"""
Raised when sampling of random transformations times out. This means the
generated config is probably too big and we should drop it.
"""
def __init__(self, message):
self.message = message
class SimpleTaskGen():
"""
docstring for SimpleTaskGen
Change name for something more sexy.
"""
def __init__(self, env, n_objects):
super(SimpleTaskGen, self).__init__()
self._env = env
self._configs = []
self.n_objects = n_objects
self._config_id = 0
def _generate_configs(self,
n,
ref_state=None,
rotations=False,
record=False,
shuffle=False):
"""
Generates the reference spatial configuration and its perturbations.
TODO : how to manage SamplingTimeouts ?
Arguments :
- n : number of output states
- ref_state (list of object vectors) : reference state. If not
provided, a new one is generated at random.
"""
self._env.reset()
if record:
rec = {'translations': [],
'scalings': [],
'rotations': []}
# generate reference config
if ref_state is None:
self._env.random_config(self.n_objects)
ref_state = self._env.to_state_list()
self._configs.append((ref_state, self._config_id))
for _ in range(n - 1):
self._env.from_state_list(ref_state)
if shuffle:
self._env.shuffle_objects()
amount, scale, phi = self._env.random_transformation(
rotations=rotations)
self._configs.append((self._env.to_state_list(), self._config_id))
if record:
rec['translations'].append(amount)
rec['scalings'].append(scale)
rec['rotations'].append(phi)
self._config_id += 1
if record:
return rec
def generate(self, n_configs, n, restart=True):
"""
Genarates n_configs * n states.
Arguments :
- n_configs (int) : number of total different configurations.
- n (int) : number of versions of the same configuration.
- restart (bool) : Whether to start from 0 for the configuration
indices. Default is True.
"""
if restart:
self._env.reset()
self._config_id = 0
for _ in range(n_configs):
self._generate_configs(n)
def generate_mix(self,
n_obj_configs,
n_spatial_configs,
n,
restart=True,
rotations=False,
record=False,
shuffle=False):
"""
Generates configs with object re-mixing.
Arguments :
- n_obj_configs (int) : number of different configurations for the
size, color, and orientation of the objects.
- n_spatial_configs (int) : number of different shufflings of the
same objects (same color, size and orientation)
- n (int) : number of transformations of the same spatial
configuration.
- restart (bool) : whether or not to restart from scratch,
resetting the internal state of the generator. Defaults to True
- rotations (bool) : whether or not to have rotations in our
generating process. Defaults to False.
- record (bool) : whether or not to record the translation vectors,
scaling factors, and rotation angles used in the generating
process.
- shuffle (bool) : whether or not to shuffle the order of objects
in the generating process. If False, the objects are always in
the same order, across configurations with the same objects.
"""
if restart:
self._env.reset()
self._config_id = 0
if record:
recs = {'translations': [],
'scalings': [],
'rotations': []}
print('Generating %s object configs :' % n_obj_configs)
for i in range(n_obj_configs):
# generate ref state
self._env.reset()
self._env.random_config(self.n_objects)
ref_state = self._env.to_state_list()
for j in tqdm(range(n_spatial_configs)):
self._env.reset()
self._env.from_state_list(ref_state)
self._env.random_mix()
state = self._env.to_state_list()
rec = self._generate_configs(n,
state,
rotations,
record,
shuffle)
if record and rec is not None:
recs['translations'] += rec['translations']
recs['scalings'] += rec['scalings']
recs['rotations'] += rec['rotations']
if record:
return recs
def save(self, path, img_path=None):
"""
Saves the current configurations to a text file at path.
"""
to_file(self._configs, path)
print('generating images')
if img_path is not None:
img_count = 0
for state, idx in tqdm(self._configs):
img_name = 'img' + str(img_count) + '.jpg'
self._env.from_state_list(state)
self._env.save_image(op.join(img_path, img_name))
self._env.reset()
img_count += 1
def load(self, path):
"""
Loads the configurations at path.
"""
self._configs = from_file(path)
self._config_id = len(self._configs) # this assumes the loaded data
# begin at 0 and increment
class Gen():
"""
Class for the generator of the Parts task.
Can also be used as a dataset, to plug a pytorch Dataloader.
"""
def __init__(self, env=None, n_d=None):
"""
Initialize the Parts task generator.
The Parts dataset trains a model to recognize if a query configuration
is present or not in a given reference. The query objects are always
present in the reference, but may be present in a different spatial
arrangement (this is a negative example).
The constructor defines the range of the number of objects in the
query range_t, and the range of the number of additional distractor
objects range_d. If no distractors are provided, the tasks comes back
to SimpleTask, judging the similarity of two scenes.
This class defines no generating functions, which must be implemented
according to the specific, concrete task at hand.
"""
if env is None:
self.env = Env(16, 20)
self.range_t = [2, 5]
self.range_d = [0, 6]
self.n_d = n_d
# has metadata
self.has_metadata = False
# data
self.reset()
def reset(self):
# reset env
self.env.reset()
# reset data
self.targets = []
self.t_batch = []
self.refs = []
self.r_batch = []
self.labels = []
# careful, those are lists of torch.tensors
self.t_idx = []
self.r_idx = []
def compute_access_indices(self):
"""
Computes lists of target and reference indices for downsream efficient
access. Computation-intensive.
"""
pass
def gen_one(self):
raise NotImplementedError()
def generate(self, N):
raise NotImplementedError()
def generate_overfit(self, N, n):
raise NotImplementedError()
# def add_one(self, targets, refs, labels):
# self.targets += targets
# self.refs += refs
# self.labels += labels
def cut(self, n):
"""
Cuts the data to the n first examples.
"""
if not self.t_idx:
self.compute_access_indices()
t_stop_index = self.t_idx[n-1][-1] + 1
if self.refs:
r_stop_index = self.r_idx[n-1][-1] + 1
self.targets = self.targets[:t_stop_index]
self.t_batch = self.t_batch[:t_stop_index]
if self.refs:
self.refs = self.refs[:r_stop_index]
self.r_batch = self.r_batch[:r_stop_index]
self.labels = self.labels[:n]
self.t_idx = self.t_idx[:n]
self.r_idx = self.r_idx[:n]
def multiply(self, n):
"""
Duplicates the existing examples n times.
"""
# if not self.t_idx:
# self.compute_access_indices()
self.targets *= n
self.refs *= n
self.labels *= n
# self.t_batch *= n
# self.r_batch *= n
mem = list(self.t_batch)
for i in range(n - 1):
mem += [elem + mem[-1] + 1 for elem in self.t_batch]
self.t_batch = mem
mem = list(self.r_batch)
for i in range(n - 1):
mem += [elem + mem[-1] + 1 for elem in self.r_batch]
self.r_batch = mem
self.compute_access_indices()
def write_targets(self, f):
"""
Writes the targets, and the t_batch to file f. Every object vector
is prepended its batch index.
"""
f.write('targets\n')
for i, obj in enumerate(self.targets):
f.write(str(self.t_batch[i]) + ' ')
for num in obj:
f.write(str(num) + ' ')
f.write('\n')
def write_refs(self, f):
"""
Writes the refs, and the r_batch to file f. Every object vector
is prepended its batch index.
"""
f.write('refs\n')
for i, obj in enumerate(self.refs):
f.write(str(self.r_batch[i]) + ' ')
for num in obj:
f.write(str(num) + ' ')
f.write('\n')
def write_labels(self, f):
"""
Writes the labels.
"""
f.write('labels\n')
for label in self.labels:
for i in label:
f.write(str(i) + ' ')
f.write('\n')
def write_t_idx(self, f):
"""
Writes the t-indices.
"""
f.write('t_idx\n')
for idx in self.t_idx:
for i in idx:
f.write(str(i.numpy()) + ' ')
f.write('\n')
def write_r_idx(self, f):
"""
Writes the r-indices.
"""
f.write('r_idx\n')
for idx in self.r_idx:
for i in idx:
f.write(str(i.numpy()) + ' ')
f.write('\n')
def write_metadata(self, path):
pass
def read_targets(self, lineit):
"""
Takes in an iterator of the lines read.
Reads the targets and t_batch from lines, returns targets, t_batch
and stopping index.
"""
targets = []
t_batch = []
line = next(lineit)
while 'refs' not in line:
if 'targets' in line:
pass # first line
else:
linelist = line.split(' ')
t_batch.append(int(linelist[0]))
targets.append(np.array(linelist[1:-1], dtype=float))
line = next(lineit)
return targets, t_batch
def read_refs(self, lineit):
"""
Takes in an iterator of the lines read.
Reads the refs and r_batch from lines, returns refs, r_batch
and stopping index.
"""
refs = []
r_batch = []
line = next(lineit)
while 'labels' not in line:
linelist = line.split(' ')
r_batch.append(int(linelist[0]))
refs.append(np.array(linelist[1:-1], dtype=float))
line = next(lineit)
return refs, r_batch
def read_labels(self, lineit):
"""
Reads the label from an iterator on the file lines.
"""
labels = []
try:
line = next(lineit)
while 't_idx' not in line:
labels.append([float(line)])
line = next(lineit)
except StopIteration: # the file may also end here
pass
return labels
def read_t_idx(self, lineit):
"""
Reads the t-indices from the file line iterator.
"""
t_idx = []
line = next(lineit)
while 'r_idx' not in line:
linelist = line.split(' ')
to_array = np.array(linelist[:-1], dtype=int)
t_idx.append(torch.tensor(to_array, dtype=torch.long))
line = next(lineit)
return t_idx
def read_r_idx(self, lineit):
r_idx = []
try:
line = next(lineit)
while 'some_other_stuff' not in line:
linelist = line.split(' ')
# print(linelist)
to_array = np.array(linelist[:-1], dtype=int)
r_idx.append(torch.tensor(to_array, dtype=torch.long))
line = next(lineit)
except StopIteration:
pass
return r_idx
def read_vectors(self, lineit, start_token, stop_token):
"""
Takes in an iterator of the lines read.
Reads the vectors from lines and returns a list of the read vectors.
"""
try:
vectors = []
line = next(lineit)
while stop_token not in line:
if start_token in line:
pass # first line
else:
linelist = line.split(' ')
vectors.append(np.array(linelist[:-1], dtype=float))
line = next(lineit)
except StopIteration:
pass
return vectors
def read_scalars(self, lineit, start_token, stop_token):
"""
Reads the scalars (one per line) and returns them as a list.
"""
try:
scalars = []
line = next(lineit)
while stop_token not in line:
linelist = line.split(' ')
scalars.append(float(linelist[0]))
line = next(lineit)
except StopIteration:
pass
return scalars
def read_metadata(self, path):
pass
def save(self, path, write_indices=True):
"""
Saves the dataset as a file.
"""
with open(path, 'w') as f:
self.write_targets(f)
self.write_refs(f)
self.write_labels(f)
if write_indices:
self.write_t_idx(f)
self.write_r_idx(f)
# self.write_metadata(path)
def load(self, path, read_indices=True, replace=True):
"""
Reads previously saved generator data.
"""
with open(path, 'r') as f:
# reads from line iterator
lines = f.readlines()
lineit = iter(lines)
targets, t_batch = self.read_targets(lineit)
refs, r_batch = self.read_refs(lineit)
labels = self.read_labels(lineit)
# self.read_metadata(path)
# stores the data
if replace:
self.targets = targets
self.t_batch = t_batch
self.refs = refs
self.r_batch = r_batch
self.labels = labels
# if read_indices:
# self.t_idx = t_idx
# self.r_idx = r_idx
else:
# this doesn't work as is, need to update indices
self.targets += targets
self.t_batch += t_batch
self.refs += refs
self.r_batch += r_batch
self.labels += labels
def to_dataset(self, n=None, label_type='long', device=torch.device('cpu')):
"""
Creates a PartsDataset from the generated data and returns it.
Arguments :
- n (int) : allows to contol the dataset size for export.
"""
ds = PartsDataset(self.targets,
self.t_batch,
self.refs,
self.r_batch,
self.labels,
self.task_type,
device=device)
return ds
class PartsGen(Gen):
"""
Generator for the Parts Task.
"""
def __init__(self, env=None, n_d=None):
"""
Initialize the Parts task generator.
The Parts dataset trains a model to recognize if a query configuration
is present or not in a given reference. The query objects are always
present in the reference, but may be present in a different spatial
arrangement (this is a negative example).
The constructor defines the range of the number of objects in the
query range_t, and the range of the number of additional distractor
objects range_d. If no distractors are provided, the tasks comes back
to SimpleTask, judging the similarity of two scenes.
This concrete class defines the generation functions.
"""
super(PartsGen, self).__init__(env, n_d)
self.task = 'parts_task'
self.task_type = 'scene'
self.label_type='long'
def gen_one(self):
"""
Generates one pair of true-false examples associated with a given
query.
The targets are perturbed (similarity + small noise) before being
completed with distractors.
"""
# Note : we could generate 4 by 4 with this code, by crossing targets
# and refs
try:
self.env.reset()
n_t = np.random.randint(*self.range_t)
if self.n_d is None:
n_d = np.random.randint(*self.range_d)
else:
n_d = self.n_d
self.env.random_config(n_t)
query = self.env.to_state_list(norm=True)
# generate positive example
self.env.shuffle_objects()
self.env.random_transformation()
self.env.random_config(n_d) # add random objects
trueworld = self.env.to_state_list(norm=True)
# generate negative example
if self.n_d is None:
n_d = np.random.randint(*self.range_d)
else:
n_d = self.n_d
self.env.reset()
self.env.from_state_list(query, norm=True)
self.env.shuffle_objects() # shuffle order of the objects
self.env.random_mix() # mix config
self.env.random_transformation()
self.env.random_config(n_d) # add random objects
falseworld = self.env.to_state_list(norm=True)
return query, trueworld, falseworld
except SamplingTimeout:
print('Sampling timed out, {} and {} objects'.format(n_t, n_d))
raise Resample('Resample configuration')
def generate(self, N):
"""
Generates a dataset of N positive and N negative examples.
Arguments :
- N (int) : half of the dataset length
Generates:
- targets (list of vectors): list of all the query objets;
- t_batch (list of ints): list of indices linking the query
objects to their corresponding scene index;
- refs (list of object vectors): list of all the reference
objects;
- r_batch (list of ints): list of indices linking the reference
objects to their corresponding scene index;
- labels (list of ints): list of scene labels.
"""
print('generating dataset of %s examples :' % (2 * N))
for i in tqdm(range(N)):
try:
query, trueworld, falseworld = self.gen_one()
except Resample:
# We resample the config once
# If there is a sampling timeout here, we let it pass
query, trueworld, falseworld = self.gen_one()
n_t = len(query)
n_r1 = len(trueworld)
n_r2 = len(falseworld)
self.targets += 2 * query
self.t_batch += n_t * [2*i] + n_t * [2*i + 1]
self.refs += trueworld + falseworld
self.r_batch += n_r1 * [2*i] + n_r2 * [2*i + 1]
self.labels += [[1], [0]]
def generate_overfit(self, N, n):
"""
Generates a dataset of size 2 * N with n positive and n negative
(n << N) samples. Used for overfitting a model to check model capacity.
"""
print('generating dataset of %s examples :' % (2 * N))
mem = []
for i in range(n):
try:
query, trueworld, falseworld = self.gen_one()
except Resample:
# We resample the config once
# If there is a sampling timeout here, we let it pass
query, trueworld, falseworld = self.gen_one()
mem.append((query, trueworld, falseworld))
for i in tqdm(range(N)):
query, trueworld, falseworld = random.choice(mem)
n_t = len(query)
n_r1 = len(trueworld)
n_r2 = len(falseworld)
self.targets += 2 * query
self.t_batch += n_t * [2*i] + n_t * [2*i + 1]
self.refs += trueworld + falseworld
self.r_batch += n_r1 * [2*i] + n_r2 * [2*i + 1]
self.labels += [[1], [0]]
class PartsGenv2(Gen):
"""
A different version of the Parts Generator, to sample configurations that
only differ slightly, in terms of configuration of the objects that
interests us. This is because in the previous generator, we only present
to the model examples of samples that differ either completely, either that
have the same configuration, up to similarity. This may make the task
harder to learn, and the model more brittle when it learns.
In this generator, we first sample the query, then for positive examples
we translate/shift a bit (maybe also jitter object positions/angles/colors
?), and for negative examples we move one to all objects (number of objects
moved sampled uniformly).
Contrary to the previous generator, we generate one example per step.
"""
def __init__(self, env=None, n_d=None):
"""
Initialize the Parts task generator, version 2.
"""
super(PartsGenv2, self).__init__(env, n_d)
self.task = 'parts_task'
self.task_type = 'scene'
self.label_type='long'
def gen_one(self):
"""
Generates one training example.
"""
try:
self.env.reset()
label = np.random.randint(0, 2)
n_t = np.random.randint(*self.range_t)
if self.n_d is None:
n_d = np.random.randint(*self.range_d)
else:
n_d = self.n_d
self.env.random_config(n_t)
query = self.env.to_state_list(norm=True)
if label:
self.env.random_transformation()
self.env.random_config(n_d)
world = self.env.to_state_list(norm=True)
else:
n_p = np.random.randint(1, n_t + 1) # number of perturbed objects
self.env.perturb_objects(n_p)
self.env.random_transformation()
self.env.random_config(n_d)
world = self.env.to_state_list(norm=True)
return query, world, label
except SamplingTimeout:
print('Sampling timed out, {} and {} objects'.format(n_t, n_d))
raise Resample('Resample configuration')
def generate(self, N):
"""
Generates a dataset of N positive and N negative examples.
Arguments :
- N (int) : half of the dataset length
Generates:
- targets (list of vectors): list of all the query objets;
- t_batch (list of ints): list of indices linking the query
objects to their corresponding scene index;
- refs (list of object vectors): list of all the reference
objects;
- r_batch (list of ints): list of indices linking the reference
objects to their corresponding scene index;
- labels (list of ints): list of scene labels.
"""
print('generating dataset of %s examples :' % N)
for i in tqdm(range(N)):
try:
query, world, label = self.gen_one()
except Resample:
# We resample the config once
# If there is a sampling timeout here, we let it pass
query, world, label = self.gen_one()
n_t = len(query)
n_r = len(world)
self.targets += query
self.t_batch += n_t * [i]
self.refs += world
self.r_batch += n_r * [i]
self.labels += [[label]]
class SimilarityObjectsGen(Gen):
"""
A generator for the Similarity-Object task.
Similar to the generator for Similarity-Boolean task, except the labels are
not 1 and 0 for each scene, but fir each object.
"""
def __init__(self, env=None, n_d=None):
"""
Initialize the Parts task generator.
The Parts dataset trains a model to recognize if a query configuration
is present or not in a given reference. The query objects are always
present in the reference, but may be present in a different spatial
arrangement (this is a negative example).
The constructor defines the range of the number of objects in the
query range_t, and the range of the number of additional distractor
objects range_d. If no distractors are provided, the tasks comes back
to SimpleTask, judging the similarity of two scenes.
This concrete class defines the generation functions.
"""
super(SimilarityObjectsGen, self).__init__(env, n_d)
self.task = 'similarity_object'
self.task_type = 'object'
self.label_type = 'long'
def gen_one(self):
"""
Generates one pair of true-false examples associated with a given
query.
The targets are perturbed (similarity + small noise) before being
completed with distractors.
"""
# Note : we could generate 4 by 4 with this code, by crossing targets
# and refs
try:
self.env.reset()
n_t = np.random.randint(*self.range_t)
if self.n_d is None:
n_d = np.random.randint(*self.range_d)
else:
n_d = self.n_d
self.env.random_config(n_t)
query = self.env.to_state_list(norm=True)
# generate positive example
self.env.shuffle_objects() # useless
self.env.random_transformation()
self.env.random_config(n_d) # add random objects
trueworld = self.env.to_state_list(norm=True)
truelabel = np.zeros(len(trueworld), dtype=int)
truelabel[:len(query)] = 1 # distractors are appended
# generate negative example
if self.n_d is None:
n_d = np.random.randint(*self.range_d)
else:
n_d = self.n_d
self.env.reset()
self.env.from_state_list(query, norm=True)
self.env.shuffle_objects() # shuffle order of the objects
self.env.random_mix() # mix config
self.env.random_transformation()
self.env.random_config(n_d) # add random objects
falseworld = self.env.to_state_list(norm=True)
falselabel = np.zeros(len(falseworld), dtype=int)
query = query
return query, trueworld, falseworld, truelabel, falselabel
except SamplingTimeout:
print('Sampling timed out, {} and {} objects'.format(n_t, n_d))
raise Resample('Resample configuration')
def generate(self, N):
"""
Generates a dataset of N positive and N negative examples.
Arguments :
- N (int) : half of the dataset length
Generates:
- targets (list of vectors): list of all the query objets;
- t_batch (list of ints): list of indices linking the query
objects to their corresponding scene index;
- refs (list of object vectors): list of all the reference
objects;
- r_batch (list of ints): list of indices linking the reference
objects to their corresponding scene index;
- labels (list of ints): list of scene labels.
"""
print('generating dataset of %s examples :' % (2 * N))
for i in tqdm(range(N)):
try:
query, trueworld, falseworld, truelabel, falselabel = \
self.gen_one()
except Resample:
# We resample the config once
# If there is a sampling timeout here, we let it pass
query, trueworld, falseworld, truelabel, falselabel = \
self.gen_one()
n_t = len(query)
n_r1 = len(trueworld)
n_r2 = len(falseworld)
self.targets += 2 * query
self.t_batch += n_t * [2*i] + n_t * [2*i + 1]
self.refs += trueworld + falseworld
self.r_batch += n_r1 * [2*i] + n_r2 * [2*i + 1]
self.labels += [[1]] * len(query)
self.labels += [[0]] * (len(trueworld) - len(query))
self.labels += [[0]] * len(falseworld)
class CountGen(Gen):
"""
A generator for the conting task.
"""
def __init__(self, env=None, n_d=None):
"""
Initialize the Number class generator.
blabla
This concrete class defines the generation functions.
"""
super(CountGen, self).__init__(env, n_d)
self.task = 'count'
self.task_type = 'scene'
self.max_n = 10
self.color_sigma = 0.05 # standard deviation for the color, test this
self.label_type = 'float'
def gen_one(self):
"""
Generates one example.
For now we consider only one object in the query, we'll see later for
greater number of objects.
To generate objects that are 'the same', we sample their color from a
3-dimensional Gaussian centered on the color of the query object, and
with small standard deviation.
"""
try:
self.env.reset()
# sample query object
self.env.add_random_object()
obj = self.env.objects[0]
color = obj.color
idx = obj.shape_index
# sample number
n = np.random.randint(1, self.max_n + 1)
query = self.env.to_state_list(norm=True)
# fill world with similar objects, as the number requires
self.env.reset()
for _ in range(n):
sampled_color = np.random.normal(
color / 255,
self.color_sigma)
sampled_color = (sampled_color * 255).astype(int)
self.env.add_random_object(color=sampled_color, shape=idx)
if self.n_d is None:
n_d = np.random.randint(*self.range_d)
else:
n_d = self.n_d
# fill with other stuff
self.env.random_config(n_d)
world = self.env.to_state_list(norm=True)
return query, world, n
except SamplingTimeout:
print('Sampling timed out, {} and {} objects'.format(n_t, n_d))
raise Resample('Resample configuration')
def generate(self, N):
"""
Generate a dataset for the task Number.
"""
for i in tqdm(range(N)):
try:
query, world, n = self.gen_one()
except Resample:
query, world, n = self.gen_one()
n_q = len(query)
n_w = len(world)
self.targets += query
self.t_batch += n_q * [i]
self.refs += world
self.r_batch += n_w * [i]
self.labels += [[n]]
class SelectGen(Gen):
"""
A generator for the object selection task. This is very similar to the
object counting task, except the prediction is done on objects : 1 for
objects to select, 0 for distractors.
"""
def __init__(self, env=None, n_d=None):
super(SelectGen, self).__init__(env, n_d)
self.task = 'select'
self.task_type = 'object'
self.max_n = 5
self.color_sigma = 0.05 # standard deviation for the color, test this
self.label_type = 'long'
def gen_one(self):
"""
Generates one example.
For now we consider only one object in the query, we'll see later for
greater number of objects.
To generate objects that are 'the same', we sample their color from a
3-dimensional Gaussian centered on the color of the query object, and
with small standard deviation.
"""
try:
self.env.reset()
# sample query object
self.env.add_random_object()
obj = self.env.objects[0]
color = obj.color
idx = obj.shape_index
# sample number
n = np.random.randint(0, self.max_n + 1)
query = self.env.to_state_list(norm=True)
# fill world with similar objects, as the number requires
self.env.reset()
for _ in range(n):
sampled_color = np.random.normal(
color / 255,
self.color_sigma)
sampled_color = (sampled_color * 255).astype(int)
self.env.add_random_object(color=sampled_color, shape=idx)
if self.n_d is None:
n_d = np.random.randint(*self.range_d)
else:
n_d = self.n_d
# fill with other stuff
self.env.random_config(n_d)
world = self.env.to_state_list(norm=True)
label = [[1]] * n + [[0]] * n_d
return query, world, label
except SamplingTimeout:
print('Sampling timed out, {} and {} objects'.format(n_t, n_d))
raise Resample('Resample configuration')
def generate(self, N):
"""
Generate a dataset for the task Select.
"""
for i in tqdm(range(N)):
try:
query, world, label = self.gen_one()
except Resample:
query, world, label = self.gen_one()
n_q = len(query)
n_w = len(world)