forked from ddbourgin/numpy-ml
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlayers.py
4218 lines (3514 loc) · 148 KB
/
layers.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
"""A collection of composable layer objects for building neural networks"""
from abc import ABC, abstractmethod
import numpy as np
from ..wrappers import init_wrappers, Dropout
from ..initializers import (
WeightInitializer,
OptimizerInitializer,
ActivationInitializer,
)
from ..utils import (
pad1D,
pad2D,
conv1D,
conv2D,
im2col,
col2im,
dilate,
deconv2D_naive,
calc_pad_dims_2D,
)
class LayerBase(ABC):
def __init__(self, optimizer=None):
"""An abstract base class inherited by all neural network layers"""
self.X = []
self.act_fn = None
self.trainable = True
self.optimizer = OptimizerInitializer(optimizer)()
self.gradients = {}
self.parameters = {}
self.derived_variables = {}
super().__init__()
@abstractmethod
def _init_params(self, **kwargs):
raise NotImplementedError
@abstractmethod
def forward(self, z, **kwargs):
"""Perform a forward pass through the layer"""
raise NotImplementedError
@abstractmethod
def backward(self, out, **kwargs):
"""Perform a backward pass through the layer"""
raise NotImplementedError
def freeze(self):
"""
Freeze the layer parameters at their current values so they can no
longer be updated.
"""
self.trainable = False
def unfreeze(self):
"""Unfreeze the layer parameters so they can be updated."""
self.trainable = True
def flush_gradients(self):
"""Erase all the layer's derived variables and gradients."""
assert self.trainable, "Layer is frozen"
self.X = []
for k, v in self.derived_variables.items():
self.derived_variables[k] = []
for k, v in self.gradients.items():
self.gradients[k] = np.zeros_like(v)
def update(self, cur_loss=None):
"""
Update the layer parameters using the accrued gradients and layer
optimizer. Flush all gradients once the update is complete.
"""
assert self.trainable, "Layer is frozen"
self.optimizer.step()
for k, v in self.gradients.items():
if k in self.parameters:
self.parameters[k] = self.optimizer(self.parameters[k], v, k, cur_loss)
self.flush_gradients()
def set_params(self, summary_dict):
"""
Set the layer parameters from a dictionary of values.
Parameters
----------
summary_dict : dict
A dictionary of layer parameters and hyperparameters. If a required
parameter or hyperparameter is not included within `summary_dict`,
this method will use the value in the current layer's
:meth:`summary` method.
Returns
-------
layer : :doc:`Layer <numpy_ml.neural_nets.layers>` object
The newly-initialized layer.
"""
layer, sd = self, summary_dict
# collapse `parameters` and `hyperparameters` nested dicts into a single
# merged dictionary
flatten_keys = ["parameters", "hyperparameters"]
for k in flatten_keys:
if k in sd:
entry = sd[k]
sd.update(entry)
del sd[k]
for k, v in sd.items():
if k in self.parameters:
layer.parameters[k] = v
if k in self.hyperparameters:
if k == "act_fn":
layer.act_fn = ActivationInitializer(v)()
elif k == "optimizer":
layer.optimizer = OptimizerInitializer(sd[k])()
elif k == "wrappers":
layer = init_wrappers(layer, sd[k])
elif k not in ["wrappers", "optimizer"]:
setattr(layer, k, v)
return layer
def summary(self):
"""Return a dict of the layer parameters, hyperparameters, and ID."""
return {
"layer": self.hyperparameters["layer"],
"parameters": self.parameters,
"hyperparameters": self.hyperparameters,
}
class DotProductAttention(LayerBase):
def __init__(self, scale=True, dropout_p=0, init="glorot_uniform", optimizer=None):
r"""
A single "attention head" layer using a dot-product for the scoring function.
Notes
-----
The equations for a dot product attention layer are:
.. math::
\mathbf{Z} &= \mathbf{K Q}^\\top \ \ \ \ &&\text{if scale = False} \\
&= \mathbf{K Q}^\top / \sqrt{d_k} \ \ \ \ &&\text{if scale = True} \\
\mathbf{Y} &= \text{dropout}(\text{softmax}(\mathbf{Z})) \mathbf{V}
Parameters
----------
scale : bool
Whether to scale the the key-query dot product by the square root
of the key/query vector dimensionality before applying the Softmax.
This is useful, since the scale of dot product will otherwise
increase as query / key dimensions grow. Default is True.
dropout_p : float in [0, 1)
The dropout propbability during training, applied to the output of
the softmax. If 0, no dropout is applied. Default is 0.
init : {'glorot_normal', 'glorot_uniform', 'he_normal', 'he_uniform'}
The weight initialization strategy. Default is `'glorot_uniform'`.
Unused.
optimizer : str, :doc:`Optimizer <numpy_ml.neural_nets.optimizers>` object, or None
The optimization strategy to use when performing gradient updates
within the :meth:`update` method. If None, use the :class:`SGD
<numpy_ml.neural_nets.optimizers.SGD>` optimizer with
default parameters. Default is None. Unused.
""" # noqa: E501
super().__init__(optimizer)
self.init = init
self.scale = scale
self.dropout_p = dropout_p
self._init_params()
def _init_params(self):
self.softmax = Dropout(Softmax(), self.dropout_p)
smdv = self.softmax.derived_variables
self.derived_variables = {
"attention_weights": [],
"dropout_mask": smdv["wrappers"][0]["dropout_mask"],
}
@property
def hyperparameters(self):
"""Return a dictionary containing the layer hyperparameters."""
return {
"layer": "DotProductAttention",
"init": self.init,
"scale": self.scale,
"dropout_p": self.dropout_p,
"optimizer": {
"cache": self.optimizer.cache,
"hyperparameters": self.optimizer.hyperparameters,
},
}
def freeze(self):
"""
Freeze the layer parameters at their current values so they can no
longer be updated.
"""
self.trainable = False
self.softmax.freeze()
def unfreeze(self):
"""Unfreeze the layer parameters so they can be updated."""
self.trainable = True
self.softmax.unfreeze()
def forward(self, Q, K, V, retain_derived=True):
r"""
Compute the attention-weighted output of a collection of keys, values,
and queries.
Notes
-----
In the most abstract (ie., hand-wave-y) sense:
- Query vectors ask questions
- Key vectors advertise their relevancy to questions
- Value vectors give possible answers to questions
- The dot product between Key and Query vectors provides scores for
each of the the `n_ex` different Value vectors
For a single query and `n` key-value pairs, dot-product attention (with
scaling) is::
w0 = dropout(softmax( (query @ key[0]) / sqrt(d_k) ))
w1 = dropout(softmax( (query @ key[1]) / sqrt(d_k) ))
...
wn = dropout(softmax( (query @ key[n]) / sqrt(d_k) ))
y = np.array([w0, ..., wn]) @ values
(1 × n_ex) (n_ex × d_v)
In words, keys and queries are combined via dot-product to produce a
score, which is then passed through a softmax to produce a weight on
each value vector in Values. We elementwise multiply each value vector
by its weight, and then take the elementwise sum of each weighted value
vector to get the :math:`1 \times d_v` output for the current example.
In vectorized form,
.. math::
\mathbf{Y} = \text{dropout}(
\text{softmax}(\mathbf{KQ}^\top / \sqrt{d_k})
) \mathbf{V}
Parameters
----------
Q : :py:class:`ndarray <numpy.ndarray>` of shape `(n_ex, *, d_k)`
A set of `n_ex` query vectors packed into a single matrix.
Optional middle dimensions can be used to specify, e.g., the number
of parallel attention heads.
K : :py:class:`ndarray <numpy.ndarray>` of shape `(n_ex, *, d_k)`
A set of `n_ex` key vectors packed into a single matrix. Optional
middle dimensions can be used to specify, e.g., the number of
parallel attention heads.
V : :py:class:`ndarray <numpy.ndarray>` of shape `(n_ex, *, d_v)`
A set of `n_ex` value vectors packed into a single matrix. Optional
middle dimensions can be used to specify, e.g., the number of
parallel attention heads.
retain_derived : bool
Whether to retain the variables calculated during the forward pass
for use later during backprop. If False, this suggests the layer
will not be expected to backprop through wrt. this input. Default
is True.
Returns
-------
Y : :py:class:`ndarray <numpy.ndarray>` of shape `(n_ex, *, d_v)`
The attention-weighted output values
"""
Y, weights = self._fwd(Q, K, V)
if retain_derived:
self.X.append((Q, K, V))
self.derived_variables["attention_weights"].append(weights)
return Y
def _fwd(self, Q, K, V):
"""Actual computation of forward pass"""
scale = 1 / np.sqrt(Q.shape[-1]) if self.scale else 1
scores = Q @ K.swapaxes(-2, -1) * scale # attention scores
weights = self.softmax.forward(scores) # attention weights
Y = weights @ V
return Y, weights
def backward(self, dLdy, retain_grads=True):
r"""
Backprop from layer outputs to inputs.
Parameters
----------
dLdY : :py:class:`ndarray <numpy.ndarray>` of shape `(n_ex, *, d_v)`
The gradient of the loss wrt. the layer output `Y`
retain_grads : bool
Whether to include the intermediate parameter gradients computed
during the backward pass in the final parameter update. Default is
True.
Returns
-------
dQ : :py:class:`ndarray <numpy.ndarray>` of shape `(n_ex, *, d_k)` or list of arrays
The gradient of the loss wrt. the layer query matrix/matrices `Q`.
dK : :py:class:`ndarray <numpy.ndarray>` of shape `(n_ex, *, d_k)` or list of arrays
The gradient of the loss wrt. the layer key matrix/matrices `K`.
dV : :py:class:`ndarray <numpy.ndarray>` of shape `(n_ex, *, d_v)` or list of arrays
The gradient of the loss wrt. the layer value matrix/matrices `V`.
""" # noqa: E501
assert self.trainable, "Layer is frozen"
if not isinstance(dLdy, list):
dLdy = [dLdy]
dQ, dK, dV = [], [], []
weights = self.derived_variables["attention_weights"]
for dy, (q, k, v), w in zip(dLdy, self.X, weights):
dq, dk, dv = self._bwd(dy, q, k, v, w)
dQ.append(dq)
dK.append(dk)
dV.append(dv)
if len(self.X) == 1:
dQ, dK, dV = dQ[0], dK[0], dV[0]
return dQ, dK, dV
def _bwd(self, dy, q, k, v, weights):
"""Actual computation of the gradient of the loss wrt. q, k, and v"""
d_k = k.shape[-1]
scale = 1 / np.sqrt(d_k) if self.scale else 1
dV = weights.swapaxes(-2, -1) @ dy
dWeights = dy @ v.swapaxes(-2, -1)
dScores = self.softmax.backward(dWeights)
dQ = dScores @ k * scale
dK = dScores.swapaxes(-2, -1) @ q * scale
return dQ, dK, dV
class RBM(LayerBase):
def __init__(self, n_out, K=1, init="glorot_uniform", optimizer=None):
"""
A Restricted Boltzmann machine with Bernoulli visible and hidden units.
Parameters
----------
n_out : int
The number of output dimensions/units.
K : int
The number of contrastive divergence steps to run before computing
a single gradient update. Default is 1.
init : {'glorot_normal', 'glorot_uniform', 'he_normal', 'he_uniform'}
The weight initialization strategy. Default is `'glorot_uniform'`.
optimizer : str, :doc:`Optimizer <numpy_ml.neural_nets.optimizers>` object, or None
The optimization strategy to use when performing gradient updates
within the :meth:`update` method. If None, use the :class:`SGD
<numpy_ml.neural_nets.optimizers.SGD>` optimizer with
default parameters. Default is None.
""" # noqa: E501
super().__init__(optimizer)
self.K = K # CD-K
self.init = init
self.n_in = None
self.n_out = n_out
self.is_initialized = False
self.act_fn_V = ActivationInitializer("Sigmoid")()
self.act_fn_H = ActivationInitializer("Sigmoid")()
self.parameters = {"W": None, "b_in": None, "b_out": None}
self._init_params()
def _init_params(self):
init_weights = WeightInitializer(str(self.act_fn_V), mode=self.init)
b_in = np.zeros((1, self.n_in))
b_out = np.zeros((1, self.n_out))
W = init_weights((self.n_in, self.n_out))
self.parameters = {"W": W, "b_in": b_in, "b_out": b_out}
self.gradients = {
"W": np.zeros_like(W),
"b_in": np.zeros_like(b_in),
"b_out": np.zeros_like(b_out),
}
self.derived_variables = {
"V": None,
"p_H": None,
"p_V_prime": None,
"p_H_prime": None,
"positive_grad": None,
"negative_grad": None,
}
self.is_initialized = True
@property
def hyperparameters(self):
"""Return a dictionary containing the layer hyperparameters."""
return {
"layer": "RBM",
"K": self.K,
"n_in": self.n_in,
"n_out": self.n_out,
"init": self.init,
"optimizer": {
"cache": self.optimizer.cache,
"hyperparameters": self.optimizer.hyperparameterse,
},
}
def CD_update(self, X):
"""
Perform a single contrastive divergence-`k` training update using the
visible inputs `X` as a starting point for the Gibbs sampler.
Parameters
----------
X : :py:class:`ndarray <numpy.ndarray>` of shape `(n_ex, n_in)`
Layer input, representing the `n_in`-dimensional features for a
minibatch of `n_ex` examples. Each feature in X should ideally be
binary-valued, although it is possible to also train on real-valued
features ranging between (0, 1) (e.g., grayscale images).
"""
self.forward(X)
self.backward()
def forward(self, V, K=None, retain_derived=True):
"""
Perform the CD-`k` "forward pass" of visible inputs into hidden units
and back.
Notes
-----
This implementation follows [1]_'s recommendations for the RBM forward
pass:
- Use real-valued probabilities for both the data and the visible
unit reconstructions.
- Only the final update of the hidden units should use the actual
probabilities -- all others should be sampled binary states.
- When collecting the pairwise statistics for learning weights or
the individual statistics for learning biases, use the
probabilities, not the binary states.
References
----------
.. [1] Hinton, G. (2010). "A practical guide to training restricted
Boltzmann machines". *UTML TR 2010-003*
Parameters
----------
V : :py:class:`ndarray <numpy.ndarray>` of shape `(n_ex, n_in)`
Visible input, representing the `n_in`-dimensional features for a
minibatch of `n_ex` examples. Each feature in V should ideally be
binary-valued, although it is possible to also train on real-valued
features ranging between (0, 1) (e.g., grayscale images).
K : int
The number of steps of contrastive divergence steps to run before
computing the gradient update. If None, use ``self.K``. Default is
None.
retain_derived : bool
Whether to retain the variables calculated during the forward pass
for use later during backprop. If False, this suggests the layer
will not be expected to backprop through wrt. this input. Default
is True.
"""
if not self.is_initialized:
self.n_in = V.shape[1]
self._init_params()
# override self.K if necessary
K = self.K if K is None else K
W = self.parameters["W"]
b_in = self.parameters["b_in"]
b_out = self.parameters["b_out"]
# compute hidden unit probabilities
Z_H = V @ W + b_out
p_H = self.act_fn_H.fn(Z_H)
# sample hidden states (stochastic binary values)
H = np.random.rand(*p_H.shape) <= p_H
H = H.astype(float)
# always use probabilities when computing gradients
positive_grad = V.T @ p_H
# perform CD-k
# TODO: use persistent CD-k
# https://www.cs.toronto.edu/~tijmen/pcd/pcd.pdf
H_prime = H.copy()
for k in range(K):
# resample v' given h (H_prime is binary for all but final step)
Z_V_prime = H_prime @ W.T + b_in
p_V_prime = self.act_fn_V.fn(Z_V_prime)
# don't resample visual units - always use raw probabilities!
V_prime = p_V_prime
# compute p(h' | v')
Z_H_prime = V_prime @ W + b_out
p_H_prime = self.act_fn_H.fn(Z_H_prime)
# if this is the final iteration of CD, keep hidden state
# probabilities (don't sample)
H_prime = p_H_prime
if k != self.K - 1:
H_prime = np.random.rand(*p_H_prime.shape) <= p_H_prime
H_prime = H_prime.astype(float)
negative_grad = p_V_prime.T @ p_H_prime
if retain_derived:
self.derived_variables["V"] = V
self.derived_variables["p_H"] = p_H
self.derived_variables["p_V_prime"] = p_V_prime
self.derived_variables["p_H_prime"] = p_H_prime
self.derived_variables["positive_grad"] = positive_grad
self.derived_variables["negative_grad"] = negative_grad
def backward(self, retain_grads=True, *args):
"""
Perform a gradient update on the layer parameters via the contrastive
divergence equations.
Parameters
----------
retain_grads : bool
Whether to include the intermediate parameter gradients computed
during the backward pass in the final parameter update. Default is
True.
"""
V = self.derived_variables["V"]
p_H = self.derived_variables["p_H"]
p_V_prime = self.derived_variables["p_V_prime"]
p_H_prime = self.derived_variables["p_H_prime"]
positive_grad = self.derived_variables["positive_grad"]
negative_grad = self.derived_variables["negative_grad"]
if retain_grads:
self.gradients["b_in"] = V - p_V_prime
self.gradients["b_out"] = p_H - p_H_prime
self.gradients["W"] = positive_grad - negative_grad
def reconstruct(self, X, n_steps=10, return_prob=False):
"""
Reconstruct an input `X` by running the trained Gibbs sampler for
`n_steps`-worth of CD-`k`.
Parameters
----------
X : :py:class:`ndarray <numpy.ndarray>` of shape `(n_ex, n_in)`
Layer input, representing the `n_in`-dimensional features for a
minibatch of `n_ex` examples. Each feature in `X` should ideally be
binary-valued, although it is possible to also train on real-valued
features ranging between (0, 1) (e.g., grayscale images). If `X` has
missing values, it may be sufficient to mark them with random
entries and allow the reconstruction to impute them.
n_steps : int
The number of Gibbs sampling steps to perform when generating the
reconstruction. Default is 10.
return_prob : bool
Whether to return the real-valued feature probabilities for the
reconstruction or the binary samples. Default is False.
Returns
-------
V : :py:class:`ndarray <numpy.ndarray>` of shape `(n_ex, in_ch)`
The reconstruction (or feature probabilities if `return_prob` is
true) of the visual input `X` after running the Gibbs sampler for
`n_steps`.
"""
self.forward(X, K=n_steps)
p_V_prime = self.derived_variables["p_V_prime"]
# ignore the gradients produced during this reconstruction
self.flush_gradients()
# sample V_prime reconstruction if return_prob is False
V = p_V_prime
if not return_prob:
V = (np.random.rand(*p_V_prime.shape) <= p_V_prime).astype(float)
return V
#######################################################################
# Layer Ops #
#######################################################################
class Add(LayerBase):
def __init__(self, act_fn=None, optimizer=None):
"""
An "addition" layer that returns the sum of its inputs, passed through
an optional nonlinearity.
Parameters
----------
act_fn : str, :doc:`Activation <numpy_ml.neural_nets.activations>` object, or None
The element-wise output nonlinearity used in computing the final
output. If None, use the identity function :math:`f(x) = x`.
Default is None.
optimizer : str, :doc:`Optimizer <numpy_ml.neural_nets.optimizers>` object, or None
The optimization strategy to use when performing gradient updates
within the :meth:`update` method. If None, use the :class:`SGD
<numpy_ml.neural_nets.optimizers.SGD>` optimizer with
default parameters. Default is None.
""" # noqa: E501
super().__init__(optimizer)
self.act_fn = ActivationInitializer(act_fn)()
self._init_params()
def _init_params(self):
self.derived_variables = {"sum": []}
@property
def hyperparameters(self):
"""Return a dictionary containing the layer hyperparameters."""
return {
"layer": "Sum",
"act_fn": str(self.act_fn),
"optimizer": {
"cache": self.optimizer.cache,
"hyperparameters": self.optimizer.hyperparameters,
},
}
def forward(self, X, retain_derived=True):
r"""
Compute the layer output on a single minibatch.
Parameters
----------
X : list of length `n_inputs`
A list of tensors, all of the same shape.
retain_derived : bool
Whether to retain the variables calculated during the forward pass
for use later during backprop. If False, this suggests the layer
will not be expected to backprop through wrt. this input. Default
is True.
Returns
-------
Y : :py:class:`ndarray <numpy.ndarray>` of shape `(n_ex, *)`
The sum over the `n_ex` examples.
"""
out = X[0].copy()
for i in range(1, len(X)):
out += X[i]
if retain_derived:
self.X.append(X)
self.derived_variables["sum"].append(out)
return self.act_fn(out)
def backward(self, dLdY, retain_grads=True):
r"""
Backprop from layer outputs to inputs.
Parameters
----------
dLdY : :py:class:`ndarray <numpy.ndarray>` of shape `(n_ex, *)`
The gradient of the loss wrt. the layer output `Y`.
retain_grads : bool
Whether to include the intermediate parameter gradients computed
during the backward pass in the final parameter update. Default is
True.
Returns
-------
dX : list of length `n_inputs`
The gradient of the loss wrt. each input in `X`.
"""
if not isinstance(dLdY, list):
dLdY = [dLdY]
X = self.X
_sum = self.derived_variables["sum"]
grads = [self._bwd(dy, x, ss) for dy, x, ss in zip(dLdY, X, _sum)]
return grads[0] if len(X) == 1 else grads
def _bwd(self, dLdY, X, _sum):
"""Actual computation of gradient of the loss wrt. each input"""
grads = [dLdY * self.act_fn.grad(_sum) for _ in X]
return grads
class Multiply(LayerBase):
def __init__(self, act_fn=None, optimizer=None):
"""
A multiplication layer that returns the *elementwise* product of its
inputs, passed through an optional nonlinearity.
Parameters
----------
act_fn : str, :doc:`Activation <numpy_ml.neural_nets.activations>` object, or None
The element-wise output nonlinearity used in computing the final
output. If None, use the identity function :math:`f(x) = x`.
Default is None.
optimizer : str, :doc:`Optimizer <numpy_ml.neural_nets.optimizers>` object, or None
The optimization strategy to use when performing gradient updates
within the :meth:`update` method. If None, use the :class:`SGD
<numpy_ml.neural_nets.optimizers.SGD>` optimizer with
default parameters. Default is None.
""" # noqa: E501
super().__init__(optimizer)
self.act_fn = ActivationInitializer(act_fn)()
self._init_params()
def _init_params(self):
self.derived_variables = {"product": []}
@property
def hyperparameters(self):
"""Return a dictionary containing the layer hyperparameters."""
return {
"layer": "Multiply",
"act_fn": str(self.act_fn),
"optimizer": {
"cache": self.optimizer.cache,
"hyperparameters": self.optimizer.hyperparameters,
},
}
def forward(self, X, retain_derived=True):
r"""
Compute the layer output on a single minibatch.
Parameters
----------
X : list of length `n_inputs`
A list of tensors, all of the same shape.
retain_derived : bool
Whether to retain the variables calculated during the forward pass
for use later during backprop. If False, this suggests the layer
will not be expected to backprop through wrt. this input. Default
is True.
Returns
-------
Y : :py:class:`ndarray <numpy.ndarray>` of shape `(n_ex, *)`
The product over the `n_ex` examples.
""" # noqa: E501
out = X[0].copy()
for i in range(1, len(X)):
out *= X[i]
if retain_derived:
self.X.append(X)
self.derived_variables["product"].append(out)
return self.act_fn(out)
def backward(self, dLdY, retain_grads=True):
r"""
Backprop from layer outputs to inputs.
Parameters
----------
dLdY : :py:class:`ndarray <numpy.ndarray>` of shape `(n_ex, *)`
The gradient of the loss wrt. the layer output `Y`.
retain_grads : bool
Whether to include the intermediate parameter gradients computed
during the backward pass in the final parameter update. Default is
True.
Returns
-------
dX : list of length `n_inputs`
The gradient of the loss wrt. each input in `X`.
"""
if not isinstance(dLdY, list):
dLdY = [dLdY]
X = self.X
_prod = self.derived_variables["product"]
grads = [self._bwd(dy, x, pr) for dy, x, pr in zip(dLdY, X, _prod)]
return grads[0] if len(X) == 1 else grads
def _bwd(self, dLdY, X, prod):
"""Actual computation of gradient of loss wrt. each input"""
grads = [dLdY * self.act_fn.grad(prod)] * len(X)
for i, x in enumerate(X):
grads = [g * x if j != i else g for j, g in enumerate(grads)]
return grads
class Flatten(LayerBase):
def __init__(self, keep_dim="first", optimizer=None):
"""
Flatten a multidimensional input into a 2D matrix.
Parameters
----------
keep_dim : {'first', 'last', -1}
The dimension of the original input to retain. Typically used for
retaining the minibatch dimension.. If -1, flatten all dimensions.
Default is 'first'.
optimizer : str, :doc:`Optimizer <numpy_ml.neural_nets.optimizers>` object, or None
The optimization strategy to use when performing gradient updates
within the :meth:`update` method. If None, use the :class:`SGD
<numpy_ml.neural_nets.optimizers.SGD>` optimizer with
default parameters. Default is None.
""" # noqa: E501
super().__init__(optimizer)
self.keep_dim = keep_dim
self._init_params()
def _init_params(self):
self.X = []
self.gradients = {}
self.parameters = {}
self.derived_variables = {"in_dims": []}
@property
def hyperparameters(self):
"""Return a dictionary containing the layer hyperparameters."""
return {
"layer": "Flatten",
"keep_dim": self.keep_dim,
"optimizer": {
"cache": self.optimizer.cache,
"hyperparameters": self.optimizer.hyperparameters,
},
}
def forward(self, X, retain_derived=True):
r"""
Compute the layer output on a single minibatch.
Parameters
----------
X : :py:class:`ndarray <numpy.ndarray>`
Input volume to flatten.
retain_derived : bool
Whether to retain the variables calculated during the forward pass
for use later during backprop. If False, this suggests the layer
will not be expected to backprop through wrt. this input. Default
is True.
Returns
-------
Y : :py:class:`ndarray <numpy.ndarray>` of shape `(*out_dims)`
Flattened output. If `keep_dim` is `'first'`, `X` is reshaped to
``(X.shape[0], -1)``, otherwise ``(-1, X.shape[0])``.
"""
if retain_derived:
self.derived_variables["in_dims"].append(X.shape)
if self.keep_dim == -1:
return X.flatten().reshape(1, -1)
rs = (X.shape[0], -1) if self.keep_dim == "first" else (-1, X.shape[-1])
return X.reshape(*rs)
def backward(self, dLdy, retain_grads=True):
r"""
Backprop from layer outputs to inputs.
Parameters
----------
dLdY : :py:class:`ndarray <numpy.ndarray>` of shape `(*out_dims)`
The gradient of the loss wrt. the layer output `Y`.
retain_grads : bool
Whether to include the intermediate parameter gradients computed
during the backward pass in the final parameter update. Default is
True.
Returns
-------
dX : :py:class:`ndarray <numpy.ndarray>` of shape `(*in_dims)` or list of arrays
The gradient of the loss wrt. the layer input(s) `X`.
""" # noqa: E501
if not isinstance(dLdy, list):
dLdy = [dLdy]
in_dims = self.derived_variables["in_dims"]
out = [dy.reshape(*dims) for dy, dims in zip(dLdy, in_dims)]
return out[0] if len(dLdy) == 1 else out
#######################################################################
# Normalization Layers #
#######################################################################
class BatchNorm2D(LayerBase):
def __init__(self, momentum=0.9, epsilon=1e-5, optimizer=None):
"""
A batch normalization layer for two-dimensional inputs with an
additional channel dimension.
Notes
-----
BatchNorm is an attempt address the problem of internal covariate
shift (ICS) during training by normalizing layer inputs.
ICS refers to the change in the distribution of layer inputs during
training as a result of the changing parameters of the previous
layer(s). ICS can make it difficult to train models with saturating
nonlinearities, and in general can slow training by requiring a lower
learning rate.
Equations [train]::
Y = scaler * norm(X) + intercept
norm(X) = (X - mean(X)) / sqrt(var(X) + epsilon)
Equations [test]::
Y = scaler * running_norm(X) + intercept
running_norm(X) = (X - running_mean) / sqrt(running_var + epsilon)
In contrast to :class:`LayerNorm2D`, the BatchNorm layer calculates
the mean and var across the *batch* rather than the output features.
This has two disadvantages:
1. It is highly affected by batch size: smaller mini-batch sizes
increase the variance of the estimates for the global mean and
variance.
2. It is difficult to apply in RNNs -- one must fit a separate
BatchNorm layer for *each* time-step.
Parameters
----------
momentum : float
The momentum term for the running mean/running std calculations.
The closer this is to 1, the less weight will be given to the
mean/std of the current batch (i.e., higher smoothing). Default is
0.9.
epsilon : float
A small smoothing constant to use during computation of ``norm(X)``
to avoid divide-by-zero errors. Default is 1e-5.
optimizer : str, :doc:`Optimizer <numpy_ml.neural_nets.optimizers>` object, or None
The optimization strategy to use when performing gradient updates
within the :meth:`update` method. If None, use the :class:`SGD
<numpy_ml.neural_nets.optimizers.SGD>` optimizer with
default parameters. Default is None.
""" # noqa: E501
super().__init__(optimizer)
self.in_ch = None
self.out_ch = None
self.epsilon = epsilon
self.momentum = momentum
self.parameters = {
"scaler": None,
"intercept": None,
"running_var": None,
"running_mean": None,
}
self.is_initialized = False
def _init_params(self):
scaler = np.random.rand(self.in_ch)
intercept = np.zeros(self.in_ch)
# init running mean and std at 0 and 1, respectively
running_mean = np.zeros(self.in_ch)
running_var = np.ones(self.in_ch)
self.parameters = {
"scaler": scaler,
"intercept": intercept,
"running_var": running_var,
"running_mean": running_mean,
}
self.gradients = {
"scaler": np.zeros_like(scaler),
"intercept": np.zeros_like(intercept),
}
self.is_initialized = True
@property
def hyperparameters(self):
"""Return a dictionary containing the layer hyperparameters."""
return {
"layer": "BatchNorm2D",
"act_fn": None,
"in_ch": self.in_ch,
"out_ch": self.out_ch,
"epsilon": self.epsilon,
"momentum": self.momentum,
"optimizer": {
"cache": self.optimizer.cache,
"hyperparameters": self.optimizer.hyperparameters,
},
}
def reset_running_stats(self):
"""Reset the running mean and variance estimates to 0 and 1."""