forked from rwth-i6/returnn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
GeneratingDataset.py
2203 lines (1975 loc) · 81 KB
/
GeneratingDataset.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
from __future__ import print_function
from Dataset import Dataset, DatasetSeq, convert_data_dims
from CachedDataset2 import CachedDataset2
from Util import class_idx_seq_to_1_of_k, CollectionReadCheckCovered
from Log import log
import numpy
import re
class GeneratingDataset(Dataset):
_input_classes = None
_output_classes = None
def __init__(self, input_dim, output_dim, num_seqs=float("inf"), fixed_random_seed=None, **kwargs):
"""
:param int input_dim:
:param int|dict[str,int|(int,int)|dict] output_dim:
:param int|float num_seqs:
:param int fixed_random_seed:
"""
super(GeneratingDataset, self).__init__(**kwargs)
assert self.shuffle_frames_of_nseqs == 0
self.num_inputs = input_dim
output_dim = convert_data_dims(output_dim, leave_dict_as_is=True)
if "data" not in output_dim:
output_dim["data"] = [input_dim, 2] # not sparse
self.num_outputs = output_dim
self.expected_load_seq_start = 0
self._num_seqs = num_seqs
self.random = numpy.random.RandomState(1)
self.fixed_random_seed = fixed_random_seed # useful when used as eval dataset
def init_seq_order(self, epoch=None, seq_list=None):
"""
:type epoch: int|None
:param seq_list: predefined order. doesn't make sense here
This is called when we start a new epoch, or at initialization.
"""
super(GeneratingDataset, self).init_seq_order(epoch=epoch)
assert not seq_list, "predefined order doesn't make sense for %s" % self.__class__.__name__
self.random.seed(self.fixed_random_seed or epoch or 1)
self._num_timesteps = 0
self.reached_final_seq = False
self.expected_load_seq_start = 0
self.added_data = []; " :type: list[DatasetSeq] "
return True
def _cleanup_old_seqs(self, seq_idx_end):
i = 0
while i < len(self.added_data):
if self.added_data[i].seq_idx >= seq_idx_end:
break
i += 1
del self.added_data[:i]
def _check_loaded_seq_idx(self, seq_idx):
if not self.added_data:
raise Exception("no data loaded yet")
start_loaded_seq_idx = self.added_data[0].seq_idx
end_loaded_seq_idx = self.added_data[-1].seq_idx
if seq_idx < start_loaded_seq_idx or seq_idx > end_loaded_seq_idx:
raise Exception("seq_idx %i not in loaded seqs range [%i,%i]" % (
seq_idx, start_loaded_seq_idx, end_loaded_seq_idx))
def _get_seq(self, seq_idx):
for data in self.added_data:
if data.seq_idx == seq_idx:
return data
return None
def is_cached(self, start, end):
# Always False, to force that we call self._load_seqs().
# This is important for our buffer management.
return False
def _load_seqs(self, start, end):
"""
:param int start: inclusive seq idx start
:param int end: exclusive seq idx end
"""
# We expect that start increase monotonic on each call
# for not-yet-loaded data.
# This will already be called with _load_seqs_superset indices.
assert start >= self.expected_load_seq_start
if start > self.expected_load_seq_start:
# Cleanup old data.
self._cleanup_old_seqs(start)
self.expected_load_seq_start = start
if self.added_data:
start = max(self.added_data[-1].seq_idx + 1, start)
if end > self.num_seqs:
end = self.num_seqs
if end >= self.num_seqs:
self.reached_final_seq = True
seqs = [self.generate_seq(seq_idx=seq_idx) for seq_idx in range(start, end)]
if self.window > 1:
for seq in seqs:
seq.features = self.sliding_window(seq.features)
self._num_timesteps += sum([seq.num_frames for seq in seqs])
self.added_data += seqs
def generate_seq(self, seq_idx):
"""
:type seq_idx: int
:rtype: DatasetSeq
"""
raise NotImplementedError
def _shuffle_frames_in_seqs(self, start, end):
assert False, "Shuffling in GeneratingDataset does not make sense."
def get_num_timesteps(self):
assert self.reached_final_seq
return self._num_timesteps
@property
def num_seqs(self):
return self._num_seqs
def get_seq_length(self, sorted_seq_idx):
# get_seq_length() can be called before the seq is loaded via load_seqs().
# Thus, we just call load_seqs() ourselves here.
assert sorted_seq_idx >= self.expected_load_seq_start
self.load_seqs(self.expected_load_seq_start, sorted_seq_idx + 1)
return self._get_seq(sorted_seq_idx).num_frames
def get_input_data(self, sorted_seq_idx):
self._check_loaded_seq_idx(sorted_seq_idx)
return self._get_seq(sorted_seq_idx).features
def get_targets(self, target, sorted_seq_idx):
self._check_loaded_seq_idx(sorted_seq_idx)
return self._get_seq(sorted_seq_idx).targets[target]
def get_ctc_targets(self, sorted_seq_idx):
self._check_loaded_seq_idx(sorted_seq_idx)
assert self._get_seq(sorted_seq_idx).ctc_targets
def get_tag(self, sorted_seq_idx):
self._check_loaded_seq_idx(sorted_seq_idx)
return self._get_seq(sorted_seq_idx).seq_tag
class Task12AXDataset(GeneratingDataset):
"""
12AX memory task.
This is a simple memory task where there is an outer loop and an inner loop.
Description here: http://psych.colorado.edu/~oreilly/pubs-abstr.html#OReillyFrank06
"""
_input_classes = "123ABCXYZ"
_output_classes = "LR"
def __init__(self, **kwargs):
super(Task12AXDataset, self).__init__(
input_dim=len(self._input_classes),
output_dim=len(self._output_classes),
**kwargs)
def get_random_seq_len(self):
return self.random.randint(10, 100)
def generate_input_seq(self, seq_len):
"""
Somewhat made up probability distribution.
Try to make in a way that at least some "R" will occur in the output seq.
Otherwise, "R"s are really rare.
"""
seq = self.random.choice(["", "1", "2"])
while len(seq) < seq_len:
if self.random.uniform() < 0.5:
seq += self.random.choice(list("12"))
if self.random.uniform() < 0.9:
seq += self.random.choice(["AX", "BY"])
while self.random.uniform() < 0.5:
seq += self.random.choice(list(self._input_classes))
return list(map(self._input_classes.index, seq[:seq_len]))
@classmethod
def make_output_seq(cls, input_seq):
"""
:type input_seq: list[int]
:rtype: list[int]
"""
outer_state = ""
inner_state = ""
input_classes = cls._input_classes
output_seq_str = ""
for i in input_seq:
c = input_classes[i]
o = "L"
if c in "12":
outer_state = c
elif c in "AB":
inner_state = c
elif c in "XY":
if outer_state + inner_state + c in ["1AX", "2BY"]:
o = "R"
inner_state = ""
# Ignore other cases, "3CZ".
output_seq_str += o
return list(map(cls._output_classes.index, output_seq_str))
def estimate_output_class_priors(self, num_trials, seq_len=10):
"""
:type num_trials: int
:rtype: (float, float)
"""
count_l, count_r = 0, 0
for i in range(num_trials):
input_seq = self.generate_input_seq(seq_len)
output_seq = self.make_output_seq(input_seq)
count_l += output_seq.count(0)
count_r += output_seq.count(1)
return float(count_l) / (num_trials * seq_len), float(count_r) / (num_trials * seq_len)
def generate_seq(self, seq_idx):
seq_len = self.get_random_seq_len()
input_seq = self.generate_input_seq(seq_len)
output_seq = self.make_output_seq(input_seq)
features = class_idx_seq_to_1_of_k(input_seq, num_classes=len(self._input_classes))
targets = numpy.array(output_seq)
return DatasetSeq(seq_idx=seq_idx, features=features, targets=targets)
class TaskEpisodicCopyDataset(GeneratingDataset):
"""
Episodic Copy memory task.
This is a simple memory task where we need to remember a sequence.
Described in: http://arxiv.org/abs/1511.06464
Also tested for Associative LSTMs.
This is a variant where the lengths are random, both for the chars and for blanks.
"""
# Blank, delimiter and some chars.
_input_classes = " .01234567"
_output_classes = _input_classes
def __init__(self, **kwargs):
super(TaskEpisodicCopyDataset, self).__init__(
input_dim=len(self._input_classes),
output_dim=len(self._output_classes),
**kwargs)
def generate_input_seq(self):
seq = ""
# Start with random chars.
rnd_char_len = self.random.randint(1, 10)
seq += "".join([self.random.choice(list(self._input_classes[2:]))
for i in range(rnd_char_len)])
blank_len = self.random.randint(1, 100)
seq += " " * blank_len # blanks
seq += "." # 1 delim
seq += "." * (rnd_char_len + 1) # we wait for the outputs + 1 delim
return list(map(self._input_classes.index, seq))
@classmethod
def make_output_seq(cls, input_seq):
"""
:type input_seq: list[int]
:rtype: list[int]
"""
input_classes = cls._input_classes
input_mem = ""
output_seq_str = ""
state = 0
for i in input_seq:
c = input_classes[i]
if state == 0:
output_seq_str += " "
if c == " ": pass # just ignore
elif c == ".": state = 1 # start with recall now
else: input_mem += c
else: # recall from memory
# Ignore input.
if not input_mem:
output_seq_str += "."
else:
output_seq_str += input_mem[:1]
input_mem = input_mem[1:]
return list(map(cls._output_classes.index, output_seq_str))
def generate_seq(self, seq_idx):
input_seq = self.generate_input_seq()
output_seq = self.make_output_seq(input_seq)
features = class_idx_seq_to_1_of_k(input_seq, num_classes=len(self._input_classes))
targets = numpy.array(output_seq)
return DatasetSeq(seq_idx=seq_idx, features=features, targets=targets)
class TaskXmlModelingDataset(GeneratingDataset):
"""
XML modeling memory task.
This is a memory task where we need to remember a stack.
Defined in Jozefowicz et al. (2015).
Also tested for Associative LSTMs.
"""
# Blank, XML-tags and some chars.
_input_classes = " <>/abcdefgh"
_output_classes = _input_classes
def __init__(self, limit_stack_depth=4, **kwargs):
super(TaskXmlModelingDataset, self).__init__(
input_dim=len(self._input_classes),
output_dim=len(self._output_classes),
**kwargs)
self.limit_stack_depth = limit_stack_depth
def generate_input_seq(self):
# Because this is a prediction task, start with blank,
# and the output seq should predict the next char after the blank.
seq = " "
xml_stack = []
while True:
if not xml_stack or (len(xml_stack) < self.limit_stack_depth and self.random.rand() > 0.6):
tag_len = self.random.randint(1, 10)
tag = "".join([self.random.choice(list(self._input_classes[4:]))
for i in range(tag_len)])
seq += "<%s>" % tag
xml_stack += [tag]
else:
seq += "</%s>" % xml_stack.pop()
if not xml_stack and self.random.rand() > 0.2:
break
return list(map(self._input_classes.index, seq))
@classmethod
def make_output_seq(cls, input_seq):
"""
:type input_seq: list[int]
:rtype: list[int]
"""
input_classes = cls._input_classes
input_seq_str = "".join(cls._input_classes[i] for i in input_seq)
xml_stack = []
output_seq_str = ""
state = 0
for c in input_seq_str:
if c in " >":
output_seq_str += "<" # We expect an open char.
assert state != 1, repr(input_seq_str)
state = 1 # expect beginning of tag
elif state == 1: # in beginning of tag
output_seq_str += " " # We don't know yet.
assert c == "<", repr(input_seq_str)
state = 2
elif state == 2: # first char in tag
if c == "/":
assert xml_stack, repr(input_seq_str)
output_seq_str += xml_stack[-1][0]
xml_stack[-1] = xml_stack[-1][1:]
state = 4 # closing tag
else: # opening tag
output_seq_str += " " # We don't know yet.
assert c not in " <>/", repr(input_seq_str)
state = 3
xml_stack += [c]
elif state == 3: # opening tag
output_seq_str += " " # We don't know.
xml_stack[-1] += c
elif state == 4: # closing tag
assert xml_stack, repr(input_seq_str)
if not xml_stack[-1]:
output_seq_str += ">"
xml_stack.pop()
state = 0
else:
output_seq_str += xml_stack[-1][0]
xml_stack[-1] = xml_stack[-1][1:]
else:
assert False, "invalid state %i. input %r" % (state, input_seq_str)
return list(map(cls._output_classes.index, output_seq_str))
def generate_seq(self, seq_idx):
input_seq = self.generate_input_seq()
output_seq = self.make_output_seq(input_seq)
features = class_idx_seq_to_1_of_k(input_seq, num_classes=len(self._input_classes))
targets = numpy.array(output_seq)
return DatasetSeq(seq_idx=seq_idx, features=features, targets=targets)
class TaskVariableAssignmentDataset(GeneratingDataset):
"""
Variable Assignment memory task.
This is a memory task to test for key-value retrieval.
Defined in Associative LSTM paper.
"""
# Blank/Delim/End, Store/Query, and some chars for key/value.
_input_classes = " ,.SQ()abcdefgh"
_output_classes = _input_classes
def __init__(self, **kwargs):
super(TaskVariableAssignmentDataset, self).__init__(
input_dim=len(self._input_classes),
output_dim=len(self._output_classes),
**kwargs)
def generate_input_seq(self):
seq = ""
from collections import OrderedDict
store = OrderedDict()
# First the assignments.
num_assignments = self.random.randint(1, 5)
for i in range(num_assignments):
key_len = self.random.randint(2, 5)
while True: # find unique key
key = "".join([self.random.choice(list(self._input_classes[7:]))
for i in range(key_len)])
if key not in store: break
value_len = self.random.randint(1, 2)
value = "".join([self.random.choice(list(self._input_classes[7:]))
for i in range(value_len)])
if seq: seq += ","
seq += "S(%s,%s)" % (key, value)
store[key] = value
# Now one query.
key = self.random.choice(store.keys())
value = store[key]
seq += ",Q(%s)" % key
seq += "%s." % value
return list(map(self._input_classes.index, seq))
@classmethod
def make_output_seq(cls, input_seq):
"""
:type input_seq: list[int]
:rtype: list[int]
"""
input_classes = cls._input_classes
input_seq_str = "".join(cls._input_classes[i] for i in input_seq)
store = {}
key, value = "", ""
output_seq_str = ""
state = 0
for c in input_seq_str:
if state == 0:
key = ""
if c == "S": state = 1 # store
elif c == "Q": state = 2 # query
elif c in " ,": pass # can be ignored
else: assert False, "c %r in %r" % (c, input_seq_str)
output_seq_str += " "
elif state == 1: # store
assert c == "(", repr(input_seq_str)
state = 1.1
output_seq_str += " "
elif state == 1.1: # store.key
if c == ",":
assert key
value = ""
state = 1.5 # store.value
else:
assert c not in " .,SQ()", repr(input_seq_str)
key += c
output_seq_str += " "
elif state == 1.5: # store.value
if c == ")":
assert value
store[key] = value
state = 0
else:
assert c not in " .,SQ()", repr(input_seq_str)
value += c
output_seq_str += " "
elif state == 2: # query
assert c == "(", repr(input_seq_str)
state = 2.1
output_seq_str += " "
elif state == 2.1: # query.key
if c == ")":
value = store[key]
output_seq_str += value[0]
value = value[1:]
state = 2.5
else:
assert c not in " .,SQ()", repr(input_seq_str)
key += c
output_seq_str += " "
elif state == 2.5: # query result
assert c not in " .,SQ()", repr(input_seq_str)
if value:
output_seq_str += value[0]
value = value[1:]
else:
output_seq_str += "."
state = 2.6
elif state == 2.6: # query result end
assert c == ".", repr(input_seq_str)
output_seq_str += " "
else:
assert False, "invalid state %i, input %r" % (state, input_seq_str)
return list(map(cls._output_classes.index, output_seq_str))
def generate_seq(self, seq_idx):
input_seq = self.generate_input_seq()
output_seq = self.make_output_seq(input_seq)
features = class_idx_seq_to_1_of_k(input_seq, num_classes=len(self._input_classes))
targets = numpy.array(output_seq)
return DatasetSeq(seq_idx=seq_idx, features=features, targets=targets)
class DummyDataset(GeneratingDataset):
def __init__(self, input_dim, output_dim, num_seqs, seq_len=2,
input_max_value=10.0, input_shift=None, input_scale=None, **kwargs):
super(DummyDataset, self).__init__(input_dim=input_dim, output_dim=output_dim, num_seqs=num_seqs, **kwargs)
self.seq_len = seq_len
self.input_max_value = input_max_value
if input_shift is None: input_shift = -input_max_value / 2.0
self.input_shift = input_shift
if input_scale is None: input_scale = 1.0 / self.input_max_value
self.input_scale = input_scale
def generate_seq(self, seq_idx):
seq_len = self.seq_len
i1 = seq_idx
i2 = i1 + seq_len * self.num_inputs
features = numpy.array([((i % self.input_max_value) + self.input_shift) * self.input_scale
for i in range(i1, i2)]).reshape((seq_len, self.num_inputs))
i1, i2 = i2, i2 + seq_len
targets = numpy.array([i % self.num_outputs["classes"][0]
for i in range(i1, i2)])
return DatasetSeq(seq_idx=seq_idx, features=features, targets=targets)
class StaticDataset(GeneratingDataset):
@classmethod
def copy_from_dataset(cls, dataset, start_seq_idx=0, max_seqs=None):
"""
:param Dataset dataset:
:param int start_seq_idx:
:param int|None max_seqs:
:rtype: StaticDataset
"""
if isinstance(dataset, StaticDataset):
return cls(
data=dataset.data, target_list=dataset.target_list,
output_dim=dataset.num_outputs, input_dim=dataset.num_inputs)
seq_idx = start_seq_idx
data = []
while dataset.is_less_than_num_seqs(seq_idx):
dataset.load_seqs(seq_idx, seq_idx + 1)
if max_seqs is not None and len(data) >= max_seqs:
break
seq_data = {key: dataset.get_data(seq_idx, key) for key in dataset.get_data_keys()}
data.append(seq_data)
seq_idx += 1
return cls(
data=data, target_list=dataset.get_target_list(),
output_dim=dataset.num_outputs, input_dim=dataset.num_inputs)
def __init__(self, data, target_list=None, output_dim=None, input_dim=None, **kwargs):
"""
:param list[dict[str,numpy.ndarray]] data: list of seqs, each provide the data for each data-key
:param int input_dim:
:param int|dict[str,(int,int)|list[int]] output_dim:
"""
assert len(data) > 0
self.data = data
num_seqs = len(data)
first_data = data[0]
assert "data" in first_data # input
if target_list is None:
target_list = []
for target in first_data.keys():
if target == "data": continue
target_list.append(target)
else:
for target in target_list:
assert target in first_data
self.target_list = target_list
if output_dim is None:
output_dim = {}
output_dim = convert_data_dims(output_dim, leave_dict_as_is=True)
first_data_input = first_data["data"]
assert len(first_data_input.shape) <= 2 # (time[,dim])
if input_dim is None:
if "data" in output_dim:
if isinstance(output_dim["data"], (list, tuple)):
input_dim = output_dim["data"][0]
elif isinstance(output_dim["data"], dict):
input_dim = output_dim["data"]["dim"]
else:
raise TypeError(type(output_dim["data"]))
else:
input_dim = first_data_input.shape[1]
for target in target_list:
first_data_output = first_data[target]
assert len(first_data_output.shape) <= 2 # (time[,dim])
if target in output_dim:
assert output_dim[target][1] == len(first_data_output.shape)
if len(first_data_output.shape) >= 2:
assert output_dim[target][0] == first_data_output.shape[1]
else:
print("%r: Warning: Data-key %r not specified in output_dim (%r)." % (self, target, output_dim), file=log.v2)
super(StaticDataset, self).__init__(input_dim=input_dim, output_dim=output_dim, num_seqs=num_seqs, **kwargs)
def generate_seq(self, seq_idx):
data = self.data[seq_idx]
return DatasetSeq(seq_idx=seq_idx,
features=data["data"],
targets={target: data[target] for target in self.target_list})
def get_target_list(self):
return self.target_list
class CopyTaskDataset(GeneratingDataset):
def __init__(self, nsymbols, minlen=0, maxlen=0, minlen_epoch_factor=0, maxlen_epoch_factor=0, **kwargs):
# Sparse data.
super(CopyTaskDataset, self).__init__(input_dim=nsymbols,
output_dim={"data": [nsymbols, 1],
"classes": [nsymbols, 1]},
**kwargs)
assert nsymbols <= 256
self.nsymbols = nsymbols
self.minlen = minlen
self.maxlen = maxlen
self.minlen_epoch_factor = minlen_epoch_factor
self.maxlen_epoch_factor = maxlen_epoch_factor
def get_random_seq_len(self):
assert isinstance(self.epoch, int)
minlen = int(self.minlen + self.minlen_epoch_factor * self.epoch)
maxlen = int(self.maxlen + self.maxlen_epoch_factor * self.epoch)
assert 0 < minlen <= maxlen
return self.random.randint(minlen, maxlen + 1)
def generate_seq(self, seq_idx):
"""
:type seq_idx: int
:rtype: DatasetSeq
"""
seq_len = self.get_random_seq_len()
seq = [self.random.randint(0, self.nsymbols) for i in range(seq_len)]
seq_np = numpy.array(seq, dtype="int8")
return DatasetSeq(seq_idx=seq_idx, features=seq_np, targets={"classes": seq_np})
class _TFKerasDataset(CachedDataset2):
"""
Wraps around any dataset from tf.contrib.keras.datasets.
See: https://www.tensorflow.org/versions/master/api_docs/python/tf/contrib/keras/datasets
TODO: Should maybe be moved to a separate file. (Only here because of tf.contrib.keras.datasets.reuters).
"""
# TODO...
class _NltkCorpusReaderDataset(CachedDataset2):
"""
Wraps around any dataset from nltk.corpus.
TODO: Should maybe be moved to a separate file, e.g. CorpusReaderDataset.py or so?
"""
# TODO ...
class ExtractAudioFeatures:
"""
Currently uses librosa to extract MFCC features.
(Alternatives: python_speech_features, talkbox.features.mfcc, librosa)
We could also add support e.g. to directly extract log-filterbanks or so.
"""
def __init__(self,
window_len=0.025, step_len=0.010,
num_feature_filters=40, with_delta=False, norm_mean=None, norm_std_dev=None,
features="mfcc", random_permute=None, random_state=None):
"""
:param float window_len: in seconds
:param float step_len: in seconds
:param int num_feature_filters:
:param bool|int with_delta:
:param numpy.ndarray|str|None norm_mean: if str, will interpret as filename
:param numpy.ndarray|str|None norm_std_dev: if str, will interpret as filename
:param str features: "mfcc", "log_mel_filterbank", "log_log_mel_filterbank"
:param CollectionReadCheckCovered|dict[str]|bool|None random_permute:
:param numpy.random.RandomState|None random_state:
:return: (audio_len // int(step_len * sample_rate), (with_delta + 1) * num_feature_filters), float32
:rtype: numpy.ndarray
"""
self.window_len = window_len
self.step_len = step_len
self.num_feature_filters = num_feature_filters
if isinstance(with_delta, bool):
with_delta = 1 if with_delta else 0
assert isinstance(with_delta, int) and with_delta >= 0
self.with_delta = with_delta
if norm_mean is not None:
norm_mean = self._load_feature_vec(norm_mean)
if norm_std_dev is not None:
norm_std_dev = self._load_feature_vec(norm_std_dev)
self.norm_mean = norm_mean
self.norm_std_dev = norm_std_dev
if random_permute and not isinstance(random_permute, CollectionReadCheckCovered):
random_permute = CollectionReadCheckCovered.from_bool_or_dict(random_permute)
self.random_permute_opts = random_permute
self.random_state = random_state
self.features = features
def _load_feature_vec(self, value):
"""
:param str|None value:
:return: shape (self.num_inputs,), float32
:rtype: numpy.ndarray|None
"""
if value is None:
return None
if isinstance(value, str):
value = numpy.loadtxt(value)
assert isinstance(value, numpy.ndarray)
assert value.shape == (self.get_feature_dimension(),)
return value.astype("float32")
def get_audio_features(self, audio, sample_rate):
"""
:param numpy.ndarray audio: raw audio samples, shape (audio_len,)
:param int sample_rate: e.g. 22050
:rtype: numpy.ndarray
"""
kwargs = {
"sample_rate": sample_rate,
"window_len": self.window_len,
"step_len": self.step_len,
"num_feature_filters": self.num_feature_filters,
}
peak = numpy.max(numpy.abs(audio))
audio /= peak
if self.random_permute_opts and self.random_permute_opts.truth_value:
audio = _get_random_permuted_audio(
audio=audio,
sample_rate=sample_rate,
opts=self.random_permute_opts,
random_state=self.random_state)
kwargs["audio"] = audio
if self.features == "mfcc":
feature_data = _get_audio_features_mfcc(**kwargs)
elif self.features == "log_mel_filterbank":
feature_data = _get_audio_log_mel_filterbank(**kwargs)
elif self.features == "log_log_mel_filterbank":
feature_data = _get_audio_log_log_mel_filterbank(**kwargs)
else:
assert False, "non-supported feature type %s" % self.features
assert feature_data.ndim == 2
assert feature_data.shape[1] == self.num_feature_filters
if self.with_delta:
import librosa
deltas = [librosa.feature.delta(feature_data, order=i, axis=0) for i in range(1, self.with_delta + 1)]
feature_data = numpy.concatenate([feature_data] + deltas, axis=1)
assert feature_data.shape[1] == self.get_feature_dimension()
if self.norm_mean is not None:
feature_data -= self.norm_mean[None, :]
if self.norm_std_dev is not None:
feature_data /= self.norm_std_dev[None, :]
return feature_data
def get_feature_dimension(self):
return (self.with_delta + 1) * self.num_feature_filters
def _get_audio_features_mfcc(audio, sample_rate, window_len=0.025, step_len=0.010, num_feature_filters=40):
"""
:param numpy.ndarray audio: raw audio samples, shape (audio_len,)
:param int sample_rate: e.g. 22050
:param float window_len: in seconds
:param float step_len: in seconds
:param int num_feature_filters:
:return: (audio_len // int(step_len * sample_rate), num_feature_filters), float32
:rtype: numpy.ndarray
"""
import librosa
mfccs = librosa.feature.mfcc(
audio, sr=sample_rate,
n_mfcc=num_feature_filters,
hop_length=int(step_len * sample_rate), n_fft=int(window_len * sample_rate))
energy = librosa.feature.rmse(
audio,
hop_length=int(step_len * sample_rate), frame_length=int(window_len * sample_rate))
mfccs[0] = energy # replace first MFCC with energy, per convention
assert mfccs.shape[0] == num_feature_filters # (dim, time)
mfccs = mfccs.transpose().astype("float32") # (time, dim)
return mfccs
def _get_audio_log_mel_filterbank(audio, sample_rate, window_len=0.025, step_len=0.010, num_feature_filters=80):
"""
Computes log Mel-filterbank features from an audio signal.
References:
https://github.com/jameslyons/python_speech_features/blob/master/python_speech_features/base.py
https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/data_generators/speech_recognition.py
:param numpy.ndarray audio: raw audio samples, shape (audio_len,)
:param int sample_rate: e.g. 22050
:param float window_len: in seconds
:param float step_len: in seconds
:param int num_feature_filters:
:return: (audio_len // int(step_len * sample_rate), num_feature_filters), float32
:rtype: numpy.ndarray
"""
import librosa
mel_filterbank = librosa.feature.melspectrogram(
audio, sr=sample_rate,
n_mels=num_feature_filters,
hop_length=int(step_len * sample_rate), n_fft=int(window_len * sample_rate))
log_noise_floor = 1e-3 # prevent numeric overflow in log
log_mel_filterbank = numpy.log(numpy.maximum(log_noise_floor, mel_filterbank))
assert log_mel_filterbank.shape[0] == num_feature_filters
log_mel_filterbank = log_mel_filterbank.transpose().astype("float32") # (time, dim)
return log_mel_filterbank
def _get_audio_log_log_mel_filterbank(audio, sample_rate, window_len=0.025, step_len=0.010, num_feature_filters=80):
"""
Computes log-log Mel-filterbank features from an audio signal.
References:
https://github.com/jameslyons/python_speech_features/blob/master/python_speech_features/base.py
https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/data_generators/speech_recognition.py
:param numpy.ndarray audio: raw audio samples, shape (audio_len,)
:param int sample_rate: e.g. 22050
:param float window_len: in seconds
:param float step_len: in seconds
:param int num_feature_filters:
:return: (audio_len // int(step_len * sample_rate), num_feature_filters), float32
:rtype: numpy.ndarray
"""
import librosa
mel_filterbank = librosa.feature.melspectrogram(
audio, sr=sample_rate,
n_mels=num_feature_filters,
hop_length=int(step_len * sample_rate), n_fft=int(window_len * sample_rate))
log_noise_floor = 1e-3 # prevent numeric overflow in log
log_mel_filterbank = numpy.log(numpy.maximum(log_noise_floor, mel_filterbank))
log_log_mel_filterbank = librosa.core.amplitude_to_db(log_mel_filterbank)
assert log_log_mel_filterbank.shape[0] == num_feature_filters
log_log_mel_filterbank = log_log_mel_filterbank.transpose().astype("float32") # (time, dim)
return log_log_mel_filterbank
def _get_random_permuted_audio(audio, sample_rate, opts, random_state):
"""
:param numpy.ndarray audio: raw time signal
:param int sample_rate:
:param CollectionReadCheckCovered opts:
:param numpy.random.RandomState random_state:
:return: audio randomly permuted
:rtype: numpy.ndarray
"""
import librosa
import scipy.ndimage
import warnings
audio = audio * random_state.uniform(opts.get("rnd_scale_lower", 0.8), opts.get("rnd_scale_upper", 1.0))
if random_state.uniform(0.0, 1.0) < opts.get("rnd_zoom_switch", 0.2):
with warnings.catch_warnings():
warnings.simplefilter("ignore")
# Alternative: scipy.interpolate.interp2d
factor = random_state.uniform(opts.get("rnd_zoom_lower", 0.9), opts.get("rnd_zoom_upper", 1.1))
audio = scipy.ndimage.zoom(audio, factor, order=3)
if random_state.uniform(0.0, 1.0) < opts.get("rnd_stretch_switch", 0.2):
rate = random_state.uniform(opts.get("rnd_stretch_lower", 0.9), opts.get("rnd_stretch_upper", 1.2))
audio = librosa.effects.time_stretch(audio, rate=rate)
if random_state.uniform(0.0, 1.0) < opts.get("rnd_pitch_switch", 0.2):
n_steps = random_state.uniform(opts.get("rnd_pitch_lower", -1.), opts.get("rnd_pitch_upper", 1.))
audio = librosa.effects.pitch_shift(audio, sr=sample_rate, n_steps=n_steps)
opts.assert_all_read()
return audio
class TimitDataset(CachedDataset2):
"""
DARPA TIMIT Acoustic-Phonetic Continuous Speech Corpus.
You must provide the data.
Demo:
tools/dump-dataset.py "{'class': 'TimitDataset', 'timit_dir': '...'}"
tools/dump-dataset.py "{'class': 'TimitDataset', 'timit_dir': '...', 'demo_play_audio': True, 'random_permute_audio': True}"
The full train data has 3696 utterances and the core test data has 192 utterances
(24-speaker core test set).
For some references:
https://github.com/ppwwyyxx/tensorpack/blob/master/examples/CTC-TIMIT/train-timit.py
https://www.cs.toronto.edu/~graves/preprint.pdf
https://arxiv.org/pdf/1303.5778.pdf
https://arxiv.org/pdf/0804.3269.pdf
"""
# via: https://github.com/kaldi-asr/kaldi/blob/master/egs/timit/s5/conf/phones.60-48-39.map
PhoneMapTo39 = {
'aa': 'aa', 'ae': 'ae', 'ah': 'ah', 'ao': 'aa', 'aw': 'aw', 'ax': 'ah', 'ax-h': 'ah', 'axr': 'er',
'ay': 'ay', 'b': 'b', 'bcl': 'sil', 'ch': 'ch', 'd': 'd', 'dcl': 'sil', 'dh': 'dh', 'dx': 'dx', 'eh': 'eh',
'el': 'l', 'em': 'm', 'en': 'n', 'eng': 'ng', 'epi': 'sil', 'er': 'er', 'ey': 'ey', 'f': 'f', 'g': 'g',
'gcl': 'sil', 'h#': 'sil', 'hh': 'hh', 'hv': 'hh', 'ih': 'ih', 'ix': 'ih', 'iy': 'iy', 'jh': 'jh',
'k': 'k', 'kcl': 'sil', 'l': 'l', 'm': 'm', 'n': 'n', 'ng': 'ng', 'nx': 'n', 'ow': 'ow', 'oy': 'oy',
'p': 'p', 'pau': 'sil', 'pcl': 'sil', 'q': None, 'r': 'r', 's': 's', 'sh': 'sh', 't': 't', 'tcl': 'sil',
'th': 'th', 'uh': 'uh', 'uw': 'uw', 'ux': 'uw', 'v': 'v', 'w': 'w', 'y': 'y', 'z': 'z', 'zh': 'sh'}
PhoneMapTo48 = {
'aa': 'aa', 'ae': 'ae', 'ah': 'ah', 'ao': 'ao', 'aw': 'aw', 'ax': 'ax', 'ax-h': 'ax', 'axr': 'er',
'ay': 'ay', 'b': 'b', 'bcl': 'vcl', 'ch': 'ch', 'd': 'd', 'dcl': 'vcl', 'dh': 'dh', 'dx': 'dx', 'eh': 'eh',
'el': 'el', 'em': 'm', 'en': 'en', 'eng': 'ng', 'epi': 'epi', 'er': 'er', 'ey': 'ey', 'f': 'f', 'g': 'g',
'gcl': 'vcl', 'h#': 'sil', 'hh': 'hh', 'hv': 'hh', 'ih': 'ih', 'ix': 'ix', 'iy': 'iy', 'jh': 'jh',
'k': 'k', 'kcl': 'cl', 'l': 'l', 'm': 'm', 'n': 'n', 'ng': 'ng', 'nx': 'n', 'ow': 'ow', 'oy': 'oy',
'p': 'p', 'pau': 'sil', 'pcl': 'cl', 'q': None, 'r': 'r', 's': 's', 'sh': 'sh', 't': 't', 'tcl': 'cl',
'th': 'th', 'uh': 'uh', 'uw': 'uw', 'ux': 'uw', 'v': 'v', 'w': 'w', 'y': 'y', 'z': 'z', 'zh': 'zh'}
Phones61 = PhoneMapTo39.keys()
PhoneMapTo61 = {p: p for p in Phones61}
@classmethod
def _get_phone_map(cls, num_phones=61):
"""
:param int num_phones:
:return: map 61-phone-set-phone -> num_phones-phone-set-phone
:rtype: dict[str,str|None]
"""
return {61: cls.PhoneMapTo61, 48: cls.PhoneMapTo48, 39: cls.PhoneMapTo39}[num_phones]
@classmethod
def _get_labels(cls, phone_map):
"""
:param dict[str,str|None] phone_map:
:rtype: list[str]
"""
labels = sorted(set(filter(None, phone_map.values())))
# Make 'sil' the 0 phoneme.
if "pau" in labels:
labels.remove("pau")
labels.insert(0, "pau")
else:
labels.remove("sil")
labels.insert(0, "sil")
return labels
@classmethod
def get_label_map(cls, source_num_phones=61, target_num_phones=39):
"""
:param int source_num_phones:
:param int target_num_phones:
:rtype: dict[int,int|None]
"""
src_phone_map = cls._get_phone_map(source_num_phones) # 61-phone -> src-phone
src_labels = cls._get_labels(src_phone_map) # src-idx -> src-phone
tgt_phone_map = cls._get_phone_map(target_num_phones) # 61-phone -> tgt-phone
tgt_labels = cls._get_labels(tgt_phone_map) # tgt-idx -> tgt-phone
d = {i: src_labels[i] for i in range(source_num_phones)} # src-idx -> src-phone|61-phone
if source_num_phones != 61:
src_phone_map_rev = {v: k for (k, v) in sorted(src_phone_map.items())} # src-phone -> 61-phone
d = {i: src_phone_map_rev[v] for (i, v) in d.items()} # src-idx -> 61-phone
d = {i: tgt_phone_map[v] for (i, v) in d.items()} # src-idx -> tgt-phone
d = {i: tgt_labels.index(v) if v else None for (i, v) in d.items()} # src-idx -> tgt-idx
return d
def __init__(self, timit_dir, train=True, preload=False,
num_feature_filters=40, feature_window_len=0.025, feature_step_len=0.010, with_delta=False,
norm_mean=None, norm_std_dev=None,
random_permute_audio=None, num_phones=61,
demo_play_audio=False, fixed_random_seed=None, **kwargs):
"""
:param str timit_dir: directory of TIMIT. should contain train/filelist.phn and test/filelist.core.phn
:param bool train: whether to use the train or core test data
:param bool preload: if True, here at __init__, we will wait until we loaded all the data
:param int num_feature_filters: e.g. number of MFCCs
:param bool|int with_delta: whether to add delta features (doubles the features dim). if int, up to this degree
:param str norm_mean: file with mean values which are used for mean-normalization of the final features
:param str norm_std_dev: file with std dev valeus for variance-normalization of the final features
:param None|bool|dict[str] random_permute_audio: enables permutation on the audio. see _get_random_permuted_audio
:param int num_phones: 39, 48 or 61. num labels of our classes
:param bool demo_play_audio: plays the audio. only make sense with tools/dump-dataset.py
:param None|int fixed_random_seed: if given, use this fixed random seed in every epoch
"""
super(TimitDataset, self).__init__(**kwargs)
from threading import Lock, Thread
self._lock = Lock()
self._num_feature_filters = num_feature_filters
self._feature_window_len = feature_window_len
self._feature_step_len = feature_step_len
self.num_inputs = self._num_feature_filters
if isinstance(with_delta, bool):
with_delta = 1 if with_delta else 0
assert isinstance(with_delta, int) and with_delta >= 0
self._with_delta = with_delta
self.num_inputs *= (1 + with_delta)
self._norm_mean = self._load_feature_vec(norm_mean)