-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
exports_layers.ts
1889 lines (1809 loc) · 62.9 KB
/
exports_layers.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 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
import {InputLayer, InputLayerArgs} from './engine/input_layer';
import {Layer, LayerArgs} from './engine/topology';
import {input} from './exports';
import {ELU, ELULayerArgs, LeakyReLU, LeakyReLULayerArgs, PReLU, PReLULayerArgs, ReLU, ReLULayerArgs, Softmax, SoftmaxLayerArgs, ThresholdedReLU, ThresholdedReLULayerArgs} from './layers/advanced_activations';
import {Conv1D, Conv2D, Conv2DTranspose, Conv3D, ConvLayerArgs, Cropping2D, Cropping2DLayerArgs, SeparableConv2D, SeparableConvLayerArgs, UpSampling2D, UpSampling2DLayerArgs, Conv3DTranspose} from './layers/convolutional';
import {DepthwiseConv2D, DepthwiseConv2DLayerArgs} from './layers/convolutional_depthwise';
import {ConvLSTM2D, ConvLSTM2DArgs, ConvLSTM2DCell, ConvLSTM2DCellArgs} from './layers/convolutional_recurrent';
import {Activation, ActivationLayerArgs, Dense, DenseLayerArgs, Dropout, DropoutLayerArgs, Flatten, FlattenLayerArgs, Masking, MaskingArgs, Permute, PermuteLayerArgs, RepeatVector, RepeatVectorLayerArgs, Reshape, ReshapeLayerArgs, SpatialDropout1D, SpatialDropout1DLayerConfig} from './layers/core';
import {Embedding, EmbeddingLayerArgs} from './layers/embeddings';
import {Add, Average, Concatenate, ConcatenateLayerArgs, Dot, DotLayerArgs, Maximum, Minimum, Multiply} from './layers/merge';
import {AlphaDropout, AlphaDropoutArgs, GaussianDropout, GaussianDropoutArgs, GaussianNoise, GaussianNoiseArgs} from './layers/noise';
import {BatchNormalization, BatchNormalizationLayerArgs, LayerNormalization, LayerNormalizationLayerArgs} from './layers/normalization';
import {ZeroPadding2D, ZeroPadding2DLayerArgs} from './layers/padding';
import {AveragePooling1D, AveragePooling2D, AveragePooling3D, GlobalAveragePooling1D, GlobalAveragePooling2D, GlobalMaxPooling1D, GlobalMaxPooling2D, GlobalPooling2DLayerArgs, MaxPooling1D, MaxPooling2D, MaxPooling3D, Pooling1DLayerArgs, Pooling2DLayerArgs, Pooling3DLayerArgs} from './layers/pooling';
import {GRU, GRUCell, GRUCellLayerArgs, GRULayerArgs, LSTM, LSTMCell, LSTMCellLayerArgs, LSTMLayerArgs, RNN, RNNCell, RNNLayerArgs, SimpleRNN, SimpleRNNCell, SimpleRNNCellLayerArgs, SimpleRNNLayerArgs, StackedRNNCells, StackedRNNCellsArgs} from './layers/recurrent';
import {Bidirectional, BidirectionalLayerArgs, TimeDistributed, WrapperLayerArgs} from './layers/wrappers';
import {Rescaling, RescalingArgs} from './layers/preprocessing/image_preprocessing';
import {CenterCrop, CenterCropArgs} from './layers/preprocessing/center_crop';
import {CategoryEncoding, CategoryEncodingArgs} from './layers/preprocessing/category_encoding';
import {Resizing, ResizingArgs} from './layers/preprocessing/image_resizing';
import {RandomWidth, RandomWidthArgs} from './layers/preprocessing/random_width';
// TODO(cais): Add doc string to all the public static functions in this
// class; include exectuable JavaScript code snippets where applicable
// (b/74074458).
// Input Layer.
/**
* An input layer is an entry point into a `tf.LayersModel`.
*
* `InputLayer` is generated automatically for `tf.Sequential` models by
* specifying the `inputshape` or `batchInputShape` for the first layer. It
* should not be specified explicitly. However, it can be useful sometimes,
* e.g., when constructing a sequential model from a subset of another
* sequential model's layers. Like the code snippet below shows.
*
* ```js
* // Define a model which simply adds two inputs.
* const model1 = tf.sequential();
* model1.add(tf.layers.dense({inputShape: [4], units: 3, activation: 'relu'}));
* model1.add(tf.layers.dense({units: 1, activation: 'sigmoid'}));
* model1.summary();
* model1.predict(tf.zeros([1, 4])).print();
*
* // Construct another model, reusing the second layer of `model1` while
* // not using the first layer of `model1`. Note that you cannot add the second
* // layer of `model` directly as the first layer of the new sequential model,
* // because doing so will lead to an error related to the fact that the layer
* // is not an input layer. Instead, you need to create an `inputLayer` and add
* // it to the new sequential model before adding the reused layer.
* const model2 = tf.sequential();
* // Use an inputShape that matches the input shape of `model1`'s second
* // layer.
* model2.add(tf.layers.inputLayer({inputShape: [3]}));
* model2.add(model1.layers[1]);
* model2.summary();
* model2.predict(tf.zeros([1, 3])).print();
* ```
*
* @doc {heading: 'Layers', subheading: 'Inputs', namespace: 'layers'}
*/
export function inputLayer(args: InputLayerArgs) {
return new InputLayer(args);
}
// Advanced Activation Layers.
/**
* Exponential Linear Unit (ELU).
*
* It follows:
* `f(x) = alpha * (exp(x) - 1.) for x < 0`,
* `f(x) = x for x >= 0`.
*
* Input shape:
* Arbitrary. Use the configuration `inputShape` when using this layer as the
* first layer in a model.
*
* Output shape:
* Same shape as the input.
*
* References:
* - [Fast and Accurate Deep Network Learning by Exponential Linear Units
* (ELUs)](https://arxiv.org/abs/1511.07289v1)
*
* @doc {
* heading: 'Layers',
* subheading: 'Advanced Activation',
* namespace: 'layers'
* }
*/
export function elu(args?: ELULayerArgs) {
return new ELU(args);
}
/**
* Rectified Linear Unit activation function.
*
* Input shape:
* Arbitrary. Use the config field `inputShape` (Array of integers, does
* not include the sample axis) when using this layer as the first layer
* in a model.
*
* Output shape:
* Same shape as the input.
*
* @doc {
* heading: 'Layers',
* subheading: 'Advanced Activation',
* namespace: 'layers'
* }
*/
export function reLU(args?: ReLULayerArgs) {
return new ReLU(args);
}
/**
* Leaky version of a rectified linear unit.
*
* It allows a small gradient when the unit is not active:
* `f(x) = alpha * x for x < 0.`
* `f(x) = x for x >= 0.`
*
* Input shape:
* Arbitrary. Use the configuration `inputShape` when using this layer as the
* first layer in a model.
*
* Output shape:
* Same shape as the input.
*
* @doc {
* heading: 'Layers',
* subheading: 'Advanced Activation',
* namespace: 'layers'
* }
*/
export function leakyReLU(args?: LeakyReLULayerArgs) {
return new LeakyReLU(args);
}
/**
* Parameterized version of a leaky rectified linear unit.
*
* It follows
* `f(x) = alpha * x for x < 0.`
* `f(x) = x for x >= 0.`
* wherein `alpha` is a trainable weight.
*
* Input shape:
* Arbitrary. Use the configuration `inputShape` when using this layer as the
* first layer in a model.
*
* Output shape:
* Same shape as the input.
*
* @doc {
* heading: 'Layers',
* subheading: 'Advanced Activation',
* namespace: 'layers'
* }
*/
export function prelu(args?: PReLULayerArgs) {
return new PReLU(args);
}
/**
* Softmax activation layer.
*
* Input shape:
* Arbitrary. Use the configuration `inputShape` when using this layer as the
* first layer in a model.
*
* Output shape:
* Same shape as the input.
*
* @doc {
* heading: 'Layers',
* subheading: 'Advanced Activation',
* namespace: 'layers'
* }
*/
export function softmax(args?: SoftmaxLayerArgs) {
return new Softmax(args);
}
/**
* Thresholded Rectified Linear Unit.
*
* It follows:
* `f(x) = x for x > theta`,
* `f(x) = 0 otherwise`.
*
* Input shape:
* Arbitrary. Use the configuration `inputShape` when using this layer as the
* first layer in a model.
*
* Output shape:
* Same shape as the input.
*
* References:
* - [Zero-Bias Autoencoders and the Benefits of Co-Adapting
* Features](http://arxiv.org/abs/1402.3337)
*
* @doc {
* heading: 'Layers',
* subheading: 'Advanced Activation',
* namespace: 'layers'
* }
*/
export function thresholdedReLU(args?: ThresholdedReLULayerArgs) {
return new ThresholdedReLU(args);
}
// Convolutional Layers.
/**
* 1D convolution layer (e.g., temporal convolution).
*
* This layer creates a convolution kernel that is convolved
* with the layer input over a single spatial (or temporal) dimension
* to produce a tensor of outputs.
*
* If `use_bias` is True, a bias vector is created and added to the outputs.
*
* If `activation` is not `null`, it is applied to the outputs as well.
*
* When using this layer as the first layer in a model, provide an
* `inputShape` argument `Array` or `null`.
*
* For example, `inputShape` would be:
* - `[10, 128]` for sequences of 10 vectors of 128-dimensional vectors
* - `[null, 128]` for variable-length sequences of 128-dimensional vectors.
*
* @doc {heading: 'Layers', subheading: 'Convolutional', namespace: 'layers'}
*/
export function conv1d(args: ConvLayerArgs) {
return new Conv1D(args);
}
/**
* 2D convolution layer (e.g. spatial convolution over images).
*
* This layer creates a convolution kernel that is convolved
* with the layer input to produce a tensor of outputs.
*
* If `useBias` is True, a bias vector is created and added to the outputs.
*
* If `activation` is not `null`, it is applied to the outputs as well.
*
* When using this layer as the first layer in a model,
* provide the keyword argument `inputShape`
* (Array of integers, does not include the sample axis),
* e.g. `inputShape=[128, 128, 3]` for 128x128 RGB pictures
* in `dataFormat='channelsLast'`.
*
* @doc {heading: 'Layers', subheading: 'Convolutional', namespace: 'layers'}
*/
export function conv2d(args: ConvLayerArgs) {
return new Conv2D(args);
}
/**
* Transposed convolutional layer (sometimes called Deconvolution).
*
* The need for transposed convolutions generally arises
* from the desire to use a transformation going in the opposite direction of
* a normal convolution, i.e., from something that has the shape of the output
* of some convolution to something that has the shape of its input while
* maintaining a connectivity pattern that is compatible with said
* convolution.
*
* When using this layer as the first layer in a model, provide the
* configuration `inputShape` (`Array` of integers, does not include the
* sample axis), e.g., `inputShape: [128, 128, 3]` for 128x128 RGB pictures in
* `dataFormat: 'channelsLast'`.
*
* Input shape:
* 4D tensor with shape:
* `[batch, channels, rows, cols]` if `dataFormat` is `'channelsFirst'`.
* or 4D tensor with shape
* `[batch, rows, cols, channels]` if `dataFormat` is `'channelsLast'`.
*
* Output shape:
* 4D tensor with shape:
* `[batch, filters, newRows, newCols]` if `dataFormat` is
* `'channelsFirst'`. or 4D tensor with shape:
* `[batch, newRows, newCols, filters]` if `dataFormat` is `'channelsLast'`.
*
* References:
* - [A guide to convolution arithmetic for deep
* learning](https://arxiv.org/abs/1603.07285v1)
* - [Deconvolutional
* Networks](http://www.matthewzeiler.com/pubs/cvpr2010/cvpr2010.pdf)
*
* @doc {heading: 'Layers', subheading: 'Convolutional', namespace: 'layers'}
*/
export function conv2dTranspose(args: ConvLayerArgs) {
return new Conv2DTranspose(args);
}
/**
* 3D convolution layer (e.g. spatial convolution over volumes).
*
* This layer creates a convolution kernel that is convolved
* with the layer input to produce a tensor of outputs.
*
* If `useBias` is True, a bias vector is created and added to the outputs.
*
* If `activation` is not `null`, it is applied to the outputs as well.
*
* When using this layer as the first layer in a model,
* provide the keyword argument `inputShape`
* (Array of integers, does not include the sample axis),
* e.g. `inputShape=[128, 128, 128, 1]` for 128x128x128 grayscale volumes
* in `dataFormat='channelsLast'`.
*
* @doc {heading: 'Layers', subheading: 'Convolutional', namespace: 'layers'}
*/
export function conv3d(args: ConvLayerArgs) {
return new Conv3D(args);
}
export function conv3dTranspose(args: ConvLayerArgs): Layer {
return new Conv3DTranspose(args);
}
/**
* Depthwise separable 2D convolution.
*
* Separable convolution consists of first performing
* a depthwise spatial convolution
* (which acts on each input channel separately)
* followed by a pointwise convolution which mixes together the resulting
* output channels. The `depthMultiplier` argument controls how many
* output channels are generated per input channel in the depthwise step.
*
* Intuitively, separable convolutions can be understood as
* a way to factorize a convolution kernel into two smaller kernels,
* or as an extreme version of an Inception block.
*
* Input shape:
* 4D tensor with shape:
* `[batch, channels, rows, cols]` if data_format='channelsFirst'
* or 4D tensor with shape:
* `[batch, rows, cols, channels]` if data_format='channelsLast'.
*
* Output shape:
* 4D tensor with shape:
* `[batch, filters, newRows, newCols]` if data_format='channelsFirst'
* or 4D tensor with shape:
* `[batch, newRows, newCols, filters]` if data_format='channelsLast'.
* `rows` and `cols` values might have changed due to padding.
*
* @doc {heading: 'Layers', subheading: 'Convolutional', namespace: 'layers'}
*/
export function separableConv2d(args: SeparableConvLayerArgs) {
return new SeparableConv2D(args);
}
/**
* Cropping layer for 2D input (e.g., image).
*
* This layer can crop an input
* at the top, bottom, left and right side of an image tensor.
*
* Input shape:
* 4D tensor with shape:
* - If `dataFormat` is `"channelsLast"`:
* `[batch, rows, cols, channels]`
* - If `data_format` is `"channels_first"`:
* `[batch, channels, rows, cols]`.
*
* Output shape:
* 4D with shape:
* - If `dataFormat` is `"channelsLast"`:
* `[batch, croppedRows, croppedCols, channels]`
* - If `dataFormat` is `"channelsFirst"`:
* `[batch, channels, croppedRows, croppedCols]`.
*
* Examples
* ```js
*
* const model = tf.sequential();
* model.add(tf.layers.cropping2D({cropping:[[2, 2], [2, 2]],
* inputShape: [128, 128, 3]}));
* //now output shape is [batch, 124, 124, 3]
* ```
*
* @doc {heading: 'Layers', subheading: 'Convolutional', namespace: 'layers'}
*/
export function cropping2D(args: Cropping2DLayerArgs) {
return new Cropping2D(args);
}
/**
* Upsampling layer for 2D inputs.
*
* Repeats the rows and columns of the data
* by size[0] and size[1] respectively.
*
*
* Input shape:
* 4D tensor with shape:
* - If `dataFormat` is `"channelsLast"`:
* `[batch, rows, cols, channels]`
* - If `dataFormat` is `"channelsFirst"`:
* `[batch, channels, rows, cols]`
*
* Output shape:
* 4D tensor with shape:
* - If `dataFormat` is `"channelsLast"`:
* `[batch, upsampledRows, upsampledCols, channels]`
* - If `dataFormat` is `"channelsFirst"`:
* `[batch, channels, upsampledRows, upsampledCols]`
*
*
* @doc {heading: 'Layers', subheading: 'Convolutional', namespace: 'layers'}
*/
export function upSampling2d(args: UpSampling2DLayerArgs) {
return new UpSampling2D(args);
}
// Convolutional(depthwise) Layers.
/**
* Depthwise separable 2D convolution.
*
* Depthwise Separable convolutions consists in performing just the first step
* in a depthwise spatial convolution (which acts on each input channel
* separately). The `depthMultiplier` argument controls how many output channels
* are generated per input channel in the depthwise step.
*
* @doc {heading: 'Layers', subheading: 'Convolutional', namespace: 'layers'}
*/
export function depthwiseConv2d(args: DepthwiseConv2DLayerArgs) {
return new DepthwiseConv2D(args);
}
// Basic Layers.
/**
* Applies an activation function to an output.
*
* This layer applies element-wise activation function. Other layers, notably
* `dense` can also apply activation functions. Use this isolated activation
* function to extract the values before and after the
* activation. For instance:
*
* ```js
* const input = tf.input({shape: [5]});
* const denseLayer = tf.layers.dense({units: 1});
* const activationLayer = tf.layers.activation({activation: 'relu6'});
*
* // Obtain the output symbolic tensors by applying the layers in order.
* const denseOutput = denseLayer.apply(input);
* const activationOutput = activationLayer.apply(denseOutput);
*
* // Create the model based on the inputs.
* const model = tf.model({
* inputs: input,
* outputs: [denseOutput, activationOutput]
* });
*
* // Collect both outputs and print separately.
* const [denseOut, activationOut] = model.predict(tf.randomNormal([6, 5]));
* denseOut.print();
* activationOut.print();
* ```
*
* @doc {heading: 'Layers', subheading: 'Basic', namespace: 'layers'}
*/
export function activation(args: ActivationLayerArgs) {
return new Activation(args);
}
/**
* Creates a dense (fully connected) layer.
*
* This layer implements the operation:
* `output = activation(dot(input, kernel) + bias)`
*
* `activation` is the element-wise activation function
* passed as the `activation` argument.
*
* `kernel` is a weights matrix created by the layer.
*
* `bias` is a bias vector created by the layer (only applicable if `useBias`
* is `true`).
*
* **Input shape:**
*
* nD `tf.Tensor` with shape: `(batchSize, ..., inputDim)`.
*
* The most common situation would be
* a 2D input with shape `(batchSize, inputDim)`.
*
* **Output shape:**
*
* nD tensor with shape: `(batchSize, ..., units)`.
*
* For instance, for a 2D input with shape `(batchSize, inputDim)`,
* the output would have shape `(batchSize, units)`.
*
* Note: if the input to the layer has a rank greater than 2, then it is
* flattened prior to the initial dot product with the kernel.
*
* @doc {heading: 'Layers', subheading: 'Basic', namespace: 'layers'}
*/
export function dense(args: DenseLayerArgs) {
return new Dense(args);
}
/**
* Applies
* [dropout](http://www.cs.toronto.edu/~rsalakhu/papers/srivastava14a.pdf) to
* the input.
*
* Dropout consists in randomly setting a fraction `rate` of input units to 0 at
* each update during training time, which helps prevent overfitting.
*
* @doc {heading: 'Layers', subheading: 'Basic', namespace: 'layers'}
*/
export function dropout(args: DropoutLayerArgs) {
return new Dropout(args);
}
/**
* Spatial 1D version of Dropout.
*
* This Layer type performs the same function as the Dropout layer, but it drops
* entire 1D feature maps instead of individual elements. For example, if an
* input example consists of 3 timesteps and the feature map for each timestep
* has a size of 4, a `spatialDropout1d` layer may zero out the feature maps
* of the 1st timesteps and 2nd timesteps completely while sparing all feature
* elements of the 3rd timestep.
*
* If adjacent frames (timesteps) are strongly correlated (as is normally the
* case in early convolution layers), regular dropout will not regularize the
* activation and will otherwise just result in merely an effective learning
* rate decrease. In this case, `spatialDropout1d` will help promote
* independence among feature maps and should be used instead.
*
* **Arguments:**
* rate: A floating-point number >=0 and <=1. Fraction of the input elements
* to drop.
*
* **Input shape:**
* 3D tensor with shape `(samples, timesteps, channels)`.
*
* **Output shape:**
* Same as the input shape.
*
* References:
* - [Efficient Object Localization Using Convolutional
* Networks](https://arxiv.org/abs/1411.4280)
*
* @doc {heading: 'Layers', subheading: 'Basic', namespace: 'layers'}
*/
export function spatialDropout1d(args: SpatialDropout1DLayerConfig) {
return new SpatialDropout1D(args);
}
/**
* Flattens the input. Does not affect the batch size.
*
* A `Flatten` layer flattens each batch in its inputs to 1D (making the output
* 2D).
*
* For example:
*
* ```js
* const input = tf.input({shape: [4, 3]});
* const flattenLayer = tf.layers.flatten();
* // Inspect the inferred output shape of the flatten layer, which
* // equals `[null, 12]`. The 2nd dimension is 4 * 3, i.e., the result of the
* // flattening. (The 1st dimension is the undermined batch size.)
* console.log(JSON.stringify(flattenLayer.apply(input).shape));
* ```
*
* @doc {heading: 'Layers', subheading: 'Basic', namespace: 'layers'}
*/
export function flatten(args?: FlattenLayerArgs) {
return new Flatten(args);
}
/**
* Repeats the input n times in a new dimension.
*
* ```js
* const model = tf.sequential();
* model.add(tf.layers.repeatVector({n: 4, inputShape: [2]}));
* const x = tf.tensor2d([[10, 20]]);
* // Use the model to do inference on a data point the model hasn't seen
* model.predict(x).print();
* // output shape is now [batch, 2, 4]
* ```
*
* @doc {heading: 'Layers', subheading: 'Basic', namespace: 'layers'}
*/
export function repeatVector(args: RepeatVectorLayerArgs) {
return new RepeatVector(args);
}
/**
* Reshapes an input to a certain shape.
*
* ```js
* const input = tf.input({shape: [4, 3]});
* const reshapeLayer = tf.layers.reshape({targetShape: [2, 6]});
* // Inspect the inferred output shape of the Reshape layer, which
* // equals `[null, 2, 6]`. (The 1st dimension is the undermined batch size.)
* console.log(JSON.stringify(reshapeLayer.apply(input).shape));
* ```
*
* Input shape:
* Arbitrary, although all dimensions in the input shape must be fixed.
* Use the configuration `inputShape` when using this layer as the
* first layer in a model.
*
*
* Output shape:
* [batchSize, targetShape[0], targetShape[1], ...,
* targetShape[targetShape.length - 1]].
*
* @doc {heading: 'Layers', subheading: 'Basic', namespace: 'layers'}
*/
export function reshape(args: ReshapeLayerArgs) {
return new Reshape(args);
}
/**
* Permutes the dimensions of the input according to a given pattern.
*
* Useful for, e.g., connecting RNNs and convnets together.
*
* Example:
*
* ```js
* const model = tf.sequential();
* model.add(tf.layers.permute({
* dims: [2, 1],
* inputShape: [10, 64]
* }));
* console.log(model.outputShape);
* // Now model's output shape is [null, 64, 10], where null is the
* // unpermuted sample (batch) dimension.
* ```
*
* Input shape:
* Arbitrary. Use the configuration field `inputShape` when using this
* layer as the first layer in a model.
*
* Output shape:
* Same rank as the input shape, but with the dimensions re-ordered (i.e.,
* permuted) according to the `dims` configuration of this layer.
*
* @doc {heading: 'Layers', subheading: 'Basic', namespace: 'layers'}
*/
export function permute(args: PermuteLayerArgs) {
return new Permute(args);
}
/**
* Maps positive integers (indices) into dense vectors of fixed size.
* E.g. [[4], [20]] -> [[0.25, 0.1], [0.6, -0.2]]
*
* **Input shape:** 2D tensor with shape: `[batchSize, sequenceLength]`.
*
* **Output shape:** 3D tensor with shape: `[batchSize, sequenceLength,
* outputDim]`.
*
* @doc {heading: 'Layers', subheading: 'Basic', namespace: 'layers'}
*/
export function embedding(args: EmbeddingLayerArgs) {
return new Embedding(args);
}
// Merge Layers.
/**
* Layer that performs element-wise addition on an `Array` of inputs.
*
* It takes as input a list of tensors, all of the same shape, and returns a
* single tensor (also of the same shape). The inputs are specified as an
* `Array` when the `apply` method of the `Add` layer instance is called. For
* example:
*
* ```js
* const input1 = tf.input({shape: [2, 2]});
* const input2 = tf.input({shape: [2, 2]});
* const addLayer = tf.layers.add();
* const sum = addLayer.apply([input1, input2]);
* console.log(JSON.stringify(sum.shape));
* // You get [null, 2, 2], with the first dimension as the undetermined batch
* // dimension.
* ```
*
* @doc {heading: 'Layers', subheading: 'Merge', namespace: 'layers'}
*/
export function add(args?: LayerArgs) {
return new Add(args);
}
/**
* Layer that performs element-wise averaging on an `Array` of inputs.
*
* It takes as input a list of tensors, all of the same shape, and returns a
* single tensor (also of the same shape). For example:
*
* ```js
* const input1 = tf.input({shape: [2, 2]});
* const input2 = tf.input({shape: [2, 2]});
* const averageLayer = tf.layers.average();
* const average = averageLayer.apply([input1, input2]);
* console.log(JSON.stringify(average.shape));
* // You get [null, 2, 2], with the first dimension as the undetermined batch
* // dimension.
* ```
*
* @doc {heading: 'Layers', subheading: 'Merge', namespace: 'layers'}
*/
export function average(args?: LayerArgs) {
return new Average(args);
}
/**
* Layer that concatenates an `Array` of inputs.
*
* It takes a list of tensors, all of the same shape except for the
* concatenation axis, and returns a single tensor, the concatenation
* of all inputs. For example:
*
* ```js
* const input1 = tf.input({shape: [2, 2]});
* const input2 = tf.input({shape: [2, 3]});
* const concatLayer = tf.layers.concatenate();
* const output = concatLayer.apply([input1, input2]);
* console.log(JSON.stringify(output.shape));
* // You get [null, 2, 5], with the first dimension as the undetermined batch
* // dimension. The last dimension (5) is the result of concatenating the
* // last dimensions of the inputs (2 and 3).
* ```
*
* @doc {heading: 'Layers', subheading: 'Merge', namespace: 'layers'}
*/
export function concatenate(args?: ConcatenateLayerArgs) {
return new Concatenate(args);
}
/**
* Layer that computes the element-wise maximum of an `Array` of inputs.
*
* It takes as input a list of tensors, all of the same shape, and returns a
* single tensor (also of the same shape). For example:
*
* ```js
* const input1 = tf.input({shape: [2, 2]});
* const input2 = tf.input({shape: [2, 2]});
* const maxLayer = tf.layers.maximum();
* const max = maxLayer.apply([input1, input2]);
* console.log(JSON.stringify(max.shape));
* // You get [null, 2, 2], with the first dimension as the undetermined batch
* // dimension.
* ```
*
* @doc {heading: 'Layers', subheading: 'Merge', namespace: 'layers'}
*/
export function maximum(args?: LayerArgs) {
return new Maximum(args);
}
/**
* Layer that computes the element-wise minimum of an `Array` of inputs.
*
* It takes as input a list of tensors, all of the same shape, and returns a
* single tensor (also of the same shape). For example:
*
* ```js
* const input1 = tf.input({shape: [2, 2]});
* const input2 = tf.input({shape: [2, 2]});
* const minLayer = tf.layers.minimum();
* const min = minLayer.apply([input1, input2]);
* console.log(JSON.stringify(min.shape));
* // You get [null, 2, 2], with the first dimension as the undetermined batch
* // dimension.
* ```
*
* @doc {heading: 'Layers', subheading: 'Merge', namespace: 'layers'}
*/
export function minimum(args?: LayerArgs) {
return new Minimum(args);
}
/**
* Layer that multiplies (element-wise) an `Array` of inputs.
*
* It takes as input an Array of tensors, all of the same
* shape, and returns a single tensor (also of the same shape).
* For example:
*
* ```js
* const input1 = tf.input({shape: [2, 2]});
* const input2 = tf.input({shape: [2, 2]});
* const input3 = tf.input({shape: [2, 2]});
* const multiplyLayer = tf.layers.multiply();
* const product = multiplyLayer.apply([input1, input2, input3]);
* console.log(product.shape);
* // You get [null, 2, 2], with the first dimension as the undetermined batch
* // dimension.
*
* @doc {heading: 'Layers', subheading: 'Merge', namespace: 'layers'}
*/
export function multiply(args?: LayerArgs) {
return new Multiply(args);
}
/**
* Layer that computes a dot product between samples in two tensors.
*
* E.g., if applied to a list of two tensors `a` and `b` both of shape
* `[batchSize, n]`, the output will be a tensor of shape `[batchSize, 1]`,
* where each entry at index `[i, 0]` will be the dot product between
* `a[i, :]` and `b[i, :]`.
*
* Example:
*
* ```js
* const dotLayer = tf.layers.dot({axes: -1});
* const x1 = tf.tensor2d([[10, 20], [30, 40]]);
* const x2 = tf.tensor2d([[-1, -2], [-3, -4]]);
*
* // Invoke the layer's apply() method in eager (imperative) mode.
* const y = dotLayer.apply([x1, x2]);
* y.print();
* ```
*
* @doc {heading: 'Layers', subheading: 'Merge', namespace: 'layers'}
*/
export function dot(args: DotLayerArgs) {
return new Dot(args);
}
// Normalization Layers.
/**
* Batch normalization layer (Ioffe and Szegedy, 2014).
*
* Normalize the activations of the previous layer at each batch,
* i.e. applies a transformation that maintains the mean activation
* close to 0 and the activation standard deviation close to 1.
*
* Input shape:
* Arbitrary. Use the keyword argument `inputShape` (Array of integers, does
* not include the sample axis) when calling the constructor of this class,
* if this layer is used as a first layer in a model.
*
* Output shape:
* Same shape as input.
*
* References:
* - [Batch Normalization: Accelerating Deep Network Training by Reducing
* Internal Covariate Shift](https://arxiv.org/abs/1502.03167)
*
* @doc {heading: 'Layers', subheading: 'Normalization', namespace: 'layers'}
*/
export function batchNormalization(args?: BatchNormalizationLayerArgs) {
return new BatchNormalization(args);
}
/**
* Layer-normalization layer (Ba et al., 2016).
*
* Normalizes the activations of the previous layer for each given example in a
* batch independently, instead of across a batch like in `batchNormalization`.
* In other words, this layer applies a transformation that maintains the mean
* activation within each example close to 0 and activation variance close to 1.
*
* Input shape:
* Arbitrary. Use the argument `inputShape` when using this layer as the first
* layer in a model.
*
* Output shape:
* Same as input.
*
* References:
* - [Layer Normalization](https://arxiv.org/abs/1607.06450)
*
* @doc {heading: 'Layers', subheading: 'Normalization', namespace: 'layers'}
*/
export function layerNormalization(args?: LayerNormalizationLayerArgs) {
return new LayerNormalization(args);
}
// Padding Layers.
/**
* Zero-padding layer for 2D input (e.g., image).
*
* This layer can add rows and columns of zeros
* at the top, bottom, left and right side of an image tensor.
*
* Input shape:
* 4D tensor with shape:
* - If `dataFormat` is `"channelsLast"`:
* `[batch, rows, cols, channels]`
* - If `data_format` is `"channels_first"`:
* `[batch, channels, rows, cols]`.
*
* Output shape:
* 4D with shape:
* - If `dataFormat` is `"channelsLast"`:
* `[batch, paddedRows, paddedCols, channels]`
* - If `dataFormat` is `"channelsFirst"`:
* `[batch, channels, paddedRows, paddedCols]`.
*
* @doc {heading: 'Layers', subheading: 'Padding', namespace: 'layers'}
*/
export function zeroPadding2d(args?: ZeroPadding2DLayerArgs) {
return new ZeroPadding2D(args);
}
// Pooling Layers.
/**
* Average pooling operation for spatial data.
*
* Input shape: `[batchSize, inLength, channels]`
*
* Output shape: `[batchSize, pooledLength, channels]`
*
* `tf.avgPool1d` is an alias.
*
* @doc {heading: 'Layers', subheading: 'Pooling', namespace: 'layers'}
*/
export function averagePooling1d(args: Pooling1DLayerArgs) {
return new AveragePooling1D(args);
}
export function avgPool1d(args: Pooling1DLayerArgs) {
return averagePooling1d(args);
}
// For backwards compatibility.
// See https://github.com/tensorflow/tfjs/issues/152
export function avgPooling1d(args: Pooling1DLayerArgs) {
return averagePooling1d(args);
}
/**
* Average pooling operation for spatial data.
*
* Input shape:
* - If `dataFormat === CHANNEL_LAST`:
* 4D tensor with shape:
* `[batchSize, rows, cols, channels]`
* - If `dataFormat === CHANNEL_FIRST`:
* 4D tensor with shape:
* `[batchSize, channels, rows, cols]`
*
* Output shape
* - If `dataFormat === CHANNEL_LAST`:
* 4D tensor with shape:
* `[batchSize, pooledRows, pooledCols, channels]`
* - If `dataFormat === CHANNEL_FIRST`:
* 4D tensor with shape:
* `[batchSize, channels, pooledRows, pooledCols]`
*
* `tf.avgPool2d` is an alias.
*
* @doc {heading: 'Layers', subheading: 'Pooling', namespace: 'layers'}
*/
export function averagePooling2d(args: Pooling2DLayerArgs) {
return new AveragePooling2D(args);
}
export function avgPool2d(args: Pooling2DLayerArgs) {
return averagePooling2d(args);
}
// For backwards compatibility.
// See https://github.com/tensorflow/tfjs/issues/152
export function avgPooling2d(args: Pooling2DLayerArgs) {
return averagePooling2d(args);
}
/**
* Average pooling operation for 3D data.
*
* Input shape
* - If `dataFormat === channelsLast`:
* 5D tensor with shape:
* `[batchSize, depths, rows, cols, channels]`
* - If `dataFormat === channelsFirst`:
* 4D tensor with shape: