-
Notifications
You must be signed in to change notification settings - Fork 4.4k
/
Copy pathdataset_test.ts
1325 lines (1175 loc) · 48.8 KB
/
dataset_test.ts
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
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
import * as tf from '@tensorflow/tfjs-core';
import {test_util} from '@tensorflow/tfjs-core';
import {normalize} from './browser_fft_utils';
import {arrayBuffer2SerializedExamples, BACKGROUND_NOISE_TAG, Dataset, DATASET_SERIALIZATION_DESCRIPTOR, DATASET_SERIALIZATION_VERSION, deserializeExample, getMaxIntensityFrameIndex, getValidWindows, serializeExample, spectrogram2IntensityCurve, SpectrogramAndTargetsTfDataset} from './dataset';
import {string2ArrayBuffer} from './generic_utils';
import {expectTensorsClose} from './test_utils';
import {Example, RawAudioData, SpectrogramData} from './types';
describe('Dataset', () => {
const FAKE_NUM_FRAMES = 4;
const FAKE_FRAME_SIZE = 16;
function getFakeExample(
label: string, numFrames = FAKE_NUM_FRAMES, frameSize = FAKE_FRAME_SIZE,
spectrogramData?: number[]): Example {
if (spectrogramData == null) {
spectrogramData = [];
let counter = 0;
for (let i = 0; i < numFrames * frameSize; ++i) {
spectrogramData.push(counter++);
}
}
return {
label,
spectrogram: {data: new Float32Array(spectrogramData), frameSize}
};
}
function addThreeExamplesToDataset(
dataset: Dataset, labelA = 'a', labelB = 'b'): string[] {
const ex1 = getFakeExample(labelA);
const uid1 = dataset.addExample(ex1);
const ex2 = getFakeExample(labelA);
const uid2 = dataset.addExample(ex2);
const ex3 = getFakeExample(labelB);
const uid3 = dataset.addExample(ex3);
return [uid1, uid2, uid3];
}
it('Constructor', () => {
const dataset = new Dataset();
expect(dataset.empty()).toEqual(true);
expect(dataset.size()).toEqual(0);
});
it('addExample', () => {
const dataset = new Dataset();
const uids: string[] = [];
const ex1 = getFakeExample('a');
const uid1 = dataset.addExample(ex1);
expect(uid1).toMatch(/^([0-9a-f]+\-)+[0-9a-f]+$/);
uids.push(uid1);
expect(dataset.empty()).toEqual(false);
expect(dataset.size()).toEqual(1);
expect(dataset.getExampleCounts()).toEqual({'a': 1});
const ex2 = getFakeExample('a');
const uid2 = dataset.addExample(ex2);
expect(uids.indexOf(uid2)).toEqual(-1);
uids.push(uid2);
expect(dataset.empty()).toEqual(false);
expect(dataset.size()).toEqual(2);
expect(dataset.getExampleCounts()).toEqual({'a': 2});
const ex3 = getFakeExample('b');
const uid3 = dataset.addExample(ex3);
expect(uids.indexOf(uid3)).toEqual(-1);
uids.push(uid3);
expect(dataset.empty()).toEqual(false);
expect(dataset.size()).toEqual(3);
expect(dataset.getExampleCounts()).toEqual({'a': 2, 'b': 1});
});
it('addExample with null fails', () => {
const dataset = new Dataset();
expect(() => dataset.addExample(null))
.toThrowError('Got null or undefined example');
});
it('addExample with invalid label fails', () => {
const dataset = new Dataset();
expect(() => dataset.addExample(getFakeExample(null)))
.toThrowError(/Expected label to be a non-empty string.*null/);
expect(() => dataset.addExample(getFakeExample(undefined)))
.toThrowError(/Expected label to be a non-empty string.*undefined/);
expect(() => dataset.addExample(getFakeExample('')))
.toThrowError(/Expected label to be a non-empty string/);
});
it('durationMillis', () => {
const dataset = new Dataset();
expect(dataset.durationMillis()).toEqual(0);
const ex1 = getFakeExample('a');
dataset.addExample(ex1);
const durationPerExample = dataset.durationMillis();
expect(durationPerExample).toBeGreaterThan(0);
const ex2 = getFakeExample('b');
dataset.addExample(ex2);
expect(dataset.durationMillis()).toEqual(durationPerExample * 2);
dataset.clear();
expect(dataset.durationMillis()).toEqual(0);
});
it('merge two non-empty datasets', () => {
const dataset = new Dataset();
addThreeExamplesToDataset(dataset);
const datasetPrime = new Dataset();
addThreeExamplesToDataset(datasetPrime);
const ex = getFakeExample('foo');
datasetPrime.addExample(ex);
const duration0 = dataset.durationMillis();
dataset.merge(datasetPrime);
expect(dataset.getExampleCounts()).toEqual({a: 4, b: 2, foo: 1});
// Check that the content of the incoming dataset is not affected.
expect(datasetPrime.getExampleCounts()).toEqual({a: 2, b: 1, foo: 1});
expect(dataset.durationMillis())
.toEqual(duration0 + datasetPrime.durationMillis());
});
it('merge non-empty dataset into an empty one', () => {
const dataset = new Dataset();
const datasetPrime = new Dataset();
addThreeExamplesToDataset(datasetPrime);
dataset.merge(datasetPrime);
expect(dataset.getExampleCounts()).toEqual({a: 2, b: 1});
// Check that the content of the incoming dataset is not affected.
expect(datasetPrime.getExampleCounts()).toEqual({a: 2, b: 1});
});
it('merge empty dataset into an non-empty one', () => {
const dataset = new Dataset();
addThreeExamplesToDataset(dataset);
const datasetPrime = new Dataset();
dataset.merge(datasetPrime);
expect(dataset.getExampleCounts()).toEqual({a: 2, b: 1});
// Check that the content of the incoming dataset is not affected.
expect(datasetPrime.empty()).toEqual(true);
});
it('getExamples', () => {
const dataset = new Dataset();
const [uid1, uid2, uid3] = addThreeExamplesToDataset(dataset);
const out1 = dataset.getExamples('a');
expect(out1.length).toEqual(2);
expect(out1[0].uid).toEqual(uid1);
expect(out1[0].example.label).toEqual('a');
expect(out1[1].uid).toEqual(uid2);
expect(out1[1].example.label).toEqual('a');
const out2 = dataset.getExamples('b');
expect(out2.length).toEqual(1);
expect(out2[0].uid).toEqual(uid3);
expect(out2[0].example.label).toEqual('b');
});
it('getExamples after addExample', () => {
const dataset = new Dataset();
const [uid1, uid2] = addThreeExamplesToDataset(dataset);
const out1 = dataset.getExamples('a');
expect(out1.length).toEqual(2);
expect(out1[0].uid).toEqual(uid1);
expect(out1[0].example.label).toEqual('a');
expect(out1[1].uid).toEqual(uid2);
expect(out1[1].example.label).toEqual('a');
const ex = getFakeExample('a');
const uid4 = dataset.addExample(ex);
const out2 = dataset.getExamples('a');
expect(out2.length).toEqual(3);
expect(out2[0].uid).toEqual(uid1);
expect(out2[0].example.label).toEqual('a');
expect(out2[1].uid).toEqual(uid2);
expect(out2[1].example.label).toEqual('a');
expect(out2[2].uid).toEqual(uid4);
expect(out2[2].example.label).toEqual('a');
});
it('getExamples after removeExample', () => {
const dataset = new Dataset();
const [uid1, uid2] = addThreeExamplesToDataset(dataset);
const out1 = dataset.getExamples('a');
expect(out1.length).toEqual(2);
expect(out1[0].uid).toEqual(uid1);
expect(out1[0].example.label).toEqual('a');
expect(out1[1].uid).toEqual(uid2);
expect(out1[1].example.label).toEqual('a');
dataset.removeExample(uid1);
const out2 = dataset.getExamples('a');
expect(out2.length).toEqual(1);
expect(out2[0].uid).toEqual(uid2);
expect(out2[0].example.label).toEqual('a');
dataset.removeExample(uid2);
expect(() => dataset.getExamples('a'))
.toThrowError(/No example .*a.* exists/);
});
it('getExamples after removeExample followed by addExample', () => {
const dataset = new Dataset();
const [uid1, uid2] = addThreeExamplesToDataset(dataset);
const out1 = dataset.getExamples('a');
expect(out1.length).toEqual(2);
expect(out1[0].uid).toEqual(uid1);
expect(out1[0].example.label).toEqual('a');
expect(out1[1].uid).toEqual(uid2);
expect(out1[1].example.label).toEqual('a');
dataset.removeExample(uid1);
const out2 = dataset.getExamples('a');
expect(out2.length).toEqual(1);
expect(out2[0].uid).toEqual(uid2);
expect(out2[0].example.label).toEqual('a');
const ex = getFakeExample('a');
const uid4 = dataset.addExample(ex);
const out3 = dataset.getExamples('a');
expect(out3.length).toEqual(2);
expect(out3[0].uid).toEqual(uid2);
expect(out3[0].example.label).toEqual('a');
expect(out3[1].uid).toEqual(uid4);
expect(out3[1].example.label).toEqual('a');
});
it('getExamples with nonexistent label fails', () => {
const dataset = new Dataset();
addThreeExamplesToDataset(dataset);
expect(() => dataset.getExamples('labelC'))
.toThrowError(/No example .*labelC.* exists/);
});
it('removeExample', () => {
const dataset = new Dataset();
const ex1 = getFakeExample('a');
const uid1 = dataset.addExample(ex1);
expect(dataset.empty()).toEqual(false);
expect(dataset.size()).toEqual(1);
expect(dataset.getExampleCounts()).toEqual({'a': 1});
const ex2 = getFakeExample('a');
const uid2 = dataset.addExample(ex2);
expect(dataset.empty()).toEqual(false);
expect(dataset.size()).toEqual(2);
expect(dataset.getExampleCounts()).toEqual({'a': 2});
const ex3 = getFakeExample('b');
const uid3 = dataset.addExample(ex3);
expect(dataset.empty()).toEqual(false);
expect(dataset.size()).toEqual(3);
expect(dataset.getExampleCounts()).toEqual({'a': 2, 'b': 1});
dataset.removeExample(uid1);
expect(dataset.empty()).toEqual(false);
expect(dataset.size()).toEqual(2);
expect(dataset.getExampleCounts()).toEqual({'a': 1, 'b': 1});
dataset.removeExample(uid2);
expect(dataset.empty()).toEqual(false);
expect(dataset.size()).toEqual(1);
expect(dataset.getExampleCounts()).toEqual({'b': 1});
dataset.removeExample(uid3);
expect(dataset.empty()).toEqual(true);
expect(dataset.size()).toEqual(0);
expect(dataset.getExampleCounts()).toEqual({});
});
it('removeExample with nonexistent UID fails', () => {
const dataset = new Dataset();
const ex1 = getFakeExample('a');
const uid1 = dataset.addExample(ex1);
dataset.removeExample(uid1);
expect(() => dataset.removeExample(uid1))
.toThrowError(/Nonexistent example UID/);
});
it('setExampleKeyFrameIndex: works`', () => {
const dataset = new Dataset();
const ex1 = getFakeExample('a');
const uid1 = dataset.addExample(ex1);
dataset.setExampleKeyFrameIndex(uid1, 1);
expect(ex1.spectrogram.keyFrameIndex).toEqual(1);
const numFrames = ex1.spectrogram.data.length / ex1.spectrogram.frameSize;
dataset.setExampleKeyFrameIndex(uid1, numFrames - 1);
expect(ex1.spectrogram.keyFrameIndex).toEqual(numFrames - 1);
});
it('setExampleFrameIndex: serialization-deserialization', () => {
const dataset = new Dataset();
const ex1 = getFakeExample('a');
const uid1 = dataset.addExample(ex1);
const numFrames = ex1.spectrogram.data.length / ex1.spectrogram.frameSize;
dataset.setExampleKeyFrameIndex(uid1, numFrames - 1);
expect(ex1.spectrogram.keyFrameIndex).toEqual(numFrames - 1);
const datasetPrime = new Dataset(dataset.serialize());
const ex1Prime = datasetPrime.getExamples('a')[0];
expect(ex1Prime.example.spectrogram.keyFrameIndex).toEqual(numFrames - 1);
});
it('setExampleKeyFrameIndex: Invalid example UID leads to error`', () => {
const dataset = new Dataset();
const ex1 = getFakeExample('a');
const uid1 = dataset.addExample(ex1);
expect(() => dataset.setExampleKeyFrameIndex(uid1 + '_foo', 0))
.toThrowError(/Nonexistent example UID/);
});
it('setExampleKeyFrameIndex: Negative index leads to error`', () => {
const dataset = new Dataset();
const ex1 = getFakeExample('a');
const uid1 = dataset.addExample(ex1);
expect(() => dataset.setExampleKeyFrameIndex(uid1, -1))
.toThrowError(/Invalid keyFrameIndex/);
});
it('setExampleKeyFrameIndex: Too large index leads to error`', () => {
const dataset = new Dataset();
const ex1 = getFakeExample('a');
const numFrames = ex1.spectrogram.data.length / ex1.spectrogram.frameSize;
const uid1 = dataset.addExample(ex1);
expect(() => dataset.setExampleKeyFrameIndex(uid1, numFrames))
.toThrowError(/Invalid keyFrameIndex/);
expect(() => dataset.setExampleKeyFrameIndex(uid1, numFrames + 1))
.toThrowError(/Invalid keyFrameIndex/);
});
it('setExampleKeyFrameIndex: Non-integr value leads to error`', () => {
const dataset = new Dataset();
const ex1 = getFakeExample('a');
const uid1 = dataset.addExample(ex1);
expect(() => dataset.setExampleKeyFrameIndex(uid1, 0.5))
.toThrowError(/Invalid keyFrameIndex/);
});
it('getVocabulary', () => {
const dataset = new Dataset();
expect(dataset.getVocabulary()).toEqual([]);
const ex1 = getFakeExample('a');
const ex2 = getFakeExample('a');
const ex3 = getFakeExample('b');
const uid1 = dataset.addExample(ex1);
expect(dataset.getVocabulary()).toEqual(['a']);
const uid2 = dataset.addExample(ex2);
expect(dataset.getVocabulary()).toEqual(['a']);
const uid3 = dataset.addExample(ex3);
expect(dataset.getVocabulary()).toEqual(['a', 'b']);
dataset.removeExample(uid1);
expect(dataset.getVocabulary()).toEqual(['a', 'b']);
dataset.removeExample(uid2);
expect(dataset.getVocabulary()).toEqual(['b']);
dataset.removeExample(uid3);
expect(dataset.getVocabulary()).toEqual([]);
});
it('getSpectrogramsAsTensors with label', () => {
const dataset = new Dataset();
addThreeExamplesToDataset(dataset);
const out1 = dataset.getData('a') as {xs: tf.Tensor, ys: tf.Tensor};
expect(out1.xs.shape).toEqual([2, FAKE_NUM_FRAMES, FAKE_FRAME_SIZE, 1]);
expect(out1.ys).toBeUndefined();
const out2 = dataset.getData('b') as {xs: tf.Tensor, ys: tf.Tensor};
expect(out2.xs.shape).toEqual([1, FAKE_NUM_FRAMES, FAKE_FRAME_SIZE, 1]);
expect(out2.ys).toBeUndefined();
});
it('getSpectrogramsAsTensors after removeExample', () => {
const dataset = new Dataset();
const [uid1, uid2] = addThreeExamplesToDataset(dataset);
dataset.removeExample(uid1);
const out1 = dataset.getData(null, {shuffle: false}) as
{xs: tf.Tensor, ys: tf.Tensor};
expect(out1.xs.shape).toEqual([2, FAKE_NUM_FRAMES, FAKE_FRAME_SIZE, 1]);
expectTensorsClose(out1.ys, tf.tensor2d([[1, 0], [0, 1]]));
const out2 = dataset.getData('a') as {xs: tf.Tensor, ys: tf.Tensor};
expect(out2.xs.shape).toEqual([1, FAKE_NUM_FRAMES, FAKE_FRAME_SIZE, 1]);
dataset.removeExample(uid2);
expect(() => dataset.getData('a'))
.toThrowError(/Label a is not in the vocabulary/);
const out3 = dataset.getData('b') as {xs: tf.Tensor, ys: tf.Tensor};
expect(out3.xs.shape).toEqual([1, FAKE_NUM_FRAMES, FAKE_FRAME_SIZE, 1]);
});
it('getSpectrogramsAsTensors w/o label on one-word vocabulary fails', () => {
const dataset = new Dataset();
const [uid1, uid2] = addThreeExamplesToDataset(dataset);
dataset.removeExample(uid1);
dataset.removeExample(uid2);
expect(() => dataset.getData())
.toThrowError(/requires .* at least two words/);
});
it('getSpectrogramsAsTensors without label', () => {
const dataset = new Dataset();
addThreeExamplesToDataset(dataset);
const out = dataset.getData(null, {shuffle: false}) as
{xs: tf.Tensor, ys: tf.Tensor};
expect(out.xs.shape).toEqual([3, FAKE_NUM_FRAMES, FAKE_FRAME_SIZE, 1]);
expectTensorsClose(out.ys, tf.tensor2d([[1, 0], [1, 0], [0, 1]]));
});
it('getSpectrogramsAsTensors without label as tf.data.Dataset', async () => {
const dataset = new Dataset();
addThreeExamplesToDataset(dataset);
const [trainDataset, valDataset] = dataset.getData(null, {
getDataset: true,
datasetBatchSize: 1,
datasetValidationSplit: 1 / 3
}) as [SpectrogramAndTargetsTfDataset, SpectrogramAndTargetsTfDataset];
let numTrain = 0;
await trainDataset.forEachAsync(
(xAndY: {xs: tf.Tensor2D, ys: tf.Tensor2D}) => {
const {xs, ys} = xAndY;
numTrain++;
expect(xs.shape).toEqual([1, FAKE_NUM_FRAMES, FAKE_FRAME_SIZE, 1]);
expect(xs.isDisposed).toEqual(false);
expect(ys.shape).toEqual([1, 2]);
expect(ys.isDisposed).toEqual(false);
});
expect(numTrain).toEqual(2);
let numVal = 0;
await valDataset.forEachAsync(
(xAndY: {xs: tf.Tensor2D, ys: tf.Tensor2D}) => {
const {xs, ys} = xAndY;
numVal++;
expect(xs.shape).toEqual([1, FAKE_NUM_FRAMES, FAKE_FRAME_SIZE, 1]);
expect(xs.isDisposed).toEqual(false);
expect(ys.shape).toEqual([1, 2]);
expect(ys.isDisposed).toEqual(false);
});
expect(numVal).toEqual(1);
});
it('getData w/ mixing-noise augmentation: get tf.data.Dataset', async () => {
const dataset = new Dataset();
dataset.addExample(getFakeExample(
BACKGROUND_NOISE_TAG, 6, 2,
[10, 10, 20, 20, 30, 30, 20, 20, 10, 10, 0, 0]));
dataset.addExample(
getFakeExample('bar', 5, 2, [1, 1, 2, 2, 3, 3, 2, 2, 1, 1]));
const numFrames = 3;
const [trainDataset, valDataset] = dataset.getData(null, {
numFrames,
hopFrames: 1,
augmentByMixingNoiseRatio: 0.5,
getDataset: true,
datasetBatchSize: 1,
datasetValidationSplit: 1 / 3
}) as [SpectrogramAndTargetsTfDataset, SpectrogramAndTargetsTfDataset];
let numTrain = 0;
await trainDataset.forEachAsync(
(xAndY: {xs: tf.Tensor2D, ys: tf.Tensor2D}) => {
const {xs, ys} = xAndY;
numTrain++;
expect(xs.shape).toEqual([1, numFrames, 2, 1]);
expect(xs.isDisposed).toEqual(false);
expect(ys.shape).toEqual([1, 2]);
expect(ys.isDisposed).toEqual(false);
});
let numVal = 0;
await valDataset.forEachAsync(
(xAndY: {xs: tf.Tensor2D, ys: tf.Tensor2D}) => {
const {xs, ys} = xAndY;
numVal++;
expect(xs.shape).toEqual([1, numFrames, 2, 1]);
expect(xs.isDisposed).toEqual(false);
expect(ys.shape).toEqual([1, 2]);
expect(ys.isDisposed).toEqual(false);
});
expect(numTrain).toEqual(7); // Without augmentation, it'd be 5.
expect(numVal).toEqual(3); // Without augmentation, it'd be 2.
});
it('getData w/ mixing-noise augmentation w/o noise tag errors', async () => {
const dataset = new Dataset();
dataset.addExample(getFakeExample(
'foo', 6, 2, [10, 10, 20, 20, 30, 30, 20, 20, 10, 10, 0, 0]));
dataset.addExample(
getFakeExample('bar', 5, 2, [1, 1, 2, 2, 3, 3, 2, 2, 1, 1]));
// Lacks BACKGROUND_NOISE_TAG.
const numFrames = 3;
expect(() => dataset.getData(null, {
numFrames,
hopFrames: 1,
augmentByMixingNoiseRatio: 0.5,
getDataset: true,
datasetBatchSize: 1,
datasetValidationSplit: 1 / 3
})).toThrowError(/Cannot perform augmentation .* no example .*noise/);
});
it('getSpectrogramsAsTensors with invalid valSplit leads to error', () => {
const dataset = new Dataset();
addThreeExamplesToDataset(dataset);
expect(() => dataset.getData(null, {
getDataset: true,
datasetValidationSplit: 1.2
})).toThrowError(/Invalid dataset validation split/);
});
it('getSpectrogramsAsTensors on nonexistent label fails', () => {
const dataset = new Dataset();
addThreeExamplesToDataset(dataset);
expect(() => dataset.getData('label3'))
.toThrowError(/Label label3 is not in the vocabulary/);
});
it('getSpectrogramsAsTensors on empty Dataset fails', () => {
const dataset = new Dataset();
expect(() => dataset.getData())
.toThrowError(/Cannot get spectrograms as tensors because.*empty/);
});
it('Ragged example lengths and one window per example', () => {
const dataset = new Dataset();
dataset.addExample(getFakeExample('foo', 5));
dataset.addExample(getFakeExample('bar', 6));
dataset.addExample(getFakeExample('foo', 7));
const {xs, ys} =
dataset.getData(null, {numFrames: 5, hopFrames: 5, shuffle: false}) as
{xs: tf.Tensor, ys: tf.Tensor};
expect(xs.shape).toEqual([3, 5, FAKE_FRAME_SIZE, 1]);
expectTensorsClose(ys, tf.tensor2d([[1, 0], [0, 1], [0, 1]]));
});
it('Ragged example lengths and one window per example, with label', () => {
const dataset = new Dataset();
dataset.addExample(getFakeExample('foo', 5));
dataset.addExample(getFakeExample('bar', 6));
dataset.addExample(getFakeExample('foo', 7));
const {xs, ys} = dataset.getData('foo', {numFrames: 5, hopFrames: 5}) as
{xs: tf.Tensor, ys: tf.Tensor};
expect(xs.shape).toEqual([2, 5, FAKE_FRAME_SIZE, 1]);
expect(ys).toBeUndefined();
});
it('Ragged example lengths and multiple windows per example', () => {
const dataset = new Dataset();
dataset.addExample(getFakeExample(
'foo', 6, 2, [10, 10, 20, 20, 30, 30, 20, 20, 10, 10, 0, 0]));
dataset.addExample(
getFakeExample('bar', 5, 2, [1, 1, 2, 2, 3, 3, 2, 2, 1, 1]));
const {xs, ys} =
dataset.getData(
null,
{numFrames: 3, hopFrames: 1, shuffle: false, normalize: false}) as
{xs: tf.Tensor, ys: tf.Tensor};
const windows = tf.unstack(xs);
expect(windows.length).toEqual(6);
expectTensorsClose(windows[0], tf.tensor3d([1, 1, 2, 2, 3, 3], [3, 2, 1]));
expectTensorsClose(windows[1], tf.tensor3d([2, 2, 3, 3, 2, 2], [3, 2, 1]));
expectTensorsClose(windows[2], tf.tensor3d([3, 3, 2, 2, 1, 1], [3, 2, 1]));
expectTensorsClose(
windows[3], tf.tensor3d([10, 10, 20, 20, 30, 30], [3, 2, 1]));
expectTensorsClose(
windows[4], tf.tensor3d([20, 20, 30, 30, 20, 20], [3, 2, 1]));
expectTensorsClose(
windows[5], tf.tensor3d([30, 30, 20, 20, 10, 10], [3, 2, 1]));
expectTensorsClose(
ys, tf.tensor2d([[1, 0], [1, 0], [1, 0], [0, 1], [0, 1], [0, 1]]));
});
it('getData with mixing-noise augmentation: get tensors', () => {
const dataset = new Dataset();
dataset.addExample(getFakeExample(
BACKGROUND_NOISE_TAG, 6, 2,
[10, 10, 20, 20, 30, 30, 20, 20, 10, 10, 0, 0]));
dataset.addExample(
getFakeExample('bar', 5, 2, [1, 1, 2, 2, 3, 3, 2, 2, 1, 1]));
const {xs, ys} = dataset.getData(null, {
numFrames: 3,
hopFrames: 1,
shuffle: false,
normalize: false,
augmentByMixingNoiseRatio: 0.5
}) as {xs: tf.Tensor, ys: tf.Tensor};
// 3 of the newly-generated ones at the end are from the augmentation.
expect(xs.shape).toEqual([10, 3, 2, 1]);
expect(ys.shape).toEqual([10, 2]);
const indices = tf.argMax(ys, -1).dataSync();
const backgroundNoiseIndex = indices[0];
for (let i = 0; i < 3; ++i) {
expect(indices[indices.length - 1 - i] === backgroundNoiseIndex)
.toEqual(false);
}
});
// TODO(cais): Test that augmentByNoise without BACKGROUND_NOISE tag leads to
// Error.
it('getSpectrogramsAsTensors: normalize=true', () => {
const dataset = new Dataset();
dataset.addExample(getFakeExample(
'foo', 6, 2, [10, 10, 20, 20, 30, 30, 20, 20, 10, 10, 0, 0]));
dataset.addExample(
getFakeExample('bar', 5, 2, [1, 1, 2, 2, 3, 3, 2, 2, 1, 1]));
// `normalize` is `true` by default.
const {xs, ys} =
dataset.getData(null, {numFrames: 3, hopFrames: 1, shuffle: false}) as
{xs: tf.Tensor, ys: tf.Tensor};
const windows = tf.unstack(xs);
expect(windows.length).toEqual(6);
for (let i = 0; i < 6; ++i) {
const {mean, variance} = tf.moments(windows[0]);
expectTensorsClose(mean, tf.scalar(0));
expectTensorsClose(variance, tf.scalar(1));
}
expectTensorsClose(
windows[0], normalize(tf.tensor3d([1, 1, 2, 2, 3, 3], [3, 2, 1])));
expectTensorsClose(
windows[1], normalize(tf.tensor3d([2, 2, 3, 3, 2, 2], [3, 2, 1])));
expectTensorsClose(
windows[2], normalize(tf.tensor3d([3, 3, 2, 2, 1, 1], [3, 2, 1])));
expectTensorsClose(
windows[3],
normalize(tf.tensor3d([10, 10, 20, 20, 30, 30], [3, 2, 1])));
expectTensorsClose(
windows[4],
normalize(tf.tensor3d([20, 20, 30, 30, 20, 20], [3, 2, 1])));
expectTensorsClose(
windows[5],
normalize(tf.tensor3d([30, 30, 20, 20, 10, 10], [3, 2, 1])));
expectTensorsClose(
ys, tf.tensor2d([[1, 0], [1, 0], [1, 0], [0, 1], [0, 1], [0, 1]]));
});
it('getSpectrogramsAsTensors: shuffle=true leads to random order', () => {
const dataset = new Dataset();
dataset.addExample(getFakeExample(
'foo', 6, 2, [10, 10, 20, 20, 30, 30, 20, 20, 10, 10, 0, 0]));
dataset.addExample(
getFakeExample('bar', 5, 2, [1, 1, 2, 2, 3, 3, 2, 2, 1, 1]));
const argMaxTensors: tf.Tensor[] = [];
for (let i = 0; i < 5; ++i) {
// `shuffle` is `true` by default.
const {ys} = dataset.getData(null, {numFrames: 3, hopFrames: 1}) as
{xs: tf.Tensor, ys: tf.Tensor};
// Use `argMax()` to convert the one-hot-encoded `ys` to indices.
argMaxTensors.push(tf.argMax(ys, -1));
}
// `argMaxTensors` are the indices for the targets.
// We stack them into a 2D tensor and then calculate the variance along
// the examples dimension, in order to detect variance in the indices
// between the iterations above.
const argMaxMerged = tf.stack(argMaxTensors);
// Assert that the orders are not all the same. This is asserting that
// the indices are not all the same among the 5 iterations above.
const {variance} = tf.moments(argMaxMerged, 0);
expect(tf.max(variance).dataSync()[0]).toBeGreaterThan(0);
});
it('getSpectrogramsAsTensors: shuffle=false leads to constant order', () => {
const dataset = new Dataset();
dataset.addExample(getFakeExample(
'foo', 6, 2, [10, 10, 20, 20, 30, 30, 20, 20, 10, 10, 0, 0]));
dataset.addExample(
getFakeExample('bar', 5, 2, [1, 1, 2, 2, 3, 3, 2, 2, 1, 1]));
const argMaxTensors: tf.Tensor[] = [];
for (let i = 0; i < 5; ++i) {
const {ys} =
dataset.getData(null, {numFrames: 3, hopFrames: 1, shuffle: false}) as
{xs: tf.Tensor, ys: tf.Tensor};
argMaxTensors.push(tf.argMax(ys, -1));
}
// `argMaxTensors` are the indices for the targets.
// We stack them into a 2D tensor and then calculate the variance along
// the examples dimension, in order to detect variance in the indices
// between the iterations above.
const argMaxMerged = tf.stack(argMaxTensors);
// Assert that the orders are not all the same. This is asserting that
// the indices are all the same among the 5 iterations above.
const {variance} = tf.moments(argMaxMerged, 0);
expect(tf.max(variance).dataSync()[0]).toEqual(0);
});
it('Uniform example lengths and multiple windows per example', () => {
const dataset = new Dataset();
dataset.addExample(getFakeExample(
'foo', 6, 2, [10, 10, 20, 20, 30, 30, 20, 20, 10, 10, 0, 0]));
dataset.addExample(
getFakeExample('bar', 6, 2, [0, 0, 1, 1, 2, 2, 3, 3, 2, 2, 1, 1]));
const {xs, ys} =
dataset.getData(
null,
{numFrames: 5, hopFrames: 1, shuffle: false, normalize: false}) as
{xs: tf.Tensor, ys: tf.Tensor};
const windows = tf.unstack(xs);
expect(windows.length).toEqual(4);
expectTensorsClose(
windows[0], tf.tensor3d([0, 0, 1, 1, 2, 2, 3, 3, 2, 2], [5, 2, 1]));
expectTensorsClose(
windows[1], tf.tensor3d([1, 1, 2, 2, 3, 3, 2, 2, 1, 1], [5, 2, 1]));
expectTensorsClose(
windows[2],
tf.tensor3d([10, 10, 20, 20, 30, 30, 20, 20, 10, 10], [5, 2, 1]));
expectTensorsClose(
windows[3],
tf.tensor3d([20, 20, 30, 30, 20, 20, 10, 10, 0, 0], [5, 2, 1]));
expectTensorsClose(ys, tf.tensor2d([[1, 0], [1, 0], [0, 1], [0, 1]]));
});
it('Ragged examples containing background noise', () => {
const dataset = new Dataset();
dataset.addExample(getFakeExample(
BACKGROUND_NOISE_TAG, 7, 2,
[0, 0, 10, 10, 20, 20, 30, 30, 20, 20, 10, 10, 0, 0]));
dataset.addExample(
getFakeExample('bar', 6, 2, [0, 0, 1, 1, 2, 2, 3, 3, 2, 2, 1, 1]));
const {xs, ys} =
dataset.getData(
null,
{numFrames: 3, hopFrames: 2, shuffle: false, normalize: false}) as
{xs: tf.Tensor, ys: tf.Tensor};
const windows = tf.unstack(xs);
expect(windows.length).toEqual(4);
expectTensorsClose(
windows[0], tf.tensor3d([0, 0, 10, 10, 20, 20], [3, 2, 1]));
expectTensorsClose(
windows[1], tf.tensor3d([20, 20, 30, 30, 20, 20], [3, 2, 1]));
expectTensorsClose(
windows[2], tf.tensor3d([20, 20, 10, 10, 0, 0], [3, 2, 1]));
expectTensorsClose(windows[3], tf.tensor3d([2, 2, 3, 3, 2, 2], [3, 2, 1]));
expectTensorsClose(ys, tf.tensor2d([[1, 0], [1, 0], [1, 0], [0, 1]]));
});
it('numFrames exceeding minmum example length leads to Error', () => {
const dataset = new Dataset();
dataset.addExample(getFakeExample(
'foo', 6, 2, [10, 10, 20, 20, 30, 30, 20, 20, 10, 10, 0, 0]));
dataset.addExample(
getFakeExample('bar', 5, 2, [1, 1, 2, 2, 3, 3, 2, 2, 1, 1]));
expect(() => dataset.getData(null, {numFrames: 6, hopFrames: 2}))
.toThrowError(/.*6.*exceeds the minimum numFrames .*5.*/);
});
it('Ragged examples with no numFrames leads to Error', () => {
const dataset = new Dataset();
dataset.addExample(getFakeExample(
'foo', 6, 2, [10, 10, 20, 20, 30, 30, 20, 20, 10, 10, 0, 0]));
dataset.addExample(
getFakeExample('bar', 5, 2, [1, 1, 2, 2, 3, 3, 2, 2, 1, 1]));
expect(() => dataset.getData(null)).toThrowError(/numFrames is required/);
});
it('Ragged examples with no hopFrames leads to Error', () => {
const dataset = new Dataset();
dataset.addExample(getFakeExample(
'foo', 6, 2, [10, 10, 20, 20, 30, 30, 20, 20, 10, 10, 0, 0]));
dataset.addExample(
getFakeExample('bar', 5, 2, [1, 1, 2, 2, 3, 3, 2, 2, 1, 1]));
expect(() => dataset.getData(null, {
numFrames: 4
})).toThrowError(/hopFrames is required/);
});
});
describe('Dataset serialization', () => {
function getRandomExample(
label: string, numFrames: number, frameSize: number,
rawAudioNumSamples?: number, rawAudioSampleRateHz?: number): Example {
const spectrogramData = [];
for (let i = 0; i < numFrames * frameSize; ++i) {
spectrogramData.push(Math.random());
}
const output: Example = {
label,
spectrogram: {data: new Float32Array(spectrogramData), frameSize}
};
if (rawAudioNumSamples != null) {
const rawAudioData: number[] = [];
for (let i = 0; i < rawAudioNumSamples; ++i) {
rawAudioData.push(Math.random());
}
const rawAudio: RawAudioData = {
data: new Float32Array(rawAudioData),
sampleRateHz: rawAudioSampleRateHz
};
output.rawAudio = rawAudio;
}
return output;
}
it('serializeExample-deserializeExample round trip, no raw audio', () => {
const label = 'foo';
const numFrames = 10;
const frameSize = 16;
const ex = getRandomExample(label, numFrames, frameSize);
const artifacts = serializeExample(ex);
expect(artifacts.spec.label).toEqual(label);
expect(artifacts.spec.spectrogramNumFrames).toEqual(numFrames);
expect(artifacts.spec.spectrogramFrameSize).toEqual(frameSize);
expect(artifacts.spec.rawAudioNumSamples).toBeUndefined();
expect(artifacts.spec.rawAudioSampleRateHz).toBeUndefined();
expect(artifacts.data.byteLength).toEqual(4 * numFrames * frameSize);
const exPrime = deserializeExample(artifacts);
expect(exPrime.label).toEqual(ex.label);
expect(exPrime.spectrogram.frameSize).toEqual(ex.spectrogram.frameSize);
test_util.expectArraysEqual(exPrime.spectrogram.data, ex.spectrogram.data);
});
it('serializeExample-deserializeExample round trip, with raw audio', () => {
const label = 'foo';
const numFrames = 10;
const frameSize = 16;
const rawAudioNumSamples = 200;
const rawAudioSampleRateHz = 48000;
const ex = getRandomExample(
label, numFrames, frameSize, rawAudioNumSamples, rawAudioSampleRateHz);
const artifacts = serializeExample(ex);
expect(artifacts.spec.label).toEqual(label);
expect(artifacts.spec.spectrogramNumFrames).toEqual(numFrames);
expect(artifacts.spec.spectrogramFrameSize).toEqual(frameSize);
expect(artifacts.spec.rawAudioNumSamples).toEqual(rawAudioNumSamples);
expect(artifacts.spec.rawAudioSampleRateHz).toEqual(rawAudioSampleRateHz);
expect(artifacts.data.byteLength)
.toEqual(4 * (numFrames * frameSize + rawAudioNumSamples));
const exPrime = deserializeExample(artifacts);
expect(exPrime.label).toEqual(ex.label);
expect(exPrime.spectrogram.frameSize).toEqual(ex.spectrogram.frameSize);
expect(exPrime.rawAudio.sampleRateHz).toEqual(ex.rawAudio.sampleRateHz);
test_util.expectArraysEqual(exPrime.spectrogram.data, ex.spectrogram.data);
test_util.expectArraysEqual(exPrime.rawAudio.data, ex.rawAudio.data);
});
it('Dataset.serialize()', () => {
const dataset = new Dataset();
const ex1 = getRandomExample('foo', 10, 16);
const ex2 = getRandomExample('bar', 12, 16);
const ex3 = getRandomExample('qux', 14, 16);
const ex4 = getRandomExample('foo', 13, 16);
dataset.addExample(ex1);
dataset.addExample(ex2);
dataset.addExample(ex3);
dataset.addExample(ex4);
const buffer = dataset.serialize();
const {manifest, data} = arrayBuffer2SerializedExamples(buffer);
expect(manifest).toEqual([
{label: 'bar', spectrogramNumFrames: 12, spectrogramFrameSize: 16},
{label: 'foo', spectrogramNumFrames: 10, spectrogramFrameSize: 16},
{label: 'foo', spectrogramNumFrames: 13, spectrogramFrameSize: 16},
{label: 'qux', spectrogramNumFrames: 14, spectrogramFrameSize: 16}
]);
expect(data.byteLength).toEqual(4 * (10 + 12 + 14 + 13) * 16);
});
it('Dataset.serialize(): limited singleton word labels', () => {
const dataset = new Dataset();
const ex1 = getRandomExample('foo', 10, 16);
const ex2 = getRandomExample('bar', 12, 16);
const ex3 = getRandomExample('qux', 14, 16);
const ex4 = getRandomExample('foo', 13, 16);
dataset.addExample(ex1);
dataset.addExample(ex2);
dataset.addExample(ex3);
dataset.addExample(ex4);
let buffer = dataset.serialize('foo');
let loaded = arrayBuffer2SerializedExamples(buffer);
expect(loaded.manifest).toEqual([
{label: 'foo', spectrogramNumFrames: 10, spectrogramFrameSize: 16},
{label: 'foo', spectrogramNumFrames: 13, spectrogramFrameSize: 16}
]);
expect(loaded.data.byteLength).toEqual(4 * (10 + 13) * 16);
buffer = dataset.serialize('bar');
loaded = arrayBuffer2SerializedExamples(buffer);
expect(loaded.manifest).toEqual([
{label: 'bar', spectrogramNumFrames: 12, spectrogramFrameSize: 16}
]);
expect(loaded.data.byteLength).toEqual(4 * 12 * 16);
});
it('Dataset.serialize(): limited array word label', () => {
const dataset = new Dataset();
const ex1 = getRandomExample('foo', 10, 16);
const ex2 = getRandomExample('bar', 12, 16);
const ex3 = getRandomExample('qux', 14, 16);
const ex4 = getRandomExample('foo', 13, 16);
dataset.addExample(ex1);
dataset.addExample(ex2);
dataset.addExample(ex3);
dataset.addExample(ex4);
const buffer = dataset.serialize(['foo', 'qux']);
const loaded = arrayBuffer2SerializedExamples(buffer);
expect(loaded.manifest).toEqual([
{label: 'foo', spectrogramNumFrames: 10, spectrogramFrameSize: 16},
{label: 'foo', spectrogramNumFrames: 13, spectrogramFrameSize: 16},
{label: 'qux', spectrogramNumFrames: 14, spectrogramFrameSize: 16}
]);
expect(loaded.data.byteLength).toEqual(4 * (10 + 13 + 14) * 16);
});
it('Dataset.serialize(): nonexistent singleton word label errors', () => {
const dataset = new Dataset();
const ex1 = getRandomExample('foo', 10, 16);
const ex2 = getRandomExample('bar', 12, 16);
const ex3 = getRandomExample('qux', 14, 16);
const ex4 = getRandomExample('foo', 13, 16);
dataset.addExample(ex1);
dataset.addExample(ex2);
dataset.addExample(ex3);
dataset.addExample(ex4);
expect(() => dataset.serialize('gralk'))
.toThrowError(/\"gralk\" does not exist/);
expect(() => dataset.serialize(['gralk']))
.toThrowError(/\"gralk\" does not exist/);
expect(() => dataset.serialize([
'foo', 'gralk'
])).toThrowError(/\"gralk\" does not exist/);
});
it('Dataset serialize-deserialize round trip', () => {
const dataset = new Dataset();
const ex1 = getRandomExample('foo', 10, 16);
const ex2 = getRandomExample('bar', 10, 16);
const ex3 = getRandomExample('qux', 10, 16);
const ex4 = getRandomExample('foo', 10, 16);
dataset.addExample(ex1);
dataset.addExample(ex2);
dataset.addExample(ex3);
dataset.addExample(ex4);
const artifacts = dataset.serialize();
const datasetPrime = new Dataset(artifacts);
expect(datasetPrime.empty()).toEqual(false);
expect(datasetPrime.size()).toEqual(4);
expect(datasetPrime.getVocabulary()).toEqual(['bar', 'foo', 'qux']);
expect(dataset.getExampleCounts()).toEqual({'bar': 1, 'foo': 2, 'qux': 1});
expect(dataset.getExamples('bar').length).toEqual(1);
expect(dataset.getExamples('foo').length).toEqual(2);
expect(dataset.getExamples('qux').length).toEqual(1);
const ex1Prime = datasetPrime.getExamples('foo')[0].example;
expect(ex1Prime.label).toEqual('foo');
expect(ex1Prime.spectrogram.frameSize).toEqual(16);
test_util.expectArraysEqual(
ex1Prime.spectrogram.data, ex1.spectrogram.data);
const ex2Prime = datasetPrime.getExamples('bar')[0].example;
expect(ex2Prime.label).toEqual('bar');
expect(ex2Prime.spectrogram.frameSize).toEqual(16);
test_util.expectArraysEqual(