diff --git a/doc/pub/week44/html/._week44-bs000.html b/doc/pub/week44/html/._week44-bs000.html index e259aad1b..a1601c23e 100644 --- a/doc/pub/week44/html/._week44-bs000.html +++ b/doc/pub/week44/html/._week44-bs000.html @@ -139,7 +139,54 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Finally, evaluate the model', 2, None, - 'finally-evaluate-the-model')]} + 'finally-evaluate-the-model'), + ('Building our own CNN code', + 2, + None, + 'building-our-own-cnn-code'), + ('List of contents:', 3, None, 'list-of-contents'), + ('Schedulers', 3, None, 'schedulers'), + ('Usage of schedulers', 3, None, 'usage-of-schedulers'), + ('Cost functions', 3, None, 'cost-functions'), + ('Usage of cost functions', 3, None, 'usage-of-cost-functions'), + ('Activation functions', 3, None, 'activation-functions'), + ('Usage of activation functions', + 3, + None, + 'usage-of-activation-functions'), + ('Convolution', 3, None, 'convolution'), + ('Layers', 3, None, 'layers'), + ('Convolution2DLayer: convolution in a hidden layer', + 3, + None, + 'convolution2dlayer-convolution-in-a-hidden-layer'), + ('Backpropagation in the convolutional layer', + 3, + None, + 'backpropagation-in-the-convolutional-layer'), + ('Demonstration', 3, None, 'demonstration'), + ('Pooling Layer', 3, None, 'pooling-layer'), + ('Flattening Layer', 3, None, 'flattening-layer'), + ('Fully Connected Layers', 3, None, 'fully-connected-layers'), + ('Optimized Convolution2DLayer', + 3, + None, + 'optimized-convolution2dlayer'), + ('The Convolutional Neural Network (CNN)', + 3, + None, + 'the-convolutional-neural-network-cnn'), + ('Usage of CNN code', 3, None, 'usage-of-cnn-code'), + ('Additional Remarks', 3, None, 'additional-remarks'), + ('Remarks on the speed', 3, None, 'remarks-on-the-speed'), + ('Convolution using separable kernels', + 3, + None, + 'convolution-using-separable-kernels'), + ('Convolution in the Fourier domain', + 3, + None, + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -174,50 +221,73 @@ MathJax.Hub.Config({ @@ -272,7 +342,7 @@ MathJax.Hub.Config({
  • 9
  • 10
  • ...
  • -
  • 45
  • +
  • 46
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs001.html b/doc/pub/week44/html/._week44-bs001.html index 963c7249b..d5212b7d6 100644 --- a/doc/pub/week44/html/._week44-bs001.html +++ b/doc/pub/week44/html/._week44-bs001.html @@ -139,7 +139,54 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Finally, evaluate the model', 2, None, - 'finally-evaluate-the-model')]} + 'finally-evaluate-the-model'), + ('Building our own CNN code', + 2, + None, + 'building-our-own-cnn-code'), + ('List of contents:', 3, None, 'list-of-contents'), + ('Schedulers', 3, None, 'schedulers'), + ('Usage of schedulers', 3, None, 'usage-of-schedulers'), + ('Cost functions', 3, None, 'cost-functions'), + ('Usage of cost functions', 3, None, 'usage-of-cost-functions'), + ('Activation functions', 3, None, 'activation-functions'), + ('Usage of activation functions', + 3, + None, + 'usage-of-activation-functions'), + ('Convolution', 3, None, 'convolution'), + ('Layers', 3, None, 'layers'), + ('Convolution2DLayer: convolution in a hidden layer', + 3, + None, + 'convolution2dlayer-convolution-in-a-hidden-layer'), + ('Backpropagation in the convolutional layer', + 3, + None, + 'backpropagation-in-the-convolutional-layer'), + ('Demonstration', 3, None, 'demonstration'), + ('Pooling Layer', 3, None, 'pooling-layer'), + ('Flattening Layer', 3, None, 'flattening-layer'), + ('Fully Connected Layers', 3, None, 'fully-connected-layers'), + ('Optimized Convolution2DLayer', + 3, + None, + 'optimized-convolution2dlayer'), + ('The Convolutional Neural Network (CNN)', + 3, + None, + 'the-convolutional-neural-network-cnn'), + ('Usage of CNN code', 3, None, 'usage-of-cnn-code'), + ('Additional Remarks', 3, None, 'additional-remarks'), + ('Remarks on the speed', 3, None, 'remarks-on-the-speed'), + ('Convolution using separable kernels', + 3, + None, + 'convolution-using-separable-kernels'), + ('Convolution in the Fourier domain', + 3, + None, + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -174,50 +221,73 @@ MathJax.Hub.Config({ @@ -293,7 +363,7 @@ MathJax.Hub.Config({
  • 10
  • 11
  • ...
  • -
  • 45
  • +
  • 46
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs002.html b/doc/pub/week44/html/._week44-bs002.html index 9fe0ca614..8902bae53 100644 --- a/doc/pub/week44/html/._week44-bs002.html +++ b/doc/pub/week44/html/._week44-bs002.html @@ -139,7 +139,54 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Finally, evaluate the model', 2, None, - 'finally-evaluate-the-model')]} + 'finally-evaluate-the-model'), + ('Building our own CNN code', + 2, + None, + 'building-our-own-cnn-code'), + ('List of contents:', 3, None, 'list-of-contents'), + ('Schedulers', 3, None, 'schedulers'), + ('Usage of schedulers', 3, None, 'usage-of-schedulers'), + ('Cost functions', 3, None, 'cost-functions'), + ('Usage of cost functions', 3, None, 'usage-of-cost-functions'), + ('Activation functions', 3, None, 'activation-functions'), + ('Usage of activation functions', + 3, + None, + 'usage-of-activation-functions'), + ('Convolution', 3, None, 'convolution'), + ('Layers', 3, None, 'layers'), + ('Convolution2DLayer: convolution in a hidden layer', + 3, + None, + 'convolution2dlayer-convolution-in-a-hidden-layer'), + ('Backpropagation in the convolutional layer', + 3, + None, + 'backpropagation-in-the-convolutional-layer'), + ('Demonstration', 3, None, 'demonstration'), + ('Pooling Layer', 3, None, 'pooling-layer'), + ('Flattening Layer', 3, None, 'flattening-layer'), + ('Fully Connected Layers', 3, None, 'fully-connected-layers'), + ('Optimized Convolution2DLayer', + 3, + None, + 'optimized-convolution2dlayer'), + ('The Convolutional Neural Network (CNN)', + 3, + None, + 'the-convolutional-neural-network-cnn'), + ('Usage of CNN code', 3, None, 'usage-of-cnn-code'), + ('Additional Remarks', 3, None, 'additional-remarks'), + ('Remarks on the speed', 3, None, 'remarks-on-the-speed'), + ('Convolution using separable kernels', + 3, + None, + 'convolution-using-separable-kernels'), + ('Convolution in the Fourier domain', + 3, + None, + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -174,50 +221,73 @@ MathJax.Hub.Config({ @@ -248,7 +318,7 @@ MathJax.Hub.Config({
  • 11
  • 12
  • ...
  • -
  • 45
  • +
  • 46
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs003.html b/doc/pub/week44/html/._week44-bs003.html index b6df3442e..bd6aa5ffb 100644 --- a/doc/pub/week44/html/._week44-bs003.html +++ b/doc/pub/week44/html/._week44-bs003.html @@ -139,7 +139,54 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Finally, evaluate the model', 2, None, - 'finally-evaluate-the-model')]} + 'finally-evaluate-the-model'), + ('Building our own CNN code', + 2, + None, + 'building-our-own-cnn-code'), + ('List of contents:', 3, None, 'list-of-contents'), + ('Schedulers', 3, None, 'schedulers'), + ('Usage of schedulers', 3, None, 'usage-of-schedulers'), + ('Cost functions', 3, None, 'cost-functions'), + ('Usage of cost functions', 3, None, 'usage-of-cost-functions'), + ('Activation functions', 3, None, 'activation-functions'), + ('Usage of activation functions', + 3, + None, + 'usage-of-activation-functions'), + ('Convolution', 3, None, 'convolution'), + ('Layers', 3, None, 'layers'), + ('Convolution2DLayer: convolution in a hidden layer', + 3, + None, + 'convolution2dlayer-convolution-in-a-hidden-layer'), + ('Backpropagation in the convolutional layer', + 3, + None, + 'backpropagation-in-the-convolutional-layer'), + ('Demonstration', 3, None, 'demonstration'), + ('Pooling Layer', 3, None, 'pooling-layer'), + ('Flattening Layer', 3, None, 'flattening-layer'), + ('Fully Connected Layers', 3, None, 'fully-connected-layers'), + ('Optimized Convolution2DLayer', + 3, + None, + 'optimized-convolution2dlayer'), + ('The Convolutional Neural Network (CNN)', + 3, + None, + 'the-convolutional-neural-network-cnn'), + ('Usage of CNN code', 3, None, 'usage-of-cnn-code'), + ('Additional Remarks', 3, None, 'additional-remarks'), + ('Remarks on the speed', 3, None, 'remarks-on-the-speed'), + ('Convolution using separable kernels', + 3, + None, + 'convolution-using-separable-kernels'), + ('Convolution in the Fourier domain', + 3, + None, + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -174,50 +221,73 @@ MathJax.Hub.Config({ @@ -268,7 +338,7 @@ Networks still apply (back propagation, gradient descent etc etc).
  • 12
  • 13
  • ...
  • -
  • 45
  • +
  • 46
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs004.html b/doc/pub/week44/html/._week44-bs004.html index 3c8413596..9c808ee43 100644 --- a/doc/pub/week44/html/._week44-bs004.html +++ b/doc/pub/week44/html/._week44-bs004.html @@ -139,7 +139,54 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Finally, evaluate the model', 2, None, - 'finally-evaluate-the-model')]} + 'finally-evaluate-the-model'), + ('Building our own CNN code', + 2, + None, + 'building-our-own-cnn-code'), + ('List of contents:', 3, None, 'list-of-contents'), + ('Schedulers', 3, None, 'schedulers'), + ('Usage of schedulers', 3, None, 'usage-of-schedulers'), + ('Cost functions', 3, None, 'cost-functions'), + ('Usage of cost functions', 3, None, 'usage-of-cost-functions'), + ('Activation functions', 3, None, 'activation-functions'), + ('Usage of activation functions', + 3, + None, + 'usage-of-activation-functions'), + ('Convolution', 3, None, 'convolution'), + ('Layers', 3, None, 'layers'), + ('Convolution2DLayer: convolution in a hidden layer', + 3, + None, + 'convolution2dlayer-convolution-in-a-hidden-layer'), + ('Backpropagation in the convolutional layer', + 3, + None, + 'backpropagation-in-the-convolutional-layer'), + ('Demonstration', 3, None, 'demonstration'), + ('Pooling Layer', 3, None, 'pooling-layer'), + ('Flattening Layer', 3, None, 'flattening-layer'), + ('Fully Connected Layers', 3, None, 'fully-connected-layers'), + ('Optimized Convolution2DLayer', + 3, + None, + 'optimized-convolution2dlayer'), + ('The Convolutional Neural Network (CNN)', + 3, + None, + 'the-convolutional-neural-network-cnn'), + ('Usage of CNN code', 3, None, 'usage-of-cnn-code'), + ('Additional Remarks', 3, None, 'additional-remarks'), + ('Remarks on the speed', 3, None, 'remarks-on-the-speed'), + ('Convolution using separable kernels', + 3, + None, + 'convolution-using-separable-kernels'), + ('Convolution in the Fourier domain', + 3, + None, + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -174,50 +221,73 @@ MathJax.Hub.Config({ @@ -264,7 +334,7 @@ and the slides of 13
  • 14
  • ...
  • -
  • 45
  • +
  • 46
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs005.html b/doc/pub/week44/html/._week44-bs005.html index c6b7b31e7..607ddb76e 100644 --- a/doc/pub/week44/html/._week44-bs005.html +++ b/doc/pub/week44/html/._week44-bs005.html @@ -139,7 +139,54 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Finally, evaluate the model', 2, None, - 'finally-evaluate-the-model')]} + 'finally-evaluate-the-model'), + ('Building our own CNN code', + 2, + None, + 'building-our-own-cnn-code'), + ('List of contents:', 3, None, 'list-of-contents'), + ('Schedulers', 3, None, 'schedulers'), + ('Usage of schedulers', 3, None, 'usage-of-schedulers'), + ('Cost functions', 3, None, 'cost-functions'), + ('Usage of cost functions', 3, None, 'usage-of-cost-functions'), + ('Activation functions', 3, None, 'activation-functions'), + ('Usage of activation functions', + 3, + None, + 'usage-of-activation-functions'), + ('Convolution', 3, None, 'convolution'), + ('Layers', 3, None, 'layers'), + ('Convolution2DLayer: convolution in a hidden layer', + 3, + None, + 'convolution2dlayer-convolution-in-a-hidden-layer'), + ('Backpropagation in the convolutional layer', + 3, + None, + 'backpropagation-in-the-convolutional-layer'), + ('Demonstration', 3, None, 'demonstration'), + ('Pooling Layer', 3, None, 'pooling-layer'), + ('Flattening Layer', 3, None, 'flattening-layer'), + ('Fully Connected Layers', 3, None, 'fully-connected-layers'), + ('Optimized Convolution2DLayer', + 3, + None, + 'optimized-convolution2dlayer'), + ('The Convolutional Neural Network (CNN)', + 3, + None, + 'the-convolutional-neural-network-cnn'), + ('Usage of CNN code', 3, None, 'usage-of-cnn-code'), + ('Additional Remarks', 3, None, 'additional-remarks'), + ('Remarks on the speed', 3, None, 'remarks-on-the-speed'), + ('Convolution using separable kernels', + 3, + None, + 'convolution-using-separable-kernels'), + ('Convolution in the Fourier domain', + 3, + None, + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -174,50 +221,73 @@ MathJax.Hub.Config({ @@ -260,7 +330,7 @@ before the transformation.
  • 14
  • 15
  • ...
  • -
  • 45
  • +
  • 46
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs006.html b/doc/pub/week44/html/._week44-bs006.html index a145969d7..856fc617d 100644 --- a/doc/pub/week44/html/._week44-bs006.html +++ b/doc/pub/week44/html/._week44-bs006.html @@ -139,7 +139,54 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Finally, evaluate the model', 2, None, - 'finally-evaluate-the-model')]} + 'finally-evaluate-the-model'), + ('Building our own CNN code', + 2, + None, + 'building-our-own-cnn-code'), + ('List of contents:', 3, None, 'list-of-contents'), + ('Schedulers', 3, None, 'schedulers'), + ('Usage of schedulers', 3, None, 'usage-of-schedulers'), + ('Cost functions', 3, None, 'cost-functions'), + ('Usage of cost functions', 3, None, 'usage-of-cost-functions'), + ('Activation functions', 3, None, 'activation-functions'), + ('Usage of activation functions', + 3, + None, + 'usage-of-activation-functions'), + ('Convolution', 3, None, 'convolution'), + ('Layers', 3, None, 'layers'), + ('Convolution2DLayer: convolution in a hidden layer', + 3, + None, + 'convolution2dlayer-convolution-in-a-hidden-layer'), + ('Backpropagation in the convolutional layer', + 3, + None, + 'backpropagation-in-the-convolutional-layer'), + ('Demonstration', 3, None, 'demonstration'), + ('Pooling Layer', 3, None, 'pooling-layer'), + ('Flattening Layer', 3, None, 'flattening-layer'), + ('Fully Connected Layers', 3, None, 'fully-connected-layers'), + ('Optimized Convolution2DLayer', + 3, + None, + 'optimized-convolution2dlayer'), + ('The Convolutional Neural Network (CNN)', + 3, + None, + 'the-convolutional-neural-network-cnn'), + ('Usage of CNN code', 3, None, 'usage-of-cnn-code'), + ('Additional Remarks', 3, None, 'additional-remarks'), + ('Remarks on the speed', 3, None, 'remarks-on-the-speed'), + ('Convolution using separable kernels', + 3, + None, + 'convolution-using-separable-kernels'), + ('Convolution in the Fourier domain', + 3, + None, + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -174,50 +221,73 @@ MathJax.Hub.Config({ @@ -274,7 +344,7 @@ in the input).
  • 15
  • 16
  • ...
  • -
  • 45
  • +
  • 46
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs007.html b/doc/pub/week44/html/._week44-bs007.html index ae8d17c73..7a816e983 100644 --- a/doc/pub/week44/html/._week44-bs007.html +++ b/doc/pub/week44/html/._week44-bs007.html @@ -139,7 +139,54 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Finally, evaluate the model', 2, None, - 'finally-evaluate-the-model')]} + 'finally-evaluate-the-model'), + ('Building our own CNN code', + 2, + None, + 'building-our-own-cnn-code'), + ('List of contents:', 3, None, 'list-of-contents'), + ('Schedulers', 3, None, 'schedulers'), + ('Usage of schedulers', 3, None, 'usage-of-schedulers'), + ('Cost functions', 3, None, 'cost-functions'), + ('Usage of cost functions', 3, None, 'usage-of-cost-functions'), + ('Activation functions', 3, None, 'activation-functions'), + ('Usage of activation functions', + 3, + None, + 'usage-of-activation-functions'), + ('Convolution', 3, None, 'convolution'), + ('Layers', 3, None, 'layers'), + ('Convolution2DLayer: convolution in a hidden layer', + 3, + None, + 'convolution2dlayer-convolution-in-a-hidden-layer'), + ('Backpropagation in the convolutional layer', + 3, + None, + 'backpropagation-in-the-convolutional-layer'), + ('Demonstration', 3, None, 'demonstration'), + ('Pooling Layer', 3, None, 'pooling-layer'), + ('Flattening Layer', 3, None, 'flattening-layer'), + ('Fully Connected Layers', 3, None, 'fully-connected-layers'), + ('Optimized Convolution2DLayer', + 3, + None, + 'optimized-convolution2dlayer'), + ('The Convolutional Neural Network (CNN)', + 3, + None, + 'the-convolutional-neural-network-cnn'), + ('Usage of CNN code', 3, None, 'usage-of-cnn-code'), + ('Additional Remarks', 3, None, 'additional-remarks'), + ('Remarks on the speed', 3, None, 'remarks-on-the-speed'), + ('Convolution using separable kernels', + 3, + None, + 'convolution-using-separable-kernels'), + ('Convolution in the Fourier domain', + 3, + None, + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -174,50 +221,73 @@ MathJax.Hub.Config({ @@ -277,7 +347,7 @@ would quickly lead to possible overfitting.
  • 16
  • 17
  • ...
  • -
  • 45
  • +
  • 46
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs008.html b/doc/pub/week44/html/._week44-bs008.html index 6a2853703..f7e28bab7 100644 --- a/doc/pub/week44/html/._week44-bs008.html +++ b/doc/pub/week44/html/._week44-bs008.html @@ -139,7 +139,54 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Finally, evaluate the model', 2, None, - 'finally-evaluate-the-model')]} + 'finally-evaluate-the-model'), + ('Building our own CNN code', + 2, + None, + 'building-our-own-cnn-code'), + ('List of contents:', 3, None, 'list-of-contents'), + ('Schedulers', 3, None, 'schedulers'), + ('Usage of schedulers', 3, None, 'usage-of-schedulers'), + ('Cost functions', 3, None, 'cost-functions'), + ('Usage of cost functions', 3, None, 'usage-of-cost-functions'), + ('Activation functions', 3, None, 'activation-functions'), + ('Usage of activation functions', + 3, + None, + 'usage-of-activation-functions'), + ('Convolution', 3, None, 'convolution'), + ('Layers', 3, None, 'layers'), + ('Convolution2DLayer: convolution in a hidden layer', + 3, + None, + 'convolution2dlayer-convolution-in-a-hidden-layer'), + ('Backpropagation in the convolutional layer', + 3, + None, + 'backpropagation-in-the-convolutional-layer'), + ('Demonstration', 3, None, 'demonstration'), + ('Pooling Layer', 3, None, 'pooling-layer'), + ('Flattening Layer', 3, None, 'flattening-layer'), + ('Fully Connected Layers', 3, None, 'fully-connected-layers'), + ('Optimized Convolution2DLayer', + 3, + None, + 'optimized-convolution2dlayer'), + ('The Convolutional Neural Network (CNN)', + 3, + None, + 'the-convolutional-neural-network-cnn'), + ('Usage of CNN code', 3, None, 'usage-of-cnn-code'), + ('Additional Remarks', 3, None, 'additional-remarks'), + ('Remarks on the speed', 3, None, 'remarks-on-the-speed'), + ('Convolution using separable kernels', + 3, + None, + 'convolution-using-separable-kernels'), + ('Convolution in the Fourier domain', + 3, + None, + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -174,50 +221,73 @@ MathJax.Hub.Config({ @@ -290,7 +360,7 @@ dimension.
  • 17
  • 18
  • ...
  • -
  • 45
  • +
  • 46
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs009.html b/doc/pub/week44/html/._week44-bs009.html index 47163d118..e2fe70cf7 100644 --- a/doc/pub/week44/html/._week44-bs009.html +++ b/doc/pub/week44/html/._week44-bs009.html @@ -139,7 +139,54 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Finally, evaluate the model', 2, None, - 'finally-evaluate-the-model')]} + 'finally-evaluate-the-model'), + ('Building our own CNN code', + 2, + None, + 'building-our-own-cnn-code'), + ('List of contents:', 3, None, 'list-of-contents'), + ('Schedulers', 3, None, 'schedulers'), + ('Usage of schedulers', 3, None, 'usage-of-schedulers'), + ('Cost functions', 3, None, 'cost-functions'), + ('Usage of cost functions', 3, None, 'usage-of-cost-functions'), + ('Activation functions', 3, None, 'activation-functions'), + ('Usage of activation functions', + 3, + None, + 'usage-of-activation-functions'), + ('Convolution', 3, None, 'convolution'), + ('Layers', 3, None, 'layers'), + ('Convolution2DLayer: convolution in a hidden layer', + 3, + None, + 'convolution2dlayer-convolution-in-a-hidden-layer'), + ('Backpropagation in the convolutional layer', + 3, + None, + 'backpropagation-in-the-convolutional-layer'), + ('Demonstration', 3, None, 'demonstration'), + ('Pooling Layer', 3, None, 'pooling-layer'), + ('Flattening Layer', 3, None, 'flattening-layer'), + ('Fully Connected Layers', 3, None, 'fully-connected-layers'), + ('Optimized Convolution2DLayer', + 3, + None, + 'optimized-convolution2dlayer'), + ('The Convolutional Neural Network (CNN)', + 3, + None, + 'the-convolutional-neural-network-cnn'), + ('Usage of CNN code', 3, None, 'usage-of-cnn-code'), + ('Additional Remarks', 3, None, 'additional-remarks'), + ('Remarks on the speed', 3, None, 'remarks-on-the-speed'), + ('Convolution using separable kernels', + 3, + None, + 'convolution-using-separable-kernels'), + ('Convolution in the Fourier domain', + 3, + None, + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -174,50 +221,73 @@ MathJax.Hub.Config({ @@ -272,7 +342,7 @@ will stack these layers to form a full CNN architecture.
  • 18
  • 19
  • ...
  • -
  • 45
  • +
  • 46
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs010.html b/doc/pub/week44/html/._week44-bs010.html index 4d3be5149..5b1657c5b 100644 --- a/doc/pub/week44/html/._week44-bs010.html +++ b/doc/pub/week44/html/._week44-bs010.html @@ -139,7 +139,54 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Finally, evaluate the model', 2, None, - 'finally-evaluate-the-model')]} + 'finally-evaluate-the-model'), + ('Building our own CNN code', + 2, + None, + 'building-our-own-cnn-code'), + ('List of contents:', 3, None, 'list-of-contents'), + ('Schedulers', 3, None, 'schedulers'), + ('Usage of schedulers', 3, None, 'usage-of-schedulers'), + ('Cost functions', 3, None, 'cost-functions'), + ('Usage of cost functions', 3, None, 'usage-of-cost-functions'), + ('Activation functions', 3, None, 'activation-functions'), + ('Usage of activation functions', + 3, + None, + 'usage-of-activation-functions'), + ('Convolution', 3, None, 'convolution'), + ('Layers', 3, None, 'layers'), + ('Convolution2DLayer: convolution in a hidden layer', + 3, + None, + 'convolution2dlayer-convolution-in-a-hidden-layer'), + ('Backpropagation in the convolutional layer', + 3, + None, + 'backpropagation-in-the-convolutional-layer'), + ('Demonstration', 3, None, 'demonstration'), + ('Pooling Layer', 3, None, 'pooling-layer'), + ('Flattening Layer', 3, None, 'flattening-layer'), + ('Fully Connected Layers', 3, None, 'fully-connected-layers'), + ('Optimized Convolution2DLayer', + 3, + None, + 'optimized-convolution2dlayer'), + ('The Convolutional Neural Network (CNN)', + 3, + None, + 'the-convolutional-neural-network-cnn'), + ('Usage of CNN code', 3, None, 'usage-of-cnn-code'), + ('Additional Remarks', 3, None, 'additional-remarks'), + ('Remarks on the speed', 3, None, 'remarks-on-the-speed'), + ('Convolution using separable kernels', + 3, + None, + 'convolution-using-separable-kernels'), + ('Convolution in the Fourier domain', + 3, + None, + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -174,50 +221,73 @@ MathJax.Hub.Config({ @@ -270,7 +340,7 @@ are consistent with the labels in the training set for each image.
  • 19
  • 20
  • ...
  • -
  • 45
  • +
  • 46
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs011.html b/doc/pub/week44/html/._week44-bs011.html index c9bd65388..805d9aa54 100644 --- a/doc/pub/week44/html/._week44-bs011.html +++ b/doc/pub/week44/html/._week44-bs011.html @@ -139,7 +139,54 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Finally, evaluate the model', 2, None, - 'finally-evaluate-the-model')]} + 'finally-evaluate-the-model'), + ('Building our own CNN code', + 2, + None, + 'building-our-own-cnn-code'), + ('List of contents:', 3, None, 'list-of-contents'), + ('Schedulers', 3, None, 'schedulers'), + ('Usage of schedulers', 3, None, 'usage-of-schedulers'), + ('Cost functions', 3, None, 'cost-functions'), + ('Usage of cost functions', 3, None, 'usage-of-cost-functions'), + ('Activation functions', 3, None, 'activation-functions'), + ('Usage of activation functions', + 3, + None, + 'usage-of-activation-functions'), + ('Convolution', 3, None, 'convolution'), + ('Layers', 3, None, 'layers'), + ('Convolution2DLayer: convolution in a hidden layer', + 3, + None, + 'convolution2dlayer-convolution-in-a-hidden-layer'), + ('Backpropagation in the convolutional layer', + 3, + None, + 'backpropagation-in-the-convolutional-layer'), + ('Demonstration', 3, None, 'demonstration'), + ('Pooling Layer', 3, None, 'pooling-layer'), + ('Flattening Layer', 3, None, 'flattening-layer'), + ('Fully Connected Layers', 3, None, 'fully-connected-layers'), + ('Optimized Convolution2DLayer', + 3, + None, + 'optimized-convolution2dlayer'), + ('The Convolutional Neural Network (CNN)', + 3, + None, + 'the-convolutional-neural-network-cnn'), + ('Usage of CNN code', 3, None, 'usage-of-cnn-code'), + ('Additional Remarks', 3, None, 'additional-remarks'), + ('Remarks on the speed', 3, None, 'remarks-on-the-speed'), + ('Convolution using separable kernels', + 3, + None, + 'convolution-using-separable-kernels'), + ('Convolution in the Fourier domain', + 3, + None, + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -174,50 +221,73 @@ MathJax.Hub.Config({ @@ -273,7 +343,7 @@ and the slides of 20
  • 21
  • ...
  • -
  • 45
  • +
  • 46
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs012.html b/doc/pub/week44/html/._week44-bs012.html index 598446790..3db16f9d0 100644 --- a/doc/pub/week44/html/._week44-bs012.html +++ b/doc/pub/week44/html/._week44-bs012.html @@ -139,7 +139,54 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Finally, evaluate the model', 2, None, - 'finally-evaluate-the-model')]} + 'finally-evaluate-the-model'), + ('Building our own CNN code', + 2, + None, + 'building-our-own-cnn-code'), + ('List of contents:', 3, None, 'list-of-contents'), + ('Schedulers', 3, None, 'schedulers'), + ('Usage of schedulers', 3, None, 'usage-of-schedulers'), + ('Cost functions', 3, None, 'cost-functions'), + ('Usage of cost functions', 3, None, 'usage-of-cost-functions'), + ('Activation functions', 3, None, 'activation-functions'), + ('Usage of activation functions', + 3, + None, + 'usage-of-activation-functions'), + ('Convolution', 3, None, 'convolution'), + ('Layers', 3, None, 'layers'), + ('Convolution2DLayer: convolution in a hidden layer', + 3, + None, + 'convolution2dlayer-convolution-in-a-hidden-layer'), + ('Backpropagation in the convolutional layer', + 3, + None, + 'backpropagation-in-the-convolutional-layer'), + ('Demonstration', 3, None, 'demonstration'), + ('Pooling Layer', 3, None, 'pooling-layer'), + ('Flattening Layer', 3, None, 'flattening-layer'), + ('Fully Connected Layers', 3, None, 'fully-connected-layers'), + ('Optimized Convolution2DLayer', + 3, + None, + 'optimized-convolution2dlayer'), + ('The Convolutional Neural Network (CNN)', + 3, + None, + 'the-convolutional-neural-network-cnn'), + ('Usage of CNN code', 3, None, 'usage-of-cnn-code'), + ('Additional Remarks', 3, None, 'additional-remarks'), + ('Remarks on the speed', 3, None, 'remarks-on-the-speed'), + ('Convolution using separable kernels', + 3, + None, + 'convolution-using-separable-kernels'), + ('Convolution in the Fourier domain', + 3, + None, + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -174,50 +221,73 @@ MathJax.Hub.Config({ @@ -264,7 +334,7 @@ only neighboring neurons in the input instead of connecting all with the first h
  • 21
  • 22
  • ...
  • -
  • 45
  • +
  • 46
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs013.html b/doc/pub/week44/html/._week44-bs013.html index 2ed0d7b98..bedb7f06f 100644 --- a/doc/pub/week44/html/._week44-bs013.html +++ b/doc/pub/week44/html/._week44-bs013.html @@ -139,7 +139,54 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Finally, evaluate the model', 2, None, - 'finally-evaluate-the-model')]} + 'finally-evaluate-the-model'), + ('Building our own CNN code', + 2, + None, + 'building-our-own-cnn-code'), + ('List of contents:', 3, None, 'list-of-contents'), + ('Schedulers', 3, None, 'schedulers'), + ('Usage of schedulers', 3, None, 'usage-of-schedulers'), + ('Cost functions', 3, None, 'cost-functions'), + ('Usage of cost functions', 3, None, 'usage-of-cost-functions'), + ('Activation functions', 3, None, 'activation-functions'), + ('Usage of activation functions', + 3, + None, + 'usage-of-activation-functions'), + ('Convolution', 3, None, 'convolution'), + ('Layers', 3, None, 'layers'), + ('Convolution2DLayer: convolution in a hidden layer', + 3, + None, + 'convolution2dlayer-convolution-in-a-hidden-layer'), + ('Backpropagation in the convolutional layer', + 3, + None, + 'backpropagation-in-the-convolutional-layer'), + ('Demonstration', 3, None, 'demonstration'), + ('Pooling Layer', 3, None, 'pooling-layer'), + ('Flattening Layer', 3, None, 'flattening-layer'), + ('Fully Connected Layers', 3, None, 'fully-connected-layers'), + ('Optimized Convolution2DLayer', + 3, + None, + 'optimized-convolution2dlayer'), + ('The Convolutional Neural Network (CNN)', + 3, + None, + 'the-convolutional-neural-network-cnn'), + ('Usage of CNN code', 3, None, 'usage-of-cnn-code'), + ('Additional Remarks', 3, None, 'additional-remarks'), + ('Remarks on the speed', 3, None, 'remarks-on-the-speed'), + ('Convolution using separable kernels', + 3, + None, + 'convolution-using-separable-kernels'), + ('Convolution in the Fourier domain', + 3, + None, + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -174,50 +221,73 @@ MathJax.Hub.Config({ @@ -287,7 +357,7 @@ $$
  • 22
  • 23
  • ...
  • -
  • 45
  • +
  • 46
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs014.html b/doc/pub/week44/html/._week44-bs014.html index 463ac4210..c32c99be7 100644 --- a/doc/pub/week44/html/._week44-bs014.html +++ b/doc/pub/week44/html/._week44-bs014.html @@ -139,7 +139,54 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Finally, evaluate the model', 2, None, - 'finally-evaluate-the-model')]} + 'finally-evaluate-the-model'), + ('Building our own CNN code', + 2, + None, + 'building-our-own-cnn-code'), + ('List of contents:', 3, None, 'list-of-contents'), + ('Schedulers', 3, None, 'schedulers'), + ('Usage of schedulers', 3, None, 'usage-of-schedulers'), + ('Cost functions', 3, None, 'cost-functions'), + ('Usage of cost functions', 3, None, 'usage-of-cost-functions'), + ('Activation functions', 3, None, 'activation-functions'), + ('Usage of activation functions', + 3, + None, + 'usage-of-activation-functions'), + ('Convolution', 3, None, 'convolution'), + ('Layers', 3, None, 'layers'), + ('Convolution2DLayer: convolution in a hidden layer', + 3, + None, + 'convolution2dlayer-convolution-in-a-hidden-layer'), + ('Backpropagation in the convolutional layer', + 3, + None, + 'backpropagation-in-the-convolutional-layer'), + ('Demonstration', 3, None, 'demonstration'), + ('Pooling Layer', 3, None, 'pooling-layer'), + ('Flattening Layer', 3, None, 'flattening-layer'), + ('Fully Connected Layers', 3, None, 'fully-connected-layers'), + ('Optimized Convolution2DLayer', + 3, + None, + 'optimized-convolution2dlayer'), + ('The Convolutional Neural Network (CNN)', + 3, + None, + 'the-convolutional-neural-network-cnn'), + ('Usage of CNN code', 3, None, 'usage-of-cnn-code'), + ('Additional Remarks', 3, None, 'additional-remarks'), + ('Remarks on the speed', 3, None, 'remarks-on-the-speed'), + ('Convolution using separable kernels', + 3, + None, + 'convolution-using-separable-kernels'), + ('Convolution in the Fourier domain', + 3, + None, + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -174,50 +221,73 @@ MathJax.Hub.Config({ @@ -276,7 +346,7 @@ $$
  • 23
  • 24
  • ...
  • -
  • 45
  • +
  • 46
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs015.html b/doc/pub/week44/html/._week44-bs015.html index 5bfff20a9..80e47b8e5 100644 --- a/doc/pub/week44/html/._week44-bs015.html +++ b/doc/pub/week44/html/._week44-bs015.html @@ -139,7 +139,54 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Finally, evaluate the model', 2, None, - 'finally-evaluate-the-model')]} + 'finally-evaluate-the-model'), + ('Building our own CNN code', + 2, + None, + 'building-our-own-cnn-code'), + ('List of contents:', 3, None, 'list-of-contents'), + ('Schedulers', 3, None, 'schedulers'), + ('Usage of schedulers', 3, None, 'usage-of-schedulers'), + ('Cost functions', 3, None, 'cost-functions'), + ('Usage of cost functions', 3, None, 'usage-of-cost-functions'), + ('Activation functions', 3, None, 'activation-functions'), + ('Usage of activation functions', + 3, + None, + 'usage-of-activation-functions'), + ('Convolution', 3, None, 'convolution'), + ('Layers', 3, None, 'layers'), + ('Convolution2DLayer: convolution in a hidden layer', + 3, + None, + 'convolution2dlayer-convolution-in-a-hidden-layer'), + ('Backpropagation in the convolutional layer', + 3, + None, + 'backpropagation-in-the-convolutional-layer'), + ('Demonstration', 3, None, 'demonstration'), + ('Pooling Layer', 3, None, 'pooling-layer'), + ('Flattening Layer', 3, None, 'flattening-layer'), + ('Fully Connected Layers', 3, None, 'fully-connected-layers'), + ('Optimized Convolution2DLayer', + 3, + None, + 'optimized-convolution2dlayer'), + ('The Convolutional Neural Network (CNN)', + 3, + None, + 'the-convolutional-neural-network-cnn'), + ('Usage of CNN code', 3, None, 'usage-of-cnn-code'), + ('Additional Remarks', 3, None, 'additional-remarks'), + ('Remarks on the speed', 3, None, 'remarks-on-the-speed'), + ('Convolution using separable kernels', + 3, + None, + 'convolution-using-separable-kernels'), + ('Convolution in the Fourier domain', + 3, + None, + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -174,50 +221,73 @@ MathJax.Hub.Config({ @@ -285,7 +355,7 @@ $$
  • 24
  • 25
  • ...
  • -
  • 45
  • +
  • 46
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs016.html b/doc/pub/week44/html/._week44-bs016.html index 30b16d890..2105e1bb8 100644 --- a/doc/pub/week44/html/._week44-bs016.html +++ b/doc/pub/week44/html/._week44-bs016.html @@ -139,7 +139,54 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Finally, evaluate the model', 2, None, - 'finally-evaluate-the-model')]} + 'finally-evaluate-the-model'), + ('Building our own CNN code', + 2, + None, + 'building-our-own-cnn-code'), + ('List of contents:', 3, None, 'list-of-contents'), + ('Schedulers', 3, None, 'schedulers'), + ('Usage of schedulers', 3, None, 'usage-of-schedulers'), + ('Cost functions', 3, None, 'cost-functions'), + ('Usage of cost functions', 3, None, 'usage-of-cost-functions'), + ('Activation functions', 3, None, 'activation-functions'), + ('Usage of activation functions', + 3, + None, + 'usage-of-activation-functions'), + ('Convolution', 3, None, 'convolution'), + ('Layers', 3, None, 'layers'), + ('Convolution2DLayer: convolution in a hidden layer', + 3, + None, + 'convolution2dlayer-convolution-in-a-hidden-layer'), + ('Backpropagation in the convolutional layer', + 3, + None, + 'backpropagation-in-the-convolutional-layer'), + ('Demonstration', 3, None, 'demonstration'), + ('Pooling Layer', 3, None, 'pooling-layer'), + ('Flattening Layer', 3, None, 'flattening-layer'), + ('Fully Connected Layers', 3, None, 'fully-connected-layers'), + ('Optimized Convolution2DLayer', + 3, + None, + 'optimized-convolution2dlayer'), + ('The Convolutional Neural Network (CNN)', + 3, + None, + 'the-convolutional-neural-network-cnn'), + ('Usage of CNN code', 3, None, 'usage-of-cnn-code'), + ('Additional Remarks', 3, None, 'additional-remarks'), + ('Remarks on the speed', 3, None, 'remarks-on-the-speed'), + ('Convolution using separable kernels', + 3, + None, + 'convolution-using-separable-kernels'), + ('Convolution in the Fourier domain', + 3, + None, + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -174,50 +221,73 @@ MathJax.Hub.Config({ @@ -291,7 +361,7 @@ We rather code the convolutions in the minimal memory footprint that they requir
  • 25
  • 26
  • ...
  • -
  • 45
  • +
  • 46
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs017.html b/doc/pub/week44/html/._week44-bs017.html index 8e5ef6c4a..69937d0ed 100644 --- a/doc/pub/week44/html/._week44-bs017.html +++ b/doc/pub/week44/html/._week44-bs017.html @@ -139,7 +139,54 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Finally, evaluate the model', 2, None, - 'finally-evaluate-the-model')]} + 'finally-evaluate-the-model'), + ('Building our own CNN code', + 2, + None, + 'building-our-own-cnn-code'), + ('List of contents:', 3, None, 'list-of-contents'), + ('Schedulers', 3, None, 'schedulers'), + ('Usage of schedulers', 3, None, 'usage-of-schedulers'), + ('Cost functions', 3, None, 'cost-functions'), + ('Usage of cost functions', 3, None, 'usage-of-cost-functions'), + ('Activation functions', 3, None, 'activation-functions'), + ('Usage of activation functions', + 3, + None, + 'usage-of-activation-functions'), + ('Convolution', 3, None, 'convolution'), + ('Layers', 3, None, 'layers'), + ('Convolution2DLayer: convolution in a hidden layer', + 3, + None, + 'convolution2dlayer-convolution-in-a-hidden-layer'), + ('Backpropagation in the convolutional layer', + 3, + None, + 'backpropagation-in-the-convolutional-layer'), + ('Demonstration', 3, None, 'demonstration'), + ('Pooling Layer', 3, None, 'pooling-layer'), + ('Flattening Layer', 3, None, 'flattening-layer'), + ('Fully Connected Layers', 3, None, 'fully-connected-layers'), + ('Optimized Convolution2DLayer', + 3, + None, + 'optimized-convolution2dlayer'), + ('The Convolutional Neural Network (CNN)', + 3, + None, + 'the-convolutional-neural-network-cnn'), + ('Usage of CNN code', 3, None, 'usage-of-cnn-code'), + ('Additional Remarks', 3, None, 'additional-remarks'), + ('Remarks on the speed', 3, None, 'remarks-on-the-speed'), + ('Convolution using separable kernels', + 3, + None, + 'convolution-using-separable-kernels'), + ('Convolution in the Fourier domain', + 3, + None, + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -174,50 +221,73 @@ MathJax.Hub.Config({ @@ -276,7 +346,7 @@ $$
  • 26
  • 27
  • ...
  • -
  • 45
  • +
  • 46
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs018.html b/doc/pub/week44/html/._week44-bs018.html index 2fcb2d7b8..6a987ce7b 100644 --- a/doc/pub/week44/html/._week44-bs018.html +++ b/doc/pub/week44/html/._week44-bs018.html @@ -139,7 +139,54 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Finally, evaluate the model', 2, None, - 'finally-evaluate-the-model')]} + 'finally-evaluate-the-model'), + ('Building our own CNN code', + 2, + None, + 'building-our-own-cnn-code'), + ('List of contents:', 3, None, 'list-of-contents'), + ('Schedulers', 3, None, 'schedulers'), + ('Usage of schedulers', 3, None, 'usage-of-schedulers'), + ('Cost functions', 3, None, 'cost-functions'), + ('Usage of cost functions', 3, None, 'usage-of-cost-functions'), + ('Activation functions', 3, None, 'activation-functions'), + ('Usage of activation functions', + 3, + None, + 'usage-of-activation-functions'), + ('Convolution', 3, None, 'convolution'), + ('Layers', 3, None, 'layers'), + ('Convolution2DLayer: convolution in a hidden layer', + 3, + None, + 'convolution2dlayer-convolution-in-a-hidden-layer'), + ('Backpropagation in the convolutional layer', + 3, + None, + 'backpropagation-in-the-convolutional-layer'), + ('Demonstration', 3, None, 'demonstration'), + ('Pooling Layer', 3, None, 'pooling-layer'), + ('Flattening Layer', 3, None, 'flattening-layer'), + ('Fully Connected Layers', 3, None, 'fully-connected-layers'), + ('Optimized Convolution2DLayer', + 3, + None, + 'optimized-convolution2dlayer'), + ('The Convolutional Neural Network (CNN)', + 3, + None, + 'the-convolutional-neural-network-cnn'), + ('Usage of CNN code', 3, None, 'usage-of-cnn-code'), + ('Additional Remarks', 3, None, 'additional-remarks'), + ('Remarks on the speed', 3, None, 'remarks-on-the-speed'), + ('Convolution using separable kernels', + 3, + None, + 'convolution-using-separable-kernels'), + ('Convolution in the Fourier domain', + 3, + None, + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -174,50 +221,73 @@ MathJax.Hub.Config({ @@ -281,7 +351,7 @@ driven by purely sinusoidal sources.
  • 27
  • 28
  • ...
  • -
  • 45
  • +
  • 46
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs019.html b/doc/pub/week44/html/._week44-bs019.html index 985cf3710..abfdc5df7 100644 --- a/doc/pub/week44/html/._week44-bs019.html +++ b/doc/pub/week44/html/._week44-bs019.html @@ -139,7 +139,54 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Finally, evaluate the model', 2, None, - 'finally-evaluate-the-model')]} + 'finally-evaluate-the-model'), + ('Building our own CNN code', + 2, + None, + 'building-our-own-cnn-code'), + ('List of contents:', 3, None, 'list-of-contents'), + ('Schedulers', 3, None, 'schedulers'), + ('Usage of schedulers', 3, None, 'usage-of-schedulers'), + ('Cost functions', 3, None, 'cost-functions'), + ('Usage of cost functions', 3, None, 'usage-of-cost-functions'), + ('Activation functions', 3, None, 'activation-functions'), + ('Usage of activation functions', + 3, + None, + 'usage-of-activation-functions'), + ('Convolution', 3, None, 'convolution'), + ('Layers', 3, None, 'layers'), + ('Convolution2DLayer: convolution in a hidden layer', + 3, + None, + 'convolution2dlayer-convolution-in-a-hidden-layer'), + ('Backpropagation in the convolutional layer', + 3, + None, + 'backpropagation-in-the-convolutional-layer'), + ('Demonstration', 3, None, 'demonstration'), + ('Pooling Layer', 3, None, 'pooling-layer'), + ('Flattening Layer', 3, None, 'flattening-layer'), + ('Fully Connected Layers', 3, None, 'fully-connected-layers'), + ('Optimized Convolution2DLayer', + 3, + None, + 'optimized-convolution2dlayer'), + ('The Convolutional Neural Network (CNN)', + 3, + None, + 'the-convolutional-neural-network-cnn'), + ('Usage of CNN code', 3, None, 'usage-of-cnn-code'), + ('Additional Remarks', 3, None, 'additional-remarks'), + ('Remarks on the speed', 3, None, 'remarks-on-the-speed'), + ('Convolution using separable kernels', + 3, + None, + 'convolution-using-separable-kernels'), + ('Convolution in the Fourier domain', + 3, + None, + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -174,50 +221,73 @@ MathJax.Hub.Config({ @@ -312,7 +382,7 @@ $$
  • 28
  • 29
  • ...
  • -
  • 45
  • +
  • 46
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs020.html b/doc/pub/week44/html/._week44-bs020.html index 1b0c94069..1f51d6d21 100644 --- a/doc/pub/week44/html/._week44-bs020.html +++ b/doc/pub/week44/html/._week44-bs020.html @@ -139,7 +139,54 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Finally, evaluate the model', 2, None, - 'finally-evaluate-the-model')]} + 'finally-evaluate-the-model'), + ('Building our own CNN code', + 2, + None, + 'building-our-own-cnn-code'), + ('List of contents:', 3, None, 'list-of-contents'), + ('Schedulers', 3, None, 'schedulers'), + ('Usage of schedulers', 3, None, 'usage-of-schedulers'), + ('Cost functions', 3, None, 'cost-functions'), + ('Usage of cost functions', 3, None, 'usage-of-cost-functions'), + ('Activation functions', 3, None, 'activation-functions'), + ('Usage of activation functions', + 3, + None, + 'usage-of-activation-functions'), + ('Convolution', 3, None, 'convolution'), + ('Layers', 3, None, 'layers'), + ('Convolution2DLayer: convolution in a hidden layer', + 3, + None, + 'convolution2dlayer-convolution-in-a-hidden-layer'), + ('Backpropagation in the convolutional layer', + 3, + None, + 'backpropagation-in-the-convolutional-layer'), + ('Demonstration', 3, None, 'demonstration'), + ('Pooling Layer', 3, None, 'pooling-layer'), + ('Flattening Layer', 3, None, 'flattening-layer'), + ('Fully Connected Layers', 3, None, 'fully-connected-layers'), + ('Optimized Convolution2DLayer', + 3, + None, + 'optimized-convolution2dlayer'), + ('The Convolutional Neural Network (CNN)', + 3, + None, + 'the-convolutional-neural-network-cnn'), + ('Usage of CNN code', 3, None, 'usage-of-cnn-code'), + ('Additional Remarks', 3, None, 'additional-remarks'), + ('Remarks on the speed', 3, None, 'remarks-on-the-speed'), + ('Convolution using separable kernels', + 3, + None, + 'convolution-using-separable-kernels'), + ('Convolution in the Fourier domain', + 3, + None, + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -174,50 +221,73 @@ MathJax.Hub.Config({ @@ -286,7 +356,7 @@ $$
  • 29
  • 30
  • ...
  • -
  • 45
  • +
  • 46
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs021.html b/doc/pub/week44/html/._week44-bs021.html index 4c48e7ce4..713721cd8 100644 --- a/doc/pub/week44/html/._week44-bs021.html +++ b/doc/pub/week44/html/._week44-bs021.html @@ -139,7 +139,54 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Finally, evaluate the model', 2, None, - 'finally-evaluate-the-model')]} + 'finally-evaluate-the-model'), + ('Building our own CNN code', + 2, + None, + 'building-our-own-cnn-code'), + ('List of contents:', 3, None, 'list-of-contents'), + ('Schedulers', 3, None, 'schedulers'), + ('Usage of schedulers', 3, None, 'usage-of-schedulers'), + ('Cost functions', 3, None, 'cost-functions'), + ('Usage of cost functions', 3, None, 'usage-of-cost-functions'), + ('Activation functions', 3, None, 'activation-functions'), + ('Usage of activation functions', + 3, + None, + 'usage-of-activation-functions'), + ('Convolution', 3, None, 'convolution'), + ('Layers', 3, None, 'layers'), + ('Convolution2DLayer: convolution in a hidden layer', + 3, + None, + 'convolution2dlayer-convolution-in-a-hidden-layer'), + ('Backpropagation in the convolutional layer', + 3, + None, + 'backpropagation-in-the-convolutional-layer'), + ('Demonstration', 3, None, 'demonstration'), + ('Pooling Layer', 3, None, 'pooling-layer'), + ('Flattening Layer', 3, None, 'flattening-layer'), + ('Fully Connected Layers', 3, None, 'fully-connected-layers'), + ('Optimized Convolution2DLayer', + 3, + None, + 'optimized-convolution2dlayer'), + ('The Convolutional Neural Network (CNN)', + 3, + None, + 'the-convolutional-neural-network-cnn'), + ('Usage of CNN code', 3, None, 'usage-of-cnn-code'), + ('Additional Remarks', 3, None, 'additional-remarks'), + ('Remarks on the speed', 3, None, 'remarks-on-the-speed'), + ('Convolution using separable kernels', + 3, + None, + 'convolution-using-separable-kernels'), + ('Convolution in the Fourier domain', + 3, + None, + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -174,50 +221,73 @@ MathJax.Hub.Config({ @@ -319,7 +389,7 @@ $$
  • 30
  • 31
  • ...
  • -
  • 45
  • +
  • 46
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs022.html b/doc/pub/week44/html/._week44-bs022.html index 533af4311..8f1a62890 100644 --- a/doc/pub/week44/html/._week44-bs022.html +++ b/doc/pub/week44/html/._week44-bs022.html @@ -139,7 +139,54 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Finally, evaluate the model', 2, None, - 'finally-evaluate-the-model')]} + 'finally-evaluate-the-model'), + ('Building our own CNN code', + 2, + None, + 'building-our-own-cnn-code'), + ('List of contents:', 3, None, 'list-of-contents'), + ('Schedulers', 3, None, 'schedulers'), + ('Usage of schedulers', 3, None, 'usage-of-schedulers'), + ('Cost functions', 3, None, 'cost-functions'), + ('Usage of cost functions', 3, None, 'usage-of-cost-functions'), + ('Activation functions', 3, None, 'activation-functions'), + ('Usage of activation functions', + 3, + None, + 'usage-of-activation-functions'), + ('Convolution', 3, None, 'convolution'), + ('Layers', 3, None, 'layers'), + ('Convolution2DLayer: convolution in a hidden layer', + 3, + None, + 'convolution2dlayer-convolution-in-a-hidden-layer'), + ('Backpropagation in the convolutional layer', + 3, + None, + 'backpropagation-in-the-convolutional-layer'), + ('Demonstration', 3, None, 'demonstration'), + ('Pooling Layer', 3, None, 'pooling-layer'), + ('Flattening Layer', 3, None, 'flattening-layer'), + ('Fully Connected Layers', 3, None, 'fully-connected-layers'), + ('Optimized Convolution2DLayer', + 3, + None, + 'optimized-convolution2dlayer'), + ('The Convolutional Neural Network (CNN)', + 3, + None, + 'the-convolutional-neural-network-cnn'), + ('Usage of CNN code', 3, None, 'usage-of-cnn-code'), + ('Additional Remarks', 3, None, 'additional-remarks'), + ('Remarks on the speed', 3, None, 'remarks-on-the-speed'), + ('Convolution using separable kernels', + 3, + None, + 'convolution-using-separable-kernels'), + ('Convolution in the Fourier domain', + 3, + None, + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -174,50 +221,73 @@ MathJax.Hub.Config({ @@ -317,7 +387,7 @@ plt.show()
  • 31
  • 32
  • ...
  • -
  • 45
  • +
  • 46
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs023.html b/doc/pub/week44/html/._week44-bs023.html index 6905de8c9..6be3d464d 100644 --- a/doc/pub/week44/html/._week44-bs023.html +++ b/doc/pub/week44/html/._week44-bs023.html @@ -139,7 +139,54 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Finally, evaluate the model', 2, None, - 'finally-evaluate-the-model')]} + 'finally-evaluate-the-model'), + ('Building our own CNN code', + 2, + None, + 'building-our-own-cnn-code'), + ('List of contents:', 3, None, 'list-of-contents'), + ('Schedulers', 3, None, 'schedulers'), + ('Usage of schedulers', 3, None, 'usage-of-schedulers'), + ('Cost functions', 3, None, 'cost-functions'), + ('Usage of cost functions', 3, None, 'usage-of-cost-functions'), + ('Activation functions', 3, None, 'activation-functions'), + ('Usage of activation functions', + 3, + None, + 'usage-of-activation-functions'), + ('Convolution', 3, None, 'convolution'), + ('Layers', 3, None, 'layers'), + ('Convolution2DLayer: convolution in a hidden layer', + 3, + None, + 'convolution2dlayer-convolution-in-a-hidden-layer'), + ('Backpropagation in the convolutional layer', + 3, + None, + 'backpropagation-in-the-convolutional-layer'), + ('Demonstration', 3, None, 'demonstration'), + ('Pooling Layer', 3, None, 'pooling-layer'), + ('Flattening Layer', 3, None, 'flattening-layer'), + ('Fully Connected Layers', 3, None, 'fully-connected-layers'), + ('Optimized Convolution2DLayer', + 3, + None, + 'optimized-convolution2dlayer'), + ('The Convolutional Neural Network (CNN)', + 3, + None, + 'the-convolutional-neural-network-cnn'), + ('Usage of CNN code', 3, None, 'usage-of-cnn-code'), + ('Additional Remarks', 3, None, 'additional-remarks'), + ('Remarks on the speed', 3, None, 'remarks-on-the-speed'), + ('Convolution using separable kernels', + 3, + None, + 'convolution-using-separable-kernels'), + ('Convolution in the Fourier domain', + 3, + None, + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -174,50 +221,73 @@ MathJax.Hub.Config({ @@ -272,7 +342,7 @@ $$
  • 32
  • 33
  • ...
  • -
  • 45
  • +
  • 46
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs024.html b/doc/pub/week44/html/._week44-bs024.html index 4e12dcfdf..9b2cc8c81 100644 --- a/doc/pub/week44/html/._week44-bs024.html +++ b/doc/pub/week44/html/._week44-bs024.html @@ -139,7 +139,54 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Finally, evaluate the model', 2, None, - 'finally-evaluate-the-model')]} + 'finally-evaluate-the-model'), + ('Building our own CNN code', + 2, + None, + 'building-our-own-cnn-code'), + ('List of contents:', 3, None, 'list-of-contents'), + ('Schedulers', 3, None, 'schedulers'), + ('Usage of schedulers', 3, None, 'usage-of-schedulers'), + ('Cost functions', 3, None, 'cost-functions'), + ('Usage of cost functions', 3, None, 'usage-of-cost-functions'), + ('Activation functions', 3, None, 'activation-functions'), + ('Usage of activation functions', + 3, + None, + 'usage-of-activation-functions'), + ('Convolution', 3, None, 'convolution'), + ('Layers', 3, None, 'layers'), + ('Convolution2DLayer: convolution in a hidden layer', + 3, + None, + 'convolution2dlayer-convolution-in-a-hidden-layer'), + ('Backpropagation in the convolutional layer', + 3, + None, + 'backpropagation-in-the-convolutional-layer'), + ('Demonstration', 3, None, 'demonstration'), + ('Pooling Layer', 3, None, 'pooling-layer'), + ('Flattening Layer', 3, None, 'flattening-layer'), + ('Fully Connected Layers', 3, None, 'fully-connected-layers'), + ('Optimized Convolution2DLayer', + 3, + None, + 'optimized-convolution2dlayer'), + ('The Convolutional Neural Network (CNN)', + 3, + None, + 'the-convolutional-neural-network-cnn'), + ('Usage of CNN code', 3, None, 'usage-of-cnn-code'), + ('Additional Remarks', 3, None, 'additional-remarks'), + ('Remarks on the speed', 3, None, 'remarks-on-the-speed'), + ('Convolution using separable kernels', + 3, + None, + 'convolution-using-separable-kernels'), + ('Convolution in the Fourier domain', + 3, + None, + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -174,50 +221,73 @@ MathJax.Hub.Config({ @@ -262,7 +332,7 @@ $$
  • 33
  • 34
  • ...
  • -
  • 45
  • +
  • 46
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs025.html b/doc/pub/week44/html/._week44-bs025.html index 998fa7a7a..ac96c8a6c 100644 --- a/doc/pub/week44/html/._week44-bs025.html +++ b/doc/pub/week44/html/._week44-bs025.html @@ -139,7 +139,54 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Finally, evaluate the model', 2, None, - 'finally-evaluate-the-model')]} + 'finally-evaluate-the-model'), + ('Building our own CNN code', + 2, + None, + 'building-our-own-cnn-code'), + ('List of contents:', 3, None, 'list-of-contents'), + ('Schedulers', 3, None, 'schedulers'), + ('Usage of schedulers', 3, None, 'usage-of-schedulers'), + ('Cost functions', 3, None, 'cost-functions'), + ('Usage of cost functions', 3, None, 'usage-of-cost-functions'), + ('Activation functions', 3, None, 'activation-functions'), + ('Usage of activation functions', + 3, + None, + 'usage-of-activation-functions'), + ('Convolution', 3, None, 'convolution'), + ('Layers', 3, None, 'layers'), + ('Convolution2DLayer: convolution in a hidden layer', + 3, + None, + 'convolution2dlayer-convolution-in-a-hidden-layer'), + ('Backpropagation in the convolutional layer', + 3, + None, + 'backpropagation-in-the-convolutional-layer'), + ('Demonstration', 3, None, 'demonstration'), + ('Pooling Layer', 3, None, 'pooling-layer'), + ('Flattening Layer', 3, None, 'flattening-layer'), + ('Fully Connected Layers', 3, None, 'fully-connected-layers'), + ('Optimized Convolution2DLayer', + 3, + None, + 'optimized-convolution2dlayer'), + ('The Convolutional Neural Network (CNN)', + 3, + None, + 'the-convolutional-neural-network-cnn'), + ('Usage of CNN code', 3, None, 'usage-of-cnn-code'), + ('Additional Remarks', 3, None, 'additional-remarks'), + ('Remarks on the speed', 3, None, 'remarks-on-the-speed'), + ('Convolution using separable kernels', + 3, + None, + 'convolution-using-separable-kernels'), + ('Convolution in the Fourier domain', + 3, + None, + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -174,50 +221,73 @@ MathJax.Hub.Config({ @@ -282,7 +352,7 @@ $$
  • 34
  • 35
  • ...
  • -
  • 45
  • +
  • 46
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs026.html b/doc/pub/week44/html/._week44-bs026.html index 5c8c0f174..0f9e1ffda 100644 --- a/doc/pub/week44/html/._week44-bs026.html +++ b/doc/pub/week44/html/._week44-bs026.html @@ -139,7 +139,54 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Finally, evaluate the model', 2, None, - 'finally-evaluate-the-model')]} + 'finally-evaluate-the-model'), + ('Building our own CNN code', + 2, + None, + 'building-our-own-cnn-code'), + ('List of contents:', 3, None, 'list-of-contents'), + ('Schedulers', 3, None, 'schedulers'), + ('Usage of schedulers', 3, None, 'usage-of-schedulers'), + ('Cost functions', 3, None, 'cost-functions'), + ('Usage of cost functions', 3, None, 'usage-of-cost-functions'), + ('Activation functions', 3, None, 'activation-functions'), + ('Usage of activation functions', + 3, + None, + 'usage-of-activation-functions'), + ('Convolution', 3, None, 'convolution'), + ('Layers', 3, None, 'layers'), + ('Convolution2DLayer: convolution in a hidden layer', + 3, + None, + 'convolution2dlayer-convolution-in-a-hidden-layer'), + ('Backpropagation in the convolutional layer', + 3, + None, + 'backpropagation-in-the-convolutional-layer'), + ('Demonstration', 3, None, 'demonstration'), + ('Pooling Layer', 3, None, 'pooling-layer'), + ('Flattening Layer', 3, None, 'flattening-layer'), + ('Fully Connected Layers', 3, None, 'fully-connected-layers'), + ('Optimized Convolution2DLayer', + 3, + None, + 'optimized-convolution2dlayer'), + ('The Convolutional Neural Network (CNN)', + 3, + None, + 'the-convolutional-neural-network-cnn'), + ('Usage of CNN code', 3, None, 'usage-of-cnn-code'), + ('Additional Remarks', 3, None, 'additional-remarks'), + ('Remarks on the speed', 3, None, 'remarks-on-the-speed'), + ('Convolution using separable kernels', + 3, + None, + 'convolution-using-separable-kernels'), + ('Convolution in the Fourier domain', + 3, + None, + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -174,50 +221,73 @@ MathJax.Hub.Config({ @@ -274,7 +344,7 @@ principles then apply to images and other similar data.
  • 35
  • 36
  • ...
  • -
  • 45
  • +
  • 46
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs027.html b/doc/pub/week44/html/._week44-bs027.html index 50d037b66..6e913d5ec 100644 --- a/doc/pub/week44/html/._week44-bs027.html +++ b/doc/pub/week44/html/._week44-bs027.html @@ -139,7 +139,54 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Finally, evaluate the model', 2, None, - 'finally-evaluate-the-model')]} + 'finally-evaluate-the-model'), + ('Building our own CNN code', + 2, + None, + 'building-our-own-cnn-code'), + ('List of contents:', 3, None, 'list-of-contents'), + ('Schedulers', 3, None, 'schedulers'), + ('Usage of schedulers', 3, None, 'usage-of-schedulers'), + ('Cost functions', 3, None, 'cost-functions'), + ('Usage of cost functions', 3, None, 'usage-of-cost-functions'), + ('Activation functions', 3, None, 'activation-functions'), + ('Usage of activation functions', + 3, + None, + 'usage-of-activation-functions'), + ('Convolution', 3, None, 'convolution'), + ('Layers', 3, None, 'layers'), + ('Convolution2DLayer: convolution in a hidden layer', + 3, + None, + 'convolution2dlayer-convolution-in-a-hidden-layer'), + ('Backpropagation in the convolutional layer', + 3, + None, + 'backpropagation-in-the-convolutional-layer'), + ('Demonstration', 3, None, 'demonstration'), + ('Pooling Layer', 3, None, 'pooling-layer'), + ('Flattening Layer', 3, None, 'flattening-layer'), + ('Fully Connected Layers', 3, None, 'fully-connected-layers'), + ('Optimized Convolution2DLayer', + 3, + None, + 'optimized-convolution2dlayer'), + ('The Convolutional Neural Network (CNN)', + 3, + None, + 'the-convolutional-neural-network-cnn'), + ('Usage of CNN code', 3, None, 'usage-of-cnn-code'), + ('Additional Remarks', 3, None, 'additional-remarks'), + ('Remarks on the speed', 3, None, 'remarks-on-the-speed'), + ('Convolution using separable kernels', + 3, + None, + 'convolution-using-separable-kernels'), + ('Convolution in the Fourier domain', + 3, + None, + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -174,50 +221,73 @@ MathJax.Hub.Config({ @@ -259,7 +329,7 @@ MathJax.Hub.Config({
  • 36
  • 37
  • ...
  • -
  • 45
  • +
  • 46
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs028.html b/doc/pub/week44/html/._week44-bs028.html index 5e1265034..338eb5ca9 100644 --- a/doc/pub/week44/html/._week44-bs028.html +++ b/doc/pub/week44/html/._week44-bs028.html @@ -139,7 +139,54 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Finally, evaluate the model', 2, None, - 'finally-evaluate-the-model')]} + 'finally-evaluate-the-model'), + ('Building our own CNN code', + 2, + None, + 'building-our-own-cnn-code'), + ('List of contents:', 3, None, 'list-of-contents'), + ('Schedulers', 3, None, 'schedulers'), + ('Usage of schedulers', 3, None, 'usage-of-schedulers'), + ('Cost functions', 3, None, 'cost-functions'), + ('Usage of cost functions', 3, None, 'usage-of-cost-functions'), + ('Activation functions', 3, None, 'activation-functions'), + ('Usage of activation functions', + 3, + None, + 'usage-of-activation-functions'), + ('Convolution', 3, None, 'convolution'), + ('Layers', 3, None, 'layers'), + ('Convolution2DLayer: convolution in a hidden layer', + 3, + None, + 'convolution2dlayer-convolution-in-a-hidden-layer'), + ('Backpropagation in the convolutional layer', + 3, + None, + 'backpropagation-in-the-convolutional-layer'), + ('Demonstration', 3, None, 'demonstration'), + ('Pooling Layer', 3, None, 'pooling-layer'), + ('Flattening Layer', 3, None, 'flattening-layer'), + ('Fully Connected Layers', 3, None, 'fully-connected-layers'), + ('Optimized Convolution2DLayer', + 3, + None, + 'optimized-convolution2dlayer'), + ('The Convolutional Neural Network (CNN)', + 3, + None, + 'the-convolutional-neural-network-cnn'), + ('Usage of CNN code', 3, None, 'usage-of-cnn-code'), + ('Additional Remarks', 3, None, 'additional-remarks'), + ('Remarks on the speed', 3, None, 'remarks-on-the-speed'), + ('Convolution using separable kernels', + 3, + None, + 'convolution-using-separable-kernels'), + ('Convolution in the Fourier domain', + 3, + None, + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -174,50 +221,73 @@ MathJax.Hub.Config({ @@ -267,7 +337,7 @@ matrices, typically 1 for each color dimension (Red, Green, Blue).
  • 37
  • 38
  • ...
  • -
  • 45
  • +
  • 46
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs029.html b/doc/pub/week44/html/._week44-bs029.html index daf11243e..9401ed9d6 100644 --- a/doc/pub/week44/html/._week44-bs029.html +++ b/doc/pub/week44/html/._week44-bs029.html @@ -139,7 +139,54 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Finally, evaluate the model', 2, None, - 'finally-evaluate-the-model')]} + 'finally-evaluate-the-model'), + ('Building our own CNN code', + 2, + None, + 'building-our-own-cnn-code'), + ('List of contents:', 3, None, 'list-of-contents'), + ('Schedulers', 3, None, 'schedulers'), + ('Usage of schedulers', 3, None, 'usage-of-schedulers'), + ('Cost functions', 3, None, 'cost-functions'), + ('Usage of cost functions', 3, None, 'usage-of-cost-functions'), + ('Activation functions', 3, None, 'activation-functions'), + ('Usage of activation functions', + 3, + None, + 'usage-of-activation-functions'), + ('Convolution', 3, None, 'convolution'), + ('Layers', 3, None, 'layers'), + ('Convolution2DLayer: convolution in a hidden layer', + 3, + None, + 'convolution2dlayer-convolution-in-a-hidden-layer'), + ('Backpropagation in the convolutional layer', + 3, + None, + 'backpropagation-in-the-convolutional-layer'), + ('Demonstration', 3, None, 'demonstration'), + ('Pooling Layer', 3, None, 'pooling-layer'), + ('Flattening Layer', 3, None, 'flattening-layer'), + ('Fully Connected Layers', 3, None, 'fully-connected-layers'), + ('Optimized Convolution2DLayer', + 3, + None, + 'optimized-convolution2dlayer'), + ('The Convolutional Neural Network (CNN)', + 3, + None, + 'the-convolutional-neural-network-cnn'), + ('Usage of CNN code', 3, None, 'usage-of-cnn-code'), + ('Additional Remarks', 3, None, 'additional-remarks'), + ('Remarks on the speed', 3, None, 'remarks-on-the-speed'), + ('Convolution using separable kernels', + 3, + None, + 'convolution-using-separable-kernels'), + ('Convolution in the Fourier domain', + 3, + None, + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -174,50 +221,73 @@ MathJax.Hub.Config({ @@ -264,7 +334,7 @@ $$
  • 38
  • 39
  • ...
  • -
  • 45
  • +
  • 46
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs030.html b/doc/pub/week44/html/._week44-bs030.html index 58bb72ed1..1ec0c4404 100644 --- a/doc/pub/week44/html/._week44-bs030.html +++ b/doc/pub/week44/html/._week44-bs030.html @@ -139,7 +139,54 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Finally, evaluate the model', 2, None, - 'finally-evaluate-the-model')]} + 'finally-evaluate-the-model'), + ('Building our own CNN code', + 2, + None, + 'building-our-own-cnn-code'), + ('List of contents:', 3, None, 'list-of-contents'), + ('Schedulers', 3, None, 'schedulers'), + ('Usage of schedulers', 3, None, 'usage-of-schedulers'), + ('Cost functions', 3, None, 'cost-functions'), + ('Usage of cost functions', 3, None, 'usage-of-cost-functions'), + ('Activation functions', 3, None, 'activation-functions'), + ('Usage of activation functions', + 3, + None, + 'usage-of-activation-functions'), + ('Convolution', 3, None, 'convolution'), + ('Layers', 3, None, 'layers'), + ('Convolution2DLayer: convolution in a hidden layer', + 3, + None, + 'convolution2dlayer-convolution-in-a-hidden-layer'), + ('Backpropagation in the convolutional layer', + 3, + None, + 'backpropagation-in-the-convolutional-layer'), + ('Demonstration', 3, None, 'demonstration'), + ('Pooling Layer', 3, None, 'pooling-layer'), + ('Flattening Layer', 3, None, 'flattening-layer'), + ('Fully Connected Layers', 3, None, 'fully-connected-layers'), + ('Optimized Convolution2DLayer', + 3, + None, + 'optimized-convolution2dlayer'), + ('The Convolutional Neural Network (CNN)', + 3, + None, + 'the-convolutional-neural-network-cnn'), + ('Usage of CNN code', 3, None, 'usage-of-cnn-code'), + ('Additional Remarks', 3, None, 'additional-remarks'), + ('Remarks on the speed', 3, None, 'remarks-on-the-speed'), + ('Convolution using separable kernels', + 3, + None, + 'convolution-using-separable-kernels'), + ('Convolution in the Fourier domain', + 3, + None, + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -174,50 +221,73 @@ MathJax.Hub.Config({ @@ -270,7 +340,7 @@ single neuron in the first hidden layer.
  • 39
  • 40
  • ...
  • -
  • 45
  • +
  • 46
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs031.html b/doc/pub/week44/html/._week44-bs031.html index 948d330bd..d1a14d88b 100644 --- a/doc/pub/week44/html/._week44-bs031.html +++ b/doc/pub/week44/html/._week44-bs031.html @@ -139,7 +139,54 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Finally, evaluate the model', 2, None, - 'finally-evaluate-the-model')]} + 'finally-evaluate-the-model'), + ('Building our own CNN code', + 2, + None, + 'building-our-own-cnn-code'), + ('List of contents:', 3, None, 'list-of-contents'), + ('Schedulers', 3, None, 'schedulers'), + ('Usage of schedulers', 3, None, 'usage-of-schedulers'), + ('Cost functions', 3, None, 'cost-functions'), + ('Usage of cost functions', 3, None, 'usage-of-cost-functions'), + ('Activation functions', 3, None, 'activation-functions'), + ('Usage of activation functions', + 3, + None, + 'usage-of-activation-functions'), + ('Convolution', 3, None, 'convolution'), + ('Layers', 3, None, 'layers'), + ('Convolution2DLayer: convolution in a hidden layer', + 3, + None, + 'convolution2dlayer-convolution-in-a-hidden-layer'), + ('Backpropagation in the convolutional layer', + 3, + None, + 'backpropagation-in-the-convolutional-layer'), + ('Demonstration', 3, None, 'demonstration'), + ('Pooling Layer', 3, None, 'pooling-layer'), + ('Flattening Layer', 3, None, 'flattening-layer'), + ('Fully Connected Layers', 3, None, 'fully-connected-layers'), + ('Optimized Convolution2DLayer', + 3, + None, + 'optimized-convolution2dlayer'), + ('The Convolutional Neural Network (CNN)', + 3, + None, + 'the-convolutional-neural-network-cnn'), + ('Usage of CNN code', 3, None, 'usage-of-cnn-code'), + ('Additional Remarks', 3, None, 'additional-remarks'), + ('Remarks on the speed', 3, None, 'remarks-on-the-speed'), + ('Convolution using separable kernels', + 3, + None, + 'convolution-using-separable-kernels'), + ('Convolution in the Fourier domain', + 3, + None, + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -174,50 +221,73 @@ MathJax.Hub.Config({ @@ -270,7 +340,7 @@ fixed, and known as a 40
  • 41
  • ...
  • -
  • 45
  • +
  • 46
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs032.html b/doc/pub/week44/html/._week44-bs032.html index db2d03c30..1174d4e3c 100644 --- a/doc/pub/week44/html/._week44-bs032.html +++ b/doc/pub/week44/html/._week44-bs032.html @@ -139,7 +139,54 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Finally, evaluate the model', 2, None, - 'finally-evaluate-the-model')]} + 'finally-evaluate-the-model'), + ('Building our own CNN code', + 2, + None, + 'building-our-own-cnn-code'), + ('List of contents:', 3, None, 'list-of-contents'), + ('Schedulers', 3, None, 'schedulers'), + ('Usage of schedulers', 3, None, 'usage-of-schedulers'), + ('Cost functions', 3, None, 'cost-functions'), + ('Usage of cost functions', 3, None, 'usage-of-cost-functions'), + ('Activation functions', 3, None, 'activation-functions'), + ('Usage of activation functions', + 3, + None, + 'usage-of-activation-functions'), + ('Convolution', 3, None, 'convolution'), + ('Layers', 3, None, 'layers'), + ('Convolution2DLayer: convolution in a hidden layer', + 3, + None, + 'convolution2dlayer-convolution-in-a-hidden-layer'), + ('Backpropagation in the convolutional layer', + 3, + None, + 'backpropagation-in-the-convolutional-layer'), + ('Demonstration', 3, None, 'demonstration'), + ('Pooling Layer', 3, None, 'pooling-layer'), + ('Flattening Layer', 3, None, 'flattening-layer'), + ('Fully Connected Layers', 3, None, 'fully-connected-layers'), + ('Optimized Convolution2DLayer', + 3, + None, + 'optimized-convolution2dlayer'), + ('The Convolutional Neural Network (CNN)', + 3, + None, + 'the-convolutional-neural-network-cnn'), + ('Usage of CNN code', 3, None, 'usage-of-cnn-code'), + ('Additional Remarks', 3, None, 'additional-remarks'), + ('Remarks on the speed', 3, None, 'remarks-on-the-speed'), + ('Convolution using separable kernels', + 3, + None, + 'convolution-using-separable-kernels'), + ('Convolution in the Fourier domain', + 3, + None, + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -174,50 +221,73 @@ MathJax.Hub.Config({ @@ -274,7 +344,7 @@ layer.
  • 41
  • 42
  • ...
  • -
  • 45
  • +
  • 46
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs033.html b/doc/pub/week44/html/._week44-bs033.html index 3d0f439d4..855d912c8 100644 --- a/doc/pub/week44/html/._week44-bs033.html +++ b/doc/pub/week44/html/._week44-bs033.html @@ -139,7 +139,54 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Finally, evaluate the model', 2, None, - 'finally-evaluate-the-model')]} + 'finally-evaluate-the-model'), + ('Building our own CNN code', + 2, + None, + 'building-our-own-cnn-code'), + ('List of contents:', 3, None, 'list-of-contents'), + ('Schedulers', 3, None, 'schedulers'), + ('Usage of schedulers', 3, None, 'usage-of-schedulers'), + ('Cost functions', 3, None, 'cost-functions'), + ('Usage of cost functions', 3, None, 'usage-of-cost-functions'), + ('Activation functions', 3, None, 'activation-functions'), + ('Usage of activation functions', + 3, + None, + 'usage-of-activation-functions'), + ('Convolution', 3, None, 'convolution'), + ('Layers', 3, None, 'layers'), + ('Convolution2DLayer: convolution in a hidden layer', + 3, + None, + 'convolution2dlayer-convolution-in-a-hidden-layer'), + ('Backpropagation in the convolutional layer', + 3, + None, + 'backpropagation-in-the-convolutional-layer'), + ('Demonstration', 3, None, 'demonstration'), + ('Pooling Layer', 3, None, 'pooling-layer'), + ('Flattening Layer', 3, None, 'flattening-layer'), + ('Fully Connected Layers', 3, None, 'fully-connected-layers'), + ('Optimized Convolution2DLayer', + 3, + None, + 'optimized-convolution2dlayer'), + ('The Convolutional Neural Network (CNN)', + 3, + None, + 'the-convolutional-neural-network-cnn'), + ('Usage of CNN code', 3, None, 'usage-of-cnn-code'), + ('Additional Remarks', 3, None, 'additional-remarks'), + ('Remarks on the speed', 3, None, 'remarks-on-the-speed'), + ('Convolution using separable kernels', + 3, + None, + 'convolution-using-separable-kernels'), + ('Convolution in the Fourier domain', + 3, + None, + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -174,50 +221,73 @@ MathJax.Hub.Config({ @@ -267,7 +337,7 @@ classification.
  • 42
  • 43
  • ...
  • -
  • 45
  • +
  • 46
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs034.html b/doc/pub/week44/html/._week44-bs034.html index 8ee9e460e..6ecbaed2b 100644 --- a/doc/pub/week44/html/._week44-bs034.html +++ b/doc/pub/week44/html/._week44-bs034.html @@ -139,7 +139,54 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Finally, evaluate the model', 2, None, - 'finally-evaluate-the-model')]} + 'finally-evaluate-the-model'), + ('Building our own CNN code', + 2, + None, + 'building-our-own-cnn-code'), + ('List of contents:', 3, None, 'list-of-contents'), + ('Schedulers', 3, None, 'schedulers'), + ('Usage of schedulers', 3, None, 'usage-of-schedulers'), + ('Cost functions', 3, None, 'cost-functions'), + ('Usage of cost functions', 3, None, 'usage-of-cost-functions'), + ('Activation functions', 3, None, 'activation-functions'), + ('Usage of activation functions', + 3, + None, + 'usage-of-activation-functions'), + ('Convolution', 3, None, 'convolution'), + ('Layers', 3, None, 'layers'), + ('Convolution2DLayer: convolution in a hidden layer', + 3, + None, + 'convolution2dlayer-convolution-in-a-hidden-layer'), + ('Backpropagation in the convolutional layer', + 3, + None, + 'backpropagation-in-the-convolutional-layer'), + ('Demonstration', 3, None, 'demonstration'), + ('Pooling Layer', 3, None, 'pooling-layer'), + ('Flattening Layer', 3, None, 'flattening-layer'), + ('Fully Connected Layers', 3, None, 'fully-connected-layers'), + ('Optimized Convolution2DLayer', + 3, + None, + 'optimized-convolution2dlayer'), + ('The Convolutional Neural Network (CNN)', + 3, + None, + 'the-convolutional-neural-network-cnn'), + ('Usage of CNN code', 3, None, 'usage-of-cnn-code'), + ('Additional Remarks', 3, None, 'additional-remarks'), + ('Remarks on the speed', 3, None, 'remarks-on-the-speed'), + ('Convolution using separable kernels', + 3, + None, + 'convolution-using-separable-kernels'), + ('Convolution in the Fourier domain', + 3, + None, + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -174,50 +221,73 @@ MathJax.Hub.Config({ @@ -318,7 +388,7 @@ plt.show()
  • 43
  • 44
  • ...
  • -
  • 45
  • +
  • 46
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs035.html b/doc/pub/week44/html/._week44-bs035.html index ce651dbe7..1a012d6f5 100644 --- a/doc/pub/week44/html/._week44-bs035.html +++ b/doc/pub/week44/html/._week44-bs035.html @@ -139,7 +139,54 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Finally, evaluate the model', 2, None, - 'finally-evaluate-the-model')]} + 'finally-evaluate-the-model'), + ('Building our own CNN code', + 2, + None, + 'building-our-own-cnn-code'), + ('List of contents:', 3, None, 'list-of-contents'), + ('Schedulers', 3, None, 'schedulers'), + ('Usage of schedulers', 3, None, 'usage-of-schedulers'), + ('Cost functions', 3, None, 'cost-functions'), + ('Usage of cost functions', 3, None, 'usage-of-cost-functions'), + ('Activation functions', 3, None, 'activation-functions'), + ('Usage of activation functions', + 3, + None, + 'usage-of-activation-functions'), + ('Convolution', 3, None, 'convolution'), + ('Layers', 3, None, 'layers'), + ('Convolution2DLayer: convolution in a hidden layer', + 3, + None, + 'convolution2dlayer-convolution-in-a-hidden-layer'), + ('Backpropagation in the convolutional layer', + 3, + None, + 'backpropagation-in-the-convolutional-layer'), + ('Demonstration', 3, None, 'demonstration'), + ('Pooling Layer', 3, None, 'pooling-layer'), + ('Flattening Layer', 3, None, 'flattening-layer'), + ('Fully Connected Layers', 3, None, 'fully-connected-layers'), + ('Optimized Convolution2DLayer', + 3, + None, + 'optimized-convolution2dlayer'), + ('The Convolutional Neural Network (CNN)', + 3, + None, + 'the-convolutional-neural-network-cnn'), + ('Usage of CNN code', 3, None, 'usage-of-cnn-code'), + ('Additional Remarks', 3, None, 'additional-remarks'), + ('Remarks on the speed', 3, None, 'remarks-on-the-speed'), + ('Convolution using separable kernels', + 3, + None, + 'convolution-using-separable-kernels'), + ('Convolution in the Fourier domain', + 3, + None, + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -174,50 +221,73 @@ MathJax.Hub.Config({ @@ -299,6 +369,8 @@ X_train, X_test, Y_train, Y_test = train_tes
  • 43
  • 44
  • 45
  • +
  • ...
  • +
  • 46
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs036.html b/doc/pub/week44/html/._week44-bs036.html index b6ba13f35..4360e26f6 100644 --- a/doc/pub/week44/html/._week44-bs036.html +++ b/doc/pub/week44/html/._week44-bs036.html @@ -139,7 +139,54 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Finally, evaluate the model', 2, None, - 'finally-evaluate-the-model')]} + 'finally-evaluate-the-model'), + ('Building our own CNN code', + 2, + None, + 'building-our-own-cnn-code'), + ('List of contents:', 3, None, 'list-of-contents'), + ('Schedulers', 3, None, 'schedulers'), + ('Usage of schedulers', 3, None, 'usage-of-schedulers'), + ('Cost functions', 3, None, 'cost-functions'), + ('Usage of cost functions', 3, None, 'usage-of-cost-functions'), + ('Activation functions', 3, None, 'activation-functions'), + ('Usage of activation functions', + 3, + None, + 'usage-of-activation-functions'), + ('Convolution', 3, None, 'convolution'), + ('Layers', 3, None, 'layers'), + ('Convolution2DLayer: convolution in a hidden layer', + 3, + None, + 'convolution2dlayer-convolution-in-a-hidden-layer'), + ('Backpropagation in the convolutional layer', + 3, + None, + 'backpropagation-in-the-convolutional-layer'), + ('Demonstration', 3, None, 'demonstration'), + ('Pooling Layer', 3, None, 'pooling-layer'), + ('Flattening Layer', 3, None, 'flattening-layer'), + ('Fully Connected Layers', 3, None, 'fully-connected-layers'), + ('Optimized Convolution2DLayer', + 3, + None, + 'optimized-convolution2dlayer'), + ('The Convolutional Neural Network (CNN)', + 3, + None, + 'the-convolutional-neural-network-cnn'), + ('Usage of CNN code', 3, None, 'usage-of-cnn-code'), + ('Additional Remarks', 3, None, 'additional-remarks'), + ('Remarks on the speed', 3, None, 'remarks-on-the-speed'), + ('Convolution using separable kernels', + 3, + None, + 'convolution-using-separable-kernels'), + ('Convolution in the Fourier domain', + 3, + None, + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -174,50 +221,73 @@ MathJax.Hub.Config({ @@ -303,6 +373,7 @@ lmbd_vals = np.
  • 43
  • 44
  • 45
  • +
  • 46
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs037.html b/doc/pub/week44/html/._week44-bs037.html index f9aec8510..2fdd82818 100644 --- a/doc/pub/week44/html/._week44-bs037.html +++ b/doc/pub/week44/html/._week44-bs037.html @@ -139,7 +139,54 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Finally, evaluate the model', 2, None, - 'finally-evaluate-the-model')]} + 'finally-evaluate-the-model'), + ('Building our own CNN code', + 2, + None, + 'building-our-own-cnn-code'), + ('List of contents:', 3, None, 'list-of-contents'), + ('Schedulers', 3, None, 'schedulers'), + ('Usage of schedulers', 3, None, 'usage-of-schedulers'), + ('Cost functions', 3, None, 'cost-functions'), + ('Usage of cost functions', 3, None, 'usage-of-cost-functions'), + ('Activation functions', 3, None, 'activation-functions'), + ('Usage of activation functions', + 3, + None, + 'usage-of-activation-functions'), + ('Convolution', 3, None, 'convolution'), + ('Layers', 3, None, 'layers'), + ('Convolution2DLayer: convolution in a hidden layer', + 3, + None, + 'convolution2dlayer-convolution-in-a-hidden-layer'), + ('Backpropagation in the convolutional layer', + 3, + None, + 'backpropagation-in-the-convolutional-layer'), + ('Demonstration', 3, None, 'demonstration'), + ('Pooling Layer', 3, None, 'pooling-layer'), + ('Flattening Layer', 3, None, 'flattening-layer'), + ('Fully Connected Layers', 3, None, 'fully-connected-layers'), + ('Optimized Convolution2DLayer', + 3, + None, + 'optimized-convolution2dlayer'), + ('The Convolutional Neural Network (CNN)', + 3, + None, + 'the-convolutional-neural-network-cnn'), + ('Usage of CNN code', 3, None, 'usage-of-cnn-code'), + ('Additional Remarks', 3, None, 'additional-remarks'), + ('Remarks on the speed', 3, None, 'remarks-on-the-speed'), + ('Convolution using separable kernels', + 3, + None, + 'convolution-using-separable-kernels'), + ('Convolution in the Fourier domain', + 3, + None, + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -174,50 +221,73 @@ MathJax.Hub.Config({ @@ -292,6 +362,7 @@ MathJax.Hub.Config({
  • 43
  • 44
  • 45
  • +
  • 46
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs038.html b/doc/pub/week44/html/._week44-bs038.html index 77a424e16..5e1c225b6 100644 --- a/doc/pub/week44/html/._week44-bs038.html +++ b/doc/pub/week44/html/._week44-bs038.html @@ -139,7 +139,54 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Finally, evaluate the model', 2, None, - 'finally-evaluate-the-model')]} + 'finally-evaluate-the-model'), + ('Building our own CNN code', + 2, + None, + 'building-our-own-cnn-code'), + ('List of contents:', 3, None, 'list-of-contents'), + ('Schedulers', 3, None, 'schedulers'), + ('Usage of schedulers', 3, None, 'usage-of-schedulers'), + ('Cost functions', 3, None, 'cost-functions'), + ('Usage of cost functions', 3, None, 'usage-of-cost-functions'), + ('Activation functions', 3, None, 'activation-functions'), + ('Usage of activation functions', + 3, + None, + 'usage-of-activation-functions'), + ('Convolution', 3, None, 'convolution'), + ('Layers', 3, None, 'layers'), + ('Convolution2DLayer: convolution in a hidden layer', + 3, + None, + 'convolution2dlayer-convolution-in-a-hidden-layer'), + ('Backpropagation in the convolutional layer', + 3, + None, + 'backpropagation-in-the-convolutional-layer'), + ('Demonstration', 3, None, 'demonstration'), + ('Pooling Layer', 3, None, 'pooling-layer'), + ('Flattening Layer', 3, None, 'flattening-layer'), + ('Fully Connected Layers', 3, None, 'fully-connected-layers'), + ('Optimized Convolution2DLayer', + 3, + None, + 'optimized-convolution2dlayer'), + ('The Convolutional Neural Network (CNN)', + 3, + None, + 'the-convolutional-neural-network-cnn'), + ('Usage of CNN code', 3, None, 'usage-of-cnn-code'), + ('Additional Remarks', 3, None, 'additional-remarks'), + ('Remarks on the speed', 3, None, 'remarks-on-the-speed'), + ('Convolution using separable kernels', + 3, + None, + 'convolution-using-separable-kernels'), + ('Convolution in the Fourier domain', + 3, + None, + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -174,50 +221,73 @@ MathJax.Hub.Config({ @@ -305,6 +375,7 @@ plt.show()
  • 43
  • 44
  • 45
  • +
  • 46
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs039.html b/doc/pub/week44/html/._week44-bs039.html index 9a76913ec..dca6c43ce 100644 --- a/doc/pub/week44/html/._week44-bs039.html +++ b/doc/pub/week44/html/._week44-bs039.html @@ -139,7 +139,54 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Finally, evaluate the model', 2, None, - 'finally-evaluate-the-model')]} + 'finally-evaluate-the-model'), + ('Building our own CNN code', + 2, + None, + 'building-our-own-cnn-code'), + ('List of contents:', 3, None, 'list-of-contents'), + ('Schedulers', 3, None, 'schedulers'), + ('Usage of schedulers', 3, None, 'usage-of-schedulers'), + ('Cost functions', 3, None, 'cost-functions'), + ('Usage of cost functions', 3, None, 'usage-of-cost-functions'), + ('Activation functions', 3, None, 'activation-functions'), + ('Usage of activation functions', + 3, + None, + 'usage-of-activation-functions'), + ('Convolution', 3, None, 'convolution'), + ('Layers', 3, None, 'layers'), + ('Convolution2DLayer: convolution in a hidden layer', + 3, + None, + 'convolution2dlayer-convolution-in-a-hidden-layer'), + ('Backpropagation in the convolutional layer', + 3, + None, + 'backpropagation-in-the-convolutional-layer'), + ('Demonstration', 3, None, 'demonstration'), + ('Pooling Layer', 3, None, 'pooling-layer'), + ('Flattening Layer', 3, None, 'flattening-layer'), + ('Fully Connected Layers', 3, None, 'fully-connected-layers'), + ('Optimized Convolution2DLayer', + 3, + None, + 'optimized-convolution2dlayer'), + ('The Convolutional Neural Network (CNN)', + 3, + None, + 'the-convolutional-neural-network-cnn'), + ('Usage of CNN code', 3, None, 'usage-of-cnn-code'), + ('Additional Remarks', 3, None, 'additional-remarks'), + ('Remarks on the speed', 3, None, 'remarks-on-the-speed'), + ('Convolution using separable kernels', + 3, + None, + 'convolution-using-separable-kernels'), + ('Convolution in the Fourier domain', + 3, + None, + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -174,50 +221,73 @@ MathJax.Hub.Config({ @@ -290,6 +360,7 @@ train_images, test_images = train_images 43
  • 44
  • 45
  • +
  • 46
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs040.html b/doc/pub/week44/html/._week44-bs040.html index 301f7771d..f765b1977 100644 --- a/doc/pub/week44/html/._week44-bs040.html +++ b/doc/pub/week44/html/._week44-bs040.html @@ -139,7 +139,54 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Finally, evaluate the model', 2, None, - 'finally-evaluate-the-model')]} + 'finally-evaluate-the-model'), + ('Building our own CNN code', + 2, + None, + 'building-our-own-cnn-code'), + ('List of contents:', 3, None, 'list-of-contents'), + ('Schedulers', 3, None, 'schedulers'), + ('Usage of schedulers', 3, None, 'usage-of-schedulers'), + ('Cost functions', 3, None, 'cost-functions'), + ('Usage of cost functions', 3, None, 'usage-of-cost-functions'), + ('Activation functions', 3, None, 'activation-functions'), + ('Usage of activation functions', + 3, + None, + 'usage-of-activation-functions'), + ('Convolution', 3, None, 'convolution'), + ('Layers', 3, None, 'layers'), + ('Convolution2DLayer: convolution in a hidden layer', + 3, + None, + 'convolution2dlayer-convolution-in-a-hidden-layer'), + ('Backpropagation in the convolutional layer', + 3, + None, + 'backpropagation-in-the-convolutional-layer'), + ('Demonstration', 3, None, 'demonstration'), + ('Pooling Layer', 3, None, 'pooling-layer'), + ('Flattening Layer', 3, None, 'flattening-layer'), + ('Fully Connected Layers', 3, None, 'fully-connected-layers'), + ('Optimized Convolution2DLayer', + 3, + None, + 'optimized-convolution2dlayer'), + ('The Convolutional Neural Network (CNN)', + 3, + None, + 'the-convolutional-neural-network-cnn'), + ('Usage of CNN code', 3, None, 'usage-of-cnn-code'), + ('Additional Remarks', 3, None, 'additional-remarks'), + ('Remarks on the speed', 3, None, 'remarks-on-the-speed'), + ('Convolution using separable kernels', + 3, + None, + 'convolution-using-separable-kernels'), + ('Convolution in the Fourier domain', + 3, + None, + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -174,50 +221,73 @@ MathJax.Hub.Config({ @@ -289,6 +359,7 @@ plt.show()
  • 43
  • 44
  • 45
  • +
  • 46
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs041.html b/doc/pub/week44/html/._week44-bs041.html index bbbc59513..3f1aabce1 100644 --- a/doc/pub/week44/html/._week44-bs041.html +++ b/doc/pub/week44/html/._week44-bs041.html @@ -139,7 +139,54 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Finally, evaluate the model', 2, None, - 'finally-evaluate-the-model')]} + 'finally-evaluate-the-model'), + ('Building our own CNN code', + 2, + None, + 'building-our-own-cnn-code'), + ('List of contents:', 3, None, 'list-of-contents'), + ('Schedulers', 3, None, 'schedulers'), + ('Usage of schedulers', 3, None, 'usage-of-schedulers'), + ('Cost functions', 3, None, 'cost-functions'), + ('Usage of cost functions', 3, None, 'usage-of-cost-functions'), + ('Activation functions', 3, None, 'activation-functions'), + ('Usage of activation functions', + 3, + None, + 'usage-of-activation-functions'), + ('Convolution', 3, None, 'convolution'), + ('Layers', 3, None, 'layers'), + ('Convolution2DLayer: convolution in a hidden layer', + 3, + None, + 'convolution2dlayer-convolution-in-a-hidden-layer'), + ('Backpropagation in the convolutional layer', + 3, + None, + 'backpropagation-in-the-convolutional-layer'), + ('Demonstration', 3, None, 'demonstration'), + ('Pooling Layer', 3, None, 'pooling-layer'), + ('Flattening Layer', 3, None, 'flattening-layer'), + ('Fully Connected Layers', 3, None, 'fully-connected-layers'), + ('Optimized Convolution2DLayer', + 3, + None, + 'optimized-convolution2dlayer'), + ('The Convolutional Neural Network (CNN)', + 3, + None, + 'the-convolutional-neural-network-cnn'), + ('Usage of CNN code', 3, None, 'usage-of-cnn-code'), + ('Additional Remarks', 3, None, 'additional-remarks'), + ('Remarks on the speed', 3, None, 'remarks-on-the-speed'), + ('Convolution using separable kernels', + 3, + None, + 'convolution-using-separable-kernels'), + ('Convolution in the Fourier domain', + 3, + None, + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -174,50 +221,73 @@ MathJax.Hub.Config({ @@ -287,6 +357,7 @@ model.summary()
  • 43
  • 44
  • 45
  • +
  • 46
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs042.html b/doc/pub/week44/html/._week44-bs042.html index 173bc751f..2d6697165 100644 --- a/doc/pub/week44/html/._week44-bs042.html +++ b/doc/pub/week44/html/._week44-bs042.html @@ -139,7 +139,54 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Finally, evaluate the model', 2, None, - 'finally-evaluate-the-model')]} + 'finally-evaluate-the-model'), + ('Building our own CNN code', + 2, + None, + 'building-our-own-cnn-code'), + ('List of contents:', 3, None, 'list-of-contents'), + ('Schedulers', 3, None, 'schedulers'), + ('Usage of schedulers', 3, None, 'usage-of-schedulers'), + ('Cost functions', 3, None, 'cost-functions'), + ('Usage of cost functions', 3, None, 'usage-of-cost-functions'), + ('Activation functions', 3, None, 'activation-functions'), + ('Usage of activation functions', + 3, + None, + 'usage-of-activation-functions'), + ('Convolution', 3, None, 'convolution'), + ('Layers', 3, None, 'layers'), + ('Convolution2DLayer: convolution in a hidden layer', + 3, + None, + 'convolution2dlayer-convolution-in-a-hidden-layer'), + ('Backpropagation in the convolutional layer', + 3, + None, + 'backpropagation-in-the-convolutional-layer'), + ('Demonstration', 3, None, 'demonstration'), + ('Pooling Layer', 3, None, 'pooling-layer'), + ('Flattening Layer', 3, None, 'flattening-layer'), + ('Fully Connected Layers', 3, None, 'fully-connected-layers'), + ('Optimized Convolution2DLayer', + 3, + None, + 'optimized-convolution2dlayer'), + ('The Convolutional Neural Network (CNN)', + 3, + None, + 'the-convolutional-neural-network-cnn'), + ('Usage of CNN code', 3, None, 'usage-of-cnn-code'), + ('Additional Remarks', 3, None, 'additional-remarks'), + ('Remarks on the speed', 3, None, 'remarks-on-the-speed'), + ('Convolution using separable kernels', + 3, + None, + 'convolution-using-separable-kernels'), + ('Convolution in the Fourier domain', + 3, + None, + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -174,50 +221,73 @@ MathJax.Hub.Config({ @@ -287,6 +357,7 @@ model.summary()
  • 43
  • 44
  • 45
  • +
  • 46
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs043.html b/doc/pub/week44/html/._week44-bs043.html index 34ecf1da5..f7ecf84bc 100644 --- a/doc/pub/week44/html/._week44-bs043.html +++ b/doc/pub/week44/html/._week44-bs043.html @@ -139,7 +139,54 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Finally, evaluate the model', 2, None, - 'finally-evaluate-the-model')]} + 'finally-evaluate-the-model'), + ('Building our own CNN code', + 2, + None, + 'building-our-own-cnn-code'), + ('List of contents:', 3, None, 'list-of-contents'), + ('Schedulers', 3, None, 'schedulers'), + ('Usage of schedulers', 3, None, 'usage-of-schedulers'), + ('Cost functions', 3, None, 'cost-functions'), + ('Usage of cost functions', 3, None, 'usage-of-cost-functions'), + ('Activation functions', 3, None, 'activation-functions'), + ('Usage of activation functions', + 3, + None, + 'usage-of-activation-functions'), + ('Convolution', 3, None, 'convolution'), + ('Layers', 3, None, 'layers'), + ('Convolution2DLayer: convolution in a hidden layer', + 3, + None, + 'convolution2dlayer-convolution-in-a-hidden-layer'), + ('Backpropagation in the convolutional layer', + 3, + None, + 'backpropagation-in-the-convolutional-layer'), + ('Demonstration', 3, None, 'demonstration'), + ('Pooling Layer', 3, None, 'pooling-layer'), + ('Flattening Layer', 3, None, 'flattening-layer'), + ('Fully Connected Layers', 3, None, 'fully-connected-layers'), + ('Optimized Convolution2DLayer', + 3, + None, + 'optimized-convolution2dlayer'), + ('The Convolutional Neural Network (CNN)', + 3, + None, + 'the-convolutional-neural-network-cnn'), + ('Usage of CNN code', 3, None, 'usage-of-cnn-code'), + ('Additional Remarks', 3, None, 'additional-remarks'), + ('Remarks on the speed', 3, None, 'remarks-on-the-speed'), + ('Convolution using separable kernels', + 3, + None, + 'convolution-using-separable-kernels'), + ('Convolution in the Fourier domain', + 3, + None, + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -174,50 +221,73 @@ MathJax.Hub.Config({ @@ -276,6 +346,7 @@ history = model
  • 43
  • 44
  • 45
  • +
  • 46
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs044.html b/doc/pub/week44/html/._week44-bs044.html index 43c2594c8..4f30a03c4 100644 --- a/doc/pub/week44/html/._week44-bs044.html +++ b/doc/pub/week44/html/._week44-bs044.html @@ -139,7 +139,54 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Finally, evaluate the model', 2, None, - 'finally-evaluate-the-model')]} + 'finally-evaluate-the-model'), + ('Building our own CNN code', + 2, + None, + 'building-our-own-cnn-code'), + ('List of contents:', 3, None, 'list-of-contents'), + ('Schedulers', 3, None, 'schedulers'), + ('Usage of schedulers', 3, None, 'usage-of-schedulers'), + ('Cost functions', 3, None, 'cost-functions'), + ('Usage of cost functions', 3, None, 'usage-of-cost-functions'), + ('Activation functions', 3, None, 'activation-functions'), + ('Usage of activation functions', + 3, + None, + 'usage-of-activation-functions'), + ('Convolution', 3, None, 'convolution'), + ('Layers', 3, None, 'layers'), + ('Convolution2DLayer: convolution in a hidden layer', + 3, + None, + 'convolution2dlayer-convolution-in-a-hidden-layer'), + ('Backpropagation in the convolutional layer', + 3, + None, + 'backpropagation-in-the-convolutional-layer'), + ('Demonstration', 3, None, 'demonstration'), + ('Pooling Layer', 3, None, 'pooling-layer'), + ('Flattening Layer', 3, None, 'flattening-layer'), + ('Fully Connected Layers', 3, None, 'fully-connected-layers'), + ('Optimized Convolution2DLayer', + 3, + None, + 'optimized-convolution2dlayer'), + ('The Convolutional Neural Network (CNN)', + 3, + None, + 'the-convolutional-neural-network-cnn'), + ('Usage of CNN code', 3, None, 'usage-of-cnn-code'), + ('Additional Remarks', 3, None, 'additional-remarks'), + ('Remarks on the speed', 3, None, 'remarks-on-the-speed'), + ('Convolution using separable kernels', + 3, + None, + 'convolution-using-separable-kernels'), + ('Convolution in the Fourier domain', + 3, + None, + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -174,50 +221,73 @@ MathJax.Hub.Config({ @@ -279,6 +349,8 @@ test_loss, test_acc = model43
  • 44
  • 45
  • +
  • 46
  • +
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs045.html b/doc/pub/week44/html/._week44-bs045.html index 5dba2a415..123d42e68 100644 --- a/doc/pub/week44/html/._week44-bs045.html +++ b/doc/pub/week44/html/._week44-bs045.html @@ -8,8 +8,8 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d - -Week 44: Decision Trees, Ensemble methods and Random Forests + +Week 44, Convolutional Neural Networks (CNN) @@ -36,191 +36,157 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d @@ -248,78 +214,80 @@ MathJax.Hub.Config({ - Week 44: Decision Trees, Ensemble methods and Random Forests + Week 44, Convolutional Neural Networks (CNN) +
    +
    +
    +
    +
    +
    +
    +
    + +

    Usage of schedulers

    + +

    To initalize a scheduler, simply create the object and pass in the necessary parameters such as the learning rate and the momentum as shown below. As the Scheduler class is an abstract class it should not called directly, and will raise an error upon usage.

    + + + +
    +
    +
    +
    +
    +
    momentum_scheduler = Momentum(eta=1e-3, momentum=0.9)
    +adam_scheduler = Adam(eta=1e-3, rho=0.9, rho2=0.999)
     
    @@ -392,7 +529,3030 @@ DATA_ID = "
    +

    Here is a small example for how a segment of code using schedulers could look. Switching out the schedulers is simple.

    + + +
    +
    +
    +
    +
    +
    weights = np.ones((3,3))
    +print(f"Before scheduler:\n{weights=}")
    +
    +epochs = 10
    +for e in range(epochs):
    +    gradient = np.random.rand(3, 3)
    +    change = adam_scheduler.update_change(gradient)
    +    weights = weights - change
    +    adam_scheduler.reset()
    +
    +print(f"\nAfter scheduler:\n{weights=}")
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    Cost functions

    + +

    In this section we will quickly look at cost functions that can be +used when creating the neural network. Every cost function takes the +target vector as its parameter, and returns a function valued only at +X such that it may easily be differentiated. +

    + + + +
    +
    +
    +
    +
    +
    def CostOLS(target):
    +    """
    +    Return OLS function valued only at X, so
    +    that it may be easily differentiated
    +    """
    +
    +    def func(X):
    +        return (1.0 / target.shape[0]) * np.sum((target - X) ** 2)
    +
    +    return func
    +
    +
    +def CostLogReg(target):
    +    """
    +    Return Logistic Regression cost function
    +    valued only at X, so that it may be easily differentiated
    +    """
    +
    +    def func(X):
    +        return -(1.0 / target.shape[0]) * np.sum(
    +            (target * np.log(X + 10e-10)) + ((1 - target) * np.log(1 - X + 10e-10))
    +        )
    +
    +    return func
    +
    +
    +def CostCrossEntropy(target):
    +    """
    +    Return cross entropy cost function valued only at X, so
    +    that it may be easily differentiated
    +    """
    +    
    +    def func(X):
    +        return -(1.0 / target.size) * np.sum(target * np.log(X + 10e-10))
    +
    +    return func
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    Usage of cost functions

    + +

    Below we will provide a short example of how these cost function may +be used to obtain results if you wish to test them out on your own +using AutoGrad's automatic differentiation. +

    + + + +
    +
    +
    +
    +
    +
    from autograd import grad
    +
    +target = np.array([[1, 2, 3]]).T
    +a = np.array([[4, 5, 6]]).T
    +
    +cost_func = CostCrossEntropy
    +cost_func_derivative = grad(cost_func(target))
    +
    +valued_at_a = cost_func_derivative(a)
    +print(f"Derivative of cost function {cost_func.__name__} valued at a:\n{valued_at_a}")
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    Activation functions

    + +

    Finally, before we look at the layers that make up the neural network, +we will look at the activation functions which can be specified +between the hidden layers and as the output function. Each function +can be valued for any given vector or matrix X, and can be +differentiated via derivate(). +

    + + + +
    +
    +
    +
    +
    +
    import autograd.numpy as np
    +from autograd import elementwise_grad
    +
    +def identity(X):
    +    return X
    +
    +
    +def sigmoid(X):
    +    try:
    +        return 1.0 / (1 + np.exp(-X))
    +    except FloatingPointError:
    +        return np.where(X > np.zeros(X.shape), np.ones(X.shape), np.zeros(X.shape))
    +
    +
    +def softmax(X):
    +    X = X - np.max(X, axis=-1, keepdims=True)
    +    delta = 10e-10
    +    return np.exp(X) / (np.sum(np.exp(X), axis=-1, keepdims=True) + delta)
    +
    +
    +def RELU(X):
    +    return np.where(X > np.zeros(X.shape), X, np.zeros(X.shape))
    +
    +
    +def LRELU(X):
    +    delta = 10e-4
    +    return np.where(X > np.zeros(X.shape), X, delta * X)
    +
    +
    +def derivate(func):
    +    if func.__name__ == "RELU":
    +
    +        def func(X):
    +            return np.where(X > 0, 1, 0)
    +
    +        return func
    +
    +    elif func.__name__ == "LRELU":
    +
    +        def func(X):
    +            delta = 10e-4
    +            return np.where(X > 0, 1, delta)
    +
    +        return func
    +
    +    else:
    +        return elementwise_grad(func)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    Usage of activation functions

    + +

    Below we present a short demonstration of how to use an activation +function. The derivative of the activation function will be important +when calculating the output delta term during backpropagation. Note +that derivate() can also be used for cost functions for a more +generalized approach. +

    + + + +
    +
    +
    +
    +
    +
    z = np.array([[4, 5, 6]]).T
    +print(f"Input to activation function:\n{z}")
    +
    +act_func = sigmoid
    +a = act_func(z)
    +print(f"\nOutput from {act_func.__name__} activation function:\n{a}")
    +
    +act_func_derivative = derivate(act_func)
    +valued_at_z = act_func_derivative(a)
    +print(f"\nDerivative of {act_func.__name__} activation function valued at z:\n{valued_at_z}")
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    Convolution

    + +

    In order to construct a convolutional neural network (CNN), it is +crucial to comprehend the fundamental principles of convolution and +how it aids in extracting information from images. Convolution, at its +core, is merely a mathematical operation between two functions that +yields another function. It is represented by an integral between two +functions, which is typically expressed as: +

    + +$$ +(f \ast g)(t):=\int_{-\infty}^{\infty} f(\tau) g(t-\tau) d \tau. +$$ + +

    Here, f and g are the two functions on which we want to perform an +operation. The outcome of the convolution operation is represented by +\( (f \ast g) \), and it is derived by sliding the function g over f and +computing the integral of their product at each position. If both +functions are continuous, convolution takes the form shown +above. However, if we discretize both f and g, the convolution +operation will take the form of a sum between the elements of f and g: +

    +$$ +(f \ast g)[n]=\sum_{m=0}^{n-1} f[m] g[n-m]. +$$ + +

    The key idea we utilize to extract the information contained in an +image is to slide an \( m \times n \) matrix g over an \( m \times n \) +matrix f. In our case, f represents the image, while g +represents the kernel, oftentimes called a filter. However, since our +convolution will be a two-dimensional variant, we need to extend our +mathematical formula with an additional summation: +

    + +$$ +(f \ast g)[i, j]\sum_{m=0}^{M-1}\sum_{n=0}^{N-1} f[m,n] g[i-m, j-n]. +$$ + +

    It is imperative to note that the size of the kernel g is +significantly smaller than the size of the input image f, thereby +reducing the amount of computation necessary for feature +extraction. Furthermore, the kernel is usually a trainable parameter +in a convolutional neural network, allowing the network to learn +appropriate kernels for specific tasks. +

    + +

    To give you an example of how 2D convolution works in practice, +suppose we have an image f of dimension \( 6 \times 6 \) +

    + +$$ +f = \begin{bmatrix} +4 & 1 & 2 & 9 & 8 & 6 \\ +9 & 5 & 9 & 5 & 8 & 5 \\ +1 & 5 & 9 & 7 & 6 & 4 \\ +2 & 9 & 8 & 3 & 7 & 1 \\ +8 & 1 & 6 & 4 & 2 & 2 \\ +1 & 0 & 5 & 7 & 8 & 2 \\ +\end{bmatrix} +$$ + +

    and a \( 3 \times 3 \) kernel g called a low-pass filter. Note that the +kernel is usually rotated by 180 degrees during convolution, however +this has no effect on this kernel. +

    + +$$ +g = \frac{1}{9} +\begin{bmatrix} +1 & 1 & 1 \\ +1 & 1 & 1 \\ +1 & 1 & 1 \\ +\end{bmatrix} +$$ + +

    In order to filter the image, we have to extract a \( 3 \times 3 \) +element from the upper left corner of f, and perform element-wise +multiplication of the extracted image pixels with the elements of the +kernel g: +

    + +$$ +\begin{bmatrix} +4 & 1 & 2 \\ +9 & 5 & 9 \\ +1 & 5 & 9 \\ +\end{bmatrix} +\cdot +\begin{bmatrix} +\frac{1}{9} & \frac{1}{9} & \frac{1}{9} \\ +\frac{1}{9} & \frac{1}{9} & \frac{1}{9} \\ +\frac{1}{9} & \frac{1}{9} & \frac{1}{9} \\ +\end{bmatrix} += +\begin{bmatrix} +\frac{4}{9} & \frac{1}{9} & \frac{2}{9} \\ +\frac{9}{9} & \frac{5}{9} & \frac{9}{9} \\ +\frac{1}{9} & \frac{5}{9} & \frac{9}{9} \\ +\end {bmatrix} += \textbf{A} +$$ + +

    Then, following the multiplication, we summarize all the elements of the resulting matrix A:

    + +$$ +(f \ast g)[0, 0]= \sum_{i=0}^{2} \sum_{j=0}^{2} a_{i,j} = 5 +$$ + +

    Which corresponds to the first element of the filtered image \( (f \ast g) \).

    + +

    Here we use a stride of 1, a parameter denoted s which describes how +many indexes we move the kernel g to the right before repeating the +calculations above for the next \( 3 \times 3 \) element of the image +f. It is usually presumed that *s*=1, however, larger values for s +can be used to reduce the dimentionality of the filtered image such +that the convolution operation is more computationally efficient. In +the context of a convolutional neural network, this will become very +useful. +

    + +

    The full result of the convolution is:

    + +$$ +(f \ast g) = +\begin{bmatrix} +5 & 5.78 & 7 & 6.44 \\ +6.33 & 6.67 & 6.89 & 5.11 \\ +5.44 & 5.78 & 5.78 & 4 \\ +4.44 & 4.78 & 5.56 & 4 \\ +\end{bmatrix} +$$ + +

    The result is markedly smaller in shape than the original image. This occurs when using convolution without first padding the image with additional columns and rows, allowing us to keep the original image shape after sliding the kernel over the image. +How many rows and columns we wish to pad the image with depends strictly on the shape of the kernel, as we wish to pad the image with r additional rows and c additional columns. +

    + +$$ +r =\lfloor \frac{kernel\ height}{2} \rfloor \cdot 2 \\ +c =\lfloor \frac{kernel\ width}{2} \rfloor \cdot 2 +$$ + +

    Note the notation \( \lfloor \frac{kernel width}{2} \rfloor \) means that +we floor the result of the division, meaning we round down to a whole +number in case \( \frac{kernel width}{2} \) results in a floating point +number. +

    + +

    Using those simple equations, we find out by how much we have to +extend the dimensions of the original image. Before proceeding, +however, we might ask what we shall fill the additional rows and +columns with? One of the most common approaches to padding is +zero-padding, which as the name suggest, involves filling the rows and +columns with zeros. This is the approach that we will be using for +this demonstration. If we apply this padding to out original \( 6 \times 6 \) +image, the result will be an \( 8 \times 8 \) image as the kernel has a width and +height of 3. Note that the original image is encapsuled by the +zero-padded rows and columns: +

    + +$$ +\begin{bmatrix} +0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ +0 & 4 & 1 & 2 & 9 & 8 & 6 & 0 \\ +0 & 9 & 5 & 9 & 5 & 8 & 5 & 0 \\ +0 & 1 & 5 & 9 & 7 & 6 & 4 & 0 \\ +0 & 2 & 9 & 8 & 3 & 7 & 1 & 0 \\ +0 & 8 & 1 & 6 & 4 & 2 & 2 & 0 \\ +0 & 1 & 0 & 5 & 7 & 8 & 2 & 0 \\ +0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ +\] +\end{bmatrix} +$$ + +

    Below we have provided code that demonstrates padding and convolution. As you will see when we run the code, the size of the image will remain unchanged when using padding. 

    + + + +
    +
    +
    +
    +
    +
    import numpy as np
    +
    +def padding(image, kernel):
    +    # calculate r and c
    +    r = (kernel.shape[0] // 2) * 2
    +    c = (kernel.shape[1] // 2) * 2
    +    
    +    # padded image dimensions
    +    padded_height = image.shape[0] + r
    +    padded_width = image.shape[1] + c
    +    
    +    # for more readable code
    +    k_half_height = kernel.shape[0] // 2
    +    k_half_width = kernel.shape[1] // 2
    +
    +    # zero matrix with padded dimensions
    +    padded_img = np.zeros((padded_height, padded_width))
    +
    +    # place image into zero matrix
    +    padded_img[k_half_height : padded_height - k_half_height,
    +               k_half_width : padded_width - k_half_width] = image[:, :]
    +
    +    return padded_img
    +
    +def convolve(original_image, padded_image, kernel, stride=1):
    +    # rotate kernel by 180 degrees
    +    kernel = np.rot90(np.rot90(kernel))
    +
    +    # note that kernel height // 2 is written as 'm'
    +    # and kernel width // 2 as 'n' in the mathematical notation
    +    m = kernel.shape[0] // 2
    +    n = kernel.shape[1] // 2
    +    
    +    r = (kernel.shape[0] // 2) * 2
    +    c = (kernel.shape[1] // 2) * 2
    +    
    +    # initialize output array
    +    convolved_image = np.zeros(original_image.shape)
    +    image_height = original_image.shape[0]
    +    image_width = original_image.shape[1]
    +
    +    # the convolution
    +    for i in range(m, image_height + m, stride):
    +        for j in range(n, image_width + n, stride):
    +            convolved_image[i-m, j-n] = np.sum(
    +                padded_image[i : i + m, j : j + n]
    +                * kernel
    +            )
    +            
    +    return convolved_image
    +
    +def convolve(image, kernel, stride=1):
    +    for i in range(2):
    +        kernel = np.rot90(kernel)
    +
    +    k_half_height = kernel.shape[0] // 2
    +    k_half_width = kernel.shape[0] // 2
    +
    +    conv_image = np.zeros(image.shape)
    +    pad_image = padding(image, kernel)
    +
    +    for i in range(k_half_height, conv_image.shape[0] + k_half_height, stride):
    +        for j in range(k_half_width, conv_image.shape[1] + k_half_width, stride):
    +            conv_image[i - k_half_height, j - k_half_width] = np.sum(
    +                pad_image[
    +                    i - k_half_height : i + k_half_height + 1, j - k_half_width : j + k_half_width + 1
    +                ]
    +                * kernel
    +            )
    +
    +    return conv_image
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    Fun fact: When filtering images, you will see that convolution involves rotating the kernel by 180 degrees. +However, this is not the case when applying convolution in a CNN, where the same operation not rotated by 180 degrees is called +cross-correlation. +

    + + + +
    +
    +
    +
    +
    +
    original_image = np.array([[4, 1, 2, 9, 8, 6],
    +                 [9, 5, 9, 5, 8, 5],
    +                 [1, 5, 9, 7, 6, 4],
    +                 [2, 9, 8, 3, 7, 1],
    +                 [8, 1, 6, 4, 2, 2],
    +                 [1, 0, 5, 7, 8, 2]])
    +
    +kernel = (1/9)*np.ones((3,3))
    +
    +print(f"{original_image.shape=}")
    +
    +# note that convolve() performs padding
    +convolved_image = convolve(original_image, kernel, stride=1)
    +
    +print(f"{convolved_image.shape=}")
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    As you can see, the resulting image is of the same size as the +original image. To round of our demonstration of convolution, we will +present the results of convolution using commonly used kernels. In a +CNN, the values of the kernels are randomly initialized, and then +learned during training. These kernels will extract information +regarding the picture, such as for example the edge detection filter +demonstrated below extracts the edges present in the picture. Of +course, there is no guarantee that the CNN will learn an edge +detection filter, but this should provide some intuiton as to how the +CNN is able to use kernels to make better predictions than a regular +feed forward neural network. +

    + + + +
    +
    +
    +
    +
    +
    # Now an example using a real image and first a gaussian low-pass filter and then a sobel filter
    +import numpy as np
    +import imageio.v3 as imageio
    +import matplotlib.pyplot as plt
    +import time
    +
    +def generate_gauss_mask(sigma, K=1):
    +    side = np.ceil(1 + 8 * sigma)
    +    y, x = np.mgrid[-side // 2 + 1 : (side // 2) + 1, -side // 2 + 1 : (side // 2) + 1]
    +    ker_coef = K / (2 * np.pi * sigma**2)
    +    g = np.exp(-((x**2 + y**2) / (2.0 * sigma**2)))
    +
    +    return g, ker_coef
    +
    +
    +img_path = "../data/IMG-2167.JPG"
    +image_of_cute_dog = imageio.imread(img_path, mode='L')
    +
    +plt.imshow(image_of_cute_dog, cmap="gray", vmin=0, vmax=255, aspect="auto")
    +plt.title("Original image")
    +plt.show()
    +
    +gauss, kernel = generate_gauss_mask(sigma=6)
    +gauss_kernel = gauss*kernel
    +
    +filtered_image = convolve(image_of_cute_dog, gauss_kernel)
    +plt.imshow(filtered_image, cmap="gray", vmin=0, vmax=255, aspect="auto")
    +plt.title("Result of convolution with gauss kernel (blurring filter)")
    +plt.show()
    +
    +sobel_kernel = np.array([[1, 2, 1],
    +                    [0, 0, 0], 
    +                    [-1, -2, -1]])
    +
    +filtered_image = convolve(image_of_cute_dog, sobel_kernel)
    +
    +plt.imshow(filtered_image, cmap="gray", vmin=0, vmax=255, aspect="auto")
    +plt.title("Result of convolution with sobel kernel (edge detection filter)")
    +plt.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    Layers

    + +

    The code below initialises global variables for readability and +describes the abstract class Layers. This is not important in order to +understand the CNN, but is benefitial for organizing the code neatly. +

    + + + +
    +
    +
    +
    +
    +
    import math
    +import autograd.numpy as np
    +from copy import deepcopy, copy
    +from autograd import grad
    +from typing import Callable
    +
    +# global variables for index readability
    +input_index = 0
    +node_index = 1
    +bias_index = 1
    +input_channel_index = 1
    +feature_maps_index = 1
    +height_index = 2
    +width_index = 3
    +kernel_feature_maps_index = 1
    +kernel_input_channels_index = 0
    +
    +
    +class Layer:
    +    def __init__(self, seed):
    +        self.seed = seed
    +
    +    def _feedforward(self):
    +        raise NotImplementedError
    +
    +    def _backpropagate(self):
    +        raise NotImplementedError
    +
    +    def _reset_weights(self, previous_nodes):
    +        raise NotImplementedError
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    Convolution2DLayer: convolution in a hidden layer

    + +

    After establishing the foundational understanding of applying +convolution to spatial data, let us delve into the intricate workings +of a convolutional layer in a Convolutional Neural Network (CNN). The +primary function of convolution, as previously discussed, is to +extract pertinent information from images while simultaneously +decreasing the scale of our data. To initiate the image processing, we +shall begin by partitioning the images into color channels (unless the +image is grayscale), comprising three primary colors: red, green, and +blue. We will subsequently utilize trainable kernels to construct a +higher-dimensional encoding of each channel called feature +maps. Successive layers will receive these feature maps as inputs, +generating further encodings, albeit with reduced dimensions. The term +trainable kernels denotes the initialization of pre-defined +kernel-shaped weights, which we will then train via backpropagation, +similar to how weights are trained in a Feedforward Neural Network. +

    + +

    To ensure seamless integration between our implementation of the +convolutional layer and popular machine learning frameworks like +Tensorflow (Keras) and PyTorch, we have adopted a design pattern that +mirrors the construction of models using these APIs. This involves +implementing our convolutional layer as a Python class or object, +which allows for a more modular and flexible approach to building +neural networks. By structuring our code in this way, users can easily +incorporate our implementation into their existing machine learning +pipelines without having to make significant changes to their +codebase. Additionally, this design pattern promotes code reusability +and makes it easier to maintain and update our convolutional layer +implementation over time. +

    + +

    Note that the Convolution2DLayer takes in an activation function as a parameter, as it also performs non-linearity.

    + + + +
    +
    +
    +
    +
    +
    class Convolution2DLayer(Layer):
    +    def __init__(
    +        self,
    +        input_channels,
    +        feature_maps,
    +        kernel_height,
    +        kernel_width,
    +        v_stride,
    +        h_stride,
    +        pad,
    +        act_func: Callable,
    +        seed=None,
    +        reset_weights_independently=True,
    +    ):
    +        super().__init__(seed)
    +        self.input_channels = input_channels
    +        self.feature_maps = feature_maps
    +        self.kernel_height = kernel_height
    +        self.kernel_width = kernel_width
    +        self.v_stride = v_stride
    +        self.h_stride = h_stride
    +        self.pad = pad
    +        self.act_func = act_func
    +
    +        # such that the layer can be used on its own
    +        # outside of the CNN module
    +        if reset_weights_independently == True:
    +            self._reset_weights_independently()
    +
    +    def _feedforward(self, X_batch):
    +        # note that the shape of X_batch = [inputs, input_maps, img_height, img_width]
    +
    +        # pad the input batch
    +        X_batch_padded = self._padding(X_batch)
    +
    +        # calculate height_index and width_index after stride
    +        strided_height = int(np.ceil(X_batch.shape[height_index] / self.v_stride))
    +        strided_width = int(np.ceil(X_batch.shape[width_index] / self.h_stride))
    +
    +        # create output array
    +        output = np.ndarray(
    +            (
    +                X_batch.shape[input_index],
    +                self.feature_maps,
    +                strided_height,
    +                strided_width,
    +            )
    +        )
    +
    +        # save input and output for backpropagation
    +        self.X_batch_feedforward = X_batch
    +        self.output_shape = output.shape
    +
    +        # checking for errors, no need to look here :)
    +        self._check_for_errors()
    +
    +        # convolve input with kernel
    +        for img in range(X_batch.shape[input_index]):
    +            for chin in range(self.input_channels):
    +                for fmap in range(self.feature_maps):
    +                    out_h = 0
    +                    for h in range(0, X_batch.shape[height_index], self.v_stride):
    +                        out_w = 0
    +                        for w in range(0, X_batch.shape[width_index], self.h_stride):
    +                            output[img, fmap, out_h, out_w] = np.sum(
    +                                X_batch_padded[
    +                                    img,
    +                                    chin,
    +                                    h : h + self.kernel_height,
    +                                    w : w + self.kernel_width,
    +                                ]
    +                                * self.kernel[chin, fmap, :, :]
    +                            )
    +                            out_w += 1
    +                        out_h += 1
    +
    +        # Pay attention to the fact that we're not rotating the kernel by 180 degrees when filtering the image in
    +        # the convolutional layer, as convolution in terms of Machine Learning is a procedure known as cross-correlation
    +        # in image processing and signal processing
    +
    +        # return a
    +        return self.act_func(output / (self.kernel_height))
    +
    +    def _backpropagate(self, delta_term_next):
    +        # intiate matrices
    +        delta_term = np.zeros((self.X_batch_feedforward.shape))
    +        gradient_kernel = np.zeros((self.kernel.shape))
    +
    +        # pad input for convolution
    +        X_batch_padded = self._padding(self.X_batch_feedforward)
    +
    +        # Since an activation function is used at the output of the convolution layer, its derivative
    +        # has to be accounted for in the backpropagation -> as if ReLU was a layer on its own.
    +        act_derivative = derivate(self.act_func)
    +        delta_term_next = act_derivative(delta_term_next)
    +
    +        # fill in 0's for values removed by vertical stride in feedforward
    +        if self.v_stride > 1:
    +            v_ind = 1
    +            for i in range(delta_term_next.shape[height_index]):
    +                for j in range(self.v_stride - 1):
    +                    delta_term_next = np.insert(
    +                        delta_term_next, v_ind, 0, axis=height_index
    +                    )
    +                v_ind += self.v_stride
    +
    +        # fill in 0's for values removed by horizontal stride in feedforward
    +        if self.h_stride > 1:
    +            h_ind = 1
    +            for i in range(delta_term_next.shape[width_index]):
    +                for k in range(self.h_stride - 1):
    +                    delta_term_next = np.insert(
    +                        delta_term_next, h_ind, 0, axis=width_index
    +                    )
    +                h_ind += self.h_stride
    +
    +        # crops out 0-rows and 0-columns
    +        delta_term_next = delta_term_next[
    +            :,
    +            :,
    +            : self.X_batch_feedforward.shape[height_index],
    +            : self.X_batch_feedforward.shape[width_index],
    +        ]
    +
    +        # the gradient received from the next layer also needs to be padded
    +        delta_term_next = self._padding(delta_term_next)
    +
    +        # calculate delta term by convolving next delta term with kernel
    +        for img in range(self.X_batch_feedforward.shape[input_index]):
    +            for chin in range(self.input_channels):
    +                for fmap in range(self.feature_maps):
    +                    for h in range(self.X_batch_feedforward.shape[height_index]):
    +                        for w in range(self.X_batch_feedforward.shape[width_index]):
    +                            delta_term[img, chin, h, w] = np.sum(
    +                                delta_term_next[
    +                                    img,
    +                                    fmap,
    +                                    h : h + self.kernel_height,
    +                                    w : w + self.kernel_width,
    +                                ]
    +                                * np.rot90(np.rot90(self.kernel[chin, fmap, :, :]))
    +                            )
    +
    +        # calculate gradient for kernel for weight update
    +        # also via convolution
    +        for chin in range(self.input_channels):
    +            for fmap in range(self.feature_maps):
    +                for k_x in range(self.kernel_height):
    +                    for k_y in range(self.kernel_width):
    +                        gradient_kernel[chin, fmap, k_x, k_y] = np.sum(
    +                            X_batch_padded[
    +                                img,
    +                                chin,
    +                                h : h + self.kernel_height,
    +                                w : w + self.kernel_width,
    +                            ]
    +                            * delta_term_next[
    +                                img,
    +                                fmap,
    +                                h : h + self.kernel_height,
    +                                w : w + self.kernel_width,
    +                            ]
    +                        )
    +        # all kernels are updated with weight gradient of kernel
    +        self.kernel -= gradient_kernel
    +
    +        # return delta term
    +        return delta_term
    +
    +    def _padding(self, X_batch, batch_type="image"):
    +
    +        # same padding for images
    +        if self.pad == "same" and batch_type == "image":
    +            padded_height = X_batch.shape[height_index] + (self.kernel_height // 2) * 2
    +            padded_width = X_batch.shape[width_index] + (self.kernel_width // 2) * 2
    +            half_kernel_height = self.kernel_height // 2
    +            half_kernel_width = self.kernel_width // 2
    +
    +            # initialize padded array
    +            X_batch_padded = np.ndarray(
    +                (
    +                    X_batch.shape[input_index],
    +                    X_batch.shape[feature_maps_index],
    +                    padded_height,
    +                    padded_width,
    +                )
    +            )
    +
    +            # zero pad all images in X_batch
    +            for img in range(X_batch.shape[input_index]):
    +                padded_img = np.zeros(
    +                    (X_batch.shape[feature_maps_index], padded_height, padded_width)
    +                )
    +                padded_img[
    +                    :,
    +                    half_kernel_height : padded_height - half_kernel_height,
    +                    half_kernel_width : padded_width - half_kernel_width,
    +                ] = X_batch[img, :, :, :]
    +                X_batch_padded[img, :, :, :] = padded_img[:, :, :]
    +
    +            return X_batch_padded
    +
    +        # same padding for gradients
    +        elif self.pad == "same" and batch_type == "grad":
    +            padded_height = X_batch.shape[height_index] + (self.kernel_height // 2) * 2
    +            padded_width = X_batch.shape[width_index] + (self.kernel_width // 2) * 2
    +            half_kernel_height = self.kernel_height // 2
    +            half_kernel_width = self.kernel_width // 2
    +
    +            # initialize padded array
    +            delta_term_padded = np.zeros(
    +                (
    +                    X_batch.shape[input_index],
    +                    X_batch.shape[feature_maps_index],
    +                    padded_height,
    +                    padded_width,
    +                )
    +            )
    +
    +            # zero pad delta term
    +            delta_term_padded[
    +                :, :, : X_batch.shape[height_index], : X_batch.shape[width_index]
    +            ] = X_batch[:, :, :, :]
    +
    +            return delta_term_padded
    +
    +        else:
    +            return X_batch
    +
    +    def _reset_weights_independently(self):
    +        # sets seed to remove randomness inbetween runs
    +        if self.seed is not None:
    +            np.random.seed(self.seed)
    +
    +        # initializes kernel matrix
    +        self.kernel = np.ndarray(
    +            (
    +                self.input_channels,
    +                self.feature_maps,
    +                self.kernel_height,
    +                self.kernel_width,
    +            )
    +        )
    +
    +        # randomly initializes weights
    +        for chin in range(self.kernel.shape[kernel_input_channels_index]):
    +            for fmap in range(self.kernel.shape[kernel_feature_maps_index]):
    +                self.kernel[chin, fmap, :, :] = np.random.rand(
    +                    self.kernel_height, self.kernel_width
    +                )
    +
    +    def _reset_weights(self, previous_nodes):
    +        # sets weights
    +        self._reset_weights_independently()
    +
    +        # returns shape of output used for subsequent layer's weight initiation
    +        strided_height = int(
    +            np.ceil(previous_nodes.shape[height_index] / self.v_stride)
    +        )
    +        strided_width = int(np.ceil(previous_nodes.shape[width_index] / self.h_stride))
    +        next_nodes = np.ones(
    +            (
    +                previous_nodes.shape[input_index],
    +                self.feature_maps,
    +                strided_height,
    +                strided_width,
    +            )
    +        )
    +        return next_nodes / self.kernel_height
    +
    +    def _check_for_errors(self):
    +        if self.X_batch_feedforward.shape[input_channel_index] != self.input_channels:
    +            raise AssertionError(
    +                f"ERROR: Number of input channels in data ({self.X_batch_feedforward.shape[input_channel_index]}) is not equal to input channels in Convolution2DLayerOPT ({self.input_channels})! Please change the number of input channels of the Convolution2DLayer such that they are equal"
    +            )
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    Backpropagation in the convolutional layer

    + +

    As you may have noticed, we have not yet explained how the +backpropagation algorithm works in a convolutional layer. However, +having covered all other major details about convolutional layers, we +are now prepared to do so. It should come as no surprise that the +calculation of delta terms at each convolutional layer takes the form +of convolution. After the gradient has been propagated backwards +through the flattening layer, where it was reshaped into an +appropriate form, calculating the update value for the kernel is +simply a matter of convolving the output gradient with the input of +the layer for which we are updating the weights. For more detail, this +article serves as an excellent resource, see +https://pavisj.medium.com/convolutions-and-backpropagations-46026a8f5d2c +

    +

    Demonstration

    + +

    We can use the convolutional layer above to perform a simple convolution on an image of the now familiar cute dog.

    + + + +
    +
    +
    +
    +
    +
    import numpy as np
    +import imageio.v3 as imageio
    +import matplotlib.pyplot as plt
    +
    +def plot_convolution_result(X, layer):
    +    plt.imshow(X[0, 0, :, :], vmin=0, vmax=255, cmap="gray")
    +    plt.title("Original image")
    +    plt.colorbar()
    +    plt.show()
    +    conv_result = layer._feedforward(X)
    +    plt.title("Result of convolutional layer")
    +    plt.imshow(conv_result[0, 0, :, :], vmin=0, vmax=255, cmap="gray")
    +    plt.colorbar()
    +    plt.show()
    +
    +# create layer
    +layer = Convolution2DLayer(
    +    input_channels=3,
    +    feature_maps=1,
    +    kernel_height=4,
    +    kernel_width=4,
    +    v_stride=2,
    +    h_stride=2,
    +    pad="same",
    +    act_func=identity,
    +    seed=2023,
    +    )
    +
    +# read in image path, make data correct format
    +img_path = img_path = "../data/IMG-2167.JPG"
    +image_of_cute_dog = imageio.imread(img_path)
    +image_shape = image_of_cute_dog.shape
    +image_of_cute_dog = image_of_cute_dog.reshape(1, image_shape[0], image_shape[1], image_shape[2])
    +image_of_cute_dog = image_of_cute_dog.transpose(0, 3, 1, 2)
    +
    +# plot the result of the convolution
    +plot_convolution_result(image_of_cute_dog, layer)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    We cobserve that the result has half the pixels on each axis due to +the fact that we've used a horizontal and vertical stride of 2. The +result of this convolution is not very insightfull, as the kernel has +completely random values for the first feedforward pass. However, as +we perform multiple forward and backward passes, the results of the +convolution should provide identifying features of the image it uses +for classification. +

    + +

    Note that image data usually comes in many different shapes and sizes, +but for our CNN we require the input data be formatted as \[Number of +inputs, input channels, input height, input width\]. Occasionally, the +data you come accross use will be formatted like this, but on many +occasions reshaping and transposing the dimensions is sadly necessary. +

    +

    Pooling Layer

    + +

    The pooling layer is another widely used type of layer in +convolutional neural networks that enables data downsampling to a more +manageable size. Despite recent technological advancements that allow +for convolution without excessive size reduction of the data, the +pooling layer still remains a fundamental component of convolutional +neural networks. It can be used before, after, or in between +convolutional layers, although finding the optimal placement of layers +and network depth requires experimentation to achieve the best +performance for a given problem. The code we provide allows you to +perform two types of pooling known as max pooling and average pooling. +

    + + + +
    +
    +
    +
    +
    +
    class Pooling2DLayer(Layer):
    +    def __init__(
    +        self,
    +        kernel_height,
    +        kernel_width,
    +        v_stride,
    +        h_stride,
    +        pooling="max",
    +        seed=None,
    +    ):
    +        super().__init__(seed)
    +        self.kernel_height = kernel_height
    +        self.kernel_width = kernel_width
    +        self.v_stride = v_stride
    +        self.h_stride = h_stride
    +        self.pooling = pooling
    +
    +    def _feedforward(self, X_batch):
    +        # Saving the input for use in the backwardpass
    +        self.X_batch_feedforward = X_batch
    +
    +        # check if user is silly
    +        self._check_for_errors()
    +
    +        # Computing the size of the feature maps based on kernel size and the stride parameter
    +        strided_height = (
    +            X_batch.shape[height_index] - self.kernel_height
    +        ) // self.v_stride + 1
    +        if X_batch.shape[height_index] == X_batch.shape[width_index]:
    +            strided_width = strided_height
    +        else:
    +            strided_width = (
    +                X_batch.shape[width_index] - self.kernel_width
    +            ) // self.h_stride + 1
    +
    +        # initialize output array
    +        output = np.ndarray(
    +            (
    +                X_batch.shape[input_index],
    +                X_batch.shape[feature_maps_index],
    +                strided_height,
    +                strided_width,
    +            )
    +        )
    +
    +        # select pooling action, either max or average pooling
    +        if self.pooling == "max":
    +            self.pooling_action = np.max
    +        elif self.pooling == "average":
    +            self.pooling_action = np.mean
    +
    +        # pool based on kernel size and stride
    +        for img in range(output.shape[input_index]):
    +            for fmap in range(output.shape[feature_maps_index]):
    +                for h in range(strided_height):
    +                    for w in range(strided_width):
    +                        output[img, fmap, h, w] = self.pooling_action(
    +                            X_batch[
    +                                img,
    +                                fmap,
    +                                (h * self.v_stride) : (h * self.v_stride)
    +                                + self.kernel_height,
    +                                (w * self.h_stride) : (w * self.h_stride)
    +                                + self.kernel_width,
    +                            ]
    +                        )
    +
    +        # output for feedforward in next layer
    +        return output
    +
    +    def _backpropagate(self, delta_term_next):
    +        # initiate delta term array
    +        delta_term = np.zeros((self.X_batch_feedforward.shape))
    +
    +        for img in range(delta_term_next.shape[input_index]):
    +            for fmap in range(delta_term_next.shape[feature_maps_index]):
    +                for h in range(0, delta_term_next.shape[height_index], self.v_stride):
    +                    for w in range(
    +                        0, delta_term_next.shape[width_index], self.h_stride
    +                    ):
    +                        # max pooling
    +                        if self.pooling == "max":
    +                            # get window
    +                            window = self.X_batch_feedforward[
    +                                img,
    +                                fmap,
    +                                h : h + self.kernel_height,
    +                                w : w + self.kernel_width,
    +                            ]
    +
    +                            # find max values indices in window
    +                            max_h, max_w = np.unravel_index(
    +                                window.argmax(), window.shape
    +                            )
    +
    +                            # set values in new, upsampled delta term
    +                            delta_term[
    +                                img,
    +                                fmap,
    +                                (h + max_h),
    +                                (w + max_w),
    +                            ] += delta_term_next[img, fmap, h, w]
    +
    +                        # average pooling
    +                        if self.pooling == "average":
    +                            delta_term[
    +                                img,
    +                                fmap,
    +                                h : h + self.kernel_height,
    +                                w : w + self.kernel_width,
    +                            ] = (
    +                                delta_term_next[img, fmap, h, w]
    +                                / self.kernel_height
    +                                / self.kernel_width
    +                            )
    +        # returns input to backpropagation in previous layer
    +        return delta_term
    +
    +    def _reset_weights(self, previous_nodes):
    +        # calculate strided height, strided width
    +        strided_height = (
    +            previous_nodes.shape[height_index] - self.kernel_height
    +        ) // self.v_stride + 1
    +        if previous_nodes.shape[height_index] == previous_nodes.shape[width_index]:
    +            strided_width = strided_height
    +        else:
    +            strided_width = (
    +                previous_nodes.shape[width_index] - self.kernel_width
    +            ) // self.h_stride + 1
    +
    +        # initiate output array
    +        output = np.ones(
    +            (
    +                previous_nodes.shape[input_index],
    +                previous_nodes.shape[feature_maps_index],
    +                strided_height,
    +                strided_width,
    +            )
    +        )
    +
    +        # returns output with shape used for reset weights in next layer
    +        return output
    +
    +    def _check_for_errors(self):
    +        # check if input is smaller than kernel size -> error
    +        assert (
    +            self.X_batch_feedforward.shape[width_index] >= self.kernel_width
    +        ), f"ERROR: Pooling kernel width_index ({self.kernel_width}) larger than data width_index ({self.X_batch_feedforward.input.shape[2]}), please lower the kernel width_index of the Pooling2DLayer"
    +        assert (
    +            self.X_batch_feedforward.shape[height_index] >= self.kernel_height
    +        ), f"ERROR: Pooling kernel height_index ({self.kernel_height}) larger than data height_index ({self.X_batch_feedforward.input.shape[3]}), please lower the kernel height_index of the Pooling2DLayer"
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    Flattening Layer

    + +

    Before we can begin building our first CNN model, we need to introduce +the flattening layer. As its name suggests, the flattening layer +transforms the data into a one-dimensional vector that can be fed into +the feedforward layers of our network. This layer plays a crucial role +in preparing the data for further processing in the +network. Additionally, the flattening layer is responsible for +reshaping the gradient to the proper shape during +backpropagation. This ensures that the kernels are correctly updated, +allowing for effective learning in the network. +

    + + + +
    +
    +
    +
    +
    +
    class FlattenLayer(Layer):
    +    def __init__(self, act_func=LRELU, seed=None):
    +        super().__init__(seed)
    +        self.act_func = act_func
    +
    +    def _feedforward(self, X_batch):
    +        # save input for backpropagation
    +        self.X_batch_feedforward_shape = X_batch.shape
    +        # Remember, the data has the following shape: (I, FM, H, W, ) in the convolutional layers
    +        # whilst the data has the shape (I, FM * H * W) in the fully connected layers
    +        # I = Inputs, FM = Feature Maps, H = Height and W = Width.
    +        X_batch = X_batch.reshape(
    +            X_batch.shape[input_index],
    +            X_batch.shape[feature_maps_index]
    +            * X_batch.shape[height_index]
    +            * X_batch.shape[width_index],
    +        )
    +
    +        # add bias to a
    +        self.z_matrix = X_batch
    +        bias = np.ones((X_batch.shape[input_index], 1)) * 0.01
    +        self.a_matrix = np.hstack([bias, X_batch])
    +
    +        # return a, the input to feedforward in next layer
    +        return self.a_matrix
    +
    +    def _backpropagate(self, weights_next, delta_term_next):
    +        activation_derivative = derivate(self.act_func)
    +
    +        # calculate delta term
    +        delta_term = (
    +            weights_next[bias_index:, :] @ delta_term_next.T
    +        ).T * activation_derivative(self.z_matrix)
    +
    +        # FlattenLayer does not update weights
    +        # reshapes delta layer to convolutional layer data format [Input, Feature_Maps, Height, Width]
    +        return delta_term.reshape(self.X_batch_feedforward_shape)
    +
    +    def _reset_weights(self, previous_nodes):
    +        # note that the previous nodes to the FlattenLayer are from the convolutional layers
    +        previous_nodes = previous_nodes.reshape(
    +            previous_nodes.shape[input_index],
    +            previous_nodes.shape[feature_maps_index]
    +            * previous_nodes.shape[height_index]
    +            * previous_nodes.shape[width_index],
    +        )
    +
    +        # return shape used in reset_weights in next layer
    +        return previous_nodes.shape[node_index]
    +
    +    def get_prev_a(self):
    +        return self.a_matrix
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    Fully Connected Layers

    + +

    Finally, the result from the flatten layer will pass to a series of +fully connected layers, which function as a normal feed forward neural +network. The fully connected layers are split into two classes; +FullyConnectedLayer which acts as a hidden layer, and OutputLayer, +which acts as the single output layer at the end of the CNN. If one +wishes to use this codebase to construct a normal feed forward neural +network, it must start with a FlattenLayer due to techincal details +regarding weight intitialization. However many FullyConnectedLayers +can be added to the CNN, and in each layer the amount of nodes, which +activation function and scheduler to use can be specified. In +practice, the scheduler will be specified in the CNN object +initialization, and inherited if no other scheduler is specified. +

    + + + +
    +
    +
    +
    +
    +
    class FullyConnectedLayer(Layer):
    +    # FullyConnectedLayer per default uses LRELU and Adam scheduler
    +    # with an eta of 0.0001, rho of 0.9 and rho2 of 0.999
    +    def __init__(
    +        self,
    +        nodes: int,
    +        act_func: Callable = LRELU,
    +        scheduler: Scheduler = Adam(eta=1e-4, rho=0.9, rho2=0.999),
    +        seed: int = None,
    +    ):
    +        super().__init__(seed)
    +        self.nodes = nodes
    +        self.act_func = act_func
    +        self.scheduler_weight = copy(scheduler)
    +        self.scheduler_bias = copy(scheduler)
    +
    +        # initiate matrices for later
    +        self.weights = None
    +        self.a_matrix = None
    +        self.z_matrix = None
    +
    +    def _feedforward(self, X_batch):
    +        # calculate z
    +        self.z_matrix = X_batch @ self.weights
    +
    +        # calculate a, add bias
    +        bias = np.ones((X_batch.shape[input_index], 1)) * 0.01
    +        self.a_matrix = self.act_func(self.z_matrix)
    +        self.a_matrix = np.hstack([bias, self.a_matrix])
    +
    +        # return a, the input for feedforward in next layer
    +        return self.a_matrix
    +
    +    def _backpropagate(self, weights_next, delta_term_next, a_previous, lam):
    +        # take the derivative of the activation function
    +        activation_derivative = derivate(self.act_func)
    +
    +        # calculate the delta term
    +        delta_term = (
    +            weights_next[bias_index:, :] @ delta_term_next.T
    +        ).T * activation_derivative(self.z_matrix)
    +
    +        # intitiate matrix to store gradient
    +        # note that we exclude the bias term, which we will calculate later
    +        gradient_weights = np.zeros(
    +            (
    +                a_previous.shape[input_index],
    +                a_previous.shape[node_index] - bias_index,
    +                delta_term.shape[node_index],
    +            )
    +        )
    +
    +        # calculate gradient = delta term * previous a
    +        for i in range(len(delta_term)):
    +            gradient_weights[i, :, :] = np.outer(
    +                a_previous[i, bias_index:], delta_term[i, :]
    +            )
    +
    +        # sum the gradient, divide by input_index
    +        gradient_weights = np.mean(gradient_weights, axis=input_index)
    +        # for the bias gradient we do not multiply by previous a
    +        gradient_bias = np.mean(delta_term, axis=input_index).reshape(
    +            1, delta_term.shape[node_index]
    +        )
    +
    +        # regularization term
    +        gradient_weights += self.weights[bias_index:, :] * lam
    +
    +        # send gradients into scheduler
    +        # returns update matrix which will be used to update the weights and bias
    +        update_matrix = np.vstack(
    +            [
    +                self.scheduler_bias.update_change(gradient_bias),
    +                self.scheduler_weight.update_change(gradient_weights),
    +            ]
    +        )
    +
    +        # update weights
    +        self.weights -= update_matrix
    +
    +        # return weights and delta term, input for backpropagation in previous layer
    +        return self.weights, delta_term
    +
    +    def _reset_weights(self, previous_nodes):
    +        # sets seed to remove randomness inbetween runs
    +        if self.seed is not None:
    +            np.random.seed(self.seed)
    +
    +        # add bias, initiate random weights
    +        bias = 1
    +        self.weights = np.random.randn(previous_nodes + bias, self.nodes)
    +
    +        # returns number of nodes, used for reset_weights in next layer
    +        return self.nodes
    +
    +    def _reset_scheduler(self):
    +        # resets scheduler per epoch
    +        self.scheduler_weight.reset()
    +        self.scheduler_bias.reset()
    +
    +    def get_prev_a(self):
    +        # returns a matrix, used in backpropagation
    +        return self.a_matrix
    +
    +
    +class OutputLayer(FullyConnectedLayer):
    +    def __init__(
    +        self,
    +        nodes: int,
    +        output_func: Callable = LRELU,
    +        cost_func: Callable = CostCrossEntropy,
    +        scheduler: Scheduler = Adam(eta=1e-4, rho=0.9, rho2=0.999),
    +        seed: int = None,
    +    ):
    +        super().__init__(nodes, output_func, copy(scheduler), seed)
    +        self.cost_func = cost_func
    +
    +        # initiate matrices for later
    +        self.weights = None
    +        self.a_matrix = None
    +        self.z_matrix = None
    +
    +        # decides if the output layer performs binary or multi-class classification
    +        self._set_pred_format()
    +
    +    def _feedforward(self, X_batch: np.ndarray):
    +        # calculate a, z
    +        # note that bias is not added as this would create an extra output class
    +        self.z_matrix = X_batch @ self.weights
    +        self.a_matrix = self.act_func(self.z_matrix)
    +
    +        # returns prediction
    +        return self.a_matrix
    +
    +    def _backpropagate(self, target, a_previous, lam):
    +        # note that in the OutputLayer the activation function is the output function
    +        activation_derivative = derivate(self.act_func)
    +
    +        # calculate output delta terms
    +        # for multi-class or binary classification
    +        if self.pred_format == "Multi-class":
    +            delta_term = self.a_matrix - target
    +        else:
    +            cost_func_derivative = grad(self.cost_func(target))
    +            delta_term = activation_derivative(self.z_matrix) * cost_func_derivative(
    +                self.a_matrix
    +            )
    +
    +        # intiate matrix that stores gradient
    +        gradient_weights = np.zeros(
    +            (
    +                a_previous.shape[input_index],
    +                a_previous.shape[node_index] - bias_index,
    +                delta_term.shape[node_index],
    +            )
    +        )
    +
    +        # calculate gradient = delta term * previous a
    +        for i in range(len(delta_term)):
    +            gradient_weights[i, :, :] = np.outer(
    +                a_previous[i, bias_index:], delta_term[i, :]
    +            )
    +
    +        # sum the gradient, divide by input_index
    +        gradient_weights = np.mean(gradient_weights, axis=input_index)
    +        # for the bias gradient we do not multiply by previous a
    +        gradient_bias = np.mean(delta_term, axis=input_index).reshape(
    +            1, delta_term.shape[node_index]
    +        )
    +
    +        # regularization term
    +        gradient_weights += self.weights[bias_index:, :] * lam
    +
    +        # send gradients into scheduler
    +        # returns update matrix which will be used to update the weights and bias
    +        update_matrix = np.vstack(
    +            [
    +                self.scheduler_bias.update_change(gradient_bias),
    +                self.scheduler_weight.update_change(gradient_weights),
    +            ]
    +        )
    +
    +        # update weights
    +        self.weights -= update_matrix
    +
    +        # return weights and delta term, input for backpropagation in previous layer
    +        return self.weights, delta_term
    +
    +    def _reset_weights(self, previous_nodes):
    +        # sets seed to remove randomness inbetween runs
    +        if self.seed is not None:
    +            np.random.seed(self.seed)
    +
    +        # add bias, initiate random weights
    +        bias = 1
    +        self.weights = np.random.rand(previous_nodes + bias, self.nodes)
    +
    +        # returns number of nodes, used for reset_weights in next layer
    +        return self.nodes
    +
    +    def _reset_scheduler(self):
    +        # resets scheduler per epoch
    +        self.scheduler_weight.reset()
    +        self.scheduler_bias.reset()
    +
    +    def _set_pred_format(self):
    +        # sets prediction format to either regression, binary or multi-class classification
    +        if self.act_func.__name__ is None or self.act_func.__name__ == "identity":
    +            self.pred_format = "Regression"
    +        elif self.act_func.__name__ == "sigmoid" or self.act_func.__name__ == "tanh":
    +            self.pred_format = "Binary"
    +        else:
    +            self.pred_format = "Multi-class"
    +
    +    def get_pred_format(self):
    +        # returns format of prediction
    +        return self.pred_format
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    Optimized Convolution2DLayer

    + +

    For our CNN, we have also implemented an optimized version of the +Convolution2DLayer, Convolution2DLayerOPT, which runs much faster. See +VII. Remarks for discussion. This layer will per default be used by +the CNN due to its computational advantages, but is much less +readable. We've documented it such that specially interested students +can understand the principles behind it, but it is not recommended to +read. In short, we reshape and transpose parts of the image such that +the convolutional operation can be swapped out for a simple matrix +multiplication. +

    + + + +
    +
    +
    +
    +
    +
    class Convolution2DLayerOPT(Convolution2DLayer):
    +    """
    +    Am optimized version of the convolution layer above which
    +    utilizes an approach of extracting windows of size equivalent
    +    in size to the filter. The convoution is then performed on those
    +    windows instead of a full feature map.
    +    """
    +
    +    def __init__(
    +        self,
    +        input_channels,
    +        feature_maps,
    +        kernel_height,
    +        kernel_width,
    +        v_stride,
    +        h_stride,
    +        pad,
    +        act_func: Callable,
    +        seed=None,
    +        reset_weights_independently=True,
    +    ):
    +        super().__init__(
    +            input_channels,
    +            feature_maps,
    +            kernel_height,
    +            kernel_width,
    +            v_stride,
    +            h_stride,
    +            pad,
    +            act_func,
    +            seed,
    +        )
    +        # true if layer is used outside of CNN
    +        if reset_weights_independently == True:
    +            self._reset_weights_independently()
    +
    +    def _feedforward(self, X_batch):
    +        # The optimized _feedforward method is difficult to understand but computationally more efficient
    +        # for a more "by the book" approach, please look at the _feedforward method of Convolution2DLayer
    +
    +        # save the input for backpropagation
    +        self.X_batch_feedforward = X_batch
    +
    +        # check that there are the correct amount of input channels
    +        self._check_for_errors()
    +
    +        # calculate new shape after stride
    +        strided_height = int(np.ceil(X_batch.shape[height_index] / self.v_stride))
    +        strided_width = int(np.ceil(X_batch.shape[width_index] / self.h_stride))
    +
    +        # get windows of the image for more computationally efficient convolution
    +        # the idea is that we want to align the dimensions that we wish to matrix
    +        # multiply, then use a simple matrix multiplication instead of convolution.
    +        # then, we reshape the size back to its intended shape
    +        windows = self._extract_windows(X_batch)
    +        windows = windows.transpose(1, 0, 2, 3, 4).reshape(
    +            X_batch.shape[input_index],
    +            strided_height * strided_width,
    +            -1,
    +        )
    +
    +        # reshape the kernel for more computationally efficient convolution
    +        kernel = self.kernel
    +        kernel = kernel.transpose(0, 2, 3, 1).reshape(
    +            kernel.shape[kernel_input_channels_index]
    +            * kernel.shape[height_index]
    +            * kernel.shape[width_index],
    +            -1,
    +        )
    +
    +        # use simple matrix calculation to obtain output
    +        output = (
    +            (windows @ kernel)
    +            .reshape(
    +                X_batch.shape[input_index],
    +                strided_height,
    +                strided_width,
    +                -1,
    +            )
    +            .transpose(0, 3, 1, 2)
    +        )
    +
    +        # The output is reshaped and rearranged to appropriate shape
    +        return self.act_func(
    +            output / (self.kernel_height * X_batch.shape[feature_maps_index])
    +        )
    +
    +    def _backpropagate(self, delta_term_next):
    +        # The optimized _backpropagate method is difficult to understand but computationally more efficient
    +        # for a more "by the book" approach, please look at the _backpropagate method of Convolution2DLayer
    +        act_derivative = derivate(self.act_func)
    +        delta_term_next = act_derivative(delta_term_next)
    +
    +        # calculate strided dimensions
    +        strided_height = int(
    +            np.ceil(self.X_batch_feedforward.shape[height_index] / self.v_stride)
    +        )
    +        strided_width = int(
    +            np.ceil(self.X_batch_feedforward.shape[width_index] / self.h_stride)
    +        )
    +
    +        # copy kernel
    +        kernel = self.kernel
    +
    +        # get windows, reshape for matrix multiplication
    +        windows = self._extract_windows(self.X_batch_feedforward, "image").reshape(
    +            self.X_batch_feedforward.shape[input_index]
    +            * strided_height
    +            * strided_width,
    +            -1,
    +        )
    +
    +        # initialize output gradient, reshape and transpose into correct shape
    +        # for matrix multiplication
    +        output_grad_tr = delta_term_next.transpose(0, 2, 3, 1).reshape(
    +            self.X_batch_feedforward.shape[input_index]
    +            * strided_height
    +            * strided_width,
    +            -1,
    +        )
    +
    +        # calculate gradient kernel via simple matrix multiplication and reshaping
    +        gradient_kernel = (
    +            (windows.T @ output_grad_tr)
    +            .reshape(
    +                kernel.shape[kernel_input_channels_index],
    +                kernel.shape[height_index],
    +                kernel.shape[width_index],
    +                kernel.shape[kernel_feature_maps_index],
    +            )
    +            .transpose(0, 3, 1, 2)
    +        )
    +
    +        # for computing the input gradient
    +        windows_out, upsampled_height, upsampled_width = self._extract_windows(
    +            delta_term_next, "grad"
    +        )
    +
    +        # calculate new window dimensions
    +        new_windows_first_dim = (
    +            self.X_batch_feedforward.shape[input_index]
    +            * upsampled_height
    +            * upsampled_width
    +        )
    +        # ceil allows for various asymmetric kernels
    +        new_windows_sec_dim = int(np.ceil(windows_out.size / new_windows_first_dim))
    +
    +        # reshape for matrix multiplication
    +        windows_out = windows_out.transpose(1, 0, 2, 3, 4).reshape(
    +            new_windows_first_dim, new_windows_sec_dim
    +        )
    +
    +        # reshape for matrix multiplication
    +        kernel_reshaped = kernel.reshape(self.input_channels, -1)
    +
    +        # calculating input gradient for next convolutional layer
    +        input_grad = (windows_out @ kernel_reshaped.T).reshape(
    +            self.X_batch_feedforward.shape[input_index],
    +            upsampled_height,
    +            upsampled_width,
    +            kernel.shape[kernel_input_channels_index],
    +        )
    +        input_grad = input_grad.transpose(0, 3, 1, 2)
    +
    +        # Update the weights in the kernel
    +        self.kernel -= gradient_kernel
    +
    +        # Output the gradient to propagate backwards
    +        return input_grad
    +
    +    def _extract_windows(self, X_batch, batch_type="image"):
    +        """
    +        Receives as input the X_batch with shape (inputs, feature_maps, image_height, image_width)
    +        and extract windows of size kernel_height * kernel_width for every image and every feature_map.
    +        It then returns an np.ndarray of shape (image_height * image_width, inputs, feature_maps, kernel_height, kernel_width)
    +        which will be used either to filter the images in feedforward or to calculate the gradient.
    +        """
    +
    +        # initialize list of windows
    +        windows = []
    +
    +        if batch_type == "image":
    +            # pad the images
    +            X_batch_padded = self._padding(X_batch, batch_type="image")
    +            img_height, img_width = X_batch_padded.shape[2:]
    +            # For each location in the image...
    +            for h in range(
    +                0,
    +                X_batch.shape[height_index],
    +                self.v_stride,
    +            ):
    +                for w in range(
    +                    0,
    +                    X_batch.shape[width_index],
    +                    self.h_stride,
    +                ):
    +                    # ...obtain an image patch of the original size (strided)
    +
    +                    # get window
    +                    window = X_batch_padded[
    +                        :,
    +                        :,
    +                        h : h + self.kernel_height,
    +                        w : w + self.kernel_width,
    +                    ]
    +
    +                    # append to list of windows
    +                    windows.append(window)
    +
    +            # return numpy array instead of list
    +            return np.stack(windows)
    +
    +        # In order to be able to perform backprogagation by the method of window extraction,
    +        # here is a modified approach to extracting the windows which allow for the necessary
    +        # upsampling of the gradient in case the on of the stride parameters is larger than one.
    +
    +        if batch_type == "grad":
    +
    +            # In the case of one of the stride parameters being odd, we have to take some
    +            # extra care in calculating the upsampled size of X_batch. We solve this
    +            # by simply flooring the result of dividing stride by 2.
    +            if self.v_stride < 2 or self.v_stride % 2 == 0:
    +                v_stride = 0
    +            else:
    +                v_stride = int(np.floor(self.v_stride / 2))
    +
    +            if self.h_stride < 2 or self.h_stride % 2 == 0:
    +                h_stride = 0
    +            else:
    +                h_stride = int(np.floor(self.h_stride / 2))
    +
    +            upsampled_height = (X_batch.shape[height_index] * self.v_stride) - v_stride
    +            upsampled_width = (X_batch.shape[width_index] * self.h_stride) - h_stride
    +
    +            # When upsampling, we need to insert rows and columns filled with zeros
    +            # into each feature map. How many of those we have to insert is purely
    +            # dependant on the value of stride parameter in the vertical and horizontal
    +            # direction.
    +            if self.v_stride > 1:
    +                v_ind = 1
    +                for i in range(X_batch.shape[height_index]):
    +                    for j in range(self.v_stride - 1):
    +                        X_batch = np.insert(X_batch, v_ind, 0, axis=height_index)
    +                    v_ind += self.v_stride
    +
    +            if self.h_stride > 1:
    +                h_ind = 1
    +                for i in range(X_batch.shape[width_index]):
    +                    for k in range(self.h_stride - 1):
    +                        X_batch = np.insert(X_batch, h_ind, 0, axis=width_index)
    +                    h_ind += self.h_stride
    +
    +            # Since the insertion of zero-filled rows and columns isn't perfect, we have
    +            # to assure that the resulting feature maps will have the expected upsampled height
    +            # and width by cutting them og at desired dimensions.
    +
    +            X_batch = X_batch[:, :, :upsampled_height, :upsampled_width]
    +
    +            X_batch_padded = self._padding(X_batch, batch_type="grad")
    +
    +            # initialize list of windows
    +            windows = []
    +
    +            # For each location in the image...
    +            for h in range(
    +                0,
    +                X_batch.shape[height_index],
    +                self.v_stride,
    +            ):
    +                for w in range(
    +                    0,
    +                    X_batch.shape[width_index],
    +                    self.h_stride,
    +                ):
    +                    # ...obtain an image patch of the original size (strided)
    +
    +                    # get window
    +                    window = X_batch_padded[
    +                        :, :, h : h + self.kernel_height, w : w + self.kernel_width
    +                    ]
    +
    +                    # append window to list
    +                    windows.append(window)
    +
    +            # return numpy array, unsampled dimensions
    +            return np.stack(windows), upsampled_height, upsampled_width
    +
    +    def _check_for_errors(self):
    +        # compares input channels of data to input channels of Convolution2DLayer
    +        if self.X_batch_feedforward.shape[input_channel_index] != self.input_channels:
    +            raise AssertionError(
    +                f"ERROR: Number of input channels in data ({self.X_batch_feedforward.shape[input_channel_index]}) is not equal to input channels in Convolution2DLayerOPT ({self.input_channels})! Please change the number of input channels of the Convolution2DLayer such that they are equal"
    +            )
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    The Convolutional Neural Network (CNN)

    + +

    Finally, we present the code for the CNN. The CNN class organizes all the layers, and allows for training on image data.

    + + + +
    +
    +
    +
    +
    +
    import math
    +import autograd.numpy as np
    +import sys
    +import warnings
    +from autograd import grad, elementwise_grad
    +from random import random, seed
    +from copy import deepcopy
    +from typing import Tuple, Callable
    +from sklearn.utils import resample
    +
    +warnings.simplefilter("error")
    +
    +
    +class CNN:
    +    def __init__(
    +        self,
    +        cost_func: Callable = CostCrossEntropy,
    +        scheduler: Scheduler = Adam(eta=1e-4, rho=0.9, rho2=0.999),
    +        seed: int = None,
    +    ):
    +        """
    +        Description:
    +        ------------
    +            Instantiates CNN object
    +
    +        Parameters:
    +        ------------
    +            I   output_func (costFunctions) cost function for feed forward neural network part of CNN,
    +                such as "CostLogReg", "CostOLS" or "CostCrossEntropy"
    +
    +            II  scheduler (Scheduler) optional parameter, default set to Adam. Can also be set to other
    +                schedulers such as AdaGrad, Momentum, RMS_prop and Constant. Note that schedulers have
    +                to be instantiated first with proper parameters (for example eta, rho and rho2 for Adam)
    +
    +            III seed (int) used for seeding all random operations
    +        """
    +        self.layers = list()
    +        self.cost_func = cost_func
    +        self.scheduler = scheduler
    +        self.schedulers_weight = list()
    +        self.schedulers_bias = list()
    +        self.seed = seed
    +        self.pred_format = None
    +
    +    def add_FullyConnectedLayer(
    +        self, nodes: int, act_func=LRELU, scheduler=None
    +    ) -> None:
    +        """
    +        Description:
    +        ------------
    +            Add a FullyConnectedLayer to the CNN, i.e. a hidden layer in the feed forward neural
    +            network part of the CNN. Often called a Dense layer in literature
    +
    +        Parameters:
    +        ------------
    +            I   nodes (int) number of nodes in FullyConnectedLayer
    +            II  act_func (activationFunctions) activation function of FullyConnectedLayer,
    +                such as "sigmoid", "RELU", "LRELU", "softmax" or "identity"
    +            III scheduler (Scheduler) optional parameter, default set to Adam. Can also be set to other
    +                schedulers such as AdaGrad, Momentum, RMS_prop and Constant
    +        """
    +        assert self.layers, "FullyConnectedLayer should follow FlattenLayer in CNN"
    +
    +        if scheduler is None:
    +            scheduler = self.scheduler
    +
    +        layer = FullyConnectedLayer(nodes, act_func, scheduler, self.seed)
    +        self.layers.append(layer)
    +
    +    def add_OutputLayer(self, nodes: int, output_func=sigmoid, scheduler=None) -> None:
    +        """
    +        Description:
    +        ------------
    +            Add an OutputLayer to the CNN, i.e. a the final layer in the feed forward neural
    +            network part of the CNN
    +
    +        Parameters:
    +        ------------
    +            I   nodes (int) number of nodes in OutputLayer. Set nodes=1 for binary classification and
    +                nodes = number of classes for multi-class classification
    +            II  output_func (activationFunctions) activation function for the output layer, such as
    +                "identity" for regression, "sigmoid" for binary classification and "softmax" for multi-class
    +                classification
    +            III scheduler (Scheduler) optional parameter, default set to Adam. Can also be set to other
    +                schedulers such as AdaGrad, Momentum, RMS_prop and Constant
    +        """
    +        assert self.layers, "OutputLayer should follow FullyConnectedLayer in CNN"
    +
    +        if scheduler is None:
    +            scheduler = self.scheduler
    +
    +        output_layer = OutputLayer(
    +            nodes, output_func, self.cost_func, scheduler, self.seed
    +        )
    +        self.layers.append(output_layer)
    +        self.pred_format = output_layer.get_pred_format()
    +
    +    def add_FlattenLayer(self, act_func=LRELU) -> None:
    +        """
    +        Description:
    +        ------------
    +            Add a FlattenLayer to the CNN, which flattens the image data such that it is formatted to
    +            be used in the feed forward neural network part of the CNN
    +        """
    +        self.layers.append(FlattenLayer(act_func=act_func, seed=self.seed))
    +
    +    def add_Convolution2DLayer(
    +        self,
    +        input_channels=1,
    +        feature_maps=1,
    +        kernel_height=3,
    +        kernel_width=3,
    +        v_stride=1,
    +        h_stride=1,
    +        pad="same",
    +        act_func=LRELU,
    +        optimized=True,
    +    ) -> None:
    +        """
    +        Description:
    +        ------------
    +            Add a Convolution2DLayer to the CNN, i.e. a convolutional layer with a 2 dimensional kernel. Should be
    +            the first layer added to the CNN
    +
    +        Parameters:
    +        ------------
    +            I   input_channels (int) specifies amount of input channels. For monochrome images, use input_channels
    +                = 1, and input_channels = 3 for colored images, where each channel represents one of R, G and B
    +            II  feature_maps (int) amount of feature maps in CNN
    +            III kernel_height (int) height of the kernel, also called 'convolutional filter' in literature
    +            IV  kernel_width (int) width of the kernel, also called 'convolutional filter' in literature
    +            V   v_stride (int) value of vertical stride for dimentionality reduction
    +            VI  h_stride (int) value of horizontal stride for dimentionality reduction
    +            VII pad (str) default = "same" ensures output size is the same as input size (given stride=1)
    +           VIII act_func (activationFunctions) default = "LRELU", nonlinear activation function
    +             IX optimized (bool) default = True, uses Convolution2DLayerOPT if True which is much faster when
    +                compared to Convolution2DLayer, which is a more straightforward, understandable implementation
    +        """
    +        if optimized:
    +            conv_layer = Convolution2DLayerOPT(
    +                input_channels,
    +                feature_maps,
    +                kernel_height,
    +                kernel_width,
    +                v_stride,
    +                h_stride,
    +                pad,
    +                act_func,
    +                self.seed,
    +                reset_weights_independently=False,
    +            )
    +        else:
    +            conv_layer = Convolution2DLayer(
    +                input_channels,
    +                feature_maps,
    +                kernel_height,
    +                kernel_width,
    +                v_stride,
    +                h_stride,
    +                pad,
    +                act_func,
    +                self.seed,
    +                reset_weights_independently=False,
    +            )
    +        self.layers.append(conv_layer)
    +
    +    def add_PoolingLayer(
    +        self, kernel_height=2, kernel_width=2, v_stride=1, h_stride=1, pooling="max"
    +    ) -> None:
    +        """
    +        Description:
    +        ------------
    +            Add a Pooling2DLayer to the CNN, i.e. a pooling layer that reduces the dimentionality of
    +            the image data. It is not necessary to use a Pooling2DLayer when creating a CNN, but it
    +            can be used to speed up the training
    +
    +        Parameters:
    +        ------------
    +            I   kernel_height (int) height of the kernel used for pooling
    +            II  kernel_width (int) width of the kernel used for pooling
    +            III v_stride (int) value of vertical stride for dimentionality reduction
    +            IV  h_stride (int) value of horizontal stride for dimentionality reduction
    +            V   pooling (str) either "max" or "average", describes type of pooling performed
    +        """
    +        pooling_layer = Pooling2DLayer(
    +            kernel_height, kernel_width, v_stride, h_stride, pooling, self.seed
    +        )
    +        self.layers.append(pooling_layer)
    +
    +    def fit(
    +        self,
    +        X: np.ndarray,
    +        t: np.ndarray,
    +        epochs: int = 100,
    +        lam: float = 0,
    +        batches: int = 1,
    +        X_val: np.ndarray = None,
    +        t_val: np.ndarray = None,
    +    ) -> dict:
    +        """
    +        Description:
    +        ------------
    +            Fits the CNN to input X for a given amount of epochs. Performs feedforward and backpropagation passes,
    +            can utilize batches, regulariziation and validation if desired.
    +
    +        Parameters:
    +        ------------
    +            X (numpy array) with input data in format [images, input channels,
    +            image height, image_width]
    +            t (numpy array) target labels for input data
    +            epochs (int) amount of epochs
    +            lam (float) regulariziation term lambda
    +            batches (int) amount of batches input data splits into
    +            X_val (numpy array) validation data
    +            t_val (numpy array) target labels for validation data
    +
    +        Returns:
    +        ------------
    +            scores (dict) a dictionary with "train_error", "train_acc", "val_error", val_acc" keys
    +            that contain numpy arrays with float values of all accuracies/errors over all epochs.
    +            Can be used to create plots. Also used to update the progress bar during training
    +        """
    +
    +        # setup
    +        if self.seed is not None:
    +            np.random.seed(self.seed)
    +
    +        # initialize weights
    +        self._initialize_weights(X)
    +
    +        # create arrays for score metrics
    +        scores = self._initialize_scores(epochs)
    +
    +        assert batches <= t.shape[0]
    +        batch_size = X.shape[0] // batches
    +
    +        try:
    +            for epoch in range(epochs):
    +                for batch in range(batches):
    +                    # minibatch gradient descent
    +                    # If the for loop has reached the last batch, take all thats left
    +                    if batch == batches - 1:
    +                        X_batch = X[batch * batch_size :, :, :, :]
    +                        t_batch = t[batch * batch_size :, :]
    +                    else:
    +                        X_batch = X[
    +                            batch * batch_size : (batch + 1) * batch_size, :, :, :
    +                        ]
    +                        t_batch = t[batch * batch_size : (batch + 1) * batch_size, :]
    +
    +                    self._feedforward(X_batch)
    +                    self._backpropagate(t_batch, lam)
    +
    +                # reset schedulers for each epoch (some schedulers pass in this call)
    +                for layer in self.layers:
    +                    if isinstance(layer, FullyConnectedLayer):
    +                        layer._reset_scheduler()
    +
    +                # computing performance metrics
    +                scores = self._compute_scores(scores, epoch, X, t, X_val, t_val)
    +
    +                # printing progress bar
    +                print_length = self._progress_bar(
    +                    epoch,
    +                    epochs,
    +                    scores,
    +                )
    +        # allows for stopping training at any point and seeing the result
    +        except KeyboardInterrupt:
    +            pass
    +
    +        # visualization of training progression (similiar to tensorflow progression bar)
    +        sys.stdout.write("\r" + " " * print_length)
    +        sys.stdout.flush()
    +        self._progress_bar(
    +            epochs,
    +            epochs,
    +            scores,
    +        )
    +        sys.stdout.write("")
    +
    +        return scores
    +
    +    def _feedforward(self, X_batch) -> np.ndarray:
    +        """
    +        Description:
    +        ------------
    +            Performs the feedforward pass for all layers in the CNN. Called from fit()
    +        """
    +        a = X_batch
    +        for layer in self.layers:
    +            a = layer._feedforward(a)
    +
    +        return a
    +
    +    def _backpropagate(self, t_batch, lam) -> None:
    +        """
    +        Description:
    +        ------------
    +            Performs backpropagation for all layers in the CNN. Called from fit()
    +        """
    +        assert len(self.layers) >= 2
    +        reversed_layers = self.layers[::-1]
    +
    +        # for every layer, backwards
    +        for i in range(len(reversed_layers) - 1):
    +            layer = reversed_layers[i]
    +            prev_layer = reversed_layers[i + 1]
    +
    +            # OutputLayer
    +            if isinstance(layer, OutputLayer):
    +                prev_a = prev_layer.get_prev_a()
    +                weights_next, delta_next = layer._backpropagate(t_batch, prev_a, lam)
    +
    +            # FullyConnectedLayer
    +            elif isinstance(layer, FullyConnectedLayer):
    +                assert (
    +                    delta_next is not None
    +                ), "No OutputLayer to follow FullyConnectedLayer"
    +                assert (
    +                    weights_next is not None
    +                ), "No OutputLayer to follow FullyConnectedLayer"
    +                prev_a = prev_layer.get_prev_a()
    +                weights_next, delta_next = layer._backpropagate(
    +                    weights_next, delta_next, prev_a, lam
    +                )
    +
    +            # FlattenLayer
    +            elif isinstance(layer, FlattenLayer):
    +                assert (
    +                    delta_next is not None
    +                ), "No FullyConnectedLayer to follow FlattenLayer"
    +                assert (
    +                    weights_next is not None
    +                ), "No FullyConnectedLayer to follow FlattenLayer"
    +                delta_next = layer._backpropagate(weights_next, delta_next)
    +
    +            # Convolution2DLayer and Convolution2DLayerOPT
    +            elif isinstance(layer, Convolution2DLayer):
    +                assert (
    +                    delta_next is not None
    +                ), "No FlattenLayer to follow Convolution2DLayer"
    +                delta_next = layer._backpropagate(delta_next)
    +
    +            # Pooling2DLayer
    +            elif isinstance(layer, Pooling2DLayer):
    +                assert delta_next is not None, "No Layer to follow Pooling2DLayer"
    +                delta_next = layer._backpropagate(delta_next)
    +
    +            # Catch error
    +            else:
    +                raise NotImplementedError
    +
    +    def _compute_scores(
    +        self,
    +        scores: dict,
    +        epoch: int,
    +        X: np.ndarray,
    +        t: np.ndarray,
    +        X_val: np.ndarray,
    +        t_val: np.ndarray,
    +    ) -> dict:
    +        """
    +        Description:
    +        ------------
    +            Computes scores such as training error, training accuracy, validation error
    +            and validation accuracy for the CNN depending on if a validation set is used
    +            and if the CNN performs classification or regression
    +
    +        Returns:
    +        ------------
    +            scores (dict) a dictionary with "train_error", "train_acc", "val_error", val_acc" keys
    +            that contain numpy arrays with float values of all accuracies/errors over all epochs.
    +            Can be used to create plots. Also used to update the progress bar during training
    +        """
    +
    +        pred_train = self.predict(X)
    +        cost_function_train = self.cost_func(t)
    +        train_error = cost_function_train(pred_train)
    +        scores["train_error"][epoch] = train_error
    +
    +        if X_val is not None and t_val is not None:
    +            cost_function_val = self.cost_func(t_val)
    +            pred_val = self.predict(X_val)
    +            val_error = cost_function_val(pred_val)
    +            scores["val_error"][epoch] = val_error
    +
    +        if self.pred_format != "Regression":
    +            train_acc = self._accuracy(pred_train, t)
    +            scores["train_acc"][epoch] = train_acc
    +            if X_val is not None and t_val is not None:
    +                val_acc = self._accuracy(pred_val, t_val)
    +                scores["val_acc"][epoch] = val_acc
    +
    +        return scores
    +
    +    def _initialize_scores(self, epochs) -> dict:
    +        """
    +        Description:
    +        ------------
    +            Initializes scores such as training error, training accuracy, validation error
    +            and validation accuracy for the CNN
    +
    +        Returns:
    +        ------------
    +            A dictionary with "train_error", "train_acc", "val_error", val_acc" keys that
    +            will contain numpy arrays with float values of all accuracies/errors over all epochs
    +            when passed through the _compute_scores() function during fit()
    +        """
    +        scores = dict()
    +
    +        train_errors = np.empty(epochs)
    +        train_errors.fill(np.nan)
    +        val_errors = np.empty(epochs)
    +        val_errors.fill(np.nan)
    +
    +        train_accs = np.empty(epochs)
    +        train_accs.fill(np.nan)
    +        val_accs = np.empty(epochs)
    +        val_accs.fill(np.nan)
    +
    +        scores["train_error"] = train_errors
    +        scores["val_error"] = val_errors
    +        scores["train_acc"] = train_accs
    +        scores["val_acc"] = val_accs
    +
    +        return scores
    +
    +    def _initialize_weights(self, X: np.ndarray) -> None:
    +        """
    +        Description:
    +        ------------
    +            Initializes weights for all layers in CNN
    +
    +        Parameters:
    +        ------------
    +            I   X (np.ndarray) input of format [img, feature_maps, height, width]
    +        """
    +        prev_nodes = X
    +        for layer in self.layers:
    +            prev_nodes = layer._reset_weights(prev_nodes)
    +
    +    def predict(self, X: np.ndarray, *, threshold=0.5) -> np.ndarray:
    +        """
    +        Description:
    +        ------------
    +            Predicts output of input X
    +
    +        Parameters:
    +        ------------
    +            I   X (np.ndarray) input [img, feature_maps, height, width]
    +        """
    +
    +        prediction = self._feedforward(X)
    +
    +        if self.pred_format == "Binary":
    +            return np.where(prediction > threshold, 1, 0)
    +        elif self.pred_format == "Multi-class":
    +            class_prediction = np.zeros(prediction.shape)
    +            for i in range(prediction.shape[0]):
    +                class_prediction[i, np.argmax(prediction[i, :])] = 1
    +            return class_prediction
    +        else:
    +            return prediction
    +
    +    def _accuracy(self, prediction: np.ndarray, target: np.ndarray) -> float:
    +        """
    +        Description:
    +        ------------
    +            Calculates accuracy of given prediction to target
    +
    +        Parameters:
    +        ------------
    +            I   prediction (np.ndarray): output of predict() fuction
    +            (1s and 0s in case of classification, and real numbers in case of regression)
    +            II  target (np.ndarray): vector of true values (What the network should predict)
    +
    +        Returns:
    +        ------------
    +            A floating point number representing the percentage of correctly classified instances.
    +        """
    +        assert prediction.size == target.size
    +        return np.average((target == prediction))
    +
    +    def _progress_bar(self, epoch: int, epochs: int, scores: dict) -> int:
    +        """
    +        Description:
    +        ------------
    +            Displays progress of training
    +        """
    +        progression = epoch / epochs
    +        epoch -= 1
    +        print_length = 40
    +        num_equals = int(progression * print_length)
    +        num_not = print_length - num_equals
    +        arrow = ">" if num_equals > 0 else ""
    +        bar = "[" + "=" * (num_equals - 1) + arrow + "-" * num_not + "]"
    +        perc_print = self._fmt(progression * 100, N=5)
    +        line = f"  {bar} {perc_print}% "
    +
    +        for key, score in scores.items():
    +            if np.isnan(score[epoch]) == False:
    +                value = self._fmt(score[epoch], N=4)
    +                line += f"| {key}: {value} "
    +        print(line, end="\r")
    +        return len(line)
    +
    +    def _fmt(self, value: int, N=4) -> str:
    +        """
    +        Description:
    +        ------------
    +            Formats decimal numbers for progress bar
    +        """
    +        if value > 0:
    +            v = value
    +        elif value < 0:
    +            v = -10 * value
    +        else:
    +            v = 1
    +        n = 1 + math.floor(math.log10(v))
    +        if n >= N - 1:
    +            return str(round(value))
    +            # or overflow
    +        return f"{value:.{N-n-1}f}"
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    Usage of CNN code

    + +

    Using the CNN codebase is very simple. We begin by initiating a CNN +object, which takes a cost function, a scheduler and a seed as its +arguments. If a scheduler is not provided, it will per default +initiate an Adam scheduler with eta=1e-4, and if a seed is not +provided, the CNN will not be seeded, meaning it will run with a +different random seed every run. Below we demonstrate an initiation of +our CNN. +

    + + + +
    +
    +
    +
    +
    +
    adam_scheduler = Adam(eta=1e-3, rho=0.9, rho2=0.999)
    +cnn = CNN(cost_func=CostCrossEntropy, scheduler=adam_scheduler, seed=2023)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    Now that we have our CNN object, we can begin to add layers to it! +Many of the add_layer functions have default values, for example +add_Convolution2DLayer() has a default v_stride and h_stride of +1. However, these can of course be set to any value you please. Note +that the input channels of a subsequent convolutional layer must equal +the previous convolutional layer's feature maps. +

    + + + +
    +
    +
    +
    +
    +
    cnn.add_Convolution2DLayer(
    +    input_channels=1,
    +    feature_maps=1,
    +    kernel_height=3,
    +    kernel_width=3,
    +    act_func=LRELU,
    +)
    +
    +cnn.add_FlattenLayer()
    +
    +cnn.add_FullyConnectedLayer(30, LRELU)
    +
    +cnn.add_FullyConnectedLayer(20, LRELU)
    +
    +cnn.add_OutputLayer(10, softmax)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    Here we have created a CNN with the following architecture:

    + +
      +
    1. A convolutional layer with 1 input channel, with a kernel height of 2 and a width of 2, which uses LRELU as its non-linearity function. This layer outputs 1 feature map, which feed into the subsequent layer.
    2. +
    3. A flatten layer
    4. +
    5. A hidden layer with 30 nodes, with LRELU as its activation function
    6. +
    7. Another hidden layer but with 20 nodes
    8. +
    9. The output layer, with softmax as its activation function and 10 nodes. We use 10 nodes because we will be using a dataset with 10 classes.
    10. +
    +

    Now, before we can train the model, we need to load in our data. We +will use the MNIST dataset and use 10000 \( 28 \times 28 images \). +

    + + + +
    +
    +
    +
    +
    +
    from sklearn.datasets import fetch_openml
    +from sklearn.model_selection import train_test_split
    +
    +def onehot(target: np.ndarray):
    +    onehot = np.zeros((target.size, target.max() + 1))
    +    onehot[np.arange(target.size), target] = 1
    +    return onehot
    +
    +# get dataset
    +dataset = fetch_openml("mnist_784", parser="auto")
    +mnist = dataset.data.to_numpy(dtype="float")[:10000, :]
    +
    +# scale data
    +for i in range(mnist.shape[1]):
    +    mnist[:, i] /= 255
    +    
    +# reshape to add single input channel to data shape [inputs, input_channels, height, width]
    +mnist = mnist.reshape(mnist.shape[0], 1, 28, 28)
    +
    +# one hot encode target as we are doing multi-class classification
    +target = onehot(np.array([int(i) for i in dataset.target.to_numpy()[:10000]]))
    +
    +# split into training and validation data
    +x_train, x_val, y_train, y_val = train_test_split(mnist, target)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    Now we may train our model. Note that we can utilize regularization in +the CNN by using the lam (lambda) parameter in fit(), and utilize +different types of gradient descent by specifying the amount of +batches via the batches parameter as shown below. +

    + +

    The functionfit() returns a score dictionary of the training error and +accuracy (and validation error and accuracy if a validation set is +provided) which can be used to plot the error and accuracy of the +model over epochs. +

    + + + +
    +
    +
    +
    +
    +
    scores = cnn.fit(
    +    x_train,
    +    y_train,
    +    lam=1e-5,
    +    batches=10,
    +    epochs=100,
    +    X_val=x_val,
    +    t_val=y_val,
    +)
    +
    +plt.plot(scores["train_acc"], label="Training")
    +plt.plot(scores["val_acc"], label="Validation")
    +plt.ylim([0.8,1])
    +plt.xlabel("Epochs")
    +plt.ylabel("Accuracy")
    +plt.legend()
    +plt.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    Considering we only trained the model for 100 epochs without any tuning of the hyperparameters, this result is pretty good.

    + +

    The codebase allows for great flexibility in CNN +architectures. Pooling layers can be added before, inbetween or after +convolutional layers, but due to the great optimizations made within +Convolution2DLayerOPT, we recommend using the v_stride and h_stride +parameters in add_Convolution2DLayer() to reduce the dimentionality of +the problem as the pooling layer is slow in comparison. To use the +unoptimized version of Convolution2DLayer, simply pass optimized=False +as an argument in add_Convolution2DLayer(). +

    + +

    If one wishes to perform binary classification using the CNN, simply +use the cost function 'CostLogReg' when initializing the CNN and use 1 +node at the OutputLayer. +

    + +

    Below we have created another, more untraditional architecture using +our code to demonstrate its flexibility and different attributes such +as asymmetric stride that might become useful when constructing your +own CNN. +

    + + + +
    +
    +
    +
    +
    +
    adam_scheduler = Adam(eta=1e-3, rho=0.9, rho2=0.999)
    +cnn = CNN(cost_func=CostCrossEntropy, scheduler=adam_scheduler, seed=2023)
    +
    +cnn.add_Convolution2DLayer(
    +    input_channels=1,
    +    feature_maps=7,
    +    kernel_height=7,
    +    kernel_width=1,
    +    act_func=LRELU,
    +)
    +
    +cnn.add_PoolingLayer(
    +    kernel_height=2,
    +    kernel_width=2,
    +    pooling="average",
    +)
    +
    +cnn.add_PoolingLayer(
    +    kernel_height=2,
    +    kernel_width=2,
    +    pooling="max",
    +)
    +
    +cnn.add_Convolution2DLayer(
    +    input_channels=7,
    +    feature_maps=1,
    +    kernel_height=4,
    +    kernel_width=4,
    +    v_stride=2,
    +    h_stride=3,
    +    act_func=LRELU,
    +    optimized=False,
    +)
    +
    +cnn.add_Convolution2DLayer(
    +    input_channels=1,
    +    feature_maps=1,
    +    kernel_height=2,
    +    kernel_width=2,
    +    act_func=sigmoid,
    +    optimized=True,
    +)
    +
    +cnn.add_PoolingLayer(
    +    kernel_height=2,
    +    kernel_width=2,
    +    pooling="max"
    +)
    +
    +cnn.add_FlattenLayer()
    +
    +cnn.add_FullyConnectedLayer(100, LRELU)
    +
    +cnn.add_FullyConnectedLayer(10, sigmoid)
    +
    +cnn.add_FullyConnectedLayer(101, identity)
    +
    +cnn.add_OutputLayer(10, softmax)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    Here we see the use of asymmetrical 1D kernels such as the \( 7 \times +1 \) kernel in the first convolutional layer, both max and average +pooling, asymmetric stride in the unoptimized convolutional layer, +more pooling, a flatten layer, a hidden layer with 100 nodes using +LRELU, another hidden layer with 10 hidden nodes that uses the sigmoid +activation function, and another hidden layer with 101 nodes which +utilizes no activation function (identity). Finally, we arrive at the +output layer with 10 nodes, which uses softmax as its activation +function. +

    +

    Additional Remarks

    + +

    The stride parameter controls the distance between each convolution +and the kernel/filter. If our image is padded, stride is the only +parameter that determines the size of the output from a convolutional +layer. However, if we decide not to perform any padding, the size of +the output feature map depends on both the stride and kernel size. It +is important to note that neither the stride nor the kernel has to be +symmetrical. This means that we can use a rectangular filter if we +choose, and the stride in the vertical direction (axis=0 in Python) +does not need to be the same as the stride in the horizontal direction +(axis=1 in Python). It may even be the case that asymmetric +combinations of stride or kernel dimensions, or both, yield better +results than symmetric values for these parameters. +

    + + + +
    +
    +
    +
    +
    +
    def convolve(image, kernel, stride=1):
    +    for i in range(2):
    +        kernel = np.rot90(kernel)
    +
    +    k_half_height = kernel.shape[0] // 2
    +    k_half_width = kernel.shape[0] // 2
    +
    +    conv_image = np.zeros(image.shape)
    +    pad_image = padding(image, kernel)
    +
    +    for i in range(k_half_height, conv_image.shape[0] + k_half_height, stride):
    +        for j in range(k_half_width, conv_image.shape[1] + k_half_width, stride):
    +            conv_image[i - k_half_height, j - k_half_width] = np.sum(
    +                pad_image[
    +                    i - k_half_height : i + k_half_height + 1, j - k_half_width : j + k_half_width + 1
    +                ]
    +                * kernel
    +            )
    +
    +    return conv_image
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    Remarks on the speed

    + +

    Despite the naive convolution algorithm shown above working finely, it +is extremely slow, requiring approximately 20-30 seconds to process a +single image. The time complexity of 2D convolution, which is O(NMnm), +rapidly becomes a constraint and may, at worst, make computations +infeasible. Consequently, optimizing the naive 2D convolution +algorithm is a necessity, as the execution time of the algorithm +significantly increases as the input data size expands. This can pose +a bottleneck in applications that necessitate real-time processing of +large data volumes, such as image and video processing, deep learning, +and scientific simulations. +

    + +

    To address this issue, we shall present two widely used optimization +techniques: the separable kernel approach and Fast Fourier Transform +(FFT). Both of these methods can drastically reduce the computational +complexity of convolution and enhance the overall efficiency of +processing substantial data quantities. While we shall refrain from +delving into the intricacies of these algorithms, we strongly +encourage you to examine at least the application of FFT to optimize +computations. +

    +

    Convolution using separable kernels

    + + + +
    +
    +
    +
    +
    +
    def conv2DSep(image, kernel, coef, stride=1, pad="zero"):
    +    for i in range(2):
    +        kernel = np.rot90(kernel)
    +
    +    # The kernel is quadratic, thus we only need one of its dimensions
    +    half_dim = kernel.shape[0] // 2
    +
    +    ker1 = np.array(kernel[0, :])
    +    ker2 = np.array(kernel[:, 0])
    +
    +    if pad == "zero":
    +        conv_image = np.zeros(image.shape)
    +        pad_image = padding(image, kernel)
    +    else:
    +        conv_image = np.zeros(
    +            (image.shape[0] - kernel.shape[0], image.shape[1] - kernel.shape[1])
    +        )
    +        pad_image = image[:, :]
    +
    +    for i in range(half_dim, conv_image.shape[0] + half_dim, stride):
    +        for j in range(half_dim, conv_image.shape[1] + half_dim, stride):
    +            conv_image[i - half_dim, j - half_dim] = (
    +                pad_image[
    +                    i - half_dim : i + half_dim + 1, j - half_dim : j + half_dim + 1
    +                ]
    +                @ ker1
    +                @ ker2.T
    +                * coef
    +            )
    +
    +    return conv_image
    +
    +img_path = img_path = "../data/IMG-2167.JPG"
    +image_of_cute_dog = imageio.imread(img_path, mode="L")
    +start_time = time.time()
    +filtered_image = conv2DSep(image_of_cute_dog, kernel=sobel_kernel, coef=1)
    +print(f'Time taken for convolution with seperated kernel on 128x128 image {time.time() - start_time}')
    +plt.imshow(filtered_image, cmap="gray", vmin=0, vmax=255, aspect="auto")
    +plt.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    By taking advantage of the capabilities of separable kernels, we can +effectively cut the computational expense of filtering an image in +half. Yet, if we seek even more rapid processing, we can turn to the +Fast Fourier Transform (FFT) algorithm provided by the numpy +library. By utilizing FFT to transform the input image and filter into +the frequency domain, we can perform convolution in this domain. This +approach significantly reduces the number of operations needed and +results in a marked speedup relative to other convolution +techniques. In addition, it is worth noting that the FFT is widely +regarded as one of the most critical algorithms developed to date, +with applications ranging from digital signal processing to scientific +computing. +

    +

    Convolution in the Fourier domain

    + + +
    +
    +
    +
    +
    +
    start_time = time.time()
    +img_fft = np.fft.fft2(image_of_cute_dog)
    +kernel_fft = np.fft.fft2(sobel_kernel, s=image_of_cute_dog.shape)
    +
    +conv_image = img_fft * kernel_fft
    +
    +filtered_image = np.fft.ifft2(conv_image)
    +print(f'Time take for convolution in the fourier domain: {time.time() - start_time}')
    +plt.imshow(filtered_image.real, cmap="gray", vmin=0, vmax=255, aspect="auto")
    +plt.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    It is evident that executing convolution in the Fourier domain yields +the quickest computation time. Nonetheless, one should exercise +caution, particularly when dealing with images of relatively small +dimensions, as one of the other methods may prove to be more +expeditious than FFT-enhanced convolution. The overhead involved in +transferring both the image and filter into the Fourier domain, +followed by their subsequent transformation back into the spatial +domain, results in a minor inconvenience. Therefore, it is imperative +to remain cognizant of this fact when utilizing FFT as the primary +optimization technique. +

    diff --git a/doc/pub/week44/html/week44-bs.html b/doc/pub/week44/html/week44-bs.html index e259aad1b..a1601c23e 100644 --- a/doc/pub/week44/html/week44-bs.html +++ b/doc/pub/week44/html/week44-bs.html @@ -139,7 +139,54 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Finally, evaluate the model', 2, None, - 'finally-evaluate-the-model')]} + 'finally-evaluate-the-model'), + ('Building our own CNN code', + 2, + None, + 'building-our-own-cnn-code'), + ('List of contents:', 3, None, 'list-of-contents'), + ('Schedulers', 3, None, 'schedulers'), + ('Usage of schedulers', 3, None, 'usage-of-schedulers'), + ('Cost functions', 3, None, 'cost-functions'), + ('Usage of cost functions', 3, None, 'usage-of-cost-functions'), + ('Activation functions', 3, None, 'activation-functions'), + ('Usage of activation functions', + 3, + None, + 'usage-of-activation-functions'), + ('Convolution', 3, None, 'convolution'), + ('Layers', 3, None, 'layers'), + ('Convolution2DLayer: convolution in a hidden layer', + 3, + None, + 'convolution2dlayer-convolution-in-a-hidden-layer'), + ('Backpropagation in the convolutional layer', + 3, + None, + 'backpropagation-in-the-convolutional-layer'), + ('Demonstration', 3, None, 'demonstration'), + ('Pooling Layer', 3, None, 'pooling-layer'), + ('Flattening Layer', 3, None, 'flattening-layer'), + ('Fully Connected Layers', 3, None, 'fully-connected-layers'), + ('Optimized Convolution2DLayer', + 3, + None, + 'optimized-convolution2dlayer'), + ('The Convolutional Neural Network (CNN)', + 3, + None, + 'the-convolutional-neural-network-cnn'), + ('Usage of CNN code', 3, None, 'usage-of-cnn-code'), + ('Additional Remarks', 3, None, 'additional-remarks'), + ('Remarks on the speed', 3, None, 'remarks-on-the-speed'), + ('Convolution using separable kernels', + 3, + None, + 'convolution-using-separable-kernels'), + ('Convolution in the Fourier domain', + 3, + None, + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -174,50 +221,73 @@ MathJax.Hub.Config({ @@ -272,7 +342,7 @@ MathJax.Hub.Config({
  • 9
  • 10
  • ...
  • -
  • 45
  • +
  • 46
  • »
  • diff --git a/doc/pub/week44/html/week44-reveal.html b/doc/pub/week44/html/week44-reveal.html index 6c1c6ddb6..6a671353e 100644 --- a/doc/pub/week44/html/week44-reveal.html +++ b/doc/pub/week44/html/week44-reveal.html @@ -1622,6 +1622,3285 @@ test_loss, test_acc = model.evaluate(test_images, test_labels, verbose= +
    +

    Building our own CNN code

    + +

    Here we present a flexible and readable python code for a CNN +implemented with NumPy. We will present the code, showcase how to use +the codebase and fit a CNN that yields a 99% accuracy on the 28x28 +MNIST dataset within reasonable time. +

    + +

    The CNN is compatible with all schedulers, cost functions and +activation functions discussed in constructing our neural network +codes. +

    + +

    The CNN code consists of different types of Layer classes, including +Convolution2DLayer, Pooling2DLayer, FlattenLayer, FullyConnectedLayer +and OutputLayer, which can be added to the CNN object using the +interface of the CNN class. This allows you to easily construct your +own CNN, as well as allowing you to get used to an interface similar +to that of TensorFlow which is used for real world applications. +

    + +

    Another important feature of this code is that it throws errors if +unreasonable decisions are made (for example using a kernel that is +larger than the image, not using a FlattenLayer, etc), and provides +the user with an informative error message. +

    +

    List of contents:

    +
      +

    1. Schedulers
    2. +

    3. Activation Functions
    4. +

    5. Cost Functions
    6. +

    7. Convolution
    8. +

    9. Layers
    10. +

    11. CNN
    12. +

    13. Some final remarks
    14. +
    +

    +

    Schedulers

    + +

    The code below shows object oriented implementations of the Constant, +Momentum, Adagrad, AdagradMomentum, RMS prop and Adam schedulers. All +of the classes belong to the shared abstract Scheduler class, and +share the update_change() and reset() methods allowing for any of the +schedulers to be seamlessly used during the training stage, as will +later be shown in the fit() method of the neural +network. Update_change() only has one parameter, the gradient +(\( \delta^{l}_{j}a^{l-1}_k \)), and returns the change which will be +subtracted from the weights. The reset() function takes no parameters, +and resets the desired variables. For Constant and Momentum, reset +does nothing. +

    + + + +
    +
    +
    +
    +
    +
    import autograd.numpy as np
    +
    +class Scheduler:
    +    """
    +    Abstract class for Schedulers
    +    """
    +
    +    def __init__(self, eta):
    +        self.eta = eta
    +
    +    # should be overwritten
    +    def update_change(self, gradient):
    +        raise NotImplementedError
    +
    +    # overwritten if needed
    +    def reset(self):
    +        pass
    +
    +
    +class Constant(Scheduler):
    +    def __init__(self, eta):
    +        super().__init__(eta)
    +
    +    def update_change(self, gradient):
    +        return self.eta * gradient
    +    
    +    def reset(self):
    +        pass
    +
    +
    +class Momentum(Scheduler):
    +    def __init__(self, eta: float, momentum: float):
    +        super().__init__(eta)
    +        self.momentum = momentum
    +        self.change = 0
    +
    +    def update_change(self, gradient):
    +        self.change = self.momentum * self.change + self.eta * gradient
    +        return self.change
    +
    +    def reset(self):
    +        pass
    +
    +
    +class Adagrad(Scheduler):
    +    def __init__(self, eta):
    +        super().__init__(eta)
    +        self.G_t = None
    +
    +    def update_change(self, gradient):
    +        delta = 1e-8  # avoid division ny zero
    +
    +        if self.G_t is None:
    +            self.G_t = np.zeros((gradient.shape[0], gradient.shape[0]))
    +
    +        self.G_t += gradient @ gradient.T
    +
    +        G_t_inverse = 1 / (
    +            delta + np.sqrt(np.reshape(np.diagonal(self.G_t), (self.G_t.shape[0], 1)))
    +        )
    +        return self.eta * gradient * G_t_inverse
    +
    +    def reset(self):
    +        self.G_t = None
    +
    +
    +class AdagradMomentum(Scheduler):
    +    def __init__(self, eta, momentum):
    +        super().__init__(eta)
    +        self.G_t = None
    +        self.momentum = momentum
    +        self.change = 0
    +
    +    def update_change(self, gradient):
    +        delta = 1e-8  # avoid division ny zero
    +
    +        if self.G_t is None:
    +            self.G_t = np.zeros((gradient.shape[0], gradient.shape[0]))
    +
    +        self.G_t += gradient @ gradient.T
    +
    +        G_t_inverse = 1 / (
    +            delta + np.sqrt(np.reshape(np.diagonal(self.G_t), (self.G_t.shape[0], 1)))
    +        )
    +        self.change = self.change * self.momentum + self.eta * gradient * G_t_inverse
    +        return self.change
    +
    +    def reset(self):
    +        self.G_t = None
    +
    +
    +class RMS_prop(Scheduler):
    +    def __init__(self, eta, rho):
    +        super().__init__(eta)
    +        self.rho = rho
    +        self.second = 0.0
    +
    +    def update_change(self, gradient):
    +        delta = 1e-8  # avoid division ny zero
    +        self.second = self.rho * self.second + (1 - self.rho) * gradient * gradient
    +        return self.eta * gradient / (np.sqrt(self.second + delta))
    +
    +    def reset(self):
    +        self.second = 0.0
    +
    +
    +class Adam(Scheduler):
    +    def __init__(self, eta, rho, rho2):
    +        super().__init__(eta)
    +        self.rho = rho
    +        self.rho2 = rho2
    +        self.moment = 0
    +        self.second = 0
    +        self.n_epochs = 1
    +
    +    def update_change(self, gradient):
    +        delta = 1e-8  # avoid division ny zero
    +
    +        self.moment = self.rho * self.moment + (1 - self.rho) * gradient
    +        self.second = self.rho2 * self.second + (1 - self.rho2) * gradient * gradient
    +
    +        moment_corrected = self.moment / (1 - self.rho**self.n_epochs)
    +        second_corrected = self.second / (1 - self.rho2**self.n_epochs)
    +
    +        return self.eta * moment_corrected / (np.sqrt(second_corrected + delta))
    +
    +    def reset(self):
    +        self.n_epochs += 1
    +        self.moment = 0
    +        self.second = 0
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    Usage of schedulers

    + +

    To initalize a scheduler, simply create the object and pass in the necessary parameters such as the learning rate and the momentum as shown below. As the Scheduler class is an abstract class it should not called directly, and will raise an error upon usage.

    + + + +
    +
    +
    +
    +
    +
    momentum_scheduler = Momentum(eta=1e-3, momentum=0.9)
    +adam_scheduler = Adam(eta=1e-3, rho=0.9, rho2=0.999)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    Here is a small example for how a segment of code using schedulers could look. Switching out the schedulers is simple.

    + + + +
    +
    +
    +
    +
    +
    weights = np.ones((3,3))
    +print(f"Before scheduler:\n{weights=}")
    +
    +epochs = 10
    +for e in range(epochs):
    +    gradient = np.random.rand(3, 3)
    +    change = adam_scheduler.update_change(gradient)
    +    weights = weights - change
    +    adam_scheduler.reset()
    +
    +print(f"\nAfter scheduler:\n{weights=}")
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    Cost functions

    + +

    In this section we will quickly look at cost functions that can be +used when creating the neural network. Every cost function takes the +target vector as its parameter, and returns a function valued only at +X such that it may easily be differentiated. +

    + + + +
    +
    +
    +
    +
    +
    def CostOLS(target):
    +    """
    +    Return OLS function valued only at X, so
    +    that it may be easily differentiated
    +    """
    +
    +    def func(X):
    +        return (1.0 / target.shape[0]) * np.sum((target - X) ** 2)
    +
    +    return func
    +
    +
    +def CostLogReg(target):
    +    """
    +    Return Logistic Regression cost function
    +    valued only at X, so that it may be easily differentiated
    +    """
    +
    +    def func(X):
    +        return -(1.0 / target.shape[0]) * np.sum(
    +            (target * np.log(X + 10e-10)) + ((1 - target) * np.log(1 - X + 10e-10))
    +        )
    +
    +    return func
    +
    +
    +def CostCrossEntropy(target):
    +    """
    +    Return cross entropy cost function valued only at X, so
    +    that it may be easily differentiated
    +    """
    +    
    +    def func(X):
    +        return -(1.0 / target.size) * np.sum(target * np.log(X + 10e-10))
    +
    +    return func
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    Usage of cost functions

    + +

    Below we will provide a short example of how these cost function may +be used to obtain results if you wish to test them out on your own +using AutoGrad's automatic differentiation. +

    + + + +
    +
    +
    +
    +
    +
    from autograd import grad
    +
    +target = np.array([[1, 2, 3]]).T
    +a = np.array([[4, 5, 6]]).T
    +
    +cost_func = CostCrossEntropy
    +cost_func_derivative = grad(cost_func(target))
    +
    +valued_at_a = cost_func_derivative(a)
    +print(f"Derivative of cost function {cost_func.__name__} valued at a:\n{valued_at_a}")
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    Activation functions

    + +

    Finally, before we look at the layers that make up the neural network, +we will look at the activation functions which can be specified +between the hidden layers and as the output function. Each function +can be valued for any given vector or matrix X, and can be +differentiated via derivate(). +

    + + + +
    +
    +
    +
    +
    +
    import autograd.numpy as np
    +from autograd import elementwise_grad
    +
    +def identity(X):
    +    return X
    +
    +
    +def sigmoid(X):
    +    try:
    +        return 1.0 / (1 + np.exp(-X))
    +    except FloatingPointError:
    +        return np.where(X > np.zeros(X.shape), np.ones(X.shape), np.zeros(X.shape))
    +
    +
    +def softmax(X):
    +    X = X - np.max(X, axis=-1, keepdims=True)
    +    delta = 10e-10
    +    return np.exp(X) / (np.sum(np.exp(X), axis=-1, keepdims=True) + delta)
    +
    +
    +def RELU(X):
    +    return np.where(X > np.zeros(X.shape), X, np.zeros(X.shape))
    +
    +
    +def LRELU(X):
    +    delta = 10e-4
    +    return np.where(X > np.zeros(X.shape), X, delta * X)
    +
    +
    +def derivate(func):
    +    if func.__name__ == "RELU":
    +
    +        def func(X):
    +            return np.where(X > 0, 1, 0)
    +
    +        return func
    +
    +    elif func.__name__ == "LRELU":
    +
    +        def func(X):
    +            delta = 10e-4
    +            return np.where(X > 0, 1, delta)
    +
    +        return func
    +
    +    else:
    +        return elementwise_grad(func)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    Usage of activation functions

    + +

    Below we present a short demonstration of how to use an activation +function. The derivative of the activation function will be important +when calculating the output delta term during backpropagation. Note +that derivate() can also be used for cost functions for a more +generalized approach. +

    + + + +
    +
    +
    +
    +
    +
    z = np.array([[4, 5, 6]]).T
    +print(f"Input to activation function:\n{z}")
    +
    +act_func = sigmoid
    +a = act_func(z)
    +print(f"\nOutput from {act_func.__name__} activation function:\n{a}")
    +
    +act_func_derivative = derivate(act_func)
    +valued_at_z = act_func_derivative(a)
    +print(f"\nDerivative of {act_func.__name__} activation function valued at z:\n{valued_at_z}")
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    Convolution

    + +

    In order to construct a convolutional neural network (CNN), it is +crucial to comprehend the fundamental principles of convolution and +how it aids in extracting information from images. Convolution, at its +core, is merely a mathematical operation between two functions that +yields another function. It is represented by an integral between two +functions, which is typically expressed as: +

    + +

     
    +$$ +(f \ast g)(t):=\int_{-\infty}^{\infty} f(\tau) g(t-\tau) d \tau. +$$ +

     
    + +

    Here, f and g are the two functions on which we want to perform an +operation. The outcome of the convolution operation is represented by +\( (f \ast g) \), and it is derived by sliding the function g over f and +computing the integral of their product at each position. If both +functions are continuous, convolution takes the form shown +above. However, if we discretize both f and g, the convolution +operation will take the form of a sum between the elements of f and g: +

    +

     
    +$$ +(f \ast g)[n]=\sum_{m=0}^{n-1} f[m] g[n-m]. +$$ +

     
    + +

    The key idea we utilize to extract the information contained in an +image is to slide an \( m \times n \) matrix g over an \( m \times n \) +matrix f. In our case, f represents the image, while g +represents the kernel, oftentimes called a filter. However, since our +convolution will be a two-dimensional variant, we need to extend our +mathematical formula with an additional summation: +

    + +

     
    +$$ +(f \ast g)[i, j]\sum_{m=0}^{M-1}\sum_{n=0}^{N-1} f[m,n] g[i-m, j-n]. +$$ +

     
    + +

    It is imperative to note that the size of the kernel g is +significantly smaller than the size of the input image f, thereby +reducing the amount of computation necessary for feature +extraction. Furthermore, the kernel is usually a trainable parameter +in a convolutional neural network, allowing the network to learn +appropriate kernels for specific tasks. +

    + +

    To give you an example of how 2D convolution works in practice, +suppose we have an image f of dimension \( 6 \times 6 \) +

    + +

     
    +$$ +f = \begin{bmatrix} +4 & 1 & 2 & 9 & 8 & 6 \\ +9 & 5 & 9 & 5 & 8 & 5 \\ +1 & 5 & 9 & 7 & 6 & 4 \\ +2 & 9 & 8 & 3 & 7 & 1 \\ +8 & 1 & 6 & 4 & 2 & 2 \\ +1 & 0 & 5 & 7 & 8 & 2 \\ +\end{bmatrix} +$$ +

     
    + +

    and a \( 3 \times 3 \) kernel g called a low-pass filter. Note that the +kernel is usually rotated by 180 degrees during convolution, however +this has no effect on this kernel. +

    + +

     
    +$$ +g = \frac{1}{9} +\begin{bmatrix} +1 & 1 & 1 \\ +1 & 1 & 1 \\ +1 & 1 & 1 \\ +\end{bmatrix} +$$ +

     
    + +

    In order to filter the image, we have to extract a \( 3 \times 3 \) +element from the upper left corner of f, and perform element-wise +multiplication of the extracted image pixels with the elements of the +kernel g: +

    + +

     
    +$$ +\begin{bmatrix} +4 & 1 & 2 \\ +9 & 5 & 9 \\ +1 & 5 & 9 \\ +\end{bmatrix} +\cdot +\begin{bmatrix} +\frac{1}{9} & \frac{1}{9} & \frac{1}{9} \\ +\frac{1}{9} & \frac{1}{9} & \frac{1}{9} \\ +\frac{1}{9} & \frac{1}{9} & \frac{1}{9} \\ +\end{bmatrix} += +\begin{bmatrix} +\frac{4}{9} & \frac{1}{9} & \frac{2}{9} \\ +\frac{9}{9} & \frac{5}{9} & \frac{9}{9} \\ +\frac{1}{9} & \frac{5}{9} & \frac{9}{9} \\ +\end {bmatrix} += \textbf{A} +$$ +

     
    + +

    Then, following the multiplication, we summarize all the elements of the resulting matrix A:

    + +

     
    +$$ +(f \ast g)[0, 0]= \sum_{i=0}^{2} \sum_{j=0}^{2} a_{i,j} = 5 +$$ +

     
    + +

    Which corresponds to the first element of the filtered image \( (f \ast g) \).

    + +

    Here we use a stride of 1, a parameter denoted s which describes how +many indexes we move the kernel g to the right before repeating the +calculations above for the next \( 3 \times 3 \) element of the image +f. It is usually presumed that *s*=1, however, larger values for s +can be used to reduce the dimentionality of the filtered image such +that the convolution operation is more computationally efficient. In +the context of a convolutional neural network, this will become very +useful. +

    + +

    The full result of the convolution is:

    + +

     
    +$$ +(f \ast g) = +\begin{bmatrix} +5 & 5.78 & 7 & 6.44 \\ +6.33 & 6.67 & 6.89 & 5.11 \\ +5.44 & 5.78 & 5.78 & 4 \\ +4.44 & 4.78 & 5.56 & 4 \\ +\end{bmatrix} +$$ +

     
    + +

    The result is markedly smaller in shape than the original image. This occurs when using convolution without first padding the image with additional columns and rows, allowing us to keep the original image shape after sliding the kernel over the image. +How many rows and columns we wish to pad the image with depends strictly on the shape of the kernel, as we wish to pad the image with r additional rows and c additional columns. +

    + +

     
    +$$ +r =\lfloor \frac{kernel\ height}{2} \rfloor \cdot 2 \\ +c =\lfloor \frac{kernel\ width}{2} \rfloor \cdot 2 +$$ +

     
    + +

    Note the notation \( \lfloor \frac{kernel width}{2} \rfloor \) means that +we floor the result of the division, meaning we round down to a whole +number in case \( \frac{kernel width}{2} \) results in a floating point +number. +

    + +

    Using those simple equations, we find out by how much we have to +extend the dimensions of the original image. Before proceeding, +however, we might ask what we shall fill the additional rows and +columns with? One of the most common approaches to padding is +zero-padding, which as the name suggest, involves filling the rows and +columns with zeros. This is the approach that we will be using for +this demonstration. If we apply this padding to out original \( 6 \times 6 \) +image, the result will be an \( 8 \times 8 \) image as the kernel has a width and +height of 3. Note that the original image is encapsuled by the +zero-padded rows and columns: +

    + +

     
    +$$ +\begin{bmatrix} +0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ +0 & 4 & 1 & 2 & 9 & 8 & 6 & 0 \\ +0 & 9 & 5 & 9 & 5 & 8 & 5 & 0 \\ +0 & 1 & 5 & 9 & 7 & 6 & 4 & 0 \\ +0 & 2 & 9 & 8 & 3 & 7 & 1 & 0 \\ +0 & 8 & 1 & 6 & 4 & 2 & 2 & 0 \\ +0 & 1 & 0 & 5 & 7 & 8 & 2 & 0 \\ +0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ +\] +\end{bmatrix} +$$ +

     
    + +

    Below we have provided code that demonstrates padding and convolution. As you will see when we run the code, the size of the image will remain unchanged when using padding. 

    + + + +
    +
    +
    +
    +
    +
    import numpy as np
    +
    +def padding(image, kernel):
    +    # calculate r and c
    +    r = (kernel.shape[0] // 2) * 2
    +    c = (kernel.shape[1] // 2) * 2
    +    
    +    # padded image dimensions
    +    padded_height = image.shape[0] + r
    +    padded_width = image.shape[1] + c
    +    
    +    # for more readable code
    +    k_half_height = kernel.shape[0] // 2
    +    k_half_width = kernel.shape[1] // 2
    +
    +    # zero matrix with padded dimensions
    +    padded_img = np.zeros((padded_height, padded_width))
    +
    +    # place image into zero matrix
    +    padded_img[k_half_height : padded_height - k_half_height,
    +               k_half_width : padded_width - k_half_width] = image[:, :]
    +
    +    return padded_img
    +
    +def convolve(original_image, padded_image, kernel, stride=1):
    +    # rotate kernel by 180 degrees
    +    kernel = np.rot90(np.rot90(kernel))
    +
    +    # note that kernel height // 2 is written as 'm'
    +    # and kernel width // 2 as 'n' in the mathematical notation
    +    m = kernel.shape[0] // 2
    +    n = kernel.shape[1] // 2
    +    
    +    r = (kernel.shape[0] // 2) * 2
    +    c = (kernel.shape[1] // 2) * 2
    +    
    +    # initialize output array
    +    convolved_image = np.zeros(original_image.shape)
    +    image_height = original_image.shape[0]
    +    image_width = original_image.shape[1]
    +
    +    # the convolution
    +    for i in range(m, image_height + m, stride):
    +        for j in range(n, image_width + n, stride):
    +            convolved_image[i-m, j-n] = np.sum(
    +                padded_image[i : i + m, j : j + n]
    +                * kernel
    +            )
    +            
    +    return convolved_image
    +
    +def convolve(image, kernel, stride=1):
    +    for i in range(2):
    +        kernel = np.rot90(kernel)
    +
    +    k_half_height = kernel.shape[0] // 2
    +    k_half_width = kernel.shape[0] // 2
    +
    +    conv_image = np.zeros(image.shape)
    +    pad_image = padding(image, kernel)
    +
    +    for i in range(k_half_height, conv_image.shape[0] + k_half_height, stride):
    +        for j in range(k_half_width, conv_image.shape[1] + k_half_width, stride):
    +            conv_image[i - k_half_height, j - k_half_width] = np.sum(
    +                pad_image[
    +                    i - k_half_height : i + k_half_height + 1, j - k_half_width : j + k_half_width + 1
    +                ]
    +                * kernel
    +            )
    +
    +    return conv_image
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    Fun fact: When filtering images, you will see that convolution involves rotating the kernel by 180 degrees. +However, this is not the case when applying convolution in a CNN, where the same operation not rotated by 180 degrees is called +cross-correlation. +

    + + + +
    +
    +
    +
    +
    +
    original_image = np.array([[4, 1, 2, 9, 8, 6],
    +                 [9, 5, 9, 5, 8, 5],
    +                 [1, 5, 9, 7, 6, 4],
    +                 [2, 9, 8, 3, 7, 1],
    +                 [8, 1, 6, 4, 2, 2],
    +                 [1, 0, 5, 7, 8, 2]])
    +
    +kernel = (1/9)*np.ones((3,3))
    +
    +print(f"{original_image.shape=}")
    +
    +# note that convolve() performs padding
    +convolved_image = convolve(original_image, kernel, stride=1)
    +
    +print(f"{convolved_image.shape=}")
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    As you can see, the resulting image is of the same size as the +original image. To round of our demonstration of convolution, we will +present the results of convolution using commonly used kernels. In a +CNN, the values of the kernels are randomly initialized, and then +learned during training. These kernels will extract information +regarding the picture, such as for example the edge detection filter +demonstrated below extracts the edges present in the picture. Of +course, there is no guarantee that the CNN will learn an edge +detection filter, but this should provide some intuiton as to how the +CNN is able to use kernels to make better predictions than a regular +feed forward neural network. +

    + + + +
    +
    +
    +
    +
    +
    # Now an example using a real image and first a gaussian low-pass filter and then a sobel filter
    +import numpy as np
    +import imageio.v3 as imageio
    +import matplotlib.pyplot as plt
    +import time
    +
    +def generate_gauss_mask(sigma, K=1):
    +    side = np.ceil(1 + 8 * sigma)
    +    y, x = np.mgrid[-side // 2 + 1 : (side // 2) + 1, -side // 2 + 1 : (side // 2) + 1]
    +    ker_coef = K / (2 * np.pi * sigma**2)
    +    g = np.exp(-((x**2 + y**2) / (2.0 * sigma**2)))
    +
    +    return g, ker_coef
    +
    +
    +img_path = "../data/IMG-2167.JPG"
    +image_of_cute_dog = imageio.imread(img_path, mode='L')
    +
    +plt.imshow(image_of_cute_dog, cmap="gray", vmin=0, vmax=255, aspect="auto")
    +plt.title("Original image")
    +plt.show()
    +
    +gauss, kernel = generate_gauss_mask(sigma=6)
    +gauss_kernel = gauss*kernel
    +
    +filtered_image = convolve(image_of_cute_dog, gauss_kernel)
    +plt.imshow(filtered_image, cmap="gray", vmin=0, vmax=255, aspect="auto")
    +plt.title("Result of convolution with gauss kernel (blurring filter)")
    +plt.show()
    +
    +sobel_kernel = np.array([[1, 2, 1],
    +                    [0, 0, 0], 
    +                    [-1, -2, -1]])
    +
    +filtered_image = convolve(image_of_cute_dog, sobel_kernel)
    +
    +plt.imshow(filtered_image, cmap="gray", vmin=0, vmax=255, aspect="auto")
    +plt.title("Result of convolution with sobel kernel (edge detection filter)")
    +plt.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    Layers

    + +

    The code below initialises global variables for readability and +describes the abstract class Layers. This is not important in order to +understand the CNN, but is benefitial for organizing the code neatly. +

    + + + +
    +
    +
    +
    +
    +
    import math
    +import autograd.numpy as np
    +from copy import deepcopy, copy
    +from autograd import grad
    +from typing import Callable
    +
    +# global variables for index readability
    +input_index = 0
    +node_index = 1
    +bias_index = 1
    +input_channel_index = 1
    +feature_maps_index = 1
    +height_index = 2
    +width_index = 3
    +kernel_feature_maps_index = 1
    +kernel_input_channels_index = 0
    +
    +
    +class Layer:
    +    def __init__(self, seed):
    +        self.seed = seed
    +
    +    def _feedforward(self):
    +        raise NotImplementedError
    +
    +    def _backpropagate(self):
    +        raise NotImplementedError
    +
    +    def _reset_weights(self, previous_nodes):
    +        raise NotImplementedError
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    Convolution2DLayer: convolution in a hidden layer

    + +

    After establishing the foundational understanding of applying +convolution to spatial data, let us delve into the intricate workings +of a convolutional layer in a Convolutional Neural Network (CNN). The +primary function of convolution, as previously discussed, is to +extract pertinent information from images while simultaneously +decreasing the scale of our data. To initiate the image processing, we +shall begin by partitioning the images into color channels (unless the +image is grayscale), comprising three primary colors: red, green, and +blue. We will subsequently utilize trainable kernels to construct a +higher-dimensional encoding of each channel called feature +maps. Successive layers will receive these feature maps as inputs, +generating further encodings, albeit with reduced dimensions. The term +trainable kernels denotes the initialization of pre-defined +kernel-shaped weights, which we will then train via backpropagation, +similar to how weights are trained in a Feedforward Neural Network. +

    + +

    To ensure seamless integration between our implementation of the +convolutional layer and popular machine learning frameworks like +Tensorflow (Keras) and PyTorch, we have adopted a design pattern that +mirrors the construction of models using these APIs. This involves +implementing our convolutional layer as a Python class or object, +which allows for a more modular and flexible approach to building +neural networks. By structuring our code in this way, users can easily +incorporate our implementation into their existing machine learning +pipelines without having to make significant changes to their +codebase. Additionally, this design pattern promotes code reusability +and makes it easier to maintain and update our convolutional layer +implementation over time. +

    + +

    Note that the Convolution2DLayer takes in an activation function as a parameter, as it also performs non-linearity.

    + + + +
    +
    +
    +
    +
    +
    class Convolution2DLayer(Layer):
    +    def __init__(
    +        self,
    +        input_channels,
    +        feature_maps,
    +        kernel_height,
    +        kernel_width,
    +        v_stride,
    +        h_stride,
    +        pad,
    +        act_func: Callable,
    +        seed=None,
    +        reset_weights_independently=True,
    +    ):
    +        super().__init__(seed)
    +        self.input_channels = input_channels
    +        self.feature_maps = feature_maps
    +        self.kernel_height = kernel_height
    +        self.kernel_width = kernel_width
    +        self.v_stride = v_stride
    +        self.h_stride = h_stride
    +        self.pad = pad
    +        self.act_func = act_func
    +
    +        # such that the layer can be used on its own
    +        # outside of the CNN module
    +        if reset_weights_independently == True:
    +            self._reset_weights_independently()
    +
    +    def _feedforward(self, X_batch):
    +        # note that the shape of X_batch = [inputs, input_maps, img_height, img_width]
    +
    +        # pad the input batch
    +        X_batch_padded = self._padding(X_batch)
    +
    +        # calculate height_index and width_index after stride
    +        strided_height = int(np.ceil(X_batch.shape[height_index] / self.v_stride))
    +        strided_width = int(np.ceil(X_batch.shape[width_index] / self.h_stride))
    +
    +        # create output array
    +        output = np.ndarray(
    +            (
    +                X_batch.shape[input_index],
    +                self.feature_maps,
    +                strided_height,
    +                strided_width,
    +            )
    +        )
    +
    +        # save input and output for backpropagation
    +        self.X_batch_feedforward = X_batch
    +        self.output_shape = output.shape
    +
    +        # checking for errors, no need to look here :)
    +        self._check_for_errors()
    +
    +        # convolve input with kernel
    +        for img in range(X_batch.shape[input_index]):
    +            for chin in range(self.input_channels):
    +                for fmap in range(self.feature_maps):
    +                    out_h = 0
    +                    for h in range(0, X_batch.shape[height_index], self.v_stride):
    +                        out_w = 0
    +                        for w in range(0, X_batch.shape[width_index], self.h_stride):
    +                            output[img, fmap, out_h, out_w] = np.sum(
    +                                X_batch_padded[
    +                                    img,
    +                                    chin,
    +                                    h : h + self.kernel_height,
    +                                    w : w + self.kernel_width,
    +                                ]
    +                                * self.kernel[chin, fmap, :, :]
    +                            )
    +                            out_w += 1
    +                        out_h += 1
    +
    +        # Pay attention to the fact that we're not rotating the kernel by 180 degrees when filtering the image in
    +        # the convolutional layer, as convolution in terms of Machine Learning is a procedure known as cross-correlation
    +        # in image processing and signal processing
    +
    +        # return a
    +        return self.act_func(output / (self.kernel_height))
    +
    +    def _backpropagate(self, delta_term_next):
    +        # intiate matrices
    +        delta_term = np.zeros((self.X_batch_feedforward.shape))
    +        gradient_kernel = np.zeros((self.kernel.shape))
    +
    +        # pad input for convolution
    +        X_batch_padded = self._padding(self.X_batch_feedforward)
    +
    +        # Since an activation function is used at the output of the convolution layer, its derivative
    +        # has to be accounted for in the backpropagation -> as if ReLU was a layer on its own.
    +        act_derivative = derivate(self.act_func)
    +        delta_term_next = act_derivative(delta_term_next)
    +
    +        # fill in 0's for values removed by vertical stride in feedforward
    +        if self.v_stride > 1:
    +            v_ind = 1
    +            for i in range(delta_term_next.shape[height_index]):
    +                for j in range(self.v_stride - 1):
    +                    delta_term_next = np.insert(
    +                        delta_term_next, v_ind, 0, axis=height_index
    +                    )
    +                v_ind += self.v_stride
    +
    +        # fill in 0's for values removed by horizontal stride in feedforward
    +        if self.h_stride > 1:
    +            h_ind = 1
    +            for i in range(delta_term_next.shape[width_index]):
    +                for k in range(self.h_stride - 1):
    +                    delta_term_next = np.insert(
    +                        delta_term_next, h_ind, 0, axis=width_index
    +                    )
    +                h_ind += self.h_stride
    +
    +        # crops out 0-rows and 0-columns
    +        delta_term_next = delta_term_next[
    +            :,
    +            :,
    +            : self.X_batch_feedforward.shape[height_index],
    +            : self.X_batch_feedforward.shape[width_index],
    +        ]
    +
    +        # the gradient received from the next layer also needs to be padded
    +        delta_term_next = self._padding(delta_term_next)
    +
    +        # calculate delta term by convolving next delta term with kernel
    +        for img in range(self.X_batch_feedforward.shape[input_index]):
    +            for chin in range(self.input_channels):
    +                for fmap in range(self.feature_maps):
    +                    for h in range(self.X_batch_feedforward.shape[height_index]):
    +                        for w in range(self.X_batch_feedforward.shape[width_index]):
    +                            delta_term[img, chin, h, w] = np.sum(
    +                                delta_term_next[
    +                                    img,
    +                                    fmap,
    +                                    h : h + self.kernel_height,
    +                                    w : w + self.kernel_width,
    +                                ]
    +                                * np.rot90(np.rot90(self.kernel[chin, fmap, :, :]))
    +                            )
    +
    +        # calculate gradient for kernel for weight update
    +        # also via convolution
    +        for chin in range(self.input_channels):
    +            for fmap in range(self.feature_maps):
    +                for k_x in range(self.kernel_height):
    +                    for k_y in range(self.kernel_width):
    +                        gradient_kernel[chin, fmap, k_x, k_y] = np.sum(
    +                            X_batch_padded[
    +                                img,
    +                                chin,
    +                                h : h + self.kernel_height,
    +                                w : w + self.kernel_width,
    +                            ]
    +                            * delta_term_next[
    +                                img,
    +                                fmap,
    +                                h : h + self.kernel_height,
    +                                w : w + self.kernel_width,
    +                            ]
    +                        )
    +        # all kernels are updated with weight gradient of kernel
    +        self.kernel -= gradient_kernel
    +
    +        # return delta term
    +        return delta_term
    +
    +    def _padding(self, X_batch, batch_type="image"):
    +
    +        # same padding for images
    +        if self.pad == "same" and batch_type == "image":
    +            padded_height = X_batch.shape[height_index] + (self.kernel_height // 2) * 2
    +            padded_width = X_batch.shape[width_index] + (self.kernel_width // 2) * 2
    +            half_kernel_height = self.kernel_height // 2
    +            half_kernel_width = self.kernel_width // 2
    +
    +            # initialize padded array
    +            X_batch_padded = np.ndarray(
    +                (
    +                    X_batch.shape[input_index],
    +                    X_batch.shape[feature_maps_index],
    +                    padded_height,
    +                    padded_width,
    +                )
    +            )
    +
    +            # zero pad all images in X_batch
    +            for img in range(X_batch.shape[input_index]):
    +                padded_img = np.zeros(
    +                    (X_batch.shape[feature_maps_index], padded_height, padded_width)
    +                )
    +                padded_img[
    +                    :,
    +                    half_kernel_height : padded_height - half_kernel_height,
    +                    half_kernel_width : padded_width - half_kernel_width,
    +                ] = X_batch[img, :, :, :]
    +                X_batch_padded[img, :, :, :] = padded_img[:, :, :]
    +
    +            return X_batch_padded
    +
    +        # same padding for gradients
    +        elif self.pad == "same" and batch_type == "grad":
    +            padded_height = X_batch.shape[height_index] + (self.kernel_height // 2) * 2
    +            padded_width = X_batch.shape[width_index] + (self.kernel_width // 2) * 2
    +            half_kernel_height = self.kernel_height // 2
    +            half_kernel_width = self.kernel_width // 2
    +
    +            # initialize padded array
    +            delta_term_padded = np.zeros(
    +                (
    +                    X_batch.shape[input_index],
    +                    X_batch.shape[feature_maps_index],
    +                    padded_height,
    +                    padded_width,
    +                )
    +            )
    +
    +            # zero pad delta term
    +            delta_term_padded[
    +                :, :, : X_batch.shape[height_index], : X_batch.shape[width_index]
    +            ] = X_batch[:, :, :, :]
    +
    +            return delta_term_padded
    +
    +        else:
    +            return X_batch
    +
    +    def _reset_weights_independently(self):
    +        # sets seed to remove randomness inbetween runs
    +        if self.seed is not None:
    +            np.random.seed(self.seed)
    +
    +        # initializes kernel matrix
    +        self.kernel = np.ndarray(
    +            (
    +                self.input_channels,
    +                self.feature_maps,
    +                self.kernel_height,
    +                self.kernel_width,
    +            )
    +        )
    +
    +        # randomly initializes weights
    +        for chin in range(self.kernel.shape[kernel_input_channels_index]):
    +            for fmap in range(self.kernel.shape[kernel_feature_maps_index]):
    +                self.kernel[chin, fmap, :, :] = np.random.rand(
    +                    self.kernel_height, self.kernel_width
    +                )
    +
    +    def _reset_weights(self, previous_nodes):
    +        # sets weights
    +        self._reset_weights_independently()
    +
    +        # returns shape of output used for subsequent layer's weight initiation
    +        strided_height = int(
    +            np.ceil(previous_nodes.shape[height_index] / self.v_stride)
    +        )
    +        strided_width = int(np.ceil(previous_nodes.shape[width_index] / self.h_stride))
    +        next_nodes = np.ones(
    +            (
    +                previous_nodes.shape[input_index],
    +                self.feature_maps,
    +                strided_height,
    +                strided_width,
    +            )
    +        )
    +        return next_nodes / self.kernel_height
    +
    +    def _check_for_errors(self):
    +        if self.X_batch_feedforward.shape[input_channel_index] != self.input_channels:
    +            raise AssertionError(
    +                f"ERROR: Number of input channels in data ({self.X_batch_feedforward.shape[input_channel_index]}) is not equal to input channels in Convolution2DLayerOPT ({self.input_channels})! Please change the number of input channels of the Convolution2DLayer such that they are equal"
    +            )
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    Backpropagation in the convolutional layer

    + +

    As you may have noticed, we have not yet explained how the +backpropagation algorithm works in a convolutional layer. However, +having covered all other major details about convolutional layers, we +are now prepared to do so. It should come as no surprise that the +calculation of delta terms at each convolutional layer takes the form +of convolution. After the gradient has been propagated backwards +through the flattening layer, where it was reshaped into an +appropriate form, calculating the update value for the kernel is +simply a matter of convolving the output gradient with the input of +the layer for which we are updating the weights. For more detail, this +article serves as an excellent resource, see +https://pavisj.medium.com/convolutions-and-backpropagations-46026a8f5d2c +

    +

    Demonstration

    + +

    We can use the convolutional layer above to perform a simple convolution on an image of the now familiar cute dog.

    + + + +
    +
    +
    +
    +
    +
    import numpy as np
    +import imageio.v3 as imageio
    +import matplotlib.pyplot as plt
    +
    +def plot_convolution_result(X, layer):
    +    plt.imshow(X[0, 0, :, :], vmin=0, vmax=255, cmap="gray")
    +    plt.title("Original image")
    +    plt.colorbar()
    +    plt.show()
    +    conv_result = layer._feedforward(X)
    +    plt.title("Result of convolutional layer")
    +    plt.imshow(conv_result[0, 0, :, :], vmin=0, vmax=255, cmap="gray")
    +    plt.colorbar()
    +    plt.show()
    +
    +# create layer
    +layer = Convolution2DLayer(
    +    input_channels=3,
    +    feature_maps=1,
    +    kernel_height=4,
    +    kernel_width=4,
    +    v_stride=2,
    +    h_stride=2,
    +    pad="same",
    +    act_func=identity,
    +    seed=2023,
    +    )
    +
    +# read in image path, make data correct format
    +img_path = img_path = "../data/IMG-2167.JPG"
    +image_of_cute_dog = imageio.imread(img_path)
    +image_shape = image_of_cute_dog.shape
    +image_of_cute_dog = image_of_cute_dog.reshape(1, image_shape[0], image_shape[1], image_shape[2])
    +image_of_cute_dog = image_of_cute_dog.transpose(0, 3, 1, 2)
    +
    +# plot the result of the convolution
    +plot_convolution_result(image_of_cute_dog, layer)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    We cobserve that the result has half the pixels on each axis due to +the fact that we've used a horizontal and vertical stride of 2. The +result of this convolution is not very insightfull, as the kernel has +completely random values for the first feedforward pass. However, as +we perform multiple forward and backward passes, the results of the +convolution should provide identifying features of the image it uses +for classification. +

    + +

    Note that image data usually comes in many different shapes and sizes, +but for our CNN we require the input data be formatted as \[Number of +inputs, input channels, input height, input width\]. Occasionally, the +data you come accross use will be formatted like this, but on many +occasions reshaping and transposing the dimensions is sadly necessary. +

    +

    Pooling Layer

    + +

    The pooling layer is another widely used type of layer in +convolutional neural networks that enables data downsampling to a more +manageable size. Despite recent technological advancements that allow +for convolution without excessive size reduction of the data, the +pooling layer still remains a fundamental component of convolutional +neural networks. It can be used before, after, or in between +convolutional layers, although finding the optimal placement of layers +and network depth requires experimentation to achieve the best +performance for a given problem. The code we provide allows you to +perform two types of pooling known as max pooling and average pooling. +

    + + + +
    +
    +
    +
    +
    +
    class Pooling2DLayer(Layer):
    +    def __init__(
    +        self,
    +        kernel_height,
    +        kernel_width,
    +        v_stride,
    +        h_stride,
    +        pooling="max",
    +        seed=None,
    +    ):
    +        super().__init__(seed)
    +        self.kernel_height = kernel_height
    +        self.kernel_width = kernel_width
    +        self.v_stride = v_stride
    +        self.h_stride = h_stride
    +        self.pooling = pooling
    +
    +    def _feedforward(self, X_batch):
    +        # Saving the input for use in the backwardpass
    +        self.X_batch_feedforward = X_batch
    +
    +        # check if user is silly
    +        self._check_for_errors()
    +
    +        # Computing the size of the feature maps based on kernel size and the stride parameter
    +        strided_height = (
    +            X_batch.shape[height_index] - self.kernel_height
    +        ) // self.v_stride + 1
    +        if X_batch.shape[height_index] == X_batch.shape[width_index]:
    +            strided_width = strided_height
    +        else:
    +            strided_width = (
    +                X_batch.shape[width_index] - self.kernel_width
    +            ) // self.h_stride + 1
    +
    +        # initialize output array
    +        output = np.ndarray(
    +            (
    +                X_batch.shape[input_index],
    +                X_batch.shape[feature_maps_index],
    +                strided_height,
    +                strided_width,
    +            )
    +        )
    +
    +        # select pooling action, either max or average pooling
    +        if self.pooling == "max":
    +            self.pooling_action = np.max
    +        elif self.pooling == "average":
    +            self.pooling_action = np.mean
    +
    +        # pool based on kernel size and stride
    +        for img in range(output.shape[input_index]):
    +            for fmap in range(output.shape[feature_maps_index]):
    +                for h in range(strided_height):
    +                    for w in range(strided_width):
    +                        output[img, fmap, h, w] = self.pooling_action(
    +                            X_batch[
    +                                img,
    +                                fmap,
    +                                (h * self.v_stride) : (h * self.v_stride)
    +                                + self.kernel_height,
    +                                (w * self.h_stride) : (w * self.h_stride)
    +                                + self.kernel_width,
    +                            ]
    +                        )
    +
    +        # output for feedforward in next layer
    +        return output
    +
    +    def _backpropagate(self, delta_term_next):
    +        # initiate delta term array
    +        delta_term = np.zeros((self.X_batch_feedforward.shape))
    +
    +        for img in range(delta_term_next.shape[input_index]):
    +            for fmap in range(delta_term_next.shape[feature_maps_index]):
    +                for h in range(0, delta_term_next.shape[height_index], self.v_stride):
    +                    for w in range(
    +                        0, delta_term_next.shape[width_index], self.h_stride
    +                    ):
    +                        # max pooling
    +                        if self.pooling == "max":
    +                            # get window
    +                            window = self.X_batch_feedforward[
    +                                img,
    +                                fmap,
    +                                h : h + self.kernel_height,
    +                                w : w + self.kernel_width,
    +                            ]
    +
    +                            # find max values indices in window
    +                            max_h, max_w = np.unravel_index(
    +                                window.argmax(), window.shape
    +                            )
    +
    +                            # set values in new, upsampled delta term
    +                            delta_term[
    +                                img,
    +                                fmap,
    +                                (h + max_h),
    +                                (w + max_w),
    +                            ] += delta_term_next[img, fmap, h, w]
    +
    +                        # average pooling
    +                        if self.pooling == "average":
    +                            delta_term[
    +                                img,
    +                                fmap,
    +                                h : h + self.kernel_height,
    +                                w : w + self.kernel_width,
    +                            ] = (
    +                                delta_term_next[img, fmap, h, w]
    +                                / self.kernel_height
    +                                / self.kernel_width
    +                            )
    +        # returns input to backpropagation in previous layer
    +        return delta_term
    +
    +    def _reset_weights(self, previous_nodes):
    +        # calculate strided height, strided width
    +        strided_height = (
    +            previous_nodes.shape[height_index] - self.kernel_height
    +        ) // self.v_stride + 1
    +        if previous_nodes.shape[height_index] == previous_nodes.shape[width_index]:
    +            strided_width = strided_height
    +        else:
    +            strided_width = (
    +                previous_nodes.shape[width_index] - self.kernel_width
    +            ) // self.h_stride + 1
    +
    +        # initiate output array
    +        output = np.ones(
    +            (
    +                previous_nodes.shape[input_index],
    +                previous_nodes.shape[feature_maps_index],
    +                strided_height,
    +                strided_width,
    +            )
    +        )
    +
    +        # returns output with shape used for reset weights in next layer
    +        return output
    +
    +    def _check_for_errors(self):
    +        # check if input is smaller than kernel size -> error
    +        assert (
    +            self.X_batch_feedforward.shape[width_index] >= self.kernel_width
    +        ), f"ERROR: Pooling kernel width_index ({self.kernel_width}) larger than data width_index ({self.X_batch_feedforward.input.shape[2]}), please lower the kernel width_index of the Pooling2DLayer"
    +        assert (
    +            self.X_batch_feedforward.shape[height_index] >= self.kernel_height
    +        ), f"ERROR: Pooling kernel height_index ({self.kernel_height}) larger than data height_index ({self.X_batch_feedforward.input.shape[3]}), please lower the kernel height_index of the Pooling2DLayer"
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    Flattening Layer

    + +

    Before we can begin building our first CNN model, we need to introduce +the flattening layer. As its name suggests, the flattening layer +transforms the data into a one-dimensional vector that can be fed into +the feedforward layers of our network. This layer plays a crucial role +in preparing the data for further processing in the +network. Additionally, the flattening layer is responsible for +reshaping the gradient to the proper shape during +backpropagation. This ensures that the kernels are correctly updated, +allowing for effective learning in the network. +

    + + + +
    +
    +
    +
    +
    +
    class FlattenLayer(Layer):
    +    def __init__(self, act_func=LRELU, seed=None):
    +        super().__init__(seed)
    +        self.act_func = act_func
    +
    +    def _feedforward(self, X_batch):
    +        # save input for backpropagation
    +        self.X_batch_feedforward_shape = X_batch.shape
    +        # Remember, the data has the following shape: (I, FM, H, W, ) in the convolutional layers
    +        # whilst the data has the shape (I, FM * H * W) in the fully connected layers
    +        # I = Inputs, FM = Feature Maps, H = Height and W = Width.
    +        X_batch = X_batch.reshape(
    +            X_batch.shape[input_index],
    +            X_batch.shape[feature_maps_index]
    +            * X_batch.shape[height_index]
    +            * X_batch.shape[width_index],
    +        )
    +
    +        # add bias to a
    +        self.z_matrix = X_batch
    +        bias = np.ones((X_batch.shape[input_index], 1)) * 0.01
    +        self.a_matrix = np.hstack([bias, X_batch])
    +
    +        # return a, the input to feedforward in next layer
    +        return self.a_matrix
    +
    +    def _backpropagate(self, weights_next, delta_term_next):
    +        activation_derivative = derivate(self.act_func)
    +
    +        # calculate delta term
    +        delta_term = (
    +            weights_next[bias_index:, :] @ delta_term_next.T
    +        ).T * activation_derivative(self.z_matrix)
    +
    +        # FlattenLayer does not update weights
    +        # reshapes delta layer to convolutional layer data format [Input, Feature_Maps, Height, Width]
    +        return delta_term.reshape(self.X_batch_feedforward_shape)
    +
    +    def _reset_weights(self, previous_nodes):
    +        # note that the previous nodes to the FlattenLayer are from the convolutional layers
    +        previous_nodes = previous_nodes.reshape(
    +            previous_nodes.shape[input_index],
    +            previous_nodes.shape[feature_maps_index]
    +            * previous_nodes.shape[height_index]
    +            * previous_nodes.shape[width_index],
    +        )
    +
    +        # return shape used in reset_weights in next layer
    +        return previous_nodes.shape[node_index]
    +
    +    def get_prev_a(self):
    +        return self.a_matrix
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    Fully Connected Layers

    + +

    Finally, the result from the flatten layer will pass to a series of +fully connected layers, which function as a normal feed forward neural +network. The fully connected layers are split into two classes; +FullyConnectedLayer which acts as a hidden layer, and OutputLayer, +which acts as the single output layer at the end of the CNN. If one +wishes to use this codebase to construct a normal feed forward neural +network, it must start with a FlattenLayer due to techincal details +regarding weight intitialization. However many FullyConnectedLayers +can be added to the CNN, and in each layer the amount of nodes, which +activation function and scheduler to use can be specified. In +practice, the scheduler will be specified in the CNN object +initialization, and inherited if no other scheduler is specified. +

    + + + +
    +
    +
    +
    +
    +
    class FullyConnectedLayer(Layer):
    +    # FullyConnectedLayer per default uses LRELU and Adam scheduler
    +    # with an eta of 0.0001, rho of 0.9 and rho2 of 0.999
    +    def __init__(
    +        self,
    +        nodes: int,
    +        act_func: Callable = LRELU,
    +        scheduler: Scheduler = Adam(eta=1e-4, rho=0.9, rho2=0.999),
    +        seed: int = None,
    +    ):
    +        super().__init__(seed)
    +        self.nodes = nodes
    +        self.act_func = act_func
    +        self.scheduler_weight = copy(scheduler)
    +        self.scheduler_bias = copy(scheduler)
    +
    +        # initiate matrices for later
    +        self.weights = None
    +        self.a_matrix = None
    +        self.z_matrix = None
    +
    +    def _feedforward(self, X_batch):
    +        # calculate z
    +        self.z_matrix = X_batch @ self.weights
    +
    +        # calculate a, add bias
    +        bias = np.ones((X_batch.shape[input_index], 1)) * 0.01
    +        self.a_matrix = self.act_func(self.z_matrix)
    +        self.a_matrix = np.hstack([bias, self.a_matrix])
    +
    +        # return a, the input for feedforward in next layer
    +        return self.a_matrix
    +
    +    def _backpropagate(self, weights_next, delta_term_next, a_previous, lam):
    +        # take the derivative of the activation function
    +        activation_derivative = derivate(self.act_func)
    +
    +        # calculate the delta term
    +        delta_term = (
    +            weights_next[bias_index:, :] @ delta_term_next.T
    +        ).T * activation_derivative(self.z_matrix)
    +
    +        # intitiate matrix to store gradient
    +        # note that we exclude the bias term, which we will calculate later
    +        gradient_weights = np.zeros(
    +            (
    +                a_previous.shape[input_index],
    +                a_previous.shape[node_index] - bias_index,
    +                delta_term.shape[node_index],
    +            )
    +        )
    +
    +        # calculate gradient = delta term * previous a
    +        for i in range(len(delta_term)):
    +            gradient_weights[i, :, :] = np.outer(
    +                a_previous[i, bias_index:], delta_term[i, :]
    +            )
    +
    +        # sum the gradient, divide by input_index
    +        gradient_weights = np.mean(gradient_weights, axis=input_index)
    +        # for the bias gradient we do not multiply by previous a
    +        gradient_bias = np.mean(delta_term, axis=input_index).reshape(
    +            1, delta_term.shape[node_index]
    +        )
    +
    +        # regularization term
    +        gradient_weights += self.weights[bias_index:, :] * lam
    +
    +        # send gradients into scheduler
    +        # returns update matrix which will be used to update the weights and bias
    +        update_matrix = np.vstack(
    +            [
    +                self.scheduler_bias.update_change(gradient_bias),
    +                self.scheduler_weight.update_change(gradient_weights),
    +            ]
    +        )
    +
    +        # update weights
    +        self.weights -= update_matrix
    +
    +        # return weights and delta term, input for backpropagation in previous layer
    +        return self.weights, delta_term
    +
    +    def _reset_weights(self, previous_nodes):
    +        # sets seed to remove randomness inbetween runs
    +        if self.seed is not None:
    +            np.random.seed(self.seed)
    +
    +        # add bias, initiate random weights
    +        bias = 1
    +        self.weights = np.random.randn(previous_nodes + bias, self.nodes)
    +
    +        # returns number of nodes, used for reset_weights in next layer
    +        return self.nodes
    +
    +    def _reset_scheduler(self):
    +        # resets scheduler per epoch
    +        self.scheduler_weight.reset()
    +        self.scheduler_bias.reset()
    +
    +    def get_prev_a(self):
    +        # returns a matrix, used in backpropagation
    +        return self.a_matrix
    +
    +
    +class OutputLayer(FullyConnectedLayer):
    +    def __init__(
    +        self,
    +        nodes: int,
    +        output_func: Callable = LRELU,
    +        cost_func: Callable = CostCrossEntropy,
    +        scheduler: Scheduler = Adam(eta=1e-4, rho=0.9, rho2=0.999),
    +        seed: int = None,
    +    ):
    +        super().__init__(nodes, output_func, copy(scheduler), seed)
    +        self.cost_func = cost_func
    +
    +        # initiate matrices for later
    +        self.weights = None
    +        self.a_matrix = None
    +        self.z_matrix = None
    +
    +        # decides if the output layer performs binary or multi-class classification
    +        self._set_pred_format()
    +
    +    def _feedforward(self, X_batch: np.ndarray):
    +        # calculate a, z
    +        # note that bias is not added as this would create an extra output class
    +        self.z_matrix = X_batch @ self.weights
    +        self.a_matrix = self.act_func(self.z_matrix)
    +
    +        # returns prediction
    +        return self.a_matrix
    +
    +    def _backpropagate(self, target, a_previous, lam):
    +        # note that in the OutputLayer the activation function is the output function
    +        activation_derivative = derivate(self.act_func)
    +
    +        # calculate output delta terms
    +        # for multi-class or binary classification
    +        if self.pred_format == "Multi-class":
    +            delta_term = self.a_matrix - target
    +        else:
    +            cost_func_derivative = grad(self.cost_func(target))
    +            delta_term = activation_derivative(self.z_matrix) * cost_func_derivative(
    +                self.a_matrix
    +            )
    +
    +        # intiate matrix that stores gradient
    +        gradient_weights = np.zeros(
    +            (
    +                a_previous.shape[input_index],
    +                a_previous.shape[node_index] - bias_index,
    +                delta_term.shape[node_index],
    +            )
    +        )
    +
    +        # calculate gradient = delta term * previous a
    +        for i in range(len(delta_term)):
    +            gradient_weights[i, :, :] = np.outer(
    +                a_previous[i, bias_index:], delta_term[i, :]
    +            )
    +
    +        # sum the gradient, divide by input_index
    +        gradient_weights = np.mean(gradient_weights, axis=input_index)
    +        # for the bias gradient we do not multiply by previous a
    +        gradient_bias = np.mean(delta_term, axis=input_index).reshape(
    +            1, delta_term.shape[node_index]
    +        )
    +
    +        # regularization term
    +        gradient_weights += self.weights[bias_index:, :] * lam
    +
    +        # send gradients into scheduler
    +        # returns update matrix which will be used to update the weights and bias
    +        update_matrix = np.vstack(
    +            [
    +                self.scheduler_bias.update_change(gradient_bias),
    +                self.scheduler_weight.update_change(gradient_weights),
    +            ]
    +        )
    +
    +        # update weights
    +        self.weights -= update_matrix
    +
    +        # return weights and delta term, input for backpropagation in previous layer
    +        return self.weights, delta_term
    +
    +    def _reset_weights(self, previous_nodes):
    +        # sets seed to remove randomness inbetween runs
    +        if self.seed is not None:
    +            np.random.seed(self.seed)
    +
    +        # add bias, initiate random weights
    +        bias = 1
    +        self.weights = np.random.rand(previous_nodes + bias, self.nodes)
    +
    +        # returns number of nodes, used for reset_weights in next layer
    +        return self.nodes
    +
    +    def _reset_scheduler(self):
    +        # resets scheduler per epoch
    +        self.scheduler_weight.reset()
    +        self.scheduler_bias.reset()
    +
    +    def _set_pred_format(self):
    +        # sets prediction format to either regression, binary or multi-class classification
    +        if self.act_func.__name__ is None or self.act_func.__name__ == "identity":
    +            self.pred_format = "Regression"
    +        elif self.act_func.__name__ == "sigmoid" or self.act_func.__name__ == "tanh":
    +            self.pred_format = "Binary"
    +        else:
    +            self.pred_format = "Multi-class"
    +
    +    def get_pred_format(self):
    +        # returns format of prediction
    +        return self.pred_format
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    Optimized Convolution2DLayer

    + +

    For our CNN, we have also implemented an optimized version of the +Convolution2DLayer, Convolution2DLayerOPT, which runs much faster. See +VII. Remarks for discussion. This layer will per default be used by +the CNN due to its computational advantages, but is much less +readable. We've documented it such that specially interested students +can understand the principles behind it, but it is not recommended to +read. In short, we reshape and transpose parts of the image such that +the convolutional operation can be swapped out for a simple matrix +multiplication. +

    + + + +
    +
    +
    +
    +
    +
    class Convolution2DLayerOPT(Convolution2DLayer):
    +    """
    +    Am optimized version of the convolution layer above which
    +    utilizes an approach of extracting windows of size equivalent
    +    in size to the filter. The convoution is then performed on those
    +    windows instead of a full feature map.
    +    """
    +
    +    def __init__(
    +        self,
    +        input_channels,
    +        feature_maps,
    +        kernel_height,
    +        kernel_width,
    +        v_stride,
    +        h_stride,
    +        pad,
    +        act_func: Callable,
    +        seed=None,
    +        reset_weights_independently=True,
    +    ):
    +        super().__init__(
    +            input_channels,
    +            feature_maps,
    +            kernel_height,
    +            kernel_width,
    +            v_stride,
    +            h_stride,
    +            pad,
    +            act_func,
    +            seed,
    +        )
    +        # true if layer is used outside of CNN
    +        if reset_weights_independently == True:
    +            self._reset_weights_independently()
    +
    +    def _feedforward(self, X_batch):
    +        # The optimized _feedforward method is difficult to understand but computationally more efficient
    +        # for a more "by the book" approach, please look at the _feedforward method of Convolution2DLayer
    +
    +        # save the input for backpropagation
    +        self.X_batch_feedforward = X_batch
    +
    +        # check that there are the correct amount of input channels
    +        self._check_for_errors()
    +
    +        # calculate new shape after stride
    +        strided_height = int(np.ceil(X_batch.shape[height_index] / self.v_stride))
    +        strided_width = int(np.ceil(X_batch.shape[width_index] / self.h_stride))
    +
    +        # get windows of the image for more computationally efficient convolution
    +        # the idea is that we want to align the dimensions that we wish to matrix
    +        # multiply, then use a simple matrix multiplication instead of convolution.
    +        # then, we reshape the size back to its intended shape
    +        windows = self._extract_windows(X_batch)
    +        windows = windows.transpose(1, 0, 2, 3, 4).reshape(
    +            X_batch.shape[input_index],
    +            strided_height * strided_width,
    +            -1,
    +        )
    +
    +        # reshape the kernel for more computationally efficient convolution
    +        kernel = self.kernel
    +        kernel = kernel.transpose(0, 2, 3, 1).reshape(
    +            kernel.shape[kernel_input_channels_index]
    +            * kernel.shape[height_index]
    +            * kernel.shape[width_index],
    +            -1,
    +        )
    +
    +        # use simple matrix calculation to obtain output
    +        output = (
    +            (windows @ kernel)
    +            .reshape(
    +                X_batch.shape[input_index],
    +                strided_height,
    +                strided_width,
    +                -1,
    +            )
    +            .transpose(0, 3, 1, 2)
    +        )
    +
    +        # The output is reshaped and rearranged to appropriate shape
    +        return self.act_func(
    +            output / (self.kernel_height * X_batch.shape[feature_maps_index])
    +        )
    +
    +    def _backpropagate(self, delta_term_next):
    +        # The optimized _backpropagate method is difficult to understand but computationally more efficient
    +        # for a more "by the book" approach, please look at the _backpropagate method of Convolution2DLayer
    +        act_derivative = derivate(self.act_func)
    +        delta_term_next = act_derivative(delta_term_next)
    +
    +        # calculate strided dimensions
    +        strided_height = int(
    +            np.ceil(self.X_batch_feedforward.shape[height_index] / self.v_stride)
    +        )
    +        strided_width = int(
    +            np.ceil(self.X_batch_feedforward.shape[width_index] / self.h_stride)
    +        )
    +
    +        # copy kernel
    +        kernel = self.kernel
    +
    +        # get windows, reshape for matrix multiplication
    +        windows = self._extract_windows(self.X_batch_feedforward, "image").reshape(
    +            self.X_batch_feedforward.shape[input_index]
    +            * strided_height
    +            * strided_width,
    +            -1,
    +        )
    +
    +        # initialize output gradient, reshape and transpose into correct shape
    +        # for matrix multiplication
    +        output_grad_tr = delta_term_next.transpose(0, 2, 3, 1).reshape(
    +            self.X_batch_feedforward.shape[input_index]
    +            * strided_height
    +            * strided_width,
    +            -1,
    +        )
    +
    +        # calculate gradient kernel via simple matrix multiplication and reshaping
    +        gradient_kernel = (
    +            (windows.T @ output_grad_tr)
    +            .reshape(
    +                kernel.shape[kernel_input_channels_index],
    +                kernel.shape[height_index],
    +                kernel.shape[width_index],
    +                kernel.shape[kernel_feature_maps_index],
    +            )
    +            .transpose(0, 3, 1, 2)
    +        )
    +
    +        # for computing the input gradient
    +        windows_out, upsampled_height, upsampled_width = self._extract_windows(
    +            delta_term_next, "grad"
    +        )
    +
    +        # calculate new window dimensions
    +        new_windows_first_dim = (
    +            self.X_batch_feedforward.shape[input_index]
    +            * upsampled_height
    +            * upsampled_width
    +        )
    +        # ceil allows for various asymmetric kernels
    +        new_windows_sec_dim = int(np.ceil(windows_out.size / new_windows_first_dim))
    +
    +        # reshape for matrix multiplication
    +        windows_out = windows_out.transpose(1, 0, 2, 3, 4).reshape(
    +            new_windows_first_dim, new_windows_sec_dim
    +        )
    +
    +        # reshape for matrix multiplication
    +        kernel_reshaped = kernel.reshape(self.input_channels, -1)
    +
    +        # calculating input gradient for next convolutional layer
    +        input_grad = (windows_out @ kernel_reshaped.T).reshape(
    +            self.X_batch_feedforward.shape[input_index],
    +            upsampled_height,
    +            upsampled_width,
    +            kernel.shape[kernel_input_channels_index],
    +        )
    +        input_grad = input_grad.transpose(0, 3, 1, 2)
    +
    +        # Update the weights in the kernel
    +        self.kernel -= gradient_kernel
    +
    +        # Output the gradient to propagate backwards
    +        return input_grad
    +
    +    def _extract_windows(self, X_batch, batch_type="image"):
    +        """
    +        Receives as input the X_batch with shape (inputs, feature_maps, image_height, image_width)
    +        and extract windows of size kernel_height * kernel_width for every image and every feature_map.
    +        It then returns an np.ndarray of shape (image_height * image_width, inputs, feature_maps, kernel_height, kernel_width)
    +        which will be used either to filter the images in feedforward or to calculate the gradient.
    +        """
    +
    +        # initialize list of windows
    +        windows = []
    +
    +        if batch_type == "image":
    +            # pad the images
    +            X_batch_padded = self._padding(X_batch, batch_type="image")
    +            img_height, img_width = X_batch_padded.shape[2:]
    +            # For each location in the image...
    +            for h in range(
    +                0,
    +                X_batch.shape[height_index],
    +                self.v_stride,
    +            ):
    +                for w in range(
    +                    0,
    +                    X_batch.shape[width_index],
    +                    self.h_stride,
    +                ):
    +                    # ...obtain an image patch of the original size (strided)
    +
    +                    # get window
    +                    window = X_batch_padded[
    +                        :,
    +                        :,
    +                        h : h + self.kernel_height,
    +                        w : w + self.kernel_width,
    +                    ]
    +
    +                    # append to list of windows
    +                    windows.append(window)
    +
    +            # return numpy array instead of list
    +            return np.stack(windows)
    +
    +        # In order to be able to perform backprogagation by the method of window extraction,
    +        # here is a modified approach to extracting the windows which allow for the necessary
    +        # upsampling of the gradient in case the on of the stride parameters is larger than one.
    +
    +        if batch_type == "grad":
    +
    +            # In the case of one of the stride parameters being odd, we have to take some
    +            # extra care in calculating the upsampled size of X_batch. We solve this
    +            # by simply flooring the result of dividing stride by 2.
    +            if self.v_stride < 2 or self.v_stride % 2 == 0:
    +                v_stride = 0
    +            else:
    +                v_stride = int(np.floor(self.v_stride / 2))
    +
    +            if self.h_stride < 2 or self.h_stride % 2 == 0:
    +                h_stride = 0
    +            else:
    +                h_stride = int(np.floor(self.h_stride / 2))
    +
    +            upsampled_height = (X_batch.shape[height_index] * self.v_stride) - v_stride
    +            upsampled_width = (X_batch.shape[width_index] * self.h_stride) - h_stride
    +
    +            # When upsampling, we need to insert rows and columns filled with zeros
    +            # into each feature map. How many of those we have to insert is purely
    +            # dependant on the value of stride parameter in the vertical and horizontal
    +            # direction.
    +            if self.v_stride > 1:
    +                v_ind = 1
    +                for i in range(X_batch.shape[height_index]):
    +                    for j in range(self.v_stride - 1):
    +                        X_batch = np.insert(X_batch, v_ind, 0, axis=height_index)
    +                    v_ind += self.v_stride
    +
    +            if self.h_stride > 1:
    +                h_ind = 1
    +                for i in range(X_batch.shape[width_index]):
    +                    for k in range(self.h_stride - 1):
    +                        X_batch = np.insert(X_batch, h_ind, 0, axis=width_index)
    +                    h_ind += self.h_stride
    +
    +            # Since the insertion of zero-filled rows and columns isn't perfect, we have
    +            # to assure that the resulting feature maps will have the expected upsampled height
    +            # and width by cutting them og at desired dimensions.
    +
    +            X_batch = X_batch[:, :, :upsampled_height, :upsampled_width]
    +
    +            X_batch_padded = self._padding(X_batch, batch_type="grad")
    +
    +            # initialize list of windows
    +            windows = []
    +
    +            # For each location in the image...
    +            for h in range(
    +                0,
    +                X_batch.shape[height_index],
    +                self.v_stride,
    +            ):
    +                for w in range(
    +                    0,
    +                    X_batch.shape[width_index],
    +                    self.h_stride,
    +                ):
    +                    # ...obtain an image patch of the original size (strided)
    +
    +                    # get window
    +                    window = X_batch_padded[
    +                        :, :, h : h + self.kernel_height, w : w + self.kernel_width
    +                    ]
    +
    +                    # append window to list
    +                    windows.append(window)
    +
    +            # return numpy array, unsampled dimensions
    +            return np.stack(windows), upsampled_height, upsampled_width
    +
    +    def _check_for_errors(self):
    +        # compares input channels of data to input channels of Convolution2DLayer
    +        if self.X_batch_feedforward.shape[input_channel_index] != self.input_channels:
    +            raise AssertionError(
    +                f"ERROR: Number of input channels in data ({self.X_batch_feedforward.shape[input_channel_index]}) is not equal to input channels in Convolution2DLayerOPT ({self.input_channels})! Please change the number of input channels of the Convolution2DLayer such that they are equal"
    +            )
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    The Convolutional Neural Network (CNN)

    + +

    Finally, we present the code for the CNN. The CNN class organizes all the layers, and allows for training on image data.

    + + + +
    +
    +
    +
    +
    +
    import math
    +import autograd.numpy as np
    +import sys
    +import warnings
    +from autograd import grad, elementwise_grad
    +from random import random, seed
    +from copy import deepcopy
    +from typing import Tuple, Callable
    +from sklearn.utils import resample
    +
    +warnings.simplefilter("error")
    +
    +
    +class CNN:
    +    def __init__(
    +        self,
    +        cost_func: Callable = CostCrossEntropy,
    +        scheduler: Scheduler = Adam(eta=1e-4, rho=0.9, rho2=0.999),
    +        seed: int = None,
    +    ):
    +        """
    +        Description:
    +        ------------
    +            Instantiates CNN object
    +
    +        Parameters:
    +        ------------
    +            I   output_func (costFunctions) cost function for feed forward neural network part of CNN,
    +                such as "CostLogReg", "CostOLS" or "CostCrossEntropy"
    +
    +            II  scheduler (Scheduler) optional parameter, default set to Adam. Can also be set to other
    +                schedulers such as AdaGrad, Momentum, RMS_prop and Constant. Note that schedulers have
    +                to be instantiated first with proper parameters (for example eta, rho and rho2 for Adam)
    +
    +            III seed (int) used for seeding all random operations
    +        """
    +        self.layers = list()
    +        self.cost_func = cost_func
    +        self.scheduler = scheduler
    +        self.schedulers_weight = list()
    +        self.schedulers_bias = list()
    +        self.seed = seed
    +        self.pred_format = None
    +
    +    def add_FullyConnectedLayer(
    +        self, nodes: int, act_func=LRELU, scheduler=None
    +    ) -> None:
    +        """
    +        Description:
    +        ------------
    +            Add a FullyConnectedLayer to the CNN, i.e. a hidden layer in the feed forward neural
    +            network part of the CNN. Often called a Dense layer in literature
    +
    +        Parameters:
    +        ------------
    +            I   nodes (int) number of nodes in FullyConnectedLayer
    +            II  act_func (activationFunctions) activation function of FullyConnectedLayer,
    +                such as "sigmoid", "RELU", "LRELU", "softmax" or "identity"
    +            III scheduler (Scheduler) optional parameter, default set to Adam. Can also be set to other
    +                schedulers such as AdaGrad, Momentum, RMS_prop and Constant
    +        """
    +        assert self.layers, "FullyConnectedLayer should follow FlattenLayer in CNN"
    +
    +        if scheduler is None:
    +            scheduler = self.scheduler
    +
    +        layer = FullyConnectedLayer(nodes, act_func, scheduler, self.seed)
    +        self.layers.append(layer)
    +
    +    def add_OutputLayer(self, nodes: int, output_func=sigmoid, scheduler=None) -> None:
    +        """
    +        Description:
    +        ------------
    +            Add an OutputLayer to the CNN, i.e. a the final layer in the feed forward neural
    +            network part of the CNN
    +
    +        Parameters:
    +        ------------
    +            I   nodes (int) number of nodes in OutputLayer. Set nodes=1 for binary classification and
    +                nodes = number of classes for multi-class classification
    +            II  output_func (activationFunctions) activation function for the output layer, such as
    +                "identity" for regression, "sigmoid" for binary classification and "softmax" for multi-class
    +                classification
    +            III scheduler (Scheduler) optional parameter, default set to Adam. Can also be set to other
    +                schedulers such as AdaGrad, Momentum, RMS_prop and Constant
    +        """
    +        assert self.layers, "OutputLayer should follow FullyConnectedLayer in CNN"
    +
    +        if scheduler is None:
    +            scheduler = self.scheduler
    +
    +        output_layer = OutputLayer(
    +            nodes, output_func, self.cost_func, scheduler, self.seed
    +        )
    +        self.layers.append(output_layer)
    +        self.pred_format = output_layer.get_pred_format()
    +
    +    def add_FlattenLayer(self, act_func=LRELU) -> None:
    +        """
    +        Description:
    +        ------------
    +            Add a FlattenLayer to the CNN, which flattens the image data such that it is formatted to
    +            be used in the feed forward neural network part of the CNN
    +        """
    +        self.layers.append(FlattenLayer(act_func=act_func, seed=self.seed))
    +
    +    def add_Convolution2DLayer(
    +        self,
    +        input_channels=1,
    +        feature_maps=1,
    +        kernel_height=3,
    +        kernel_width=3,
    +        v_stride=1,
    +        h_stride=1,
    +        pad="same",
    +        act_func=LRELU,
    +        optimized=True,
    +    ) -> None:
    +        """
    +        Description:
    +        ------------
    +            Add a Convolution2DLayer to the CNN, i.e. a convolutional layer with a 2 dimensional kernel. Should be
    +            the first layer added to the CNN
    +
    +        Parameters:
    +        ------------
    +            I   input_channels (int) specifies amount of input channels. For monochrome images, use input_channels
    +                = 1, and input_channels = 3 for colored images, where each channel represents one of R, G and B
    +            II  feature_maps (int) amount of feature maps in CNN
    +            III kernel_height (int) height of the kernel, also called 'convolutional filter' in literature
    +            IV  kernel_width (int) width of the kernel, also called 'convolutional filter' in literature
    +            V   v_stride (int) value of vertical stride for dimentionality reduction
    +            VI  h_stride (int) value of horizontal stride for dimentionality reduction
    +            VII pad (str) default = "same" ensures output size is the same as input size (given stride=1)
    +           VIII act_func (activationFunctions) default = "LRELU", nonlinear activation function
    +             IX optimized (bool) default = True, uses Convolution2DLayerOPT if True which is much faster when
    +                compared to Convolution2DLayer, which is a more straightforward, understandable implementation
    +        """
    +        if optimized:
    +            conv_layer = Convolution2DLayerOPT(
    +                input_channels,
    +                feature_maps,
    +                kernel_height,
    +                kernel_width,
    +                v_stride,
    +                h_stride,
    +                pad,
    +                act_func,
    +                self.seed,
    +                reset_weights_independently=False,
    +            )
    +        else:
    +            conv_layer = Convolution2DLayer(
    +                input_channels,
    +                feature_maps,
    +                kernel_height,
    +                kernel_width,
    +                v_stride,
    +                h_stride,
    +                pad,
    +                act_func,
    +                self.seed,
    +                reset_weights_independently=False,
    +            )
    +        self.layers.append(conv_layer)
    +
    +    def add_PoolingLayer(
    +        self, kernel_height=2, kernel_width=2, v_stride=1, h_stride=1, pooling="max"
    +    ) -> None:
    +        """
    +        Description:
    +        ------------
    +            Add a Pooling2DLayer to the CNN, i.e. a pooling layer that reduces the dimentionality of
    +            the image data. It is not necessary to use a Pooling2DLayer when creating a CNN, but it
    +            can be used to speed up the training
    +
    +        Parameters:
    +        ------------
    +            I   kernel_height (int) height of the kernel used for pooling
    +            II  kernel_width (int) width of the kernel used for pooling
    +            III v_stride (int) value of vertical stride for dimentionality reduction
    +            IV  h_stride (int) value of horizontal stride for dimentionality reduction
    +            V   pooling (str) either "max" or "average", describes type of pooling performed
    +        """
    +        pooling_layer = Pooling2DLayer(
    +            kernel_height, kernel_width, v_stride, h_stride, pooling, self.seed
    +        )
    +        self.layers.append(pooling_layer)
    +
    +    def fit(
    +        self,
    +        X: np.ndarray,
    +        t: np.ndarray,
    +        epochs: int = 100,
    +        lam: float = 0,
    +        batches: int = 1,
    +        X_val: np.ndarray = None,
    +        t_val: np.ndarray = None,
    +    ) -> dict:
    +        """
    +        Description:
    +        ------------
    +            Fits the CNN to input X for a given amount of epochs. Performs feedforward and backpropagation passes,
    +            can utilize batches, regulariziation and validation if desired.
    +
    +        Parameters:
    +        ------------
    +            X (numpy array) with input data in format [images, input channels,
    +            image height, image_width]
    +            t (numpy array) target labels for input data
    +            epochs (int) amount of epochs
    +            lam (float) regulariziation term lambda
    +            batches (int) amount of batches input data splits into
    +            X_val (numpy array) validation data
    +            t_val (numpy array) target labels for validation data
    +
    +        Returns:
    +        ------------
    +            scores (dict) a dictionary with "train_error", "train_acc", "val_error", val_acc" keys
    +            that contain numpy arrays with float values of all accuracies/errors over all epochs.
    +            Can be used to create plots. Also used to update the progress bar during training
    +        """
    +
    +        # setup
    +        if self.seed is not None:
    +            np.random.seed(self.seed)
    +
    +        # initialize weights
    +        self._initialize_weights(X)
    +
    +        # create arrays for score metrics
    +        scores = self._initialize_scores(epochs)
    +
    +        assert batches <= t.shape[0]
    +        batch_size = X.shape[0] // batches
    +
    +        try:
    +            for epoch in range(epochs):
    +                for batch in range(batches):
    +                    # minibatch gradient descent
    +                    # If the for loop has reached the last batch, take all thats left
    +                    if batch == batches - 1:
    +                        X_batch = X[batch * batch_size :, :, :, :]
    +                        t_batch = t[batch * batch_size :, :]
    +                    else:
    +                        X_batch = X[
    +                            batch * batch_size : (batch + 1) * batch_size, :, :, :
    +                        ]
    +                        t_batch = t[batch * batch_size : (batch + 1) * batch_size, :]
    +
    +                    self._feedforward(X_batch)
    +                    self._backpropagate(t_batch, lam)
    +
    +                # reset schedulers for each epoch (some schedulers pass in this call)
    +                for layer in self.layers:
    +                    if isinstance(layer, FullyConnectedLayer):
    +                        layer._reset_scheduler()
    +
    +                # computing performance metrics
    +                scores = self._compute_scores(scores, epoch, X, t, X_val, t_val)
    +
    +                # printing progress bar
    +                print_length = self._progress_bar(
    +                    epoch,
    +                    epochs,
    +                    scores,
    +                )
    +        # allows for stopping training at any point and seeing the result
    +        except KeyboardInterrupt:
    +            pass
    +
    +        # visualization of training progression (similiar to tensorflow progression bar)
    +        sys.stdout.write("\r" + " " * print_length)
    +        sys.stdout.flush()
    +        self._progress_bar(
    +            epochs,
    +            epochs,
    +            scores,
    +        )
    +        sys.stdout.write("")
    +
    +        return scores
    +
    +    def _feedforward(self, X_batch) -> np.ndarray:
    +        """
    +        Description:
    +        ------------
    +            Performs the feedforward pass for all layers in the CNN. Called from fit()
    +        """
    +        a = X_batch
    +        for layer in self.layers:
    +            a = layer._feedforward(a)
    +
    +        return a
    +
    +    def _backpropagate(self, t_batch, lam) -> None:
    +        """
    +        Description:
    +        ------------
    +            Performs backpropagation for all layers in the CNN. Called from fit()
    +        """
    +        assert len(self.layers) >= 2
    +        reversed_layers = self.layers[::-1]
    +
    +        # for every layer, backwards
    +        for i in range(len(reversed_layers) - 1):
    +            layer = reversed_layers[i]
    +            prev_layer = reversed_layers[i + 1]
    +
    +            # OutputLayer
    +            if isinstance(layer, OutputLayer):
    +                prev_a = prev_layer.get_prev_a()
    +                weights_next, delta_next = layer._backpropagate(t_batch, prev_a, lam)
    +
    +            # FullyConnectedLayer
    +            elif isinstance(layer, FullyConnectedLayer):
    +                assert (
    +                    delta_next is not None
    +                ), "No OutputLayer to follow FullyConnectedLayer"
    +                assert (
    +                    weights_next is not None
    +                ), "No OutputLayer to follow FullyConnectedLayer"
    +                prev_a = prev_layer.get_prev_a()
    +                weights_next, delta_next = layer._backpropagate(
    +                    weights_next, delta_next, prev_a, lam
    +                )
    +
    +            # FlattenLayer
    +            elif isinstance(layer, FlattenLayer):
    +                assert (
    +                    delta_next is not None
    +                ), "No FullyConnectedLayer to follow FlattenLayer"
    +                assert (
    +                    weights_next is not None
    +                ), "No FullyConnectedLayer to follow FlattenLayer"
    +                delta_next = layer._backpropagate(weights_next, delta_next)
    +
    +            # Convolution2DLayer and Convolution2DLayerOPT
    +            elif isinstance(layer, Convolution2DLayer):
    +                assert (
    +                    delta_next is not None
    +                ), "No FlattenLayer to follow Convolution2DLayer"
    +                delta_next = layer._backpropagate(delta_next)
    +
    +            # Pooling2DLayer
    +            elif isinstance(layer, Pooling2DLayer):
    +                assert delta_next is not None, "No Layer to follow Pooling2DLayer"
    +                delta_next = layer._backpropagate(delta_next)
    +
    +            # Catch error
    +            else:
    +                raise NotImplementedError
    +
    +    def _compute_scores(
    +        self,
    +        scores: dict,
    +        epoch: int,
    +        X: np.ndarray,
    +        t: np.ndarray,
    +        X_val: np.ndarray,
    +        t_val: np.ndarray,
    +    ) -> dict:
    +        """
    +        Description:
    +        ------------
    +            Computes scores such as training error, training accuracy, validation error
    +            and validation accuracy for the CNN depending on if a validation set is used
    +            and if the CNN performs classification or regression
    +
    +        Returns:
    +        ------------
    +            scores (dict) a dictionary with "train_error", "train_acc", "val_error", val_acc" keys
    +            that contain numpy arrays with float values of all accuracies/errors over all epochs.
    +            Can be used to create plots. Also used to update the progress bar during training
    +        """
    +
    +        pred_train = self.predict(X)
    +        cost_function_train = self.cost_func(t)
    +        train_error = cost_function_train(pred_train)
    +        scores["train_error"][epoch] = train_error
    +
    +        if X_val is not None and t_val is not None:
    +            cost_function_val = self.cost_func(t_val)
    +            pred_val = self.predict(X_val)
    +            val_error = cost_function_val(pred_val)
    +            scores["val_error"][epoch] = val_error
    +
    +        if self.pred_format != "Regression":
    +            train_acc = self._accuracy(pred_train, t)
    +            scores["train_acc"][epoch] = train_acc
    +            if X_val is not None and t_val is not None:
    +                val_acc = self._accuracy(pred_val, t_val)
    +                scores["val_acc"][epoch] = val_acc
    +
    +        return scores
    +
    +    def _initialize_scores(self, epochs) -> dict:
    +        """
    +        Description:
    +        ------------
    +            Initializes scores such as training error, training accuracy, validation error
    +            and validation accuracy for the CNN
    +
    +        Returns:
    +        ------------
    +            A dictionary with "train_error", "train_acc", "val_error", val_acc" keys that
    +            will contain numpy arrays with float values of all accuracies/errors over all epochs
    +            when passed through the _compute_scores() function during fit()
    +        """
    +        scores = dict()
    +
    +        train_errors = np.empty(epochs)
    +        train_errors.fill(np.nan)
    +        val_errors = np.empty(epochs)
    +        val_errors.fill(np.nan)
    +
    +        train_accs = np.empty(epochs)
    +        train_accs.fill(np.nan)
    +        val_accs = np.empty(epochs)
    +        val_accs.fill(np.nan)
    +
    +        scores["train_error"] = train_errors
    +        scores["val_error"] = val_errors
    +        scores["train_acc"] = train_accs
    +        scores["val_acc"] = val_accs
    +
    +        return scores
    +
    +    def _initialize_weights(self, X: np.ndarray) -> None:
    +        """
    +        Description:
    +        ------------
    +            Initializes weights for all layers in CNN
    +
    +        Parameters:
    +        ------------
    +            I   X (np.ndarray) input of format [img, feature_maps, height, width]
    +        """
    +        prev_nodes = X
    +        for layer in self.layers:
    +            prev_nodes = layer._reset_weights(prev_nodes)
    +
    +    def predict(self, X: np.ndarray, *, threshold=0.5) -> np.ndarray:
    +        """
    +        Description:
    +        ------------
    +            Predicts output of input X
    +
    +        Parameters:
    +        ------------
    +            I   X (np.ndarray) input [img, feature_maps, height, width]
    +        """
    +
    +        prediction = self._feedforward(X)
    +
    +        if self.pred_format == "Binary":
    +            return np.where(prediction > threshold, 1, 0)
    +        elif self.pred_format == "Multi-class":
    +            class_prediction = np.zeros(prediction.shape)
    +            for i in range(prediction.shape[0]):
    +                class_prediction[i, np.argmax(prediction[i, :])] = 1
    +            return class_prediction
    +        else:
    +            return prediction
    +
    +    def _accuracy(self, prediction: np.ndarray, target: np.ndarray) -> float:
    +        """
    +        Description:
    +        ------------
    +            Calculates accuracy of given prediction to target
    +
    +        Parameters:
    +        ------------
    +            I   prediction (np.ndarray): output of predict() fuction
    +            (1s and 0s in case of classification, and real numbers in case of regression)
    +            II  target (np.ndarray): vector of true values (What the network should predict)
    +
    +        Returns:
    +        ------------
    +            A floating point number representing the percentage of correctly classified instances.
    +        """
    +        assert prediction.size == target.size
    +        return np.average((target == prediction))
    +
    +    def _progress_bar(self, epoch: int, epochs: int, scores: dict) -> int:
    +        """
    +        Description:
    +        ------------
    +            Displays progress of training
    +        """
    +        progression = epoch / epochs
    +        epoch -= 1
    +        print_length = 40
    +        num_equals = int(progression * print_length)
    +        num_not = print_length - num_equals
    +        arrow = ">" if num_equals > 0 else ""
    +        bar = "[" + "=" * (num_equals - 1) + arrow + "-" * num_not + "]"
    +        perc_print = self._fmt(progression * 100, N=5)
    +        line = f"  {bar} {perc_print}% "
    +
    +        for key, score in scores.items():
    +            if np.isnan(score[epoch]) == False:
    +                value = self._fmt(score[epoch], N=4)
    +                line += f"| {key}: {value} "
    +        print(line, end="\r")
    +        return len(line)
    +
    +    def _fmt(self, value: int, N=4) -> str:
    +        """
    +        Description:
    +        ------------
    +            Formats decimal numbers for progress bar
    +        """
    +        if value > 0:
    +            v = value
    +        elif value < 0:
    +            v = -10 * value
    +        else:
    +            v = 1
    +        n = 1 + math.floor(math.log10(v))
    +        if n >= N - 1:
    +            return str(round(value))
    +            # or overflow
    +        return f"{value:.{N-n-1}f}"
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    Usage of CNN code

    + +

    Using the CNN codebase is very simple. We begin by initiating a CNN +object, which takes a cost function, a scheduler and a seed as its +arguments. If a scheduler is not provided, it will per default +initiate an Adam scheduler with eta=1e-4, and if a seed is not +provided, the CNN will not be seeded, meaning it will run with a +different random seed every run. Below we demonstrate an initiation of +our CNN. +

    + + + +
    +
    +
    +
    +
    +
    adam_scheduler = Adam(eta=1e-3, rho=0.9, rho2=0.999)
    +cnn = CNN(cost_func=CostCrossEntropy, scheduler=adam_scheduler, seed=2023)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    Now that we have our CNN object, we can begin to add layers to it! +Many of the add_layer functions have default values, for example +add_Convolution2DLayer() has a default v_stride and h_stride of +1. However, these can of course be set to any value you please. Note +that the input channels of a subsequent convolutional layer must equal +the previous convolutional layer's feature maps. +

    + + + +
    +
    +
    +
    +
    +
    cnn.add_Convolution2DLayer(
    +    input_channels=1,
    +    feature_maps=1,
    +    kernel_height=3,
    +    kernel_width=3,
    +    act_func=LRELU,
    +)
    +
    +cnn.add_FlattenLayer()
    +
    +cnn.add_FullyConnectedLayer(30, LRELU)
    +
    +cnn.add_FullyConnectedLayer(20, LRELU)
    +
    +cnn.add_OutputLayer(10, softmax)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    Here we have created a CNN with the following architecture:

    + +
      +

    1. A convolutional layer with 1 input channel, with a kernel height of 2 and a width of 2, which uses LRELU as its non-linearity function. This layer outputs 1 feature map, which feed into the subsequent layer.
    2. +

    3. A flatten layer
    4. +

    5. A hidden layer with 30 nodes, with LRELU as its activation function
    6. +

    7. Another hidden layer but with 20 nodes
    8. +

    9. The output layer, with softmax as its activation function and 10 nodes. We use 10 nodes because we will be using a dataset with 10 classes.
    10. +
    +

    +

    Now, before we can train the model, we need to load in our data. We +will use the MNIST dataset and use 10000 \( 28 \times 28 images \). +

    + + + +
    +
    +
    +
    +
    +
    from sklearn.datasets import fetch_openml
    +from sklearn.model_selection import train_test_split
    +
    +def onehot(target: np.ndarray):
    +    onehot = np.zeros((target.size, target.max() + 1))
    +    onehot[np.arange(target.size), target] = 1
    +    return onehot
    +
    +# get dataset
    +dataset = fetch_openml("mnist_784", parser="auto")
    +mnist = dataset.data.to_numpy(dtype="float")[:10000, :]
    +
    +# scale data
    +for i in range(mnist.shape[1]):
    +    mnist[:, i] /= 255
    +    
    +# reshape to add single input channel to data shape [inputs, input_channels, height, width]
    +mnist = mnist.reshape(mnist.shape[0], 1, 28, 28)
    +
    +# one hot encode target as we are doing multi-class classification
    +target = onehot(np.array([int(i) for i in dataset.target.to_numpy()[:10000]]))
    +
    +# split into training and validation data
    +x_train, x_val, y_train, y_val = train_test_split(mnist, target)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    Now we may train our model. Note that we can utilize regularization in +the CNN by using the lam (lambda) parameter in fit(), and utilize +different types of gradient descent by specifying the amount of +batches via the batches parameter as shown below. +

    + +

    The functionfit() returns a score dictionary of the training error and +accuracy (and validation error and accuracy if a validation set is +provided) which can be used to plot the error and accuracy of the +model over epochs. +

    + + + +
    +
    +
    +
    +
    +
    scores = cnn.fit(
    +    x_train,
    +    y_train,
    +    lam=1e-5,
    +    batches=10,
    +    epochs=100,
    +    X_val=x_val,
    +    t_val=y_val,
    +)
    +
    +plt.plot(scores["train_acc"], label="Training")
    +plt.plot(scores["val_acc"], label="Validation")
    +plt.ylim([0.8,1])
    +plt.xlabel("Epochs")
    +plt.ylabel("Accuracy")
    +plt.legend()
    +plt.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    Considering we only trained the model for 100 epochs without any tuning of the hyperparameters, this result is pretty good.

    + +

    The codebase allows for great flexibility in CNN +architectures. Pooling layers can be added before, inbetween or after +convolutional layers, but due to the great optimizations made within +Convolution2DLayerOPT, we recommend using the v_stride and h_stride +parameters in add_Convolution2DLayer() to reduce the dimentionality of +the problem as the pooling layer is slow in comparison. To use the +unoptimized version of Convolution2DLayer, simply pass optimized=False +as an argument in add_Convolution2DLayer(). +

    + +

    If one wishes to perform binary classification using the CNN, simply +use the cost function 'CostLogReg' when initializing the CNN and use 1 +node at the OutputLayer. +

    + +

    Below we have created another, more untraditional architecture using +our code to demonstrate its flexibility and different attributes such +as asymmetric stride that might become useful when constructing your +own CNN. +

    + + + +
    +
    +
    +
    +
    +
    adam_scheduler = Adam(eta=1e-3, rho=0.9, rho2=0.999)
    +cnn = CNN(cost_func=CostCrossEntropy, scheduler=adam_scheduler, seed=2023)
    +
    +cnn.add_Convolution2DLayer(
    +    input_channels=1,
    +    feature_maps=7,
    +    kernel_height=7,
    +    kernel_width=1,
    +    act_func=LRELU,
    +)
    +
    +cnn.add_PoolingLayer(
    +    kernel_height=2,
    +    kernel_width=2,
    +    pooling="average",
    +)
    +
    +cnn.add_PoolingLayer(
    +    kernel_height=2,
    +    kernel_width=2,
    +    pooling="max",
    +)
    +
    +cnn.add_Convolution2DLayer(
    +    input_channels=7,
    +    feature_maps=1,
    +    kernel_height=4,
    +    kernel_width=4,
    +    v_stride=2,
    +    h_stride=3,
    +    act_func=LRELU,
    +    optimized=False,
    +)
    +
    +cnn.add_Convolution2DLayer(
    +    input_channels=1,
    +    feature_maps=1,
    +    kernel_height=2,
    +    kernel_width=2,
    +    act_func=sigmoid,
    +    optimized=True,
    +)
    +
    +cnn.add_PoolingLayer(
    +    kernel_height=2,
    +    kernel_width=2,
    +    pooling="max"
    +)
    +
    +cnn.add_FlattenLayer()
    +
    +cnn.add_FullyConnectedLayer(100, LRELU)
    +
    +cnn.add_FullyConnectedLayer(10, sigmoid)
    +
    +cnn.add_FullyConnectedLayer(101, identity)
    +
    +cnn.add_OutputLayer(10, softmax)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    Here we see the use of asymmetrical 1D kernels such as the \( 7 \times +1 \) kernel in the first convolutional layer, both max and average +pooling, asymmetric stride in the unoptimized convolutional layer, +more pooling, a flatten layer, a hidden layer with 100 nodes using +LRELU, another hidden layer with 10 hidden nodes that uses the sigmoid +activation function, and another hidden layer with 101 nodes which +utilizes no activation function (identity). Finally, we arrive at the +output layer with 10 nodes, which uses softmax as its activation +function. +

    +

    Additional Remarks

    + +

    The stride parameter controls the distance between each convolution +and the kernel/filter. If our image is padded, stride is the only +parameter that determines the size of the output from a convolutional +layer. However, if we decide not to perform any padding, the size of +the output feature map depends on both the stride and kernel size. It +is important to note that neither the stride nor the kernel has to be +symmetrical. This means that we can use a rectangular filter if we +choose, and the stride in the vertical direction (axis=0 in Python) +does not need to be the same as the stride in the horizontal direction +(axis=1 in Python). It may even be the case that asymmetric +combinations of stride or kernel dimensions, or both, yield better +results than symmetric values for these parameters. +

    + + + +
    +
    +
    +
    +
    +
    def convolve(image, kernel, stride=1):
    +    for i in range(2):
    +        kernel = np.rot90(kernel)
    +
    +    k_half_height = kernel.shape[0] // 2
    +    k_half_width = kernel.shape[0] // 2
    +
    +    conv_image = np.zeros(image.shape)
    +    pad_image = padding(image, kernel)
    +
    +    for i in range(k_half_height, conv_image.shape[0] + k_half_height, stride):
    +        for j in range(k_half_width, conv_image.shape[1] + k_half_width, stride):
    +            conv_image[i - k_half_height, j - k_half_width] = np.sum(
    +                pad_image[
    +                    i - k_half_height : i + k_half_height + 1, j - k_half_width : j + k_half_width + 1
    +                ]
    +                * kernel
    +            )
    +
    +    return conv_image
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    Remarks on the speed

    + +

    Despite the naive convolution algorithm shown above working finely, it +is extremely slow, requiring approximately 20-30 seconds to process a +single image. The time complexity of 2D convolution, which is O(NMnm), +rapidly becomes a constraint and may, at worst, make computations +infeasible. Consequently, optimizing the naive 2D convolution +algorithm is a necessity, as the execution time of the algorithm +significantly increases as the input data size expands. This can pose +a bottleneck in applications that necessitate real-time processing of +large data volumes, such as image and video processing, deep learning, +and scientific simulations. +

    + +

    To address this issue, we shall present two widely used optimization +techniques: the separable kernel approach and Fast Fourier Transform +(FFT). Both of these methods can drastically reduce the computational +complexity of convolution and enhance the overall efficiency of +processing substantial data quantities. While we shall refrain from +delving into the intricacies of these algorithms, we strongly +encourage you to examine at least the application of FFT to optimize +computations. +

    +

    Convolution using separable kernels

    + + + +
    +
    +
    +
    +
    +
    def conv2DSep(image, kernel, coef, stride=1, pad="zero"):
    +    for i in range(2):
    +        kernel = np.rot90(kernel)
    +
    +    # The kernel is quadratic, thus we only need one of its dimensions
    +    half_dim = kernel.shape[0] // 2
    +
    +    ker1 = np.array(kernel[0, :])
    +    ker2 = np.array(kernel[:, 0])
    +
    +    if pad == "zero":
    +        conv_image = np.zeros(image.shape)
    +        pad_image = padding(image, kernel)
    +    else:
    +        conv_image = np.zeros(
    +            (image.shape[0] - kernel.shape[0], image.shape[1] - kernel.shape[1])
    +        )
    +        pad_image = image[:, :]
    +
    +    for i in range(half_dim, conv_image.shape[0] + half_dim, stride):
    +        for j in range(half_dim, conv_image.shape[1] + half_dim, stride):
    +            conv_image[i - half_dim, j - half_dim] = (
    +                pad_image[
    +                    i - half_dim : i + half_dim + 1, j - half_dim : j + half_dim + 1
    +                ]
    +                @ ker1
    +                @ ker2.T
    +                * coef
    +            )
    +
    +    return conv_image
    +
    +img_path = img_path = "../data/IMG-2167.JPG"
    +image_of_cute_dog = imageio.imread(img_path, mode="L")
    +start_time = time.time()
    +filtered_image = conv2DSep(image_of_cute_dog, kernel=sobel_kernel, coef=1)
    +print(f'Time taken for convolution with seperated kernel on 128x128 image {time.time() - start_time}')
    +plt.imshow(filtered_image, cmap="gray", vmin=0, vmax=255, aspect="auto")
    +plt.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    By taking advantage of the capabilities of separable kernels, we can +effectively cut the computational expense of filtering an image in +half. Yet, if we seek even more rapid processing, we can turn to the +Fast Fourier Transform (FFT) algorithm provided by the numpy +library. By utilizing FFT to transform the input image and filter into +the frequency domain, we can perform convolution in this domain. This +approach significantly reduces the number of operations needed and +results in a marked speedup relative to other convolution +techniques. In addition, it is worth noting that the FFT is widely +regarded as one of the most critical algorithms developed to date, +with applications ranging from digital signal processing to scientific +computing. +

    +

    Convolution in the Fourier domain

    + + +
    +
    +
    +
    +
    +
    start_time = time.time()
    +img_fft = np.fft.fft2(image_of_cute_dog)
    +kernel_fft = np.fft.fft2(sobel_kernel, s=image_of_cute_dog.shape)
    +
    +conv_image = img_fft * kernel_fft
    +
    +filtered_image = np.fft.ifft2(conv_image)
    +print(f'Time take for convolution in the fourier domain: {time.time() - start_time}')
    +plt.imshow(filtered_image.real, cmap="gray", vmin=0, vmax=255, aspect="auto")
    +plt.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    It is evident that executing convolution in the Fourier domain yields +the quickest computation time. Nonetheless, one should exercise +caution, particularly when dealing with images of relatively small +dimensions, as one of the other methods may prove to be more +expeditious than FFT-enhanced convolution. The overhead involved in +transferring both the image and filter into the Fourier domain, +followed by their subsequent transformation back into the spatial +domain, results in a minor inconvenience. Therefore, it is imperative +to remain cognizant of this fact when utilizing FFT as the primary +optimization technique. +

    +
    + diff --git a/doc/pub/week44/html/week44-solarized.html b/doc/pub/week44/html/week44-solarized.html index d7c90aa59..9f7c94415 100644 --- a/doc/pub/week44/html/week44-solarized.html +++ b/doc/pub/week44/html/week44-solarized.html @@ -166,7 +166,54 @@ div.toc p,a { ('Finally, evaluate the model', 2, None, - 'finally-evaluate-the-model')]} + 'finally-evaluate-the-model'), + ('Building our own CNN code', + 2, + None, + 'building-our-own-cnn-code'), + ('List of contents:', 3, None, 'list-of-contents'), + ('Schedulers', 3, None, 'schedulers'), + ('Usage of schedulers', 3, None, 'usage-of-schedulers'), + ('Cost functions', 3, None, 'cost-functions'), + ('Usage of cost functions', 3, None, 'usage-of-cost-functions'), + ('Activation functions', 3, None, 'activation-functions'), + ('Usage of activation functions', + 3, + None, + 'usage-of-activation-functions'), + ('Convolution', 3, None, 'convolution'), + ('Layers', 3, None, 'layers'), + ('Convolution2DLayer: convolution in a hidden layer', + 3, + None, + 'convolution2dlayer-convolution-in-a-hidden-layer'), + ('Backpropagation in the convolutional layer', + 3, + None, + 'backpropagation-in-the-convolutional-layer'), + ('Demonstration', 3, None, 'demonstration'), + ('Pooling Layer', 3, None, 'pooling-layer'), + ('Flattening Layer', 3, None, 'flattening-layer'), + ('Fully Connected Layers', 3, None, 'fully-connected-layers'), + ('Optimized Convolution2DLayer', + 3, + None, + 'optimized-convolution2dlayer'), + ('The Convolutional Neural Network (CNN)', + 3, + None, + 'the-convolutional-neural-network-cnn'), + ('Usage of CNN code', 3, None, 'usage-of-cnn-code'), + ('Additional Remarks', 3, None, 'additional-remarks'), + ('Remarks on the speed', 3, None, 'remarks-on-the-speed'), + ('Convolution using separable kernels', + 3, + None, + 'convolution-using-separable-kernels'), + ('Convolution in the Fourier domain', + 3, + None, + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -1542,6 +1589,3261 @@ test_loss, test_acc = model.evaluate(test_images, test_labels, verbose= +









    +

    Building our own CNN code

    + +

    Here we present a flexible and readable python code for a CNN +implemented with NumPy. We will present the code, showcase how to use +the codebase and fit a CNN that yields a 99% accuracy on the 28x28 +MNIST dataset within reasonable time. +

    + +

    The CNN is compatible with all schedulers, cost functions and +activation functions discussed in constructing our neural network +codes. +

    + +

    The CNN code consists of different types of Layer classes, including +Convolution2DLayer, Pooling2DLayer, FlattenLayer, FullyConnectedLayer +and OutputLayer, which can be added to the CNN object using the +interface of the CNN class. This allows you to easily construct your +own CNN, as well as allowing you to get used to an interface similar +to that of TensorFlow which is used for real world applications. +

    + +

    Another important feature of this code is that it throws errors if +unreasonable decisions are made (for example using a kernel that is +larger than the image, not using a FlattenLayer, etc), and provides +the user with an informative error message. +

    +

    List of contents:

    +
      +
    1. Schedulers
    2. +
    3. Activation Functions
    4. +
    5. Cost Functions
    6. +
    7. Convolution
    8. +
    9. Layers
    10. +
    11. CNN
    12. +
    13. Some final remarks
    14. +
    +

    Schedulers

    + +

    The code below shows object oriented implementations of the Constant, +Momentum, Adagrad, AdagradMomentum, RMS prop and Adam schedulers. All +of the classes belong to the shared abstract Scheduler class, and +share the update_change() and reset() methods allowing for any of the +schedulers to be seamlessly used during the training stage, as will +later be shown in the fit() method of the neural +network. Update_change() only has one parameter, the gradient +(\( \delta^{l}_{j}a^{l-1}_k \)), and returns the change which will be +subtracted from the weights. The reset() function takes no parameters, +and resets the desired variables. For Constant and Momentum, reset +does nothing. +

    + + + +
    +
    +
    +
    +
    +
    import autograd.numpy as np
    +
    +class Scheduler:
    +    """
    +    Abstract class for Schedulers
    +    """
    +
    +    def __init__(self, eta):
    +        self.eta = eta
    +
    +    # should be overwritten
    +    def update_change(self, gradient):
    +        raise NotImplementedError
    +
    +    # overwritten if needed
    +    def reset(self):
    +        pass
    +
    +
    +class Constant(Scheduler):
    +    def __init__(self, eta):
    +        super().__init__(eta)
    +
    +    def update_change(self, gradient):
    +        return self.eta * gradient
    +    
    +    def reset(self):
    +        pass
    +
    +
    +class Momentum(Scheduler):
    +    def __init__(self, eta: float, momentum: float):
    +        super().__init__(eta)
    +        self.momentum = momentum
    +        self.change = 0
    +
    +    def update_change(self, gradient):
    +        self.change = self.momentum * self.change + self.eta * gradient
    +        return self.change
    +
    +    def reset(self):
    +        pass
    +
    +
    +class Adagrad(Scheduler):
    +    def __init__(self, eta):
    +        super().__init__(eta)
    +        self.G_t = None
    +
    +    def update_change(self, gradient):
    +        delta = 1e-8  # avoid division ny zero
    +
    +        if self.G_t is None:
    +            self.G_t = np.zeros((gradient.shape[0], gradient.shape[0]))
    +
    +        self.G_t += gradient @ gradient.T
    +
    +        G_t_inverse = 1 / (
    +            delta + np.sqrt(np.reshape(np.diagonal(self.G_t), (self.G_t.shape[0], 1)))
    +        )
    +        return self.eta * gradient * G_t_inverse
    +
    +    def reset(self):
    +        self.G_t = None
    +
    +
    +class AdagradMomentum(Scheduler):
    +    def __init__(self, eta, momentum):
    +        super().__init__(eta)
    +        self.G_t = None
    +        self.momentum = momentum
    +        self.change = 0
    +
    +    def update_change(self, gradient):
    +        delta = 1e-8  # avoid division ny zero
    +
    +        if self.G_t is None:
    +            self.G_t = np.zeros((gradient.shape[0], gradient.shape[0]))
    +
    +        self.G_t += gradient @ gradient.T
    +
    +        G_t_inverse = 1 / (
    +            delta + np.sqrt(np.reshape(np.diagonal(self.G_t), (self.G_t.shape[0], 1)))
    +        )
    +        self.change = self.change * self.momentum + self.eta * gradient * G_t_inverse
    +        return self.change
    +
    +    def reset(self):
    +        self.G_t = None
    +
    +
    +class RMS_prop(Scheduler):
    +    def __init__(self, eta, rho):
    +        super().__init__(eta)
    +        self.rho = rho
    +        self.second = 0.0
    +
    +    def update_change(self, gradient):
    +        delta = 1e-8  # avoid division ny zero
    +        self.second = self.rho * self.second + (1 - self.rho) * gradient * gradient
    +        return self.eta * gradient / (np.sqrt(self.second + delta))
    +
    +    def reset(self):
    +        self.second = 0.0
    +
    +
    +class Adam(Scheduler):
    +    def __init__(self, eta, rho, rho2):
    +        super().__init__(eta)
    +        self.rho = rho
    +        self.rho2 = rho2
    +        self.moment = 0
    +        self.second = 0
    +        self.n_epochs = 1
    +
    +    def update_change(self, gradient):
    +        delta = 1e-8  # avoid division ny zero
    +
    +        self.moment = self.rho * self.moment + (1 - self.rho) * gradient
    +        self.second = self.rho2 * self.second + (1 - self.rho2) * gradient * gradient
    +
    +        moment_corrected = self.moment / (1 - self.rho**self.n_epochs)
    +        second_corrected = self.second / (1 - self.rho2**self.n_epochs)
    +
    +        return self.eta * moment_corrected / (np.sqrt(second_corrected + delta))
    +
    +    def reset(self):
    +        self.n_epochs += 1
    +        self.moment = 0
    +        self.second = 0
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    Usage of schedulers

    + +

    To initalize a scheduler, simply create the object and pass in the necessary parameters such as the learning rate and the momentum as shown below. As the Scheduler class is an abstract class it should not called directly, and will raise an error upon usage.

    + + + +
    +
    +
    +
    +
    +
    momentum_scheduler = Momentum(eta=1e-3, momentum=0.9)
    +adam_scheduler = Adam(eta=1e-3, rho=0.9, rho2=0.999)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    Here is a small example for how a segment of code using schedulers could look. Switching out the schedulers is simple.

    + + + +
    +
    +
    +
    +
    +
    weights = np.ones((3,3))
    +print(f"Before scheduler:\n{weights=}")
    +
    +epochs = 10
    +for e in range(epochs):
    +    gradient = np.random.rand(3, 3)
    +    change = adam_scheduler.update_change(gradient)
    +    weights = weights - change
    +    adam_scheduler.reset()
    +
    +print(f"\nAfter scheduler:\n{weights=}")
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    Cost functions

    + +

    In this section we will quickly look at cost functions that can be +used when creating the neural network. Every cost function takes the +target vector as its parameter, and returns a function valued only at +X such that it may easily be differentiated. +

    + + + +
    +
    +
    +
    +
    +
    def CostOLS(target):
    +    """
    +    Return OLS function valued only at X, so
    +    that it may be easily differentiated
    +    """
    +
    +    def func(X):
    +        return (1.0 / target.shape[0]) * np.sum((target - X) ** 2)
    +
    +    return func
    +
    +
    +def CostLogReg(target):
    +    """
    +    Return Logistic Regression cost function
    +    valued only at X, so that it may be easily differentiated
    +    """
    +
    +    def func(X):
    +        return -(1.0 / target.shape[0]) * np.sum(
    +            (target * np.log(X + 10e-10)) + ((1 - target) * np.log(1 - X + 10e-10))
    +        )
    +
    +    return func
    +
    +
    +def CostCrossEntropy(target):
    +    """
    +    Return cross entropy cost function valued only at X, so
    +    that it may be easily differentiated
    +    """
    +    
    +    def func(X):
    +        return -(1.0 / target.size) * np.sum(target * np.log(X + 10e-10))
    +
    +    return func
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    Usage of cost functions

    + +

    Below we will provide a short example of how these cost function may +be used to obtain results if you wish to test them out on your own +using AutoGrad's automatic differentiation. +

    + + + +
    +
    +
    +
    +
    +
    from autograd import grad
    +
    +target = np.array([[1, 2, 3]]).T
    +a = np.array([[4, 5, 6]]).T
    +
    +cost_func = CostCrossEntropy
    +cost_func_derivative = grad(cost_func(target))
    +
    +valued_at_a = cost_func_derivative(a)
    +print(f"Derivative of cost function {cost_func.__name__} valued at a:\n{valued_at_a}")
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    Activation functions

    + +

    Finally, before we look at the layers that make up the neural network, +we will look at the activation functions which can be specified +between the hidden layers and as the output function. Each function +can be valued for any given vector or matrix X, and can be +differentiated via derivate(). +

    + + + +
    +
    +
    +
    +
    +
    import autograd.numpy as np
    +from autograd import elementwise_grad
    +
    +def identity(X):
    +    return X
    +
    +
    +def sigmoid(X):
    +    try:
    +        return 1.0 / (1 + np.exp(-X))
    +    except FloatingPointError:
    +        return np.where(X > np.zeros(X.shape), np.ones(X.shape), np.zeros(X.shape))
    +
    +
    +def softmax(X):
    +    X = X - np.max(X, axis=-1, keepdims=True)
    +    delta = 10e-10
    +    return np.exp(X) / (np.sum(np.exp(X), axis=-1, keepdims=True) + delta)
    +
    +
    +def RELU(X):
    +    return np.where(X > np.zeros(X.shape), X, np.zeros(X.shape))
    +
    +
    +def LRELU(X):
    +    delta = 10e-4
    +    return np.where(X > np.zeros(X.shape), X, delta * X)
    +
    +
    +def derivate(func):
    +    if func.__name__ == "RELU":
    +
    +        def func(X):
    +            return np.where(X > 0, 1, 0)
    +
    +        return func
    +
    +    elif func.__name__ == "LRELU":
    +
    +        def func(X):
    +            delta = 10e-4
    +            return np.where(X > 0, 1, delta)
    +
    +        return func
    +
    +    else:
    +        return elementwise_grad(func)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    Usage of activation functions

    + +

    Below we present a short demonstration of how to use an activation +function. The derivative of the activation function will be important +when calculating the output delta term during backpropagation. Note +that derivate() can also be used for cost functions for a more +generalized approach. +

    + + + +
    +
    +
    +
    +
    +
    z = np.array([[4, 5, 6]]).T
    +print(f"Input to activation function:\n{z}")
    +
    +act_func = sigmoid
    +a = act_func(z)
    +print(f"\nOutput from {act_func.__name__} activation function:\n{a}")
    +
    +act_func_derivative = derivate(act_func)
    +valued_at_z = act_func_derivative(a)
    +print(f"\nDerivative of {act_func.__name__} activation function valued at z:\n{valued_at_z}")
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    Convolution

    + +

    In order to construct a convolutional neural network (CNN), it is +crucial to comprehend the fundamental principles of convolution and +how it aids in extracting information from images. Convolution, at its +core, is merely a mathematical operation between two functions that +yields another function. It is represented by an integral between two +functions, which is typically expressed as: +

    + +$$ +(f \ast g)(t):=\int_{-\infty}^{\infty} f(\tau) g(t-\tau) d \tau. +$$ + +

    Here, f and g are the two functions on which we want to perform an +operation. The outcome of the convolution operation is represented by +\( (f \ast g) \), and it is derived by sliding the function g over f and +computing the integral of their product at each position. If both +functions are continuous, convolution takes the form shown +above. However, if we discretize both f and g, the convolution +operation will take the form of a sum between the elements of f and g: +

    +$$ +(f \ast g)[n]=\sum_{m=0}^{n-1} f[m] g[n-m]. +$$ + +

    The key idea we utilize to extract the information contained in an +image is to slide an \( m \times n \) matrix g over an \( m \times n \) +matrix f. In our case, f represents the image, while g +represents the kernel, oftentimes called a filter. However, since our +convolution will be a two-dimensional variant, we need to extend our +mathematical formula with an additional summation: +

    + +$$ +(f \ast g)[i, j]\sum_{m=0}^{M-1}\sum_{n=0}^{N-1} f[m,n] g[i-m, j-n]. +$$ + +

    It is imperative to note that the size of the kernel g is +significantly smaller than the size of the input image f, thereby +reducing the amount of computation necessary for feature +extraction. Furthermore, the kernel is usually a trainable parameter +in a convolutional neural network, allowing the network to learn +appropriate kernels for specific tasks. +

    + +

    To give you an example of how 2D convolution works in practice, +suppose we have an image f of dimension \( 6 \times 6 \) +

    + +$$ +f = \begin{bmatrix} +4 & 1 & 2 & 9 & 8 & 6 \\ +9 & 5 & 9 & 5 & 8 & 5 \\ +1 & 5 & 9 & 7 & 6 & 4 \\ +2 & 9 & 8 & 3 & 7 & 1 \\ +8 & 1 & 6 & 4 & 2 & 2 \\ +1 & 0 & 5 & 7 & 8 & 2 \\ +\end{bmatrix} +$$ + +

    and a \( 3 \times 3 \) kernel g called a low-pass filter. Note that the +kernel is usually rotated by 180 degrees during convolution, however +this has no effect on this kernel. +

    + +$$ +g = \frac{1}{9} +\begin{bmatrix} +1 & 1 & 1 \\ +1 & 1 & 1 \\ +1 & 1 & 1 \\ +\end{bmatrix} +$$ + +

    In order to filter the image, we have to extract a \( 3 \times 3 \) +element from the upper left corner of f, and perform element-wise +multiplication of the extracted image pixels with the elements of the +kernel g: +

    + +$$ +\begin{bmatrix} +4 & 1 & 2 \\ +9 & 5 & 9 \\ +1 & 5 & 9 \\ +\end{bmatrix} +\cdot +\begin{bmatrix} +\frac{1}{9} & \frac{1}{9} & \frac{1}{9} \\ +\frac{1}{9} & \frac{1}{9} & \frac{1}{9} \\ +\frac{1}{9} & \frac{1}{9} & \frac{1}{9} \\ +\end{bmatrix} += +\begin{bmatrix} +\frac{4}{9} & \frac{1}{9} & \frac{2}{9} \\ +\frac{9}{9} & \frac{5}{9} & \frac{9}{9} \\ +\frac{1}{9} & \frac{5}{9} & \frac{9}{9} \\ +\end {bmatrix} += \textbf{A} +$$ + +

    Then, following the multiplication, we summarize all the elements of the resulting matrix A:

    + +$$ +(f \ast g)[0, 0]= \sum_{i=0}^{2} \sum_{j=0}^{2} a_{i,j} = 5 +$$ + +

    Which corresponds to the first element of the filtered image \( (f \ast g) \).

    + +

    Here we use a stride of 1, a parameter denoted s which describes how +many indexes we move the kernel g to the right before repeating the +calculations above for the next \( 3 \times 3 \) element of the image +f. It is usually presumed that *s*=1, however, larger values for s +can be used to reduce the dimentionality of the filtered image such +that the convolution operation is more computationally efficient. In +the context of a convolutional neural network, this will become very +useful. +

    + +

    The full result of the convolution is:

    + +$$ +(f \ast g) = +\begin{bmatrix} +5 & 5.78 & 7 & 6.44 \\ +6.33 & 6.67 & 6.89 & 5.11 \\ +5.44 & 5.78 & 5.78 & 4 \\ +4.44 & 4.78 & 5.56 & 4 \\ +\end{bmatrix} +$$ + +

    The result is markedly smaller in shape than the original image. This occurs when using convolution without first padding the image with additional columns and rows, allowing us to keep the original image shape after sliding the kernel over the image. +How many rows and columns we wish to pad the image with depends strictly on the shape of the kernel, as we wish to pad the image with r additional rows and c additional columns. +

    + +$$ +r =\lfloor \frac{kernel\ height}{2} \rfloor \cdot 2 \\ +c =\lfloor \frac{kernel\ width}{2} \rfloor \cdot 2 +$$ + +

    Note the notation \( \lfloor \frac{kernel width}{2} \rfloor \) means that +we floor the result of the division, meaning we round down to a whole +number in case \( \frac{kernel width}{2} \) results in a floating point +number. +

    + +

    Using those simple equations, we find out by how much we have to +extend the dimensions of the original image. Before proceeding, +however, we might ask what we shall fill the additional rows and +columns with? One of the most common approaches to padding is +zero-padding, which as the name suggest, involves filling the rows and +columns with zeros. This is the approach that we will be using for +this demonstration. If we apply this padding to out original \( 6 \times 6 \) +image, the result will be an \( 8 \times 8 \) image as the kernel has a width and +height of 3. Note that the original image is encapsuled by the +zero-padded rows and columns: +

    + +$$ +\begin{bmatrix} +0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ +0 & 4 & 1 & 2 & 9 & 8 & 6 & 0 \\ +0 & 9 & 5 & 9 & 5 & 8 & 5 & 0 \\ +0 & 1 & 5 & 9 & 7 & 6 & 4 & 0 \\ +0 & 2 & 9 & 8 & 3 & 7 & 1 & 0 \\ +0 & 8 & 1 & 6 & 4 & 2 & 2 & 0 \\ +0 & 1 & 0 & 5 & 7 & 8 & 2 & 0 \\ +0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ +\] +\end{bmatrix} +$$ + +

    Below we have provided code that demonstrates padding and convolution. As you will see when we run the code, the size of the image will remain unchanged when using padding. 

    + + + +
    +
    +
    +
    +
    +
    import numpy as np
    +
    +def padding(image, kernel):
    +    # calculate r and c
    +    r = (kernel.shape[0] // 2) * 2
    +    c = (kernel.shape[1] // 2) * 2
    +    
    +    # padded image dimensions
    +    padded_height = image.shape[0] + r
    +    padded_width = image.shape[1] + c
    +    
    +    # for more readable code
    +    k_half_height = kernel.shape[0] // 2
    +    k_half_width = kernel.shape[1] // 2
    +
    +    # zero matrix with padded dimensions
    +    padded_img = np.zeros((padded_height, padded_width))
    +
    +    # place image into zero matrix
    +    padded_img[k_half_height : padded_height - k_half_height,
    +               k_half_width : padded_width - k_half_width] = image[:, :]
    +
    +    return padded_img
    +
    +def convolve(original_image, padded_image, kernel, stride=1):
    +    # rotate kernel by 180 degrees
    +    kernel = np.rot90(np.rot90(kernel))
    +
    +    # note that kernel height // 2 is written as 'm'
    +    # and kernel width // 2 as 'n' in the mathematical notation
    +    m = kernel.shape[0] // 2
    +    n = kernel.shape[1] // 2
    +    
    +    r = (kernel.shape[0] // 2) * 2
    +    c = (kernel.shape[1] // 2) * 2
    +    
    +    # initialize output array
    +    convolved_image = np.zeros(original_image.shape)
    +    image_height = original_image.shape[0]
    +    image_width = original_image.shape[1]
    +
    +    # the convolution
    +    for i in range(m, image_height + m, stride):
    +        for j in range(n, image_width + n, stride):
    +            convolved_image[i-m, j-n] = np.sum(
    +                padded_image[i : i + m, j : j + n]
    +                * kernel
    +            )
    +            
    +    return convolved_image
    +
    +def convolve(image, kernel, stride=1):
    +    for i in range(2):
    +        kernel = np.rot90(kernel)
    +
    +    k_half_height = kernel.shape[0] // 2
    +    k_half_width = kernel.shape[0] // 2
    +
    +    conv_image = np.zeros(image.shape)
    +    pad_image = padding(image, kernel)
    +
    +    for i in range(k_half_height, conv_image.shape[0] + k_half_height, stride):
    +        for j in range(k_half_width, conv_image.shape[1] + k_half_width, stride):
    +            conv_image[i - k_half_height, j - k_half_width] = np.sum(
    +                pad_image[
    +                    i - k_half_height : i + k_half_height + 1, j - k_half_width : j + k_half_width + 1
    +                ]
    +                * kernel
    +            )
    +
    +    return conv_image
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    Fun fact: When filtering images, you will see that convolution involves rotating the kernel by 180 degrees. +However, this is not the case when applying convolution in a CNN, where the same operation not rotated by 180 degrees is called +cross-correlation. +

    + + + +
    +
    +
    +
    +
    +
    original_image = np.array([[4, 1, 2, 9, 8, 6],
    +                 [9, 5, 9, 5, 8, 5],
    +                 [1, 5, 9, 7, 6, 4],
    +                 [2, 9, 8, 3, 7, 1],
    +                 [8, 1, 6, 4, 2, 2],
    +                 [1, 0, 5, 7, 8, 2]])
    +
    +kernel = (1/9)*np.ones((3,3))
    +
    +print(f"{original_image.shape=}")
    +
    +# note that convolve() performs padding
    +convolved_image = convolve(original_image, kernel, stride=1)
    +
    +print(f"{convolved_image.shape=}")
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    As you can see, the resulting image is of the same size as the +original image. To round of our demonstration of convolution, we will +present the results of convolution using commonly used kernels. In a +CNN, the values of the kernels are randomly initialized, and then +learned during training. These kernels will extract information +regarding the picture, such as for example the edge detection filter +demonstrated below extracts the edges present in the picture. Of +course, there is no guarantee that the CNN will learn an edge +detection filter, but this should provide some intuiton as to how the +CNN is able to use kernels to make better predictions than a regular +feed forward neural network. +

    + + + +
    +
    +
    +
    +
    +
    # Now an example using a real image and first a gaussian low-pass filter and then a sobel filter
    +import numpy as np
    +import imageio.v3 as imageio
    +import matplotlib.pyplot as plt
    +import time
    +
    +def generate_gauss_mask(sigma, K=1):
    +    side = np.ceil(1 + 8 * sigma)
    +    y, x = np.mgrid[-side // 2 + 1 : (side // 2) + 1, -side // 2 + 1 : (side // 2) + 1]
    +    ker_coef = K / (2 * np.pi * sigma**2)
    +    g = np.exp(-((x**2 + y**2) / (2.0 * sigma**2)))
    +
    +    return g, ker_coef
    +
    +
    +img_path = "../data/IMG-2167.JPG"
    +image_of_cute_dog = imageio.imread(img_path, mode='L')
    +
    +plt.imshow(image_of_cute_dog, cmap="gray", vmin=0, vmax=255, aspect="auto")
    +plt.title("Original image")
    +plt.show()
    +
    +gauss, kernel = generate_gauss_mask(sigma=6)
    +gauss_kernel = gauss*kernel
    +
    +filtered_image = convolve(image_of_cute_dog, gauss_kernel)
    +plt.imshow(filtered_image, cmap="gray", vmin=0, vmax=255, aspect="auto")
    +plt.title("Result of convolution with gauss kernel (blurring filter)")
    +plt.show()
    +
    +sobel_kernel = np.array([[1, 2, 1],
    +                    [0, 0, 0], 
    +                    [-1, -2, -1]])
    +
    +filtered_image = convolve(image_of_cute_dog, sobel_kernel)
    +
    +plt.imshow(filtered_image, cmap="gray", vmin=0, vmax=255, aspect="auto")
    +plt.title("Result of convolution with sobel kernel (edge detection filter)")
    +plt.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    Layers

    + +

    The code below initialises global variables for readability and +describes the abstract class Layers. This is not important in order to +understand the CNN, but is benefitial for organizing the code neatly. +

    + + + +
    +
    +
    +
    +
    +
    import math
    +import autograd.numpy as np
    +from copy import deepcopy, copy
    +from autograd import grad
    +from typing import Callable
    +
    +# global variables for index readability
    +input_index = 0
    +node_index = 1
    +bias_index = 1
    +input_channel_index = 1
    +feature_maps_index = 1
    +height_index = 2
    +width_index = 3
    +kernel_feature_maps_index = 1
    +kernel_input_channels_index = 0
    +
    +
    +class Layer:
    +    def __init__(self, seed):
    +        self.seed = seed
    +
    +    def _feedforward(self):
    +        raise NotImplementedError
    +
    +    def _backpropagate(self):
    +        raise NotImplementedError
    +
    +    def _reset_weights(self, previous_nodes):
    +        raise NotImplementedError
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    Convolution2DLayer: convolution in a hidden layer

    + +

    After establishing the foundational understanding of applying +convolution to spatial data, let us delve into the intricate workings +of a convolutional layer in a Convolutional Neural Network (CNN). The +primary function of convolution, as previously discussed, is to +extract pertinent information from images while simultaneously +decreasing the scale of our data. To initiate the image processing, we +shall begin by partitioning the images into color channels (unless the +image is grayscale), comprising three primary colors: red, green, and +blue. We will subsequently utilize trainable kernels to construct a +higher-dimensional encoding of each channel called feature +maps. Successive layers will receive these feature maps as inputs, +generating further encodings, albeit with reduced dimensions. The term +trainable kernels denotes the initialization of pre-defined +kernel-shaped weights, which we will then train via backpropagation, +similar to how weights are trained in a Feedforward Neural Network. +

    + +

    To ensure seamless integration between our implementation of the +convolutional layer and popular machine learning frameworks like +Tensorflow (Keras) and PyTorch, we have adopted a design pattern that +mirrors the construction of models using these APIs. This involves +implementing our convolutional layer as a Python class or object, +which allows for a more modular and flexible approach to building +neural networks. By structuring our code in this way, users can easily +incorporate our implementation into their existing machine learning +pipelines without having to make significant changes to their +codebase. Additionally, this design pattern promotes code reusability +and makes it easier to maintain and update our convolutional layer +implementation over time. +

    + +

    Note that the Convolution2DLayer takes in an activation function as a parameter, as it also performs non-linearity.

    + + + +
    +
    +
    +
    +
    +
    class Convolution2DLayer(Layer):
    +    def __init__(
    +        self,
    +        input_channels,
    +        feature_maps,
    +        kernel_height,
    +        kernel_width,
    +        v_stride,
    +        h_stride,
    +        pad,
    +        act_func: Callable,
    +        seed=None,
    +        reset_weights_independently=True,
    +    ):
    +        super().__init__(seed)
    +        self.input_channels = input_channels
    +        self.feature_maps = feature_maps
    +        self.kernel_height = kernel_height
    +        self.kernel_width = kernel_width
    +        self.v_stride = v_stride
    +        self.h_stride = h_stride
    +        self.pad = pad
    +        self.act_func = act_func
    +
    +        # such that the layer can be used on its own
    +        # outside of the CNN module
    +        if reset_weights_independently == True:
    +            self._reset_weights_independently()
    +
    +    def _feedforward(self, X_batch):
    +        # note that the shape of X_batch = [inputs, input_maps, img_height, img_width]
    +
    +        # pad the input batch
    +        X_batch_padded = self._padding(X_batch)
    +
    +        # calculate height_index and width_index after stride
    +        strided_height = int(np.ceil(X_batch.shape[height_index] / self.v_stride))
    +        strided_width = int(np.ceil(X_batch.shape[width_index] / self.h_stride))
    +
    +        # create output array
    +        output = np.ndarray(
    +            (
    +                X_batch.shape[input_index],
    +                self.feature_maps,
    +                strided_height,
    +                strided_width,
    +            )
    +        )
    +
    +        # save input and output for backpropagation
    +        self.X_batch_feedforward = X_batch
    +        self.output_shape = output.shape
    +
    +        # checking for errors, no need to look here :)
    +        self._check_for_errors()
    +
    +        # convolve input with kernel
    +        for img in range(X_batch.shape[input_index]):
    +            for chin in range(self.input_channels):
    +                for fmap in range(self.feature_maps):
    +                    out_h = 0
    +                    for h in range(0, X_batch.shape[height_index], self.v_stride):
    +                        out_w = 0
    +                        for w in range(0, X_batch.shape[width_index], self.h_stride):
    +                            output[img, fmap, out_h, out_w] = np.sum(
    +                                X_batch_padded[
    +                                    img,
    +                                    chin,
    +                                    h : h + self.kernel_height,
    +                                    w : w + self.kernel_width,
    +                                ]
    +                                * self.kernel[chin, fmap, :, :]
    +                            )
    +                            out_w += 1
    +                        out_h += 1
    +
    +        # Pay attention to the fact that we're not rotating the kernel by 180 degrees when filtering the image in
    +        # the convolutional layer, as convolution in terms of Machine Learning is a procedure known as cross-correlation
    +        # in image processing and signal processing
    +
    +        # return a
    +        return self.act_func(output / (self.kernel_height))
    +
    +    def _backpropagate(self, delta_term_next):
    +        # intiate matrices
    +        delta_term = np.zeros((self.X_batch_feedforward.shape))
    +        gradient_kernel = np.zeros((self.kernel.shape))
    +
    +        # pad input for convolution
    +        X_batch_padded = self._padding(self.X_batch_feedforward)
    +
    +        # Since an activation function is used at the output of the convolution layer, its derivative
    +        # has to be accounted for in the backpropagation -> as if ReLU was a layer on its own.
    +        act_derivative = derivate(self.act_func)
    +        delta_term_next = act_derivative(delta_term_next)
    +
    +        # fill in 0's for values removed by vertical stride in feedforward
    +        if self.v_stride > 1:
    +            v_ind = 1
    +            for i in range(delta_term_next.shape[height_index]):
    +                for j in range(self.v_stride - 1):
    +                    delta_term_next = np.insert(
    +                        delta_term_next, v_ind, 0, axis=height_index
    +                    )
    +                v_ind += self.v_stride
    +
    +        # fill in 0's for values removed by horizontal stride in feedforward
    +        if self.h_stride > 1:
    +            h_ind = 1
    +            for i in range(delta_term_next.shape[width_index]):
    +                for k in range(self.h_stride - 1):
    +                    delta_term_next = np.insert(
    +                        delta_term_next, h_ind, 0, axis=width_index
    +                    )
    +                h_ind += self.h_stride
    +
    +        # crops out 0-rows and 0-columns
    +        delta_term_next = delta_term_next[
    +            :,
    +            :,
    +            : self.X_batch_feedforward.shape[height_index],
    +            : self.X_batch_feedforward.shape[width_index],
    +        ]
    +
    +        # the gradient received from the next layer also needs to be padded
    +        delta_term_next = self._padding(delta_term_next)
    +
    +        # calculate delta term by convolving next delta term with kernel
    +        for img in range(self.X_batch_feedforward.shape[input_index]):
    +            for chin in range(self.input_channels):
    +                for fmap in range(self.feature_maps):
    +                    for h in range(self.X_batch_feedforward.shape[height_index]):
    +                        for w in range(self.X_batch_feedforward.shape[width_index]):
    +                            delta_term[img, chin, h, w] = np.sum(
    +                                delta_term_next[
    +                                    img,
    +                                    fmap,
    +                                    h : h + self.kernel_height,
    +                                    w : w + self.kernel_width,
    +                                ]
    +                                * np.rot90(np.rot90(self.kernel[chin, fmap, :, :]))
    +                            )
    +
    +        # calculate gradient for kernel for weight update
    +        # also via convolution
    +        for chin in range(self.input_channels):
    +            for fmap in range(self.feature_maps):
    +                for k_x in range(self.kernel_height):
    +                    for k_y in range(self.kernel_width):
    +                        gradient_kernel[chin, fmap, k_x, k_y] = np.sum(
    +                            X_batch_padded[
    +                                img,
    +                                chin,
    +                                h : h + self.kernel_height,
    +                                w : w + self.kernel_width,
    +                            ]
    +                            * delta_term_next[
    +                                img,
    +                                fmap,
    +                                h : h + self.kernel_height,
    +                                w : w + self.kernel_width,
    +                            ]
    +                        )
    +        # all kernels are updated with weight gradient of kernel
    +        self.kernel -= gradient_kernel
    +
    +        # return delta term
    +        return delta_term
    +
    +    def _padding(self, X_batch, batch_type="image"):
    +
    +        # same padding for images
    +        if self.pad == "same" and batch_type == "image":
    +            padded_height = X_batch.shape[height_index] + (self.kernel_height // 2) * 2
    +            padded_width = X_batch.shape[width_index] + (self.kernel_width // 2) * 2
    +            half_kernel_height = self.kernel_height // 2
    +            half_kernel_width = self.kernel_width // 2
    +
    +            # initialize padded array
    +            X_batch_padded = np.ndarray(
    +                (
    +                    X_batch.shape[input_index],
    +                    X_batch.shape[feature_maps_index],
    +                    padded_height,
    +                    padded_width,
    +                )
    +            )
    +
    +            # zero pad all images in X_batch
    +            for img in range(X_batch.shape[input_index]):
    +                padded_img = np.zeros(
    +                    (X_batch.shape[feature_maps_index], padded_height, padded_width)
    +                )
    +                padded_img[
    +                    :,
    +                    half_kernel_height : padded_height - half_kernel_height,
    +                    half_kernel_width : padded_width - half_kernel_width,
    +                ] = X_batch[img, :, :, :]
    +                X_batch_padded[img, :, :, :] = padded_img[:, :, :]
    +
    +            return X_batch_padded
    +
    +        # same padding for gradients
    +        elif self.pad == "same" and batch_type == "grad":
    +            padded_height = X_batch.shape[height_index] + (self.kernel_height // 2) * 2
    +            padded_width = X_batch.shape[width_index] + (self.kernel_width // 2) * 2
    +            half_kernel_height = self.kernel_height // 2
    +            half_kernel_width = self.kernel_width // 2
    +
    +            # initialize padded array
    +            delta_term_padded = np.zeros(
    +                (
    +                    X_batch.shape[input_index],
    +                    X_batch.shape[feature_maps_index],
    +                    padded_height,
    +                    padded_width,
    +                )
    +            )
    +
    +            # zero pad delta term
    +            delta_term_padded[
    +                :, :, : X_batch.shape[height_index], : X_batch.shape[width_index]
    +            ] = X_batch[:, :, :, :]
    +
    +            return delta_term_padded
    +
    +        else:
    +            return X_batch
    +
    +    def _reset_weights_independently(self):
    +        # sets seed to remove randomness inbetween runs
    +        if self.seed is not None:
    +            np.random.seed(self.seed)
    +
    +        # initializes kernel matrix
    +        self.kernel = np.ndarray(
    +            (
    +                self.input_channels,
    +                self.feature_maps,
    +                self.kernel_height,
    +                self.kernel_width,
    +            )
    +        )
    +
    +        # randomly initializes weights
    +        for chin in range(self.kernel.shape[kernel_input_channels_index]):
    +            for fmap in range(self.kernel.shape[kernel_feature_maps_index]):
    +                self.kernel[chin, fmap, :, :] = np.random.rand(
    +                    self.kernel_height, self.kernel_width
    +                )
    +
    +    def _reset_weights(self, previous_nodes):
    +        # sets weights
    +        self._reset_weights_independently()
    +
    +        # returns shape of output used for subsequent layer's weight initiation
    +        strided_height = int(
    +            np.ceil(previous_nodes.shape[height_index] / self.v_stride)
    +        )
    +        strided_width = int(np.ceil(previous_nodes.shape[width_index] / self.h_stride))
    +        next_nodes = np.ones(
    +            (
    +                previous_nodes.shape[input_index],
    +                self.feature_maps,
    +                strided_height,
    +                strided_width,
    +            )
    +        )
    +        return next_nodes / self.kernel_height
    +
    +    def _check_for_errors(self):
    +        if self.X_batch_feedforward.shape[input_channel_index] != self.input_channels:
    +            raise AssertionError(
    +                f"ERROR: Number of input channels in data ({self.X_batch_feedforward.shape[input_channel_index]}) is not equal to input channels in Convolution2DLayerOPT ({self.input_channels})! Please change the number of input channels of the Convolution2DLayer such that they are equal"
    +            )
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    Backpropagation in the convolutional layer

    + +

    As you may have noticed, we have not yet explained how the +backpropagation algorithm works in a convolutional layer. However, +having covered all other major details about convolutional layers, we +are now prepared to do so. It should come as no surprise that the +calculation of delta terms at each convolutional layer takes the form +of convolution. After the gradient has been propagated backwards +through the flattening layer, where it was reshaped into an +appropriate form, calculating the update value for the kernel is +simply a matter of convolving the output gradient with the input of +the layer for which we are updating the weights. For more detail, this +article serves as an excellent resource, see +https://pavisj.medium.com/convolutions-and-backpropagations-46026a8f5d2c +

    +

    Demonstration

    + +

    We can use the convolutional layer above to perform a simple convolution on an image of the now familiar cute dog.

    + + + +
    +
    +
    +
    +
    +
    import numpy as np
    +import imageio.v3 as imageio
    +import matplotlib.pyplot as plt
    +
    +def plot_convolution_result(X, layer):
    +    plt.imshow(X[0, 0, :, :], vmin=0, vmax=255, cmap="gray")
    +    plt.title("Original image")
    +    plt.colorbar()
    +    plt.show()
    +    conv_result = layer._feedforward(X)
    +    plt.title("Result of convolutional layer")
    +    plt.imshow(conv_result[0, 0, :, :], vmin=0, vmax=255, cmap="gray")
    +    plt.colorbar()
    +    plt.show()
    +
    +# create layer
    +layer = Convolution2DLayer(
    +    input_channels=3,
    +    feature_maps=1,
    +    kernel_height=4,
    +    kernel_width=4,
    +    v_stride=2,
    +    h_stride=2,
    +    pad="same",
    +    act_func=identity,
    +    seed=2023,
    +    )
    +
    +# read in image path, make data correct format
    +img_path = img_path = "../data/IMG-2167.JPG"
    +image_of_cute_dog = imageio.imread(img_path)
    +image_shape = image_of_cute_dog.shape
    +image_of_cute_dog = image_of_cute_dog.reshape(1, image_shape[0], image_shape[1], image_shape[2])
    +image_of_cute_dog = image_of_cute_dog.transpose(0, 3, 1, 2)
    +
    +# plot the result of the convolution
    +plot_convolution_result(image_of_cute_dog, layer)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    We cobserve that the result has half the pixels on each axis due to +the fact that we've used a horizontal and vertical stride of 2. The +result of this convolution is not very insightfull, as the kernel has +completely random values for the first feedforward pass. However, as +we perform multiple forward and backward passes, the results of the +convolution should provide identifying features of the image it uses +for classification. +

    + +

    Note that image data usually comes in many different shapes and sizes, +but for our CNN we require the input data be formatted as \[Number of +inputs, input channels, input height, input width\]. Occasionally, the +data you come accross use will be formatted like this, but on many +occasions reshaping and transposing the dimensions is sadly necessary. +

    +

    Pooling Layer

    + +

    The pooling layer is another widely used type of layer in +convolutional neural networks that enables data downsampling to a more +manageable size. Despite recent technological advancements that allow +for convolution without excessive size reduction of the data, the +pooling layer still remains a fundamental component of convolutional +neural networks. It can be used before, after, or in between +convolutional layers, although finding the optimal placement of layers +and network depth requires experimentation to achieve the best +performance for a given problem. The code we provide allows you to +perform two types of pooling known as max pooling and average pooling. +

    + + + +
    +
    +
    +
    +
    +
    class Pooling2DLayer(Layer):
    +    def __init__(
    +        self,
    +        kernel_height,
    +        kernel_width,
    +        v_stride,
    +        h_stride,
    +        pooling="max",
    +        seed=None,
    +    ):
    +        super().__init__(seed)
    +        self.kernel_height = kernel_height
    +        self.kernel_width = kernel_width
    +        self.v_stride = v_stride
    +        self.h_stride = h_stride
    +        self.pooling = pooling
    +
    +    def _feedforward(self, X_batch):
    +        # Saving the input for use in the backwardpass
    +        self.X_batch_feedforward = X_batch
    +
    +        # check if user is silly
    +        self._check_for_errors()
    +
    +        # Computing the size of the feature maps based on kernel size and the stride parameter
    +        strided_height = (
    +            X_batch.shape[height_index] - self.kernel_height
    +        ) // self.v_stride + 1
    +        if X_batch.shape[height_index] == X_batch.shape[width_index]:
    +            strided_width = strided_height
    +        else:
    +            strided_width = (
    +                X_batch.shape[width_index] - self.kernel_width
    +            ) // self.h_stride + 1
    +
    +        # initialize output array
    +        output = np.ndarray(
    +            (
    +                X_batch.shape[input_index],
    +                X_batch.shape[feature_maps_index],
    +                strided_height,
    +                strided_width,
    +            )
    +        )
    +
    +        # select pooling action, either max or average pooling
    +        if self.pooling == "max":
    +            self.pooling_action = np.max
    +        elif self.pooling == "average":
    +            self.pooling_action = np.mean
    +
    +        # pool based on kernel size and stride
    +        for img in range(output.shape[input_index]):
    +            for fmap in range(output.shape[feature_maps_index]):
    +                for h in range(strided_height):
    +                    for w in range(strided_width):
    +                        output[img, fmap, h, w] = self.pooling_action(
    +                            X_batch[
    +                                img,
    +                                fmap,
    +                                (h * self.v_stride) : (h * self.v_stride)
    +                                + self.kernel_height,
    +                                (w * self.h_stride) : (w * self.h_stride)
    +                                + self.kernel_width,
    +                            ]
    +                        )
    +
    +        # output for feedforward in next layer
    +        return output
    +
    +    def _backpropagate(self, delta_term_next):
    +        # initiate delta term array
    +        delta_term = np.zeros((self.X_batch_feedforward.shape))
    +
    +        for img in range(delta_term_next.shape[input_index]):
    +            for fmap in range(delta_term_next.shape[feature_maps_index]):
    +                for h in range(0, delta_term_next.shape[height_index], self.v_stride):
    +                    for w in range(
    +                        0, delta_term_next.shape[width_index], self.h_stride
    +                    ):
    +                        # max pooling
    +                        if self.pooling == "max":
    +                            # get window
    +                            window = self.X_batch_feedforward[
    +                                img,
    +                                fmap,
    +                                h : h + self.kernel_height,
    +                                w : w + self.kernel_width,
    +                            ]
    +
    +                            # find max values indices in window
    +                            max_h, max_w = np.unravel_index(
    +                                window.argmax(), window.shape
    +                            )
    +
    +                            # set values in new, upsampled delta term
    +                            delta_term[
    +                                img,
    +                                fmap,
    +                                (h + max_h),
    +                                (w + max_w),
    +                            ] += delta_term_next[img, fmap, h, w]
    +
    +                        # average pooling
    +                        if self.pooling == "average":
    +                            delta_term[
    +                                img,
    +                                fmap,
    +                                h : h + self.kernel_height,
    +                                w : w + self.kernel_width,
    +                            ] = (
    +                                delta_term_next[img, fmap, h, w]
    +                                / self.kernel_height
    +                                / self.kernel_width
    +                            )
    +        # returns input to backpropagation in previous layer
    +        return delta_term
    +
    +    def _reset_weights(self, previous_nodes):
    +        # calculate strided height, strided width
    +        strided_height = (
    +            previous_nodes.shape[height_index] - self.kernel_height
    +        ) // self.v_stride + 1
    +        if previous_nodes.shape[height_index] == previous_nodes.shape[width_index]:
    +            strided_width = strided_height
    +        else:
    +            strided_width = (
    +                previous_nodes.shape[width_index] - self.kernel_width
    +            ) // self.h_stride + 1
    +
    +        # initiate output array
    +        output = np.ones(
    +            (
    +                previous_nodes.shape[input_index],
    +                previous_nodes.shape[feature_maps_index],
    +                strided_height,
    +                strided_width,
    +            )
    +        )
    +
    +        # returns output with shape used for reset weights in next layer
    +        return output
    +
    +    def _check_for_errors(self):
    +        # check if input is smaller than kernel size -> error
    +        assert (
    +            self.X_batch_feedforward.shape[width_index] >= self.kernel_width
    +        ), f"ERROR: Pooling kernel width_index ({self.kernel_width}) larger than data width_index ({self.X_batch_feedforward.input.shape[2]}), please lower the kernel width_index of the Pooling2DLayer"
    +        assert (
    +            self.X_batch_feedforward.shape[height_index] >= self.kernel_height
    +        ), f"ERROR: Pooling kernel height_index ({self.kernel_height}) larger than data height_index ({self.X_batch_feedforward.input.shape[3]}), please lower the kernel height_index of the Pooling2DLayer"
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    Flattening Layer

    + +

    Before we can begin building our first CNN model, we need to introduce +the flattening layer. As its name suggests, the flattening layer +transforms the data into a one-dimensional vector that can be fed into +the feedforward layers of our network. This layer plays a crucial role +in preparing the data for further processing in the +network. Additionally, the flattening layer is responsible for +reshaping the gradient to the proper shape during +backpropagation. This ensures that the kernels are correctly updated, +allowing for effective learning in the network. +

    + + + +
    +
    +
    +
    +
    +
    class FlattenLayer(Layer):
    +    def __init__(self, act_func=LRELU, seed=None):
    +        super().__init__(seed)
    +        self.act_func = act_func
    +
    +    def _feedforward(self, X_batch):
    +        # save input for backpropagation
    +        self.X_batch_feedforward_shape = X_batch.shape
    +        # Remember, the data has the following shape: (I, FM, H, W, ) in the convolutional layers
    +        # whilst the data has the shape (I, FM * H * W) in the fully connected layers
    +        # I = Inputs, FM = Feature Maps, H = Height and W = Width.
    +        X_batch = X_batch.reshape(
    +            X_batch.shape[input_index],
    +            X_batch.shape[feature_maps_index]
    +            * X_batch.shape[height_index]
    +            * X_batch.shape[width_index],
    +        )
    +
    +        # add bias to a
    +        self.z_matrix = X_batch
    +        bias = np.ones((X_batch.shape[input_index], 1)) * 0.01
    +        self.a_matrix = np.hstack([bias, X_batch])
    +
    +        # return a, the input to feedforward in next layer
    +        return self.a_matrix
    +
    +    def _backpropagate(self, weights_next, delta_term_next):
    +        activation_derivative = derivate(self.act_func)
    +
    +        # calculate delta term
    +        delta_term = (
    +            weights_next[bias_index:, :] @ delta_term_next.T
    +        ).T * activation_derivative(self.z_matrix)
    +
    +        # FlattenLayer does not update weights
    +        # reshapes delta layer to convolutional layer data format [Input, Feature_Maps, Height, Width]
    +        return delta_term.reshape(self.X_batch_feedforward_shape)
    +
    +    def _reset_weights(self, previous_nodes):
    +        # note that the previous nodes to the FlattenLayer are from the convolutional layers
    +        previous_nodes = previous_nodes.reshape(
    +            previous_nodes.shape[input_index],
    +            previous_nodes.shape[feature_maps_index]
    +            * previous_nodes.shape[height_index]
    +            * previous_nodes.shape[width_index],
    +        )
    +
    +        # return shape used in reset_weights in next layer
    +        return previous_nodes.shape[node_index]
    +
    +    def get_prev_a(self):
    +        return self.a_matrix
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    Fully Connected Layers

    + +

    Finally, the result from the flatten layer will pass to a series of +fully connected layers, which function as a normal feed forward neural +network. The fully connected layers are split into two classes; +FullyConnectedLayer which acts as a hidden layer, and OutputLayer, +which acts as the single output layer at the end of the CNN. If one +wishes to use this codebase to construct a normal feed forward neural +network, it must start with a FlattenLayer due to techincal details +regarding weight intitialization. However many FullyConnectedLayers +can be added to the CNN, and in each layer the amount of nodes, which +activation function and scheduler to use can be specified. In +practice, the scheduler will be specified in the CNN object +initialization, and inherited if no other scheduler is specified. +

    + + + +
    +
    +
    +
    +
    +
    class FullyConnectedLayer(Layer):
    +    # FullyConnectedLayer per default uses LRELU and Adam scheduler
    +    # with an eta of 0.0001, rho of 0.9 and rho2 of 0.999
    +    def __init__(
    +        self,
    +        nodes: int,
    +        act_func: Callable = LRELU,
    +        scheduler: Scheduler = Adam(eta=1e-4, rho=0.9, rho2=0.999),
    +        seed: int = None,
    +    ):
    +        super().__init__(seed)
    +        self.nodes = nodes
    +        self.act_func = act_func
    +        self.scheduler_weight = copy(scheduler)
    +        self.scheduler_bias = copy(scheduler)
    +
    +        # initiate matrices for later
    +        self.weights = None
    +        self.a_matrix = None
    +        self.z_matrix = None
    +
    +    def _feedforward(self, X_batch):
    +        # calculate z
    +        self.z_matrix = X_batch @ self.weights
    +
    +        # calculate a, add bias
    +        bias = np.ones((X_batch.shape[input_index], 1)) * 0.01
    +        self.a_matrix = self.act_func(self.z_matrix)
    +        self.a_matrix = np.hstack([bias, self.a_matrix])
    +
    +        # return a, the input for feedforward in next layer
    +        return self.a_matrix
    +
    +    def _backpropagate(self, weights_next, delta_term_next, a_previous, lam):
    +        # take the derivative of the activation function
    +        activation_derivative = derivate(self.act_func)
    +
    +        # calculate the delta term
    +        delta_term = (
    +            weights_next[bias_index:, :] @ delta_term_next.T
    +        ).T * activation_derivative(self.z_matrix)
    +
    +        # intitiate matrix to store gradient
    +        # note that we exclude the bias term, which we will calculate later
    +        gradient_weights = np.zeros(
    +            (
    +                a_previous.shape[input_index],
    +                a_previous.shape[node_index] - bias_index,
    +                delta_term.shape[node_index],
    +            )
    +        )
    +
    +        # calculate gradient = delta term * previous a
    +        for i in range(len(delta_term)):
    +            gradient_weights[i, :, :] = np.outer(
    +                a_previous[i, bias_index:], delta_term[i, :]
    +            )
    +
    +        # sum the gradient, divide by input_index
    +        gradient_weights = np.mean(gradient_weights, axis=input_index)
    +        # for the bias gradient we do not multiply by previous a
    +        gradient_bias = np.mean(delta_term, axis=input_index).reshape(
    +            1, delta_term.shape[node_index]
    +        )
    +
    +        # regularization term
    +        gradient_weights += self.weights[bias_index:, :] * lam
    +
    +        # send gradients into scheduler
    +        # returns update matrix which will be used to update the weights and bias
    +        update_matrix = np.vstack(
    +            [
    +                self.scheduler_bias.update_change(gradient_bias),
    +                self.scheduler_weight.update_change(gradient_weights),
    +            ]
    +        )
    +
    +        # update weights
    +        self.weights -= update_matrix
    +
    +        # return weights and delta term, input for backpropagation in previous layer
    +        return self.weights, delta_term
    +
    +    def _reset_weights(self, previous_nodes):
    +        # sets seed to remove randomness inbetween runs
    +        if self.seed is not None:
    +            np.random.seed(self.seed)
    +
    +        # add bias, initiate random weights
    +        bias = 1
    +        self.weights = np.random.randn(previous_nodes + bias, self.nodes)
    +
    +        # returns number of nodes, used for reset_weights in next layer
    +        return self.nodes
    +
    +    def _reset_scheduler(self):
    +        # resets scheduler per epoch
    +        self.scheduler_weight.reset()
    +        self.scheduler_bias.reset()
    +
    +    def get_prev_a(self):
    +        # returns a matrix, used in backpropagation
    +        return self.a_matrix
    +
    +
    +class OutputLayer(FullyConnectedLayer):
    +    def __init__(
    +        self,
    +        nodes: int,
    +        output_func: Callable = LRELU,
    +        cost_func: Callable = CostCrossEntropy,
    +        scheduler: Scheduler = Adam(eta=1e-4, rho=0.9, rho2=0.999),
    +        seed: int = None,
    +    ):
    +        super().__init__(nodes, output_func, copy(scheduler), seed)
    +        self.cost_func = cost_func
    +
    +        # initiate matrices for later
    +        self.weights = None
    +        self.a_matrix = None
    +        self.z_matrix = None
    +
    +        # decides if the output layer performs binary or multi-class classification
    +        self._set_pred_format()
    +
    +    def _feedforward(self, X_batch: np.ndarray):
    +        # calculate a, z
    +        # note that bias is not added as this would create an extra output class
    +        self.z_matrix = X_batch @ self.weights
    +        self.a_matrix = self.act_func(self.z_matrix)
    +
    +        # returns prediction
    +        return self.a_matrix
    +
    +    def _backpropagate(self, target, a_previous, lam):
    +        # note that in the OutputLayer the activation function is the output function
    +        activation_derivative = derivate(self.act_func)
    +
    +        # calculate output delta terms
    +        # for multi-class or binary classification
    +        if self.pred_format == "Multi-class":
    +            delta_term = self.a_matrix - target
    +        else:
    +            cost_func_derivative = grad(self.cost_func(target))
    +            delta_term = activation_derivative(self.z_matrix) * cost_func_derivative(
    +                self.a_matrix
    +            )
    +
    +        # intiate matrix that stores gradient
    +        gradient_weights = np.zeros(
    +            (
    +                a_previous.shape[input_index],
    +                a_previous.shape[node_index] - bias_index,
    +                delta_term.shape[node_index],
    +            )
    +        )
    +
    +        # calculate gradient = delta term * previous a
    +        for i in range(len(delta_term)):
    +            gradient_weights[i, :, :] = np.outer(
    +                a_previous[i, bias_index:], delta_term[i, :]
    +            )
    +
    +        # sum the gradient, divide by input_index
    +        gradient_weights = np.mean(gradient_weights, axis=input_index)
    +        # for the bias gradient we do not multiply by previous a
    +        gradient_bias = np.mean(delta_term, axis=input_index).reshape(
    +            1, delta_term.shape[node_index]
    +        )
    +
    +        # regularization term
    +        gradient_weights += self.weights[bias_index:, :] * lam
    +
    +        # send gradients into scheduler
    +        # returns update matrix which will be used to update the weights and bias
    +        update_matrix = np.vstack(
    +            [
    +                self.scheduler_bias.update_change(gradient_bias),
    +                self.scheduler_weight.update_change(gradient_weights),
    +            ]
    +        )
    +
    +        # update weights
    +        self.weights -= update_matrix
    +
    +        # return weights and delta term, input for backpropagation in previous layer
    +        return self.weights, delta_term
    +
    +    def _reset_weights(self, previous_nodes):
    +        # sets seed to remove randomness inbetween runs
    +        if self.seed is not None:
    +            np.random.seed(self.seed)
    +
    +        # add bias, initiate random weights
    +        bias = 1
    +        self.weights = np.random.rand(previous_nodes + bias, self.nodes)
    +
    +        # returns number of nodes, used for reset_weights in next layer
    +        return self.nodes
    +
    +    def _reset_scheduler(self):
    +        # resets scheduler per epoch
    +        self.scheduler_weight.reset()
    +        self.scheduler_bias.reset()
    +
    +    def _set_pred_format(self):
    +        # sets prediction format to either regression, binary or multi-class classification
    +        if self.act_func.__name__ is None or self.act_func.__name__ == "identity":
    +            self.pred_format = "Regression"
    +        elif self.act_func.__name__ == "sigmoid" or self.act_func.__name__ == "tanh":
    +            self.pred_format = "Binary"
    +        else:
    +            self.pred_format = "Multi-class"
    +
    +    def get_pred_format(self):
    +        # returns format of prediction
    +        return self.pred_format
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    Optimized Convolution2DLayer

    + +

    For our CNN, we have also implemented an optimized version of the +Convolution2DLayer, Convolution2DLayerOPT, which runs much faster. See +VII. Remarks for discussion. This layer will per default be used by +the CNN due to its computational advantages, but is much less +readable. We've documented it such that specially interested students +can understand the principles behind it, but it is not recommended to +read. In short, we reshape and transpose parts of the image such that +the convolutional operation can be swapped out for a simple matrix +multiplication. +

    + + + +
    +
    +
    +
    +
    +
    class Convolution2DLayerOPT(Convolution2DLayer):
    +    """
    +    Am optimized version of the convolution layer above which
    +    utilizes an approach of extracting windows of size equivalent
    +    in size to the filter. The convoution is then performed on those
    +    windows instead of a full feature map.
    +    """
    +
    +    def __init__(
    +        self,
    +        input_channels,
    +        feature_maps,
    +        kernel_height,
    +        kernel_width,
    +        v_stride,
    +        h_stride,
    +        pad,
    +        act_func: Callable,
    +        seed=None,
    +        reset_weights_independently=True,
    +    ):
    +        super().__init__(
    +            input_channels,
    +            feature_maps,
    +            kernel_height,
    +            kernel_width,
    +            v_stride,
    +            h_stride,
    +            pad,
    +            act_func,
    +            seed,
    +        )
    +        # true if layer is used outside of CNN
    +        if reset_weights_independently == True:
    +            self._reset_weights_independently()
    +
    +    def _feedforward(self, X_batch):
    +        # The optimized _feedforward method is difficult to understand but computationally more efficient
    +        # for a more "by the book" approach, please look at the _feedforward method of Convolution2DLayer
    +
    +        # save the input for backpropagation
    +        self.X_batch_feedforward = X_batch
    +
    +        # check that there are the correct amount of input channels
    +        self._check_for_errors()
    +
    +        # calculate new shape after stride
    +        strided_height = int(np.ceil(X_batch.shape[height_index] / self.v_stride))
    +        strided_width = int(np.ceil(X_batch.shape[width_index] / self.h_stride))
    +
    +        # get windows of the image for more computationally efficient convolution
    +        # the idea is that we want to align the dimensions that we wish to matrix
    +        # multiply, then use a simple matrix multiplication instead of convolution.
    +        # then, we reshape the size back to its intended shape
    +        windows = self._extract_windows(X_batch)
    +        windows = windows.transpose(1, 0, 2, 3, 4).reshape(
    +            X_batch.shape[input_index],
    +            strided_height * strided_width,
    +            -1,
    +        )
    +
    +        # reshape the kernel for more computationally efficient convolution
    +        kernel = self.kernel
    +        kernel = kernel.transpose(0, 2, 3, 1).reshape(
    +            kernel.shape[kernel_input_channels_index]
    +            * kernel.shape[height_index]
    +            * kernel.shape[width_index],
    +            -1,
    +        )
    +
    +        # use simple matrix calculation to obtain output
    +        output = (
    +            (windows @ kernel)
    +            .reshape(
    +                X_batch.shape[input_index],
    +                strided_height,
    +                strided_width,
    +                -1,
    +            )
    +            .transpose(0, 3, 1, 2)
    +        )
    +
    +        # The output is reshaped and rearranged to appropriate shape
    +        return self.act_func(
    +            output / (self.kernel_height * X_batch.shape[feature_maps_index])
    +        )
    +
    +    def _backpropagate(self, delta_term_next):
    +        # The optimized _backpropagate method is difficult to understand but computationally more efficient
    +        # for a more "by the book" approach, please look at the _backpropagate method of Convolution2DLayer
    +        act_derivative = derivate(self.act_func)
    +        delta_term_next = act_derivative(delta_term_next)
    +
    +        # calculate strided dimensions
    +        strided_height = int(
    +            np.ceil(self.X_batch_feedforward.shape[height_index] / self.v_stride)
    +        )
    +        strided_width = int(
    +            np.ceil(self.X_batch_feedforward.shape[width_index] / self.h_stride)
    +        )
    +
    +        # copy kernel
    +        kernel = self.kernel
    +
    +        # get windows, reshape for matrix multiplication
    +        windows = self._extract_windows(self.X_batch_feedforward, "image").reshape(
    +            self.X_batch_feedforward.shape[input_index]
    +            * strided_height
    +            * strided_width,
    +            -1,
    +        )
    +
    +        # initialize output gradient, reshape and transpose into correct shape
    +        # for matrix multiplication
    +        output_grad_tr = delta_term_next.transpose(0, 2, 3, 1).reshape(
    +            self.X_batch_feedforward.shape[input_index]
    +            * strided_height
    +            * strided_width,
    +            -1,
    +        )
    +
    +        # calculate gradient kernel via simple matrix multiplication and reshaping
    +        gradient_kernel = (
    +            (windows.T @ output_grad_tr)
    +            .reshape(
    +                kernel.shape[kernel_input_channels_index],
    +                kernel.shape[height_index],
    +                kernel.shape[width_index],
    +                kernel.shape[kernel_feature_maps_index],
    +            )
    +            .transpose(0, 3, 1, 2)
    +        )
    +
    +        # for computing the input gradient
    +        windows_out, upsampled_height, upsampled_width = self._extract_windows(
    +            delta_term_next, "grad"
    +        )
    +
    +        # calculate new window dimensions
    +        new_windows_first_dim = (
    +            self.X_batch_feedforward.shape[input_index]
    +            * upsampled_height
    +            * upsampled_width
    +        )
    +        # ceil allows for various asymmetric kernels
    +        new_windows_sec_dim = int(np.ceil(windows_out.size / new_windows_first_dim))
    +
    +        # reshape for matrix multiplication
    +        windows_out = windows_out.transpose(1, 0, 2, 3, 4).reshape(
    +            new_windows_first_dim, new_windows_sec_dim
    +        )
    +
    +        # reshape for matrix multiplication
    +        kernel_reshaped = kernel.reshape(self.input_channels, -1)
    +
    +        # calculating input gradient for next convolutional layer
    +        input_grad = (windows_out @ kernel_reshaped.T).reshape(
    +            self.X_batch_feedforward.shape[input_index],
    +            upsampled_height,
    +            upsampled_width,
    +            kernel.shape[kernel_input_channels_index],
    +        )
    +        input_grad = input_grad.transpose(0, 3, 1, 2)
    +
    +        # Update the weights in the kernel
    +        self.kernel -= gradient_kernel
    +
    +        # Output the gradient to propagate backwards
    +        return input_grad
    +
    +    def _extract_windows(self, X_batch, batch_type="image"):
    +        """
    +        Receives as input the X_batch with shape (inputs, feature_maps, image_height, image_width)
    +        and extract windows of size kernel_height * kernel_width for every image and every feature_map.
    +        It then returns an np.ndarray of shape (image_height * image_width, inputs, feature_maps, kernel_height, kernel_width)
    +        which will be used either to filter the images in feedforward or to calculate the gradient.
    +        """
    +
    +        # initialize list of windows
    +        windows = []
    +
    +        if batch_type == "image":
    +            # pad the images
    +            X_batch_padded = self._padding(X_batch, batch_type="image")
    +            img_height, img_width = X_batch_padded.shape[2:]
    +            # For each location in the image...
    +            for h in range(
    +                0,
    +                X_batch.shape[height_index],
    +                self.v_stride,
    +            ):
    +                for w in range(
    +                    0,
    +                    X_batch.shape[width_index],
    +                    self.h_stride,
    +                ):
    +                    # ...obtain an image patch of the original size (strided)
    +
    +                    # get window
    +                    window = X_batch_padded[
    +                        :,
    +                        :,
    +                        h : h + self.kernel_height,
    +                        w : w + self.kernel_width,
    +                    ]
    +
    +                    # append to list of windows
    +                    windows.append(window)
    +
    +            # return numpy array instead of list
    +            return np.stack(windows)
    +
    +        # In order to be able to perform backprogagation by the method of window extraction,
    +        # here is a modified approach to extracting the windows which allow for the necessary
    +        # upsampling of the gradient in case the on of the stride parameters is larger than one.
    +
    +        if batch_type == "grad":
    +
    +            # In the case of one of the stride parameters being odd, we have to take some
    +            # extra care in calculating the upsampled size of X_batch. We solve this
    +            # by simply flooring the result of dividing stride by 2.
    +            if self.v_stride < 2 or self.v_stride % 2 == 0:
    +                v_stride = 0
    +            else:
    +                v_stride = int(np.floor(self.v_stride / 2))
    +
    +            if self.h_stride < 2 or self.h_stride % 2 == 0:
    +                h_stride = 0
    +            else:
    +                h_stride = int(np.floor(self.h_stride / 2))
    +
    +            upsampled_height = (X_batch.shape[height_index] * self.v_stride) - v_stride
    +            upsampled_width = (X_batch.shape[width_index] * self.h_stride) - h_stride
    +
    +            # When upsampling, we need to insert rows and columns filled with zeros
    +            # into each feature map. How many of those we have to insert is purely
    +            # dependant on the value of stride parameter in the vertical and horizontal
    +            # direction.
    +            if self.v_stride > 1:
    +                v_ind = 1
    +                for i in range(X_batch.shape[height_index]):
    +                    for j in range(self.v_stride - 1):
    +                        X_batch = np.insert(X_batch, v_ind, 0, axis=height_index)
    +                    v_ind += self.v_stride
    +
    +            if self.h_stride > 1:
    +                h_ind = 1
    +                for i in range(X_batch.shape[width_index]):
    +                    for k in range(self.h_stride - 1):
    +                        X_batch = np.insert(X_batch, h_ind, 0, axis=width_index)
    +                    h_ind += self.h_stride
    +
    +            # Since the insertion of zero-filled rows and columns isn't perfect, we have
    +            # to assure that the resulting feature maps will have the expected upsampled height
    +            # and width by cutting them og at desired dimensions.
    +
    +            X_batch = X_batch[:, :, :upsampled_height, :upsampled_width]
    +
    +            X_batch_padded = self._padding(X_batch, batch_type="grad")
    +
    +            # initialize list of windows
    +            windows = []
    +
    +            # For each location in the image...
    +            for h in range(
    +                0,
    +                X_batch.shape[height_index],
    +                self.v_stride,
    +            ):
    +                for w in range(
    +                    0,
    +                    X_batch.shape[width_index],
    +                    self.h_stride,
    +                ):
    +                    # ...obtain an image patch of the original size (strided)
    +
    +                    # get window
    +                    window = X_batch_padded[
    +                        :, :, h : h + self.kernel_height, w : w + self.kernel_width
    +                    ]
    +
    +                    # append window to list
    +                    windows.append(window)
    +
    +            # return numpy array, unsampled dimensions
    +            return np.stack(windows), upsampled_height, upsampled_width
    +
    +    def _check_for_errors(self):
    +        # compares input channels of data to input channels of Convolution2DLayer
    +        if self.X_batch_feedforward.shape[input_channel_index] != self.input_channels:
    +            raise AssertionError(
    +                f"ERROR: Number of input channels in data ({self.X_batch_feedforward.shape[input_channel_index]}) is not equal to input channels in Convolution2DLayerOPT ({self.input_channels})! Please change the number of input channels of the Convolution2DLayer such that they are equal"
    +            )
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    The Convolutional Neural Network (CNN)

    + +

    Finally, we present the code for the CNN. The CNN class organizes all the layers, and allows for training on image data.

    + + + +
    +
    +
    +
    +
    +
    import math
    +import autograd.numpy as np
    +import sys
    +import warnings
    +from autograd import grad, elementwise_grad
    +from random import random, seed
    +from copy import deepcopy
    +from typing import Tuple, Callable
    +from sklearn.utils import resample
    +
    +warnings.simplefilter("error")
    +
    +
    +class CNN:
    +    def __init__(
    +        self,
    +        cost_func: Callable = CostCrossEntropy,
    +        scheduler: Scheduler = Adam(eta=1e-4, rho=0.9, rho2=0.999),
    +        seed: int = None,
    +    ):
    +        """
    +        Description:
    +        ------------
    +            Instantiates CNN object
    +
    +        Parameters:
    +        ------------
    +            I   output_func (costFunctions) cost function for feed forward neural network part of CNN,
    +                such as "CostLogReg", "CostOLS" or "CostCrossEntropy"
    +
    +            II  scheduler (Scheduler) optional parameter, default set to Adam. Can also be set to other
    +                schedulers such as AdaGrad, Momentum, RMS_prop and Constant. Note that schedulers have
    +                to be instantiated first with proper parameters (for example eta, rho and rho2 for Adam)
    +
    +            III seed (int) used for seeding all random operations
    +        """
    +        self.layers = list()
    +        self.cost_func = cost_func
    +        self.scheduler = scheduler
    +        self.schedulers_weight = list()
    +        self.schedulers_bias = list()
    +        self.seed = seed
    +        self.pred_format = None
    +
    +    def add_FullyConnectedLayer(
    +        self, nodes: int, act_func=LRELU, scheduler=None
    +    ) -> None:
    +        """
    +        Description:
    +        ------------
    +            Add a FullyConnectedLayer to the CNN, i.e. a hidden layer in the feed forward neural
    +            network part of the CNN. Often called a Dense layer in literature
    +
    +        Parameters:
    +        ------------
    +            I   nodes (int) number of nodes in FullyConnectedLayer
    +            II  act_func (activationFunctions) activation function of FullyConnectedLayer,
    +                such as "sigmoid", "RELU", "LRELU", "softmax" or "identity"
    +            III scheduler (Scheduler) optional parameter, default set to Adam. Can also be set to other
    +                schedulers such as AdaGrad, Momentum, RMS_prop and Constant
    +        """
    +        assert self.layers, "FullyConnectedLayer should follow FlattenLayer in CNN"
    +
    +        if scheduler is None:
    +            scheduler = self.scheduler
    +
    +        layer = FullyConnectedLayer(nodes, act_func, scheduler, self.seed)
    +        self.layers.append(layer)
    +
    +    def add_OutputLayer(self, nodes: int, output_func=sigmoid, scheduler=None) -> None:
    +        """
    +        Description:
    +        ------------
    +            Add an OutputLayer to the CNN, i.e. a the final layer in the feed forward neural
    +            network part of the CNN
    +
    +        Parameters:
    +        ------------
    +            I   nodes (int) number of nodes in OutputLayer. Set nodes=1 for binary classification and
    +                nodes = number of classes for multi-class classification
    +            II  output_func (activationFunctions) activation function for the output layer, such as
    +                "identity" for regression, "sigmoid" for binary classification and "softmax" for multi-class
    +                classification
    +            III scheduler (Scheduler) optional parameter, default set to Adam. Can also be set to other
    +                schedulers such as AdaGrad, Momentum, RMS_prop and Constant
    +        """
    +        assert self.layers, "OutputLayer should follow FullyConnectedLayer in CNN"
    +
    +        if scheduler is None:
    +            scheduler = self.scheduler
    +
    +        output_layer = OutputLayer(
    +            nodes, output_func, self.cost_func, scheduler, self.seed
    +        )
    +        self.layers.append(output_layer)
    +        self.pred_format = output_layer.get_pred_format()
    +
    +    def add_FlattenLayer(self, act_func=LRELU) -> None:
    +        """
    +        Description:
    +        ------------
    +            Add a FlattenLayer to the CNN, which flattens the image data such that it is formatted to
    +            be used in the feed forward neural network part of the CNN
    +        """
    +        self.layers.append(FlattenLayer(act_func=act_func, seed=self.seed))
    +
    +    def add_Convolution2DLayer(
    +        self,
    +        input_channels=1,
    +        feature_maps=1,
    +        kernel_height=3,
    +        kernel_width=3,
    +        v_stride=1,
    +        h_stride=1,
    +        pad="same",
    +        act_func=LRELU,
    +        optimized=True,
    +    ) -> None:
    +        """
    +        Description:
    +        ------------
    +            Add a Convolution2DLayer to the CNN, i.e. a convolutional layer with a 2 dimensional kernel. Should be
    +            the first layer added to the CNN
    +
    +        Parameters:
    +        ------------
    +            I   input_channels (int) specifies amount of input channels. For monochrome images, use input_channels
    +                = 1, and input_channels = 3 for colored images, where each channel represents one of R, G and B
    +            II  feature_maps (int) amount of feature maps in CNN
    +            III kernel_height (int) height of the kernel, also called 'convolutional filter' in literature
    +            IV  kernel_width (int) width of the kernel, also called 'convolutional filter' in literature
    +            V   v_stride (int) value of vertical stride for dimentionality reduction
    +            VI  h_stride (int) value of horizontal stride for dimentionality reduction
    +            VII pad (str) default = "same" ensures output size is the same as input size (given stride=1)
    +           VIII act_func (activationFunctions) default = "LRELU", nonlinear activation function
    +             IX optimized (bool) default = True, uses Convolution2DLayerOPT if True which is much faster when
    +                compared to Convolution2DLayer, which is a more straightforward, understandable implementation
    +        """
    +        if optimized:
    +            conv_layer = Convolution2DLayerOPT(
    +                input_channels,
    +                feature_maps,
    +                kernel_height,
    +                kernel_width,
    +                v_stride,
    +                h_stride,
    +                pad,
    +                act_func,
    +                self.seed,
    +                reset_weights_independently=False,
    +            )
    +        else:
    +            conv_layer = Convolution2DLayer(
    +                input_channels,
    +                feature_maps,
    +                kernel_height,
    +                kernel_width,
    +                v_stride,
    +                h_stride,
    +                pad,
    +                act_func,
    +                self.seed,
    +                reset_weights_independently=False,
    +            )
    +        self.layers.append(conv_layer)
    +
    +    def add_PoolingLayer(
    +        self, kernel_height=2, kernel_width=2, v_stride=1, h_stride=1, pooling="max"
    +    ) -> None:
    +        """
    +        Description:
    +        ------------
    +            Add a Pooling2DLayer to the CNN, i.e. a pooling layer that reduces the dimentionality of
    +            the image data. It is not necessary to use a Pooling2DLayer when creating a CNN, but it
    +            can be used to speed up the training
    +
    +        Parameters:
    +        ------------
    +            I   kernel_height (int) height of the kernel used for pooling
    +            II  kernel_width (int) width of the kernel used for pooling
    +            III v_stride (int) value of vertical stride for dimentionality reduction
    +            IV  h_stride (int) value of horizontal stride for dimentionality reduction
    +            V   pooling (str) either "max" or "average", describes type of pooling performed
    +        """
    +        pooling_layer = Pooling2DLayer(
    +            kernel_height, kernel_width, v_stride, h_stride, pooling, self.seed
    +        )
    +        self.layers.append(pooling_layer)
    +
    +    def fit(
    +        self,
    +        X: np.ndarray,
    +        t: np.ndarray,
    +        epochs: int = 100,
    +        lam: float = 0,
    +        batches: int = 1,
    +        X_val: np.ndarray = None,
    +        t_val: np.ndarray = None,
    +    ) -> dict:
    +        """
    +        Description:
    +        ------------
    +            Fits the CNN to input X for a given amount of epochs. Performs feedforward and backpropagation passes,
    +            can utilize batches, regulariziation and validation if desired.
    +
    +        Parameters:
    +        ------------
    +            X (numpy array) with input data in format [images, input channels,
    +            image height, image_width]
    +            t (numpy array) target labels for input data
    +            epochs (int) amount of epochs
    +            lam (float) regulariziation term lambda
    +            batches (int) amount of batches input data splits into
    +            X_val (numpy array) validation data
    +            t_val (numpy array) target labels for validation data
    +
    +        Returns:
    +        ------------
    +            scores (dict) a dictionary with "train_error", "train_acc", "val_error", val_acc" keys
    +            that contain numpy arrays with float values of all accuracies/errors over all epochs.
    +            Can be used to create plots. Also used to update the progress bar during training
    +        """
    +
    +        # setup
    +        if self.seed is not None:
    +            np.random.seed(self.seed)
    +
    +        # initialize weights
    +        self._initialize_weights(X)
    +
    +        # create arrays for score metrics
    +        scores = self._initialize_scores(epochs)
    +
    +        assert batches <= t.shape[0]
    +        batch_size = X.shape[0] // batches
    +
    +        try:
    +            for epoch in range(epochs):
    +                for batch in range(batches):
    +                    # minibatch gradient descent
    +                    # If the for loop has reached the last batch, take all thats left
    +                    if batch == batches - 1:
    +                        X_batch = X[batch * batch_size :, :, :, :]
    +                        t_batch = t[batch * batch_size :, :]
    +                    else:
    +                        X_batch = X[
    +                            batch * batch_size : (batch + 1) * batch_size, :, :, :
    +                        ]
    +                        t_batch = t[batch * batch_size : (batch + 1) * batch_size, :]
    +
    +                    self._feedforward(X_batch)
    +                    self._backpropagate(t_batch, lam)
    +
    +                # reset schedulers for each epoch (some schedulers pass in this call)
    +                for layer in self.layers:
    +                    if isinstance(layer, FullyConnectedLayer):
    +                        layer._reset_scheduler()
    +
    +                # computing performance metrics
    +                scores = self._compute_scores(scores, epoch, X, t, X_val, t_val)
    +
    +                # printing progress bar
    +                print_length = self._progress_bar(
    +                    epoch,
    +                    epochs,
    +                    scores,
    +                )
    +        # allows for stopping training at any point and seeing the result
    +        except KeyboardInterrupt:
    +            pass
    +
    +        # visualization of training progression (similiar to tensorflow progression bar)
    +        sys.stdout.write("\r" + " " * print_length)
    +        sys.stdout.flush()
    +        self._progress_bar(
    +            epochs,
    +            epochs,
    +            scores,
    +        )
    +        sys.stdout.write("")
    +
    +        return scores
    +
    +    def _feedforward(self, X_batch) -> np.ndarray:
    +        """
    +        Description:
    +        ------------
    +            Performs the feedforward pass for all layers in the CNN. Called from fit()
    +        """
    +        a = X_batch
    +        for layer in self.layers:
    +            a = layer._feedforward(a)
    +
    +        return a
    +
    +    def _backpropagate(self, t_batch, lam) -> None:
    +        """
    +        Description:
    +        ------------
    +            Performs backpropagation for all layers in the CNN. Called from fit()
    +        """
    +        assert len(self.layers) >= 2
    +        reversed_layers = self.layers[::-1]
    +
    +        # for every layer, backwards
    +        for i in range(len(reversed_layers) - 1):
    +            layer = reversed_layers[i]
    +            prev_layer = reversed_layers[i + 1]
    +
    +            # OutputLayer
    +            if isinstance(layer, OutputLayer):
    +                prev_a = prev_layer.get_prev_a()
    +                weights_next, delta_next = layer._backpropagate(t_batch, prev_a, lam)
    +
    +            # FullyConnectedLayer
    +            elif isinstance(layer, FullyConnectedLayer):
    +                assert (
    +                    delta_next is not None
    +                ), "No OutputLayer to follow FullyConnectedLayer"
    +                assert (
    +                    weights_next is not None
    +                ), "No OutputLayer to follow FullyConnectedLayer"
    +                prev_a = prev_layer.get_prev_a()
    +                weights_next, delta_next = layer._backpropagate(
    +                    weights_next, delta_next, prev_a, lam
    +                )
    +
    +            # FlattenLayer
    +            elif isinstance(layer, FlattenLayer):
    +                assert (
    +                    delta_next is not None
    +                ), "No FullyConnectedLayer to follow FlattenLayer"
    +                assert (
    +                    weights_next is not None
    +                ), "No FullyConnectedLayer to follow FlattenLayer"
    +                delta_next = layer._backpropagate(weights_next, delta_next)
    +
    +            # Convolution2DLayer and Convolution2DLayerOPT
    +            elif isinstance(layer, Convolution2DLayer):
    +                assert (
    +                    delta_next is not None
    +                ), "No FlattenLayer to follow Convolution2DLayer"
    +                delta_next = layer._backpropagate(delta_next)
    +
    +            # Pooling2DLayer
    +            elif isinstance(layer, Pooling2DLayer):
    +                assert delta_next is not None, "No Layer to follow Pooling2DLayer"
    +                delta_next = layer._backpropagate(delta_next)
    +
    +            # Catch error
    +            else:
    +                raise NotImplementedError
    +
    +    def _compute_scores(
    +        self,
    +        scores: dict,
    +        epoch: int,
    +        X: np.ndarray,
    +        t: np.ndarray,
    +        X_val: np.ndarray,
    +        t_val: np.ndarray,
    +    ) -> dict:
    +        """
    +        Description:
    +        ------------
    +            Computes scores such as training error, training accuracy, validation error
    +            and validation accuracy for the CNN depending on if a validation set is used
    +            and if the CNN performs classification or regression
    +
    +        Returns:
    +        ------------
    +            scores (dict) a dictionary with "train_error", "train_acc", "val_error", val_acc" keys
    +            that contain numpy arrays with float values of all accuracies/errors over all epochs.
    +            Can be used to create plots. Also used to update the progress bar during training
    +        """
    +
    +        pred_train = self.predict(X)
    +        cost_function_train = self.cost_func(t)
    +        train_error = cost_function_train(pred_train)
    +        scores["train_error"][epoch] = train_error
    +
    +        if X_val is not None and t_val is not None:
    +            cost_function_val = self.cost_func(t_val)
    +            pred_val = self.predict(X_val)
    +            val_error = cost_function_val(pred_val)
    +            scores["val_error"][epoch] = val_error
    +
    +        if self.pred_format != "Regression":
    +            train_acc = self._accuracy(pred_train, t)
    +            scores["train_acc"][epoch] = train_acc
    +            if X_val is not None and t_val is not None:
    +                val_acc = self._accuracy(pred_val, t_val)
    +                scores["val_acc"][epoch] = val_acc
    +
    +        return scores
    +
    +    def _initialize_scores(self, epochs) -> dict:
    +        """
    +        Description:
    +        ------------
    +            Initializes scores such as training error, training accuracy, validation error
    +            and validation accuracy for the CNN
    +
    +        Returns:
    +        ------------
    +            A dictionary with "train_error", "train_acc", "val_error", val_acc" keys that
    +            will contain numpy arrays with float values of all accuracies/errors over all epochs
    +            when passed through the _compute_scores() function during fit()
    +        """
    +        scores = dict()
    +
    +        train_errors = np.empty(epochs)
    +        train_errors.fill(np.nan)
    +        val_errors = np.empty(epochs)
    +        val_errors.fill(np.nan)
    +
    +        train_accs = np.empty(epochs)
    +        train_accs.fill(np.nan)
    +        val_accs = np.empty(epochs)
    +        val_accs.fill(np.nan)
    +
    +        scores["train_error"] = train_errors
    +        scores["val_error"] = val_errors
    +        scores["train_acc"] = train_accs
    +        scores["val_acc"] = val_accs
    +
    +        return scores
    +
    +    def _initialize_weights(self, X: np.ndarray) -> None:
    +        """
    +        Description:
    +        ------------
    +            Initializes weights for all layers in CNN
    +
    +        Parameters:
    +        ------------
    +            I   X (np.ndarray) input of format [img, feature_maps, height, width]
    +        """
    +        prev_nodes = X
    +        for layer in self.layers:
    +            prev_nodes = layer._reset_weights(prev_nodes)
    +
    +    def predict(self, X: np.ndarray, *, threshold=0.5) -> np.ndarray:
    +        """
    +        Description:
    +        ------------
    +            Predicts output of input X
    +
    +        Parameters:
    +        ------------
    +            I   X (np.ndarray) input [img, feature_maps, height, width]
    +        """
    +
    +        prediction = self._feedforward(X)
    +
    +        if self.pred_format == "Binary":
    +            return np.where(prediction > threshold, 1, 0)
    +        elif self.pred_format == "Multi-class":
    +            class_prediction = np.zeros(prediction.shape)
    +            for i in range(prediction.shape[0]):
    +                class_prediction[i, np.argmax(prediction[i, :])] = 1
    +            return class_prediction
    +        else:
    +            return prediction
    +
    +    def _accuracy(self, prediction: np.ndarray, target: np.ndarray) -> float:
    +        """
    +        Description:
    +        ------------
    +            Calculates accuracy of given prediction to target
    +
    +        Parameters:
    +        ------------
    +            I   prediction (np.ndarray): output of predict() fuction
    +            (1s and 0s in case of classification, and real numbers in case of regression)
    +            II  target (np.ndarray): vector of true values (What the network should predict)
    +
    +        Returns:
    +        ------------
    +            A floating point number representing the percentage of correctly classified instances.
    +        """
    +        assert prediction.size == target.size
    +        return np.average((target == prediction))
    +
    +    def _progress_bar(self, epoch: int, epochs: int, scores: dict) -> int:
    +        """
    +        Description:
    +        ------------
    +            Displays progress of training
    +        """
    +        progression = epoch / epochs
    +        epoch -= 1
    +        print_length = 40
    +        num_equals = int(progression * print_length)
    +        num_not = print_length - num_equals
    +        arrow = ">" if num_equals > 0 else ""
    +        bar = "[" + "=" * (num_equals - 1) + arrow + "-" * num_not + "]"
    +        perc_print = self._fmt(progression * 100, N=5)
    +        line = f"  {bar} {perc_print}% "
    +
    +        for key, score in scores.items():
    +            if np.isnan(score[epoch]) == False:
    +                value = self._fmt(score[epoch], N=4)
    +                line += f"| {key}: {value} "
    +        print(line, end="\r")
    +        return len(line)
    +
    +    def _fmt(self, value: int, N=4) -> str:
    +        """
    +        Description:
    +        ------------
    +            Formats decimal numbers for progress bar
    +        """
    +        if value > 0:
    +            v = value
    +        elif value < 0:
    +            v = -10 * value
    +        else:
    +            v = 1
    +        n = 1 + math.floor(math.log10(v))
    +        if n >= N - 1:
    +            return str(round(value))
    +            # or overflow
    +        return f"{value:.{N-n-1}f}"
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    Usage of CNN code

    + +

    Using the CNN codebase is very simple. We begin by initiating a CNN +object, which takes a cost function, a scheduler and a seed as its +arguments. If a scheduler is not provided, it will per default +initiate an Adam scheduler with eta=1e-4, and if a seed is not +provided, the CNN will not be seeded, meaning it will run with a +different random seed every run. Below we demonstrate an initiation of +our CNN. +

    + + + +
    +
    +
    +
    +
    +
    adam_scheduler = Adam(eta=1e-3, rho=0.9, rho2=0.999)
    +cnn = CNN(cost_func=CostCrossEntropy, scheduler=adam_scheduler, seed=2023)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    Now that we have our CNN object, we can begin to add layers to it! +Many of the add_layer functions have default values, for example +add_Convolution2DLayer() has a default v_stride and h_stride of +1. However, these can of course be set to any value you please. Note +that the input channels of a subsequent convolutional layer must equal +the previous convolutional layer's feature maps. +

    + + + +
    +
    +
    +
    +
    +
    cnn.add_Convolution2DLayer(
    +    input_channels=1,
    +    feature_maps=1,
    +    kernel_height=3,
    +    kernel_width=3,
    +    act_func=LRELU,
    +)
    +
    +cnn.add_FlattenLayer()
    +
    +cnn.add_FullyConnectedLayer(30, LRELU)
    +
    +cnn.add_FullyConnectedLayer(20, LRELU)
    +
    +cnn.add_OutputLayer(10, softmax)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    Here we have created a CNN with the following architecture:

    + +
      +
    1. A convolutional layer with 1 input channel, with a kernel height of 2 and a width of 2, which uses LRELU as its non-linearity function. This layer outputs 1 feature map, which feed into the subsequent layer.
    2. +
    3. A flatten layer
    4. +
    5. A hidden layer with 30 nodes, with LRELU as its activation function
    6. +
    7. Another hidden layer but with 20 nodes
    8. +
    9. The output layer, with softmax as its activation function and 10 nodes. We use 10 nodes because we will be using a dataset with 10 classes.
    10. +
    +

    Now, before we can train the model, we need to load in our data. We +will use the MNIST dataset and use 10000 \( 28 \times 28 images \). +

    + + + +
    +
    +
    +
    +
    +
    from sklearn.datasets import fetch_openml
    +from sklearn.model_selection import train_test_split
    +
    +def onehot(target: np.ndarray):
    +    onehot = np.zeros((target.size, target.max() + 1))
    +    onehot[np.arange(target.size), target] = 1
    +    return onehot
    +
    +# get dataset
    +dataset = fetch_openml("mnist_784", parser="auto")
    +mnist = dataset.data.to_numpy(dtype="float")[:10000, :]
    +
    +# scale data
    +for i in range(mnist.shape[1]):
    +    mnist[:, i] /= 255
    +    
    +# reshape to add single input channel to data shape [inputs, input_channels, height, width]
    +mnist = mnist.reshape(mnist.shape[0], 1, 28, 28)
    +
    +# one hot encode target as we are doing multi-class classification
    +target = onehot(np.array([int(i) for i in dataset.target.to_numpy()[:10000]]))
    +
    +# split into training and validation data
    +x_train, x_val, y_train, y_val = train_test_split(mnist, target)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    Now we may train our model. Note that we can utilize regularization in +the CNN by using the lam (lambda) parameter in fit(), and utilize +different types of gradient descent by specifying the amount of +batches via the batches parameter as shown below. +

    + +

    The functionfit() returns a score dictionary of the training error and +accuracy (and validation error and accuracy if a validation set is +provided) which can be used to plot the error and accuracy of the +model over epochs. +

    + + + +
    +
    +
    +
    +
    +
    scores = cnn.fit(
    +    x_train,
    +    y_train,
    +    lam=1e-5,
    +    batches=10,
    +    epochs=100,
    +    X_val=x_val,
    +    t_val=y_val,
    +)
    +
    +plt.plot(scores["train_acc"], label="Training")
    +plt.plot(scores["val_acc"], label="Validation")
    +plt.ylim([0.8,1])
    +plt.xlabel("Epochs")
    +plt.ylabel("Accuracy")
    +plt.legend()
    +plt.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    Considering we only trained the model for 100 epochs without any tuning of the hyperparameters, this result is pretty good.

    + +

    The codebase allows for great flexibility in CNN +architectures. Pooling layers can be added before, inbetween or after +convolutional layers, but due to the great optimizations made within +Convolution2DLayerOPT, we recommend using the v_stride and h_stride +parameters in add_Convolution2DLayer() to reduce the dimentionality of +the problem as the pooling layer is slow in comparison. To use the +unoptimized version of Convolution2DLayer, simply pass optimized=False +as an argument in add_Convolution2DLayer(). +

    + +

    If one wishes to perform binary classification using the CNN, simply +use the cost function 'CostLogReg' when initializing the CNN and use 1 +node at the OutputLayer. +

    + +

    Below we have created another, more untraditional architecture using +our code to demonstrate its flexibility and different attributes such +as asymmetric stride that might become useful when constructing your +own CNN. +

    + + + +
    +
    +
    +
    +
    +
    adam_scheduler = Adam(eta=1e-3, rho=0.9, rho2=0.999)
    +cnn = CNN(cost_func=CostCrossEntropy, scheduler=adam_scheduler, seed=2023)
    +
    +cnn.add_Convolution2DLayer(
    +    input_channels=1,
    +    feature_maps=7,
    +    kernel_height=7,
    +    kernel_width=1,
    +    act_func=LRELU,
    +)
    +
    +cnn.add_PoolingLayer(
    +    kernel_height=2,
    +    kernel_width=2,
    +    pooling="average",
    +)
    +
    +cnn.add_PoolingLayer(
    +    kernel_height=2,
    +    kernel_width=2,
    +    pooling="max",
    +)
    +
    +cnn.add_Convolution2DLayer(
    +    input_channels=7,
    +    feature_maps=1,
    +    kernel_height=4,
    +    kernel_width=4,
    +    v_stride=2,
    +    h_stride=3,
    +    act_func=LRELU,
    +    optimized=False,
    +)
    +
    +cnn.add_Convolution2DLayer(
    +    input_channels=1,
    +    feature_maps=1,
    +    kernel_height=2,
    +    kernel_width=2,
    +    act_func=sigmoid,
    +    optimized=True,
    +)
    +
    +cnn.add_PoolingLayer(
    +    kernel_height=2,
    +    kernel_width=2,
    +    pooling="max"
    +)
    +
    +cnn.add_FlattenLayer()
    +
    +cnn.add_FullyConnectedLayer(100, LRELU)
    +
    +cnn.add_FullyConnectedLayer(10, sigmoid)
    +
    +cnn.add_FullyConnectedLayer(101, identity)
    +
    +cnn.add_OutputLayer(10, softmax)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    Here we see the use of asymmetrical 1D kernels such as the \( 7 \times +1 \) kernel in the first convolutional layer, both max and average +pooling, asymmetric stride in the unoptimized convolutional layer, +more pooling, a flatten layer, a hidden layer with 100 nodes using +LRELU, another hidden layer with 10 hidden nodes that uses the sigmoid +activation function, and another hidden layer with 101 nodes which +utilizes no activation function (identity). Finally, we arrive at the +output layer with 10 nodes, which uses softmax as its activation +function. +

    +

    Additional Remarks

    + +

    The stride parameter controls the distance between each convolution +and the kernel/filter. If our image is padded, stride is the only +parameter that determines the size of the output from a convolutional +layer. However, if we decide not to perform any padding, the size of +the output feature map depends on both the stride and kernel size. It +is important to note that neither the stride nor the kernel has to be +symmetrical. This means that we can use a rectangular filter if we +choose, and the stride in the vertical direction (axis=0 in Python) +does not need to be the same as the stride in the horizontal direction +(axis=1 in Python). It may even be the case that asymmetric +combinations of stride or kernel dimensions, or both, yield better +results than symmetric values for these parameters. +

    + + + +
    +
    +
    +
    +
    +
    def convolve(image, kernel, stride=1):
    +    for i in range(2):
    +        kernel = np.rot90(kernel)
    +
    +    k_half_height = kernel.shape[0] // 2
    +    k_half_width = kernel.shape[0] // 2
    +
    +    conv_image = np.zeros(image.shape)
    +    pad_image = padding(image, kernel)
    +
    +    for i in range(k_half_height, conv_image.shape[0] + k_half_height, stride):
    +        for j in range(k_half_width, conv_image.shape[1] + k_half_width, stride):
    +            conv_image[i - k_half_height, j - k_half_width] = np.sum(
    +                pad_image[
    +                    i - k_half_height : i + k_half_height + 1, j - k_half_width : j + k_half_width + 1
    +                ]
    +                * kernel
    +            )
    +
    +    return conv_image
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    Remarks on the speed

    + +

    Despite the naive convolution algorithm shown above working finely, it +is extremely slow, requiring approximately 20-30 seconds to process a +single image. The time complexity of 2D convolution, which is O(NMnm), +rapidly becomes a constraint and may, at worst, make computations +infeasible. Consequently, optimizing the naive 2D convolution +algorithm is a necessity, as the execution time of the algorithm +significantly increases as the input data size expands. This can pose +a bottleneck in applications that necessitate real-time processing of +large data volumes, such as image and video processing, deep learning, +and scientific simulations. +

    + +

    To address this issue, we shall present two widely used optimization +techniques: the separable kernel approach and Fast Fourier Transform +(FFT). Both of these methods can drastically reduce the computational +complexity of convolution and enhance the overall efficiency of +processing substantial data quantities. While we shall refrain from +delving into the intricacies of these algorithms, we strongly +encourage you to examine at least the application of FFT to optimize +computations. +

    +

    Convolution using separable kernels

    + + + +
    +
    +
    +
    +
    +
    def conv2DSep(image, kernel, coef, stride=1, pad="zero"):
    +    for i in range(2):
    +        kernel = np.rot90(kernel)
    +
    +    # The kernel is quadratic, thus we only need one of its dimensions
    +    half_dim = kernel.shape[0] // 2
    +
    +    ker1 = np.array(kernel[0, :])
    +    ker2 = np.array(kernel[:, 0])
    +
    +    if pad == "zero":
    +        conv_image = np.zeros(image.shape)
    +        pad_image = padding(image, kernel)
    +    else:
    +        conv_image = np.zeros(
    +            (image.shape[0] - kernel.shape[0], image.shape[1] - kernel.shape[1])
    +        )
    +        pad_image = image[:, :]
    +
    +    for i in range(half_dim, conv_image.shape[0] + half_dim, stride):
    +        for j in range(half_dim, conv_image.shape[1] + half_dim, stride):
    +            conv_image[i - half_dim, j - half_dim] = (
    +                pad_image[
    +                    i - half_dim : i + half_dim + 1, j - half_dim : j + half_dim + 1
    +                ]
    +                @ ker1
    +                @ ker2.T
    +                * coef
    +            )
    +
    +    return conv_image
    +
    +img_path = img_path = "../data/IMG-2167.JPG"
    +image_of_cute_dog = imageio.imread(img_path, mode="L")
    +start_time = time.time()
    +filtered_image = conv2DSep(image_of_cute_dog, kernel=sobel_kernel, coef=1)
    +print(f'Time taken for convolution with seperated kernel on 128x128 image {time.time() - start_time}')
    +plt.imshow(filtered_image, cmap="gray", vmin=0, vmax=255, aspect="auto")
    +plt.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    By taking advantage of the capabilities of separable kernels, we can +effectively cut the computational expense of filtering an image in +half. Yet, if we seek even more rapid processing, we can turn to the +Fast Fourier Transform (FFT) algorithm provided by the numpy +library. By utilizing FFT to transform the input image and filter into +the frequency domain, we can perform convolution in this domain. This +approach significantly reduces the number of operations needed and +results in a marked speedup relative to other convolution +techniques. In addition, it is worth noting that the FFT is widely +regarded as one of the most critical algorithms developed to date, +with applications ranging from digital signal processing to scientific +computing. +

    +

    Convolution in the Fourier domain

    + + +
    +
    +
    +
    +
    +
    start_time = time.time()
    +img_fft = np.fft.fft2(image_of_cute_dog)
    +kernel_fft = np.fft.fft2(sobel_kernel, s=image_of_cute_dog.shape)
    +
    +conv_image = img_fft * kernel_fft
    +
    +filtered_image = np.fft.ifft2(conv_image)
    +print(f'Time take for convolution in the fourier domain: {time.time() - start_time}')
    +plt.imshow(filtered_image.real, cmap="gray", vmin=0, vmax=255, aspect="auto")
    +plt.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    It is evident that executing convolution in the Fourier domain yields +the quickest computation time. Nonetheless, one should exercise +caution, particularly when dealing with images of relatively small +dimensions, as one of the other methods may prove to be more +expeditious than FFT-enhanced convolution. The overhead involved in +transferring both the image and filter into the Fourier domain, +followed by their subsequent transformation back into the spatial +domain, results in a minor inconvenience. Therefore, it is imperative +to remain cognizant of this fact when utilizing FFT as the primary +optimization technique. +

    © 1999-2023, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license diff --git a/doc/pub/week44/html/week44.html b/doc/pub/week44/html/week44.html index b327d6360..d9b9c5751 100644 --- a/doc/pub/week44/html/week44.html +++ b/doc/pub/week44/html/week44.html @@ -243,7 +243,54 @@ div.toc p,a { ('Finally, evaluate the model', 2, None, - 'finally-evaluate-the-model')]} + 'finally-evaluate-the-model'), + ('Building our own CNN code', + 2, + None, + 'building-our-own-cnn-code'), + ('List of contents:', 3, None, 'list-of-contents'), + ('Schedulers', 3, None, 'schedulers'), + ('Usage of schedulers', 3, None, 'usage-of-schedulers'), + ('Cost functions', 3, None, 'cost-functions'), + ('Usage of cost functions', 3, None, 'usage-of-cost-functions'), + ('Activation functions', 3, None, 'activation-functions'), + ('Usage of activation functions', + 3, + None, + 'usage-of-activation-functions'), + ('Convolution', 3, None, 'convolution'), + ('Layers', 3, None, 'layers'), + ('Convolution2DLayer: convolution in a hidden layer', + 3, + None, + 'convolution2dlayer-convolution-in-a-hidden-layer'), + ('Backpropagation in the convolutional layer', + 3, + None, + 'backpropagation-in-the-convolutional-layer'), + ('Demonstration', 3, None, 'demonstration'), + ('Pooling Layer', 3, None, 'pooling-layer'), + ('Flattening Layer', 3, None, 'flattening-layer'), + ('Fully Connected Layers', 3, None, 'fully-connected-layers'), + ('Optimized Convolution2DLayer', + 3, + None, + 'optimized-convolution2dlayer'), + ('The Convolutional Neural Network (CNN)', + 3, + None, + 'the-convolutional-neural-network-cnn'), + ('Usage of CNN code', 3, None, 'usage-of-cnn-code'), + ('Additional Remarks', 3, None, 'additional-remarks'), + ('Remarks on the speed', 3, None, 'remarks-on-the-speed'), + ('Convolution using separable kernels', + 3, + None, + 'convolution-using-separable-kernels'), + ('Convolution in the Fourier domain', + 3, + None, + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -1619,6 +1666,3261 @@ test_loss, test_acc = modelBuilding our own CNN code + +

    Here we present a flexible and readable python code for a CNN +implemented with NumPy. We will present the code, showcase how to use +the codebase and fit a CNN that yields a 99% accuracy on the 28x28 +MNIST dataset within reasonable time. +

    + +

    The CNN is compatible with all schedulers, cost functions and +activation functions discussed in constructing our neural network +codes. +

    + +

    The CNN code consists of different types of Layer classes, including +Convolution2DLayer, Pooling2DLayer, FlattenLayer, FullyConnectedLayer +and OutputLayer, which can be added to the CNN object using the +interface of the CNN class. This allows you to easily construct your +own CNN, as well as allowing you to get used to an interface similar +to that of TensorFlow which is used for real world applications. +

    + +

    Another important feature of this code is that it throws errors if +unreasonable decisions are made (for example using a kernel that is +larger than the image, not using a FlattenLayer, etc), and provides +the user with an informative error message. +

    +

    List of contents:

    +
      +
    1. Schedulers
    2. +
    3. Activation Functions
    4. +
    5. Cost Functions
    6. +
    7. Convolution
    8. +
    9. Layers
    10. +
    11. CNN
    12. +
    13. Some final remarks
    14. +
    +

    Schedulers

    + +

    The code below shows object oriented implementations of the Constant, +Momentum, Adagrad, AdagradMomentum, RMS prop and Adam schedulers. All +of the classes belong to the shared abstract Scheduler class, and +share the update_change() and reset() methods allowing for any of the +schedulers to be seamlessly used during the training stage, as will +later be shown in the fit() method of the neural +network. Update_change() only has one parameter, the gradient +(\( \delta^{l}_{j}a^{l-1}_k \)), and returns the change which will be +subtracted from the weights. The reset() function takes no parameters, +and resets the desired variables. For Constant and Momentum, reset +does nothing. +

    + + + +
    +
    +
    +
    +
    +
    import autograd.numpy as np
    +
    +class Scheduler:
    +    """
    +    Abstract class for Schedulers
    +    """
    +
    +    def __init__(self, eta):
    +        self.eta = eta
    +
    +    # should be overwritten
    +    def update_change(self, gradient):
    +        raise NotImplementedError
    +
    +    # overwritten if needed
    +    def reset(self):
    +        pass
    +
    +
    +class Constant(Scheduler):
    +    def __init__(self, eta):
    +        super().__init__(eta)
    +
    +    def update_change(self, gradient):
    +        return self.eta * gradient
    +    
    +    def reset(self):
    +        pass
    +
    +
    +class Momentum(Scheduler):
    +    def __init__(self, eta: float, momentum: float):
    +        super().__init__(eta)
    +        self.momentum = momentum
    +        self.change = 0
    +
    +    def update_change(self, gradient):
    +        self.change = self.momentum * self.change + self.eta * gradient
    +        return self.change
    +
    +    def reset(self):
    +        pass
    +
    +
    +class Adagrad(Scheduler):
    +    def __init__(self, eta):
    +        super().__init__(eta)
    +        self.G_t = None
    +
    +    def update_change(self, gradient):
    +        delta = 1e-8  # avoid division ny zero
    +
    +        if self.G_t is None:
    +            self.G_t = np.zeros((gradient.shape[0], gradient.shape[0]))
    +
    +        self.G_t += gradient @ gradient.T
    +
    +        G_t_inverse = 1 / (
    +            delta + np.sqrt(np.reshape(np.diagonal(self.G_t), (self.G_t.shape[0], 1)))
    +        )
    +        return self.eta * gradient * G_t_inverse
    +
    +    def reset(self):
    +        self.G_t = None
    +
    +
    +class AdagradMomentum(Scheduler):
    +    def __init__(self, eta, momentum):
    +        super().__init__(eta)
    +        self.G_t = None
    +        self.momentum = momentum
    +        self.change = 0
    +
    +    def update_change(self, gradient):
    +        delta = 1e-8  # avoid division ny zero
    +
    +        if self.G_t is None:
    +            self.G_t = np.zeros((gradient.shape[0], gradient.shape[0]))
    +
    +        self.G_t += gradient @ gradient.T
    +
    +        G_t_inverse = 1 / (
    +            delta + np.sqrt(np.reshape(np.diagonal(self.G_t), (self.G_t.shape[0], 1)))
    +        )
    +        self.change = self.change * self.momentum + self.eta * gradient * G_t_inverse
    +        return self.change
    +
    +    def reset(self):
    +        self.G_t = None
    +
    +
    +class RMS_prop(Scheduler):
    +    def __init__(self, eta, rho):
    +        super().__init__(eta)
    +        self.rho = rho
    +        self.second = 0.0
    +
    +    def update_change(self, gradient):
    +        delta = 1e-8  # avoid division ny zero
    +        self.second = self.rho * self.second + (1 - self.rho) * gradient * gradient
    +        return self.eta * gradient / (np.sqrt(self.second + delta))
    +
    +    def reset(self):
    +        self.second = 0.0
    +
    +
    +class Adam(Scheduler):
    +    def __init__(self, eta, rho, rho2):
    +        super().__init__(eta)
    +        self.rho = rho
    +        self.rho2 = rho2
    +        self.moment = 0
    +        self.second = 0
    +        self.n_epochs = 1
    +
    +    def update_change(self, gradient):
    +        delta = 1e-8  # avoid division ny zero
    +
    +        self.moment = self.rho * self.moment + (1 - self.rho) * gradient
    +        self.second = self.rho2 * self.second + (1 - self.rho2) * gradient * gradient
    +
    +        moment_corrected = self.moment / (1 - self.rho**self.n_epochs)
    +        second_corrected = self.second / (1 - self.rho2**self.n_epochs)
    +
    +        return self.eta * moment_corrected / (np.sqrt(second_corrected + delta))
    +
    +    def reset(self):
    +        self.n_epochs += 1
    +        self.moment = 0
    +        self.second = 0
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    Usage of schedulers

    + +

    To initalize a scheduler, simply create the object and pass in the necessary parameters such as the learning rate and the momentum as shown below. As the Scheduler class is an abstract class it should not called directly, and will raise an error upon usage.

    + + + +
    +
    +
    +
    +
    +
    momentum_scheduler = Momentum(eta=1e-3, momentum=0.9)
    +adam_scheduler = Adam(eta=1e-3, rho=0.9, rho2=0.999)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    Here is a small example for how a segment of code using schedulers could look. Switching out the schedulers is simple.

    + + + +
    +
    +
    +
    +
    +
    weights = np.ones((3,3))
    +print(f"Before scheduler:\n{weights=}")
    +
    +epochs = 10
    +for e in range(epochs):
    +    gradient = np.random.rand(3, 3)
    +    change = adam_scheduler.update_change(gradient)
    +    weights = weights - change
    +    adam_scheduler.reset()
    +
    +print(f"\nAfter scheduler:\n{weights=}")
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    Cost functions

    + +

    In this section we will quickly look at cost functions that can be +used when creating the neural network. Every cost function takes the +target vector as its parameter, and returns a function valued only at +X such that it may easily be differentiated. +

    + + + +
    +
    +
    +
    +
    +
    def CostOLS(target):
    +    """
    +    Return OLS function valued only at X, so
    +    that it may be easily differentiated
    +    """
    +
    +    def func(X):
    +        return (1.0 / target.shape[0]) * np.sum((target - X) ** 2)
    +
    +    return func
    +
    +
    +def CostLogReg(target):
    +    """
    +    Return Logistic Regression cost function
    +    valued only at X, so that it may be easily differentiated
    +    """
    +
    +    def func(X):
    +        return -(1.0 / target.shape[0]) * np.sum(
    +            (target * np.log(X + 10e-10)) + ((1 - target) * np.log(1 - X + 10e-10))
    +        )
    +
    +    return func
    +
    +
    +def CostCrossEntropy(target):
    +    """
    +    Return cross entropy cost function valued only at X, so
    +    that it may be easily differentiated
    +    """
    +    
    +    def func(X):
    +        return -(1.0 / target.size) * np.sum(target * np.log(X + 10e-10))
    +
    +    return func
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    Usage of cost functions

    + +

    Below we will provide a short example of how these cost function may +be used to obtain results if you wish to test them out on your own +using AutoGrad's automatic differentiation. +

    + + + +
    +
    +
    +
    +
    +
    from autograd import grad
    +
    +target = np.array([[1, 2, 3]]).T
    +a = np.array([[4, 5, 6]]).T
    +
    +cost_func = CostCrossEntropy
    +cost_func_derivative = grad(cost_func(target))
    +
    +valued_at_a = cost_func_derivative(a)
    +print(f"Derivative of cost function {cost_func.__name__} valued at a:\n{valued_at_a}")
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    Activation functions

    + +

    Finally, before we look at the layers that make up the neural network, +we will look at the activation functions which can be specified +between the hidden layers and as the output function. Each function +can be valued for any given vector or matrix X, and can be +differentiated via derivate(). +

    + + + +
    +
    +
    +
    +
    +
    import autograd.numpy as np
    +from autograd import elementwise_grad
    +
    +def identity(X):
    +    return X
    +
    +
    +def sigmoid(X):
    +    try:
    +        return 1.0 / (1 + np.exp(-X))
    +    except FloatingPointError:
    +        return np.where(X > np.zeros(X.shape), np.ones(X.shape), np.zeros(X.shape))
    +
    +
    +def softmax(X):
    +    X = X - np.max(X, axis=-1, keepdims=True)
    +    delta = 10e-10
    +    return np.exp(X) / (np.sum(np.exp(X), axis=-1, keepdims=True) + delta)
    +
    +
    +def RELU(X):
    +    return np.where(X > np.zeros(X.shape), X, np.zeros(X.shape))
    +
    +
    +def LRELU(X):
    +    delta = 10e-4
    +    return np.where(X > np.zeros(X.shape), X, delta * X)
    +
    +
    +def derivate(func):
    +    if func.__name__ == "RELU":
    +
    +        def func(X):
    +            return np.where(X > 0, 1, 0)
    +
    +        return func
    +
    +    elif func.__name__ == "LRELU":
    +
    +        def func(X):
    +            delta = 10e-4
    +            return np.where(X > 0, 1, delta)
    +
    +        return func
    +
    +    else:
    +        return elementwise_grad(func)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    Usage of activation functions

    + +

    Below we present a short demonstration of how to use an activation +function. The derivative of the activation function will be important +when calculating the output delta term during backpropagation. Note +that derivate() can also be used for cost functions for a more +generalized approach. +

    + + + +
    +
    +
    +
    +
    +
    z = np.array([[4, 5, 6]]).T
    +print(f"Input to activation function:\n{z}")
    +
    +act_func = sigmoid
    +a = act_func(z)
    +print(f"\nOutput from {act_func.__name__} activation function:\n{a}")
    +
    +act_func_derivative = derivate(act_func)
    +valued_at_z = act_func_derivative(a)
    +print(f"\nDerivative of {act_func.__name__} activation function valued at z:\n{valued_at_z}")
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    Convolution

    + +

    In order to construct a convolutional neural network (CNN), it is +crucial to comprehend the fundamental principles of convolution and +how it aids in extracting information from images. Convolution, at its +core, is merely a mathematical operation between two functions that +yields another function. It is represented by an integral between two +functions, which is typically expressed as: +

    + +$$ +(f \ast g)(t):=\int_{-\infty}^{\infty} f(\tau) g(t-\tau) d \tau. +$$ + +

    Here, f and g are the two functions on which we want to perform an +operation. The outcome of the convolution operation is represented by +\( (f \ast g) \), and it is derived by sliding the function g over f and +computing the integral of their product at each position. If both +functions are continuous, convolution takes the form shown +above. However, if we discretize both f and g, the convolution +operation will take the form of a sum between the elements of f and g: +

    +$$ +(f \ast g)[n]=\sum_{m=0}^{n-1} f[m] g[n-m]. +$$ + +

    The key idea we utilize to extract the information contained in an +image is to slide an \( m \times n \) matrix g over an \( m \times n \) +matrix f. In our case, f represents the image, while g +represents the kernel, oftentimes called a filter. However, since our +convolution will be a two-dimensional variant, we need to extend our +mathematical formula with an additional summation: +

    + +$$ +(f \ast g)[i, j]\sum_{m=0}^{M-1}\sum_{n=0}^{N-1} f[m,n] g[i-m, j-n]. +$$ + +

    It is imperative to note that the size of the kernel g is +significantly smaller than the size of the input image f, thereby +reducing the amount of computation necessary for feature +extraction. Furthermore, the kernel is usually a trainable parameter +in a convolutional neural network, allowing the network to learn +appropriate kernels for specific tasks. +

    + +

    To give you an example of how 2D convolution works in practice, +suppose we have an image f of dimension \( 6 \times 6 \) +

    + +$$ +f = \begin{bmatrix} +4 & 1 & 2 & 9 & 8 & 6 \\ +9 & 5 & 9 & 5 & 8 & 5 \\ +1 & 5 & 9 & 7 & 6 & 4 \\ +2 & 9 & 8 & 3 & 7 & 1 \\ +8 & 1 & 6 & 4 & 2 & 2 \\ +1 & 0 & 5 & 7 & 8 & 2 \\ +\end{bmatrix} +$$ + +

    and a \( 3 \times 3 \) kernel g called a low-pass filter. Note that the +kernel is usually rotated by 180 degrees during convolution, however +this has no effect on this kernel. +

    + +$$ +g = \frac{1}{9} +\begin{bmatrix} +1 & 1 & 1 \\ +1 & 1 & 1 \\ +1 & 1 & 1 \\ +\end{bmatrix} +$$ + +

    In order to filter the image, we have to extract a \( 3 \times 3 \) +element from the upper left corner of f, and perform element-wise +multiplication of the extracted image pixels with the elements of the +kernel g: +

    + +$$ +\begin{bmatrix} +4 & 1 & 2 \\ +9 & 5 & 9 \\ +1 & 5 & 9 \\ +\end{bmatrix} +\cdot +\begin{bmatrix} +\frac{1}{9} & \frac{1}{9} & \frac{1}{9} \\ +\frac{1}{9} & \frac{1}{9} & \frac{1}{9} \\ +\frac{1}{9} & \frac{1}{9} & \frac{1}{9} \\ +\end{bmatrix} += +\begin{bmatrix} +\frac{4}{9} & \frac{1}{9} & \frac{2}{9} \\ +\frac{9}{9} & \frac{5}{9} & \frac{9}{9} \\ +\frac{1}{9} & \frac{5}{9} & \frac{9}{9} \\ +\end {bmatrix} += \textbf{A} +$$ + +

    Then, following the multiplication, we summarize all the elements of the resulting matrix A:

    + +$$ +(f \ast g)[0, 0]= \sum_{i=0}^{2} \sum_{j=0}^{2} a_{i,j} = 5 +$$ + +

    Which corresponds to the first element of the filtered image \( (f \ast g) \).

    + +

    Here we use a stride of 1, a parameter denoted s which describes how +many indexes we move the kernel g to the right before repeating the +calculations above for the next \( 3 \times 3 \) element of the image +f. It is usually presumed that *s*=1, however, larger values for s +can be used to reduce the dimentionality of the filtered image such +that the convolution operation is more computationally efficient. In +the context of a convolutional neural network, this will become very +useful. +

    + +

    The full result of the convolution is:

    + +$$ +(f \ast g) = +\begin{bmatrix} +5 & 5.78 & 7 & 6.44 \\ +6.33 & 6.67 & 6.89 & 5.11 \\ +5.44 & 5.78 & 5.78 & 4 \\ +4.44 & 4.78 & 5.56 & 4 \\ +\end{bmatrix} +$$ + +

    The result is markedly smaller in shape than the original image. This occurs when using convolution without first padding the image with additional columns and rows, allowing us to keep the original image shape after sliding the kernel over the image. +How many rows and columns we wish to pad the image with depends strictly on the shape of the kernel, as we wish to pad the image with r additional rows and c additional columns. +

    + +$$ +r =\lfloor \frac{kernel\ height}{2} \rfloor \cdot 2 \\ +c =\lfloor \frac{kernel\ width}{2} \rfloor \cdot 2 +$$ + +

    Note the notation \( \lfloor \frac{kernel width}{2} \rfloor \) means that +we floor the result of the division, meaning we round down to a whole +number in case \( \frac{kernel width}{2} \) results in a floating point +number. +

    + +

    Using those simple equations, we find out by how much we have to +extend the dimensions of the original image. Before proceeding, +however, we might ask what we shall fill the additional rows and +columns with? One of the most common approaches to padding is +zero-padding, which as the name suggest, involves filling the rows and +columns with zeros. This is the approach that we will be using for +this demonstration. If we apply this padding to out original \( 6 \times 6 \) +image, the result will be an \( 8 \times 8 \) image as the kernel has a width and +height of 3. Note that the original image is encapsuled by the +zero-padded rows and columns: +

    + +$$ +\begin{bmatrix} +0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ +0 & 4 & 1 & 2 & 9 & 8 & 6 & 0 \\ +0 & 9 & 5 & 9 & 5 & 8 & 5 & 0 \\ +0 & 1 & 5 & 9 & 7 & 6 & 4 & 0 \\ +0 & 2 & 9 & 8 & 3 & 7 & 1 & 0 \\ +0 & 8 & 1 & 6 & 4 & 2 & 2 & 0 \\ +0 & 1 & 0 & 5 & 7 & 8 & 2 & 0 \\ +0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ +\] +\end{bmatrix} +$$ + +

    Below we have provided code that demonstrates padding and convolution. As you will see when we run the code, the size of the image will remain unchanged when using padding. 

    + + + +
    +
    +
    +
    +
    +
    import numpy as np
    +
    +def padding(image, kernel):
    +    # calculate r and c
    +    r = (kernel.shape[0] // 2) * 2
    +    c = (kernel.shape[1] // 2) * 2
    +    
    +    # padded image dimensions
    +    padded_height = image.shape[0] + r
    +    padded_width = image.shape[1] + c
    +    
    +    # for more readable code
    +    k_half_height = kernel.shape[0] // 2
    +    k_half_width = kernel.shape[1] // 2
    +
    +    # zero matrix with padded dimensions
    +    padded_img = np.zeros((padded_height, padded_width))
    +
    +    # place image into zero matrix
    +    padded_img[k_half_height : padded_height - k_half_height,
    +               k_half_width : padded_width - k_half_width] = image[:, :]
    +
    +    return padded_img
    +
    +def convolve(original_image, padded_image, kernel, stride=1):
    +    # rotate kernel by 180 degrees
    +    kernel = np.rot90(np.rot90(kernel))
    +
    +    # note that kernel height // 2 is written as 'm'
    +    # and kernel width // 2 as 'n' in the mathematical notation
    +    m = kernel.shape[0] // 2
    +    n = kernel.shape[1] // 2
    +    
    +    r = (kernel.shape[0] // 2) * 2
    +    c = (kernel.shape[1] // 2) * 2
    +    
    +    # initialize output array
    +    convolved_image = np.zeros(original_image.shape)
    +    image_height = original_image.shape[0]
    +    image_width = original_image.shape[1]
    +
    +    # the convolution
    +    for i in range(m, image_height + m, stride):
    +        for j in range(n, image_width + n, stride):
    +            convolved_image[i-m, j-n] = np.sum(
    +                padded_image[i : i + m, j : j + n]
    +                * kernel
    +            )
    +            
    +    return convolved_image
    +
    +def convolve(image, kernel, stride=1):
    +    for i in range(2):
    +        kernel = np.rot90(kernel)
    +
    +    k_half_height = kernel.shape[0] // 2
    +    k_half_width = kernel.shape[0] // 2
    +
    +    conv_image = np.zeros(image.shape)
    +    pad_image = padding(image, kernel)
    +
    +    for i in range(k_half_height, conv_image.shape[0] + k_half_height, stride):
    +        for j in range(k_half_width, conv_image.shape[1] + k_half_width, stride):
    +            conv_image[i - k_half_height, j - k_half_width] = np.sum(
    +                pad_image[
    +                    i - k_half_height : i + k_half_height + 1, j - k_half_width : j + k_half_width + 1
    +                ]
    +                * kernel
    +            )
    +
    +    return conv_image
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    Fun fact: When filtering images, you will see that convolution involves rotating the kernel by 180 degrees. +However, this is not the case when applying convolution in a CNN, where the same operation not rotated by 180 degrees is called +cross-correlation. +

    + + + +
    +
    +
    +
    +
    +
    original_image = np.array([[4, 1, 2, 9, 8, 6],
    +                 [9, 5, 9, 5, 8, 5],
    +                 [1, 5, 9, 7, 6, 4],
    +                 [2, 9, 8, 3, 7, 1],
    +                 [8, 1, 6, 4, 2, 2],
    +                 [1, 0, 5, 7, 8, 2]])
    +
    +kernel = (1/9)*np.ones((3,3))
    +
    +print(f"{original_image.shape=}")
    +
    +# note that convolve() performs padding
    +convolved_image = convolve(original_image, kernel, stride=1)
    +
    +print(f"{convolved_image.shape=}")
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    As you can see, the resulting image is of the same size as the +original image. To round of our demonstration of convolution, we will +present the results of convolution using commonly used kernels. In a +CNN, the values of the kernels are randomly initialized, and then +learned during training. These kernels will extract information +regarding the picture, such as for example the edge detection filter +demonstrated below extracts the edges present in the picture. Of +course, there is no guarantee that the CNN will learn an edge +detection filter, but this should provide some intuiton as to how the +CNN is able to use kernels to make better predictions than a regular +feed forward neural network. +

    + + + +
    +
    +
    +
    +
    +
    # Now an example using a real image and first a gaussian low-pass filter and then a sobel filter
    +import numpy as np
    +import imageio.v3 as imageio
    +import matplotlib.pyplot as plt
    +import time
    +
    +def generate_gauss_mask(sigma, K=1):
    +    side = np.ceil(1 + 8 * sigma)
    +    y, x = np.mgrid[-side // 2 + 1 : (side // 2) + 1, -side // 2 + 1 : (side // 2) + 1]
    +    ker_coef = K / (2 * np.pi * sigma**2)
    +    g = np.exp(-((x**2 + y**2) / (2.0 * sigma**2)))
    +
    +    return g, ker_coef
    +
    +
    +img_path = "../data/IMG-2167.JPG"
    +image_of_cute_dog = imageio.imread(img_path, mode='L')
    +
    +plt.imshow(image_of_cute_dog, cmap="gray", vmin=0, vmax=255, aspect="auto")
    +plt.title("Original image")
    +plt.show()
    +
    +gauss, kernel = generate_gauss_mask(sigma=6)
    +gauss_kernel = gauss*kernel
    +
    +filtered_image = convolve(image_of_cute_dog, gauss_kernel)
    +plt.imshow(filtered_image, cmap="gray", vmin=0, vmax=255, aspect="auto")
    +plt.title("Result of convolution with gauss kernel (blurring filter)")
    +plt.show()
    +
    +sobel_kernel = np.array([[1, 2, 1],
    +                    [0, 0, 0], 
    +                    [-1, -2, -1]])
    +
    +filtered_image = convolve(image_of_cute_dog, sobel_kernel)
    +
    +plt.imshow(filtered_image, cmap="gray", vmin=0, vmax=255, aspect="auto")
    +plt.title("Result of convolution with sobel kernel (edge detection filter)")
    +plt.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    Layers

    + +

    The code below initialises global variables for readability and +describes the abstract class Layers. This is not important in order to +understand the CNN, but is benefitial for organizing the code neatly. +

    + + + +
    +
    +
    +
    +
    +
    import math
    +import autograd.numpy as np
    +from copy import deepcopy, copy
    +from autograd import grad
    +from typing import Callable
    +
    +# global variables for index readability
    +input_index = 0
    +node_index = 1
    +bias_index = 1
    +input_channel_index = 1
    +feature_maps_index = 1
    +height_index = 2
    +width_index = 3
    +kernel_feature_maps_index = 1
    +kernel_input_channels_index = 0
    +
    +
    +class Layer:
    +    def __init__(self, seed):
    +        self.seed = seed
    +
    +    def _feedforward(self):
    +        raise NotImplementedError
    +
    +    def _backpropagate(self):
    +        raise NotImplementedError
    +
    +    def _reset_weights(self, previous_nodes):
    +        raise NotImplementedError
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    Convolution2DLayer: convolution in a hidden layer

    + +

    After establishing the foundational understanding of applying +convolution to spatial data, let us delve into the intricate workings +of a convolutional layer in a Convolutional Neural Network (CNN). The +primary function of convolution, as previously discussed, is to +extract pertinent information from images while simultaneously +decreasing the scale of our data. To initiate the image processing, we +shall begin by partitioning the images into color channels (unless the +image is grayscale), comprising three primary colors: red, green, and +blue. We will subsequently utilize trainable kernels to construct a +higher-dimensional encoding of each channel called feature +maps. Successive layers will receive these feature maps as inputs, +generating further encodings, albeit with reduced dimensions. The term +trainable kernels denotes the initialization of pre-defined +kernel-shaped weights, which we will then train via backpropagation, +similar to how weights are trained in a Feedforward Neural Network. +

    + +

    To ensure seamless integration between our implementation of the +convolutional layer and popular machine learning frameworks like +Tensorflow (Keras) and PyTorch, we have adopted a design pattern that +mirrors the construction of models using these APIs. This involves +implementing our convolutional layer as a Python class or object, +which allows for a more modular and flexible approach to building +neural networks. By structuring our code in this way, users can easily +incorporate our implementation into their existing machine learning +pipelines without having to make significant changes to their +codebase. Additionally, this design pattern promotes code reusability +and makes it easier to maintain and update our convolutional layer +implementation over time. +

    + +

    Note that the Convolution2DLayer takes in an activation function as a parameter, as it also performs non-linearity.

    + + + +
    +
    +
    +
    +
    +
    class Convolution2DLayer(Layer):
    +    def __init__(
    +        self,
    +        input_channels,
    +        feature_maps,
    +        kernel_height,
    +        kernel_width,
    +        v_stride,
    +        h_stride,
    +        pad,
    +        act_func: Callable,
    +        seed=None,
    +        reset_weights_independently=True,
    +    ):
    +        super().__init__(seed)
    +        self.input_channels = input_channels
    +        self.feature_maps = feature_maps
    +        self.kernel_height = kernel_height
    +        self.kernel_width = kernel_width
    +        self.v_stride = v_stride
    +        self.h_stride = h_stride
    +        self.pad = pad
    +        self.act_func = act_func
    +
    +        # such that the layer can be used on its own
    +        # outside of the CNN module
    +        if reset_weights_independently == True:
    +            self._reset_weights_independently()
    +
    +    def _feedforward(self, X_batch):
    +        # note that the shape of X_batch = [inputs, input_maps, img_height, img_width]
    +
    +        # pad the input batch
    +        X_batch_padded = self._padding(X_batch)
    +
    +        # calculate height_index and width_index after stride
    +        strided_height = int(np.ceil(X_batch.shape[height_index] / self.v_stride))
    +        strided_width = int(np.ceil(X_batch.shape[width_index] / self.h_stride))
    +
    +        # create output array
    +        output = np.ndarray(
    +            (
    +                X_batch.shape[input_index],
    +                self.feature_maps,
    +                strided_height,
    +                strided_width,
    +            )
    +        )
    +
    +        # save input and output for backpropagation
    +        self.X_batch_feedforward = X_batch
    +        self.output_shape = output.shape
    +
    +        # checking for errors, no need to look here :)
    +        self._check_for_errors()
    +
    +        # convolve input with kernel
    +        for img in range(X_batch.shape[input_index]):
    +            for chin in range(self.input_channels):
    +                for fmap in range(self.feature_maps):
    +                    out_h = 0
    +                    for h in range(0, X_batch.shape[height_index], self.v_stride):
    +                        out_w = 0
    +                        for w in range(0, X_batch.shape[width_index], self.h_stride):
    +                            output[img, fmap, out_h, out_w] = np.sum(
    +                                X_batch_padded[
    +                                    img,
    +                                    chin,
    +                                    h : h + self.kernel_height,
    +                                    w : w + self.kernel_width,
    +                                ]
    +                                * self.kernel[chin, fmap, :, :]
    +                            )
    +                            out_w += 1
    +                        out_h += 1
    +
    +        # Pay attention to the fact that we're not rotating the kernel by 180 degrees when filtering the image in
    +        # the convolutional layer, as convolution in terms of Machine Learning is a procedure known as cross-correlation
    +        # in image processing and signal processing
    +
    +        # return a
    +        return self.act_func(output / (self.kernel_height))
    +
    +    def _backpropagate(self, delta_term_next):
    +        # intiate matrices
    +        delta_term = np.zeros((self.X_batch_feedforward.shape))
    +        gradient_kernel = np.zeros((self.kernel.shape))
    +
    +        # pad input for convolution
    +        X_batch_padded = self._padding(self.X_batch_feedforward)
    +
    +        # Since an activation function is used at the output of the convolution layer, its derivative
    +        # has to be accounted for in the backpropagation -> as if ReLU was a layer on its own.
    +        act_derivative = derivate(self.act_func)
    +        delta_term_next = act_derivative(delta_term_next)
    +
    +        # fill in 0's for values removed by vertical stride in feedforward
    +        if self.v_stride > 1:
    +            v_ind = 1
    +            for i in range(delta_term_next.shape[height_index]):
    +                for j in range(self.v_stride - 1):
    +                    delta_term_next = np.insert(
    +                        delta_term_next, v_ind, 0, axis=height_index
    +                    )
    +                v_ind += self.v_stride
    +
    +        # fill in 0's for values removed by horizontal stride in feedforward
    +        if self.h_stride > 1:
    +            h_ind = 1
    +            for i in range(delta_term_next.shape[width_index]):
    +                for k in range(self.h_stride - 1):
    +                    delta_term_next = np.insert(
    +                        delta_term_next, h_ind, 0, axis=width_index
    +                    )
    +                h_ind += self.h_stride
    +
    +        # crops out 0-rows and 0-columns
    +        delta_term_next = delta_term_next[
    +            :,
    +            :,
    +            : self.X_batch_feedforward.shape[height_index],
    +            : self.X_batch_feedforward.shape[width_index],
    +        ]
    +
    +        # the gradient received from the next layer also needs to be padded
    +        delta_term_next = self._padding(delta_term_next)
    +
    +        # calculate delta term by convolving next delta term with kernel
    +        for img in range(self.X_batch_feedforward.shape[input_index]):
    +            for chin in range(self.input_channels):
    +                for fmap in range(self.feature_maps):
    +                    for h in range(self.X_batch_feedforward.shape[height_index]):
    +                        for w in range(self.X_batch_feedforward.shape[width_index]):
    +                            delta_term[img, chin, h, w] = np.sum(
    +                                delta_term_next[
    +                                    img,
    +                                    fmap,
    +                                    h : h + self.kernel_height,
    +                                    w : w + self.kernel_width,
    +                                ]
    +                                * np.rot90(np.rot90(self.kernel[chin, fmap, :, :]))
    +                            )
    +
    +        # calculate gradient for kernel for weight update
    +        # also via convolution
    +        for chin in range(self.input_channels):
    +            for fmap in range(self.feature_maps):
    +                for k_x in range(self.kernel_height):
    +                    for k_y in range(self.kernel_width):
    +                        gradient_kernel[chin, fmap, k_x, k_y] = np.sum(
    +                            X_batch_padded[
    +                                img,
    +                                chin,
    +                                h : h + self.kernel_height,
    +                                w : w + self.kernel_width,
    +                            ]
    +                            * delta_term_next[
    +                                img,
    +                                fmap,
    +                                h : h + self.kernel_height,
    +                                w : w + self.kernel_width,
    +                            ]
    +                        )
    +        # all kernels are updated with weight gradient of kernel
    +        self.kernel -= gradient_kernel
    +
    +        # return delta term
    +        return delta_term
    +
    +    def _padding(self, X_batch, batch_type="image"):
    +
    +        # same padding for images
    +        if self.pad == "same" and batch_type == "image":
    +            padded_height = X_batch.shape[height_index] + (self.kernel_height // 2) * 2
    +            padded_width = X_batch.shape[width_index] + (self.kernel_width // 2) * 2
    +            half_kernel_height = self.kernel_height // 2
    +            half_kernel_width = self.kernel_width // 2
    +
    +            # initialize padded array
    +            X_batch_padded = np.ndarray(
    +                (
    +                    X_batch.shape[input_index],
    +                    X_batch.shape[feature_maps_index],
    +                    padded_height,
    +                    padded_width,
    +                )
    +            )
    +
    +            # zero pad all images in X_batch
    +            for img in range(X_batch.shape[input_index]):
    +                padded_img = np.zeros(
    +                    (X_batch.shape[feature_maps_index], padded_height, padded_width)
    +                )
    +                padded_img[
    +                    :,
    +                    half_kernel_height : padded_height - half_kernel_height,
    +                    half_kernel_width : padded_width - half_kernel_width,
    +                ] = X_batch[img, :, :, :]
    +                X_batch_padded[img, :, :, :] = padded_img[:, :, :]
    +
    +            return X_batch_padded
    +
    +        # same padding for gradients
    +        elif self.pad == "same" and batch_type == "grad":
    +            padded_height = X_batch.shape[height_index] + (self.kernel_height // 2) * 2
    +            padded_width = X_batch.shape[width_index] + (self.kernel_width // 2) * 2
    +            half_kernel_height = self.kernel_height // 2
    +            half_kernel_width = self.kernel_width // 2
    +
    +            # initialize padded array
    +            delta_term_padded = np.zeros(
    +                (
    +                    X_batch.shape[input_index],
    +                    X_batch.shape[feature_maps_index],
    +                    padded_height,
    +                    padded_width,
    +                )
    +            )
    +
    +            # zero pad delta term
    +            delta_term_padded[
    +                :, :, : X_batch.shape[height_index], : X_batch.shape[width_index]
    +            ] = X_batch[:, :, :, :]
    +
    +            return delta_term_padded
    +
    +        else:
    +            return X_batch
    +
    +    def _reset_weights_independently(self):
    +        # sets seed to remove randomness inbetween runs
    +        if self.seed is not None:
    +            np.random.seed(self.seed)
    +
    +        # initializes kernel matrix
    +        self.kernel = np.ndarray(
    +            (
    +                self.input_channels,
    +                self.feature_maps,
    +                self.kernel_height,
    +                self.kernel_width,
    +            )
    +        )
    +
    +        # randomly initializes weights
    +        for chin in range(self.kernel.shape[kernel_input_channels_index]):
    +            for fmap in range(self.kernel.shape[kernel_feature_maps_index]):
    +                self.kernel[chin, fmap, :, :] = np.random.rand(
    +                    self.kernel_height, self.kernel_width
    +                )
    +
    +    def _reset_weights(self, previous_nodes):
    +        # sets weights
    +        self._reset_weights_independently()
    +
    +        # returns shape of output used for subsequent layer's weight initiation
    +        strided_height = int(
    +            np.ceil(previous_nodes.shape[height_index] / self.v_stride)
    +        )
    +        strided_width = int(np.ceil(previous_nodes.shape[width_index] / self.h_stride))
    +        next_nodes = np.ones(
    +            (
    +                previous_nodes.shape[input_index],
    +                self.feature_maps,
    +                strided_height,
    +                strided_width,
    +            )
    +        )
    +        return next_nodes / self.kernel_height
    +
    +    def _check_for_errors(self):
    +        if self.X_batch_feedforward.shape[input_channel_index] != self.input_channels:
    +            raise AssertionError(
    +                f"ERROR: Number of input channels in data ({self.X_batch_feedforward.shape[input_channel_index]}) is not equal to input channels in Convolution2DLayerOPT ({self.input_channels})! Please change the number of input channels of the Convolution2DLayer such that they are equal"
    +            )
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    Backpropagation in the convolutional layer

    + +

    As you may have noticed, we have not yet explained how the +backpropagation algorithm works in a convolutional layer. However, +having covered all other major details about convolutional layers, we +are now prepared to do so. It should come as no surprise that the +calculation of delta terms at each convolutional layer takes the form +of convolution. After the gradient has been propagated backwards +through the flattening layer, where it was reshaped into an +appropriate form, calculating the update value for the kernel is +simply a matter of convolving the output gradient with the input of +the layer for which we are updating the weights. For more detail, this +article serves as an excellent resource, see +https://pavisj.medium.com/convolutions-and-backpropagations-46026a8f5d2c +

    +

    Demonstration

    + +

    We can use the convolutional layer above to perform a simple convolution on an image of the now familiar cute dog.

    + + + +
    +
    +
    +
    +
    +
    import numpy as np
    +import imageio.v3 as imageio
    +import matplotlib.pyplot as plt
    +
    +def plot_convolution_result(X, layer):
    +    plt.imshow(X[0, 0, :, :], vmin=0, vmax=255, cmap="gray")
    +    plt.title("Original image")
    +    plt.colorbar()
    +    plt.show()
    +    conv_result = layer._feedforward(X)
    +    plt.title("Result of convolutional layer")
    +    plt.imshow(conv_result[0, 0, :, :], vmin=0, vmax=255, cmap="gray")
    +    plt.colorbar()
    +    plt.show()
    +
    +# create layer
    +layer = Convolution2DLayer(
    +    input_channels=3,
    +    feature_maps=1,
    +    kernel_height=4,
    +    kernel_width=4,
    +    v_stride=2,
    +    h_stride=2,
    +    pad="same",
    +    act_func=identity,
    +    seed=2023,
    +    )
    +
    +# read in image path, make data correct format
    +img_path = img_path = "../data/IMG-2167.JPG"
    +image_of_cute_dog = imageio.imread(img_path)
    +image_shape = image_of_cute_dog.shape
    +image_of_cute_dog = image_of_cute_dog.reshape(1, image_shape[0], image_shape[1], image_shape[2])
    +image_of_cute_dog = image_of_cute_dog.transpose(0, 3, 1, 2)
    +
    +# plot the result of the convolution
    +plot_convolution_result(image_of_cute_dog, layer)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    We cobserve that the result has half the pixels on each axis due to +the fact that we've used a horizontal and vertical stride of 2. The +result of this convolution is not very insightfull, as the kernel has +completely random values for the first feedforward pass. However, as +we perform multiple forward and backward passes, the results of the +convolution should provide identifying features of the image it uses +for classification. +

    + +

    Note that image data usually comes in many different shapes and sizes, +but for our CNN we require the input data be formatted as \[Number of +inputs, input channels, input height, input width\]. Occasionally, the +data you come accross use will be formatted like this, but on many +occasions reshaping and transposing the dimensions is sadly necessary. +

    +

    Pooling Layer

    + +

    The pooling layer is another widely used type of layer in +convolutional neural networks that enables data downsampling to a more +manageable size. Despite recent technological advancements that allow +for convolution without excessive size reduction of the data, the +pooling layer still remains a fundamental component of convolutional +neural networks. It can be used before, after, or in between +convolutional layers, although finding the optimal placement of layers +and network depth requires experimentation to achieve the best +performance for a given problem. The code we provide allows you to +perform two types of pooling known as max pooling and average pooling. +

    + + + +
    +
    +
    +
    +
    +
    class Pooling2DLayer(Layer):
    +    def __init__(
    +        self,
    +        kernel_height,
    +        kernel_width,
    +        v_stride,
    +        h_stride,
    +        pooling="max",
    +        seed=None,
    +    ):
    +        super().__init__(seed)
    +        self.kernel_height = kernel_height
    +        self.kernel_width = kernel_width
    +        self.v_stride = v_stride
    +        self.h_stride = h_stride
    +        self.pooling = pooling
    +
    +    def _feedforward(self, X_batch):
    +        # Saving the input for use in the backwardpass
    +        self.X_batch_feedforward = X_batch
    +
    +        # check if user is silly
    +        self._check_for_errors()
    +
    +        # Computing the size of the feature maps based on kernel size and the stride parameter
    +        strided_height = (
    +            X_batch.shape[height_index] - self.kernel_height
    +        ) // self.v_stride + 1
    +        if X_batch.shape[height_index] == X_batch.shape[width_index]:
    +            strided_width = strided_height
    +        else:
    +            strided_width = (
    +                X_batch.shape[width_index] - self.kernel_width
    +            ) // self.h_stride + 1
    +
    +        # initialize output array
    +        output = np.ndarray(
    +            (
    +                X_batch.shape[input_index],
    +                X_batch.shape[feature_maps_index],
    +                strided_height,
    +                strided_width,
    +            )
    +        )
    +
    +        # select pooling action, either max or average pooling
    +        if self.pooling == "max":
    +            self.pooling_action = np.max
    +        elif self.pooling == "average":
    +            self.pooling_action = np.mean
    +
    +        # pool based on kernel size and stride
    +        for img in range(output.shape[input_index]):
    +            for fmap in range(output.shape[feature_maps_index]):
    +                for h in range(strided_height):
    +                    for w in range(strided_width):
    +                        output[img, fmap, h, w] = self.pooling_action(
    +                            X_batch[
    +                                img,
    +                                fmap,
    +                                (h * self.v_stride) : (h * self.v_stride)
    +                                + self.kernel_height,
    +                                (w * self.h_stride) : (w * self.h_stride)
    +                                + self.kernel_width,
    +                            ]
    +                        )
    +
    +        # output for feedforward in next layer
    +        return output
    +
    +    def _backpropagate(self, delta_term_next):
    +        # initiate delta term array
    +        delta_term = np.zeros((self.X_batch_feedforward.shape))
    +
    +        for img in range(delta_term_next.shape[input_index]):
    +            for fmap in range(delta_term_next.shape[feature_maps_index]):
    +                for h in range(0, delta_term_next.shape[height_index], self.v_stride):
    +                    for w in range(
    +                        0, delta_term_next.shape[width_index], self.h_stride
    +                    ):
    +                        # max pooling
    +                        if self.pooling == "max":
    +                            # get window
    +                            window = self.X_batch_feedforward[
    +                                img,
    +                                fmap,
    +                                h : h + self.kernel_height,
    +                                w : w + self.kernel_width,
    +                            ]
    +
    +                            # find max values indices in window
    +                            max_h, max_w = np.unravel_index(
    +                                window.argmax(), window.shape
    +                            )
    +
    +                            # set values in new, upsampled delta term
    +                            delta_term[
    +                                img,
    +                                fmap,
    +                                (h + max_h),
    +                                (w + max_w),
    +                            ] += delta_term_next[img, fmap, h, w]
    +
    +                        # average pooling
    +                        if self.pooling == "average":
    +                            delta_term[
    +                                img,
    +                                fmap,
    +                                h : h + self.kernel_height,
    +                                w : w + self.kernel_width,
    +                            ] = (
    +                                delta_term_next[img, fmap, h, w]
    +                                / self.kernel_height
    +                                / self.kernel_width
    +                            )
    +        # returns input to backpropagation in previous layer
    +        return delta_term
    +
    +    def _reset_weights(self, previous_nodes):
    +        # calculate strided height, strided width
    +        strided_height = (
    +            previous_nodes.shape[height_index] - self.kernel_height
    +        ) // self.v_stride + 1
    +        if previous_nodes.shape[height_index] == previous_nodes.shape[width_index]:
    +            strided_width = strided_height
    +        else:
    +            strided_width = (
    +                previous_nodes.shape[width_index] - self.kernel_width
    +            ) // self.h_stride + 1
    +
    +        # initiate output array
    +        output = np.ones(
    +            (
    +                previous_nodes.shape[input_index],
    +                previous_nodes.shape[feature_maps_index],
    +                strided_height,
    +                strided_width,
    +            )
    +        )
    +
    +        # returns output with shape used for reset weights in next layer
    +        return output
    +
    +    def _check_for_errors(self):
    +        # check if input is smaller than kernel size -> error
    +        assert (
    +            self.X_batch_feedforward.shape[width_index] >= self.kernel_width
    +        ), f"ERROR: Pooling kernel width_index ({self.kernel_width}) larger than data width_index ({self.X_batch_feedforward.input.shape[2]}), please lower the kernel width_index of the Pooling2DLayer"
    +        assert (
    +            self.X_batch_feedforward.shape[height_index] >= self.kernel_height
    +        ), f"ERROR: Pooling kernel height_index ({self.kernel_height}) larger than data height_index ({self.X_batch_feedforward.input.shape[3]}), please lower the kernel height_index of the Pooling2DLayer"
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    Flattening Layer

    + +

    Before we can begin building our first CNN model, we need to introduce +the flattening layer. As its name suggests, the flattening layer +transforms the data into a one-dimensional vector that can be fed into +the feedforward layers of our network. This layer plays a crucial role +in preparing the data for further processing in the +network. Additionally, the flattening layer is responsible for +reshaping the gradient to the proper shape during +backpropagation. This ensures that the kernels are correctly updated, +allowing for effective learning in the network. +

    + + + +
    +
    +
    +
    +
    +
    class FlattenLayer(Layer):
    +    def __init__(self, act_func=LRELU, seed=None):
    +        super().__init__(seed)
    +        self.act_func = act_func
    +
    +    def _feedforward(self, X_batch):
    +        # save input for backpropagation
    +        self.X_batch_feedforward_shape = X_batch.shape
    +        # Remember, the data has the following shape: (I, FM, H, W, ) in the convolutional layers
    +        # whilst the data has the shape (I, FM * H * W) in the fully connected layers
    +        # I = Inputs, FM = Feature Maps, H = Height and W = Width.
    +        X_batch = X_batch.reshape(
    +            X_batch.shape[input_index],
    +            X_batch.shape[feature_maps_index]
    +            * X_batch.shape[height_index]
    +            * X_batch.shape[width_index],
    +        )
    +
    +        # add bias to a
    +        self.z_matrix = X_batch
    +        bias = np.ones((X_batch.shape[input_index], 1)) * 0.01
    +        self.a_matrix = np.hstack([bias, X_batch])
    +
    +        # return a, the input to feedforward in next layer
    +        return self.a_matrix
    +
    +    def _backpropagate(self, weights_next, delta_term_next):
    +        activation_derivative = derivate(self.act_func)
    +
    +        # calculate delta term
    +        delta_term = (
    +            weights_next[bias_index:, :] @ delta_term_next.T
    +        ).T * activation_derivative(self.z_matrix)
    +
    +        # FlattenLayer does not update weights
    +        # reshapes delta layer to convolutional layer data format [Input, Feature_Maps, Height, Width]
    +        return delta_term.reshape(self.X_batch_feedforward_shape)
    +
    +    def _reset_weights(self, previous_nodes):
    +        # note that the previous nodes to the FlattenLayer are from the convolutional layers
    +        previous_nodes = previous_nodes.reshape(
    +            previous_nodes.shape[input_index],
    +            previous_nodes.shape[feature_maps_index]
    +            * previous_nodes.shape[height_index]
    +            * previous_nodes.shape[width_index],
    +        )
    +
    +        # return shape used in reset_weights in next layer
    +        return previous_nodes.shape[node_index]
    +
    +    def get_prev_a(self):
    +        return self.a_matrix
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    Fully Connected Layers

    + +

    Finally, the result from the flatten layer will pass to a series of +fully connected layers, which function as a normal feed forward neural +network. The fully connected layers are split into two classes; +FullyConnectedLayer which acts as a hidden layer, and OutputLayer, +which acts as the single output layer at the end of the CNN. If one +wishes to use this codebase to construct a normal feed forward neural +network, it must start with a FlattenLayer due to techincal details +regarding weight intitialization. However many FullyConnectedLayers +can be added to the CNN, and in each layer the amount of nodes, which +activation function and scheduler to use can be specified. In +practice, the scheduler will be specified in the CNN object +initialization, and inherited if no other scheduler is specified. +

    + + + +
    +
    +
    +
    +
    +
    class FullyConnectedLayer(Layer):
    +    # FullyConnectedLayer per default uses LRELU and Adam scheduler
    +    # with an eta of 0.0001, rho of 0.9 and rho2 of 0.999
    +    def __init__(
    +        self,
    +        nodes: int,
    +        act_func: Callable = LRELU,
    +        scheduler: Scheduler = Adam(eta=1e-4, rho=0.9, rho2=0.999),
    +        seed: int = None,
    +    ):
    +        super().__init__(seed)
    +        self.nodes = nodes
    +        self.act_func = act_func
    +        self.scheduler_weight = copy(scheduler)
    +        self.scheduler_bias = copy(scheduler)
    +
    +        # initiate matrices for later
    +        self.weights = None
    +        self.a_matrix = None
    +        self.z_matrix = None
    +
    +    def _feedforward(self, X_batch):
    +        # calculate z
    +        self.z_matrix = X_batch @ self.weights
    +
    +        # calculate a, add bias
    +        bias = np.ones((X_batch.shape[input_index], 1)) * 0.01
    +        self.a_matrix = self.act_func(self.z_matrix)
    +        self.a_matrix = np.hstack([bias, self.a_matrix])
    +
    +        # return a, the input for feedforward in next layer
    +        return self.a_matrix
    +
    +    def _backpropagate(self, weights_next, delta_term_next, a_previous, lam):
    +        # take the derivative of the activation function
    +        activation_derivative = derivate(self.act_func)
    +
    +        # calculate the delta term
    +        delta_term = (
    +            weights_next[bias_index:, :] @ delta_term_next.T
    +        ).T * activation_derivative(self.z_matrix)
    +
    +        # intitiate matrix to store gradient
    +        # note that we exclude the bias term, which we will calculate later
    +        gradient_weights = np.zeros(
    +            (
    +                a_previous.shape[input_index],
    +                a_previous.shape[node_index] - bias_index,
    +                delta_term.shape[node_index],
    +            )
    +        )
    +
    +        # calculate gradient = delta term * previous a
    +        for i in range(len(delta_term)):
    +            gradient_weights[i, :, :] = np.outer(
    +                a_previous[i, bias_index:], delta_term[i, :]
    +            )
    +
    +        # sum the gradient, divide by input_index
    +        gradient_weights = np.mean(gradient_weights, axis=input_index)
    +        # for the bias gradient we do not multiply by previous a
    +        gradient_bias = np.mean(delta_term, axis=input_index).reshape(
    +            1, delta_term.shape[node_index]
    +        )
    +
    +        # regularization term
    +        gradient_weights += self.weights[bias_index:, :] * lam
    +
    +        # send gradients into scheduler
    +        # returns update matrix which will be used to update the weights and bias
    +        update_matrix = np.vstack(
    +            [
    +                self.scheduler_bias.update_change(gradient_bias),
    +                self.scheduler_weight.update_change(gradient_weights),
    +            ]
    +        )
    +
    +        # update weights
    +        self.weights -= update_matrix
    +
    +        # return weights and delta term, input for backpropagation in previous layer
    +        return self.weights, delta_term
    +
    +    def _reset_weights(self, previous_nodes):
    +        # sets seed to remove randomness inbetween runs
    +        if self.seed is not None:
    +            np.random.seed(self.seed)
    +
    +        # add bias, initiate random weights
    +        bias = 1
    +        self.weights = np.random.randn(previous_nodes + bias, self.nodes)
    +
    +        # returns number of nodes, used for reset_weights in next layer
    +        return self.nodes
    +
    +    def _reset_scheduler(self):
    +        # resets scheduler per epoch
    +        self.scheduler_weight.reset()
    +        self.scheduler_bias.reset()
    +
    +    def get_prev_a(self):
    +        # returns a matrix, used in backpropagation
    +        return self.a_matrix
    +
    +
    +class OutputLayer(FullyConnectedLayer):
    +    def __init__(
    +        self,
    +        nodes: int,
    +        output_func: Callable = LRELU,
    +        cost_func: Callable = CostCrossEntropy,
    +        scheduler: Scheduler = Adam(eta=1e-4, rho=0.9, rho2=0.999),
    +        seed: int = None,
    +    ):
    +        super().__init__(nodes, output_func, copy(scheduler), seed)
    +        self.cost_func = cost_func
    +
    +        # initiate matrices for later
    +        self.weights = None
    +        self.a_matrix = None
    +        self.z_matrix = None
    +
    +        # decides if the output layer performs binary or multi-class classification
    +        self._set_pred_format()
    +
    +    def _feedforward(self, X_batch: np.ndarray):
    +        # calculate a, z
    +        # note that bias is not added as this would create an extra output class
    +        self.z_matrix = X_batch @ self.weights
    +        self.a_matrix = self.act_func(self.z_matrix)
    +
    +        # returns prediction
    +        return self.a_matrix
    +
    +    def _backpropagate(self, target, a_previous, lam):
    +        # note that in the OutputLayer the activation function is the output function
    +        activation_derivative = derivate(self.act_func)
    +
    +        # calculate output delta terms
    +        # for multi-class or binary classification
    +        if self.pred_format == "Multi-class":
    +            delta_term = self.a_matrix - target
    +        else:
    +            cost_func_derivative = grad(self.cost_func(target))
    +            delta_term = activation_derivative(self.z_matrix) * cost_func_derivative(
    +                self.a_matrix
    +            )
    +
    +        # intiate matrix that stores gradient
    +        gradient_weights = np.zeros(
    +            (
    +                a_previous.shape[input_index],
    +                a_previous.shape[node_index] - bias_index,
    +                delta_term.shape[node_index],
    +            )
    +        )
    +
    +        # calculate gradient = delta term * previous a
    +        for i in range(len(delta_term)):
    +            gradient_weights[i, :, :] = np.outer(
    +                a_previous[i, bias_index:], delta_term[i, :]
    +            )
    +
    +        # sum the gradient, divide by input_index
    +        gradient_weights = np.mean(gradient_weights, axis=input_index)
    +        # for the bias gradient we do not multiply by previous a
    +        gradient_bias = np.mean(delta_term, axis=input_index).reshape(
    +            1, delta_term.shape[node_index]
    +        )
    +
    +        # regularization term
    +        gradient_weights += self.weights[bias_index:, :] * lam
    +
    +        # send gradients into scheduler
    +        # returns update matrix which will be used to update the weights and bias
    +        update_matrix = np.vstack(
    +            [
    +                self.scheduler_bias.update_change(gradient_bias),
    +                self.scheduler_weight.update_change(gradient_weights),
    +            ]
    +        )
    +
    +        # update weights
    +        self.weights -= update_matrix
    +
    +        # return weights and delta term, input for backpropagation in previous layer
    +        return self.weights, delta_term
    +
    +    def _reset_weights(self, previous_nodes):
    +        # sets seed to remove randomness inbetween runs
    +        if self.seed is not None:
    +            np.random.seed(self.seed)
    +
    +        # add bias, initiate random weights
    +        bias = 1
    +        self.weights = np.random.rand(previous_nodes + bias, self.nodes)
    +
    +        # returns number of nodes, used for reset_weights in next layer
    +        return self.nodes
    +
    +    def _reset_scheduler(self):
    +        # resets scheduler per epoch
    +        self.scheduler_weight.reset()
    +        self.scheduler_bias.reset()
    +
    +    def _set_pred_format(self):
    +        # sets prediction format to either regression, binary or multi-class classification
    +        if self.act_func.__name__ is None or self.act_func.__name__ == "identity":
    +            self.pred_format = "Regression"
    +        elif self.act_func.__name__ == "sigmoid" or self.act_func.__name__ == "tanh":
    +            self.pred_format = "Binary"
    +        else:
    +            self.pred_format = "Multi-class"
    +
    +    def get_pred_format(self):
    +        # returns format of prediction
    +        return self.pred_format
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    Optimized Convolution2DLayer

    + +

    For our CNN, we have also implemented an optimized version of the +Convolution2DLayer, Convolution2DLayerOPT, which runs much faster. See +VII. Remarks for discussion. This layer will per default be used by +the CNN due to its computational advantages, but is much less +readable. We've documented it such that specially interested students +can understand the principles behind it, but it is not recommended to +read. In short, we reshape and transpose parts of the image such that +the convolutional operation can be swapped out for a simple matrix +multiplication. +

    + + + +
    +
    +
    +
    +
    +
    class Convolution2DLayerOPT(Convolution2DLayer):
    +    """
    +    Am optimized version of the convolution layer above which
    +    utilizes an approach of extracting windows of size equivalent
    +    in size to the filter. The convoution is then performed on those
    +    windows instead of a full feature map.
    +    """
    +
    +    def __init__(
    +        self,
    +        input_channels,
    +        feature_maps,
    +        kernel_height,
    +        kernel_width,
    +        v_stride,
    +        h_stride,
    +        pad,
    +        act_func: Callable,
    +        seed=None,
    +        reset_weights_independently=True,
    +    ):
    +        super().__init__(
    +            input_channels,
    +            feature_maps,
    +            kernel_height,
    +            kernel_width,
    +            v_stride,
    +            h_stride,
    +            pad,
    +            act_func,
    +            seed,
    +        )
    +        # true if layer is used outside of CNN
    +        if reset_weights_independently == True:
    +            self._reset_weights_independently()
    +
    +    def _feedforward(self, X_batch):
    +        # The optimized _feedforward method is difficult to understand but computationally more efficient
    +        # for a more "by the book" approach, please look at the _feedforward method of Convolution2DLayer
    +
    +        # save the input for backpropagation
    +        self.X_batch_feedforward = X_batch
    +
    +        # check that there are the correct amount of input channels
    +        self._check_for_errors()
    +
    +        # calculate new shape after stride
    +        strided_height = int(np.ceil(X_batch.shape[height_index] / self.v_stride))
    +        strided_width = int(np.ceil(X_batch.shape[width_index] / self.h_stride))
    +
    +        # get windows of the image for more computationally efficient convolution
    +        # the idea is that we want to align the dimensions that we wish to matrix
    +        # multiply, then use a simple matrix multiplication instead of convolution.
    +        # then, we reshape the size back to its intended shape
    +        windows = self._extract_windows(X_batch)
    +        windows = windows.transpose(1, 0, 2, 3, 4).reshape(
    +            X_batch.shape[input_index],
    +            strided_height * strided_width,
    +            -1,
    +        )
    +
    +        # reshape the kernel for more computationally efficient convolution
    +        kernel = self.kernel
    +        kernel = kernel.transpose(0, 2, 3, 1).reshape(
    +            kernel.shape[kernel_input_channels_index]
    +            * kernel.shape[height_index]
    +            * kernel.shape[width_index],
    +            -1,
    +        )
    +
    +        # use simple matrix calculation to obtain output
    +        output = (
    +            (windows @ kernel)
    +            .reshape(
    +                X_batch.shape[input_index],
    +                strided_height,
    +                strided_width,
    +                -1,
    +            )
    +            .transpose(0, 3, 1, 2)
    +        )
    +
    +        # The output is reshaped and rearranged to appropriate shape
    +        return self.act_func(
    +            output / (self.kernel_height * X_batch.shape[feature_maps_index])
    +        )
    +
    +    def _backpropagate(self, delta_term_next):
    +        # The optimized _backpropagate method is difficult to understand but computationally more efficient
    +        # for a more "by the book" approach, please look at the _backpropagate method of Convolution2DLayer
    +        act_derivative = derivate(self.act_func)
    +        delta_term_next = act_derivative(delta_term_next)
    +
    +        # calculate strided dimensions
    +        strided_height = int(
    +            np.ceil(self.X_batch_feedforward.shape[height_index] / self.v_stride)
    +        )
    +        strided_width = int(
    +            np.ceil(self.X_batch_feedforward.shape[width_index] / self.h_stride)
    +        )
    +
    +        # copy kernel
    +        kernel = self.kernel
    +
    +        # get windows, reshape for matrix multiplication
    +        windows = self._extract_windows(self.X_batch_feedforward, "image").reshape(
    +            self.X_batch_feedforward.shape[input_index]
    +            * strided_height
    +            * strided_width,
    +            -1,
    +        )
    +
    +        # initialize output gradient, reshape and transpose into correct shape
    +        # for matrix multiplication
    +        output_grad_tr = delta_term_next.transpose(0, 2, 3, 1).reshape(
    +            self.X_batch_feedforward.shape[input_index]
    +            * strided_height
    +            * strided_width,
    +            -1,
    +        )
    +
    +        # calculate gradient kernel via simple matrix multiplication and reshaping
    +        gradient_kernel = (
    +            (windows.T @ output_grad_tr)
    +            .reshape(
    +                kernel.shape[kernel_input_channels_index],
    +                kernel.shape[height_index],
    +                kernel.shape[width_index],
    +                kernel.shape[kernel_feature_maps_index],
    +            )
    +            .transpose(0, 3, 1, 2)
    +        )
    +
    +        # for computing the input gradient
    +        windows_out, upsampled_height, upsampled_width = self._extract_windows(
    +            delta_term_next, "grad"
    +        )
    +
    +        # calculate new window dimensions
    +        new_windows_first_dim = (
    +            self.X_batch_feedforward.shape[input_index]
    +            * upsampled_height
    +            * upsampled_width
    +        )
    +        # ceil allows for various asymmetric kernels
    +        new_windows_sec_dim = int(np.ceil(windows_out.size / new_windows_first_dim))
    +
    +        # reshape for matrix multiplication
    +        windows_out = windows_out.transpose(1, 0, 2, 3, 4).reshape(
    +            new_windows_first_dim, new_windows_sec_dim
    +        )
    +
    +        # reshape for matrix multiplication
    +        kernel_reshaped = kernel.reshape(self.input_channels, -1)
    +
    +        # calculating input gradient for next convolutional layer
    +        input_grad = (windows_out @ kernel_reshaped.T).reshape(
    +            self.X_batch_feedforward.shape[input_index],
    +            upsampled_height,
    +            upsampled_width,
    +            kernel.shape[kernel_input_channels_index],
    +        )
    +        input_grad = input_grad.transpose(0, 3, 1, 2)
    +
    +        # Update the weights in the kernel
    +        self.kernel -= gradient_kernel
    +
    +        # Output the gradient to propagate backwards
    +        return input_grad
    +
    +    def _extract_windows(self, X_batch, batch_type="image"):
    +        """
    +        Receives as input the X_batch with shape (inputs, feature_maps, image_height, image_width)
    +        and extract windows of size kernel_height * kernel_width for every image and every feature_map.
    +        It then returns an np.ndarray of shape (image_height * image_width, inputs, feature_maps, kernel_height, kernel_width)
    +        which will be used either to filter the images in feedforward or to calculate the gradient.
    +        """
    +
    +        # initialize list of windows
    +        windows = []
    +
    +        if batch_type == "image":
    +            # pad the images
    +            X_batch_padded = self._padding(X_batch, batch_type="image")
    +            img_height, img_width = X_batch_padded.shape[2:]
    +            # For each location in the image...
    +            for h in range(
    +                0,
    +                X_batch.shape[height_index],
    +                self.v_stride,
    +            ):
    +                for w in range(
    +                    0,
    +                    X_batch.shape[width_index],
    +                    self.h_stride,
    +                ):
    +                    # ...obtain an image patch of the original size (strided)
    +
    +                    # get window
    +                    window = X_batch_padded[
    +                        :,
    +                        :,
    +                        h : h + self.kernel_height,
    +                        w : w + self.kernel_width,
    +                    ]
    +
    +                    # append to list of windows
    +                    windows.append(window)
    +
    +            # return numpy array instead of list
    +            return np.stack(windows)
    +
    +        # In order to be able to perform backprogagation by the method of window extraction,
    +        # here is a modified approach to extracting the windows which allow for the necessary
    +        # upsampling of the gradient in case the on of the stride parameters is larger than one.
    +
    +        if batch_type == "grad":
    +
    +            # In the case of one of the stride parameters being odd, we have to take some
    +            # extra care in calculating the upsampled size of X_batch. We solve this
    +            # by simply flooring the result of dividing stride by 2.
    +            if self.v_stride < 2 or self.v_stride % 2 == 0:
    +                v_stride = 0
    +            else:
    +                v_stride = int(np.floor(self.v_stride / 2))
    +
    +            if self.h_stride < 2 or self.h_stride % 2 == 0:
    +                h_stride = 0
    +            else:
    +                h_stride = int(np.floor(self.h_stride / 2))
    +
    +            upsampled_height = (X_batch.shape[height_index] * self.v_stride) - v_stride
    +            upsampled_width = (X_batch.shape[width_index] * self.h_stride) - h_stride
    +
    +            # When upsampling, we need to insert rows and columns filled with zeros
    +            # into each feature map. How many of those we have to insert is purely
    +            # dependant on the value of stride parameter in the vertical and horizontal
    +            # direction.
    +            if self.v_stride > 1:
    +                v_ind = 1
    +                for i in range(X_batch.shape[height_index]):
    +                    for j in range(self.v_stride - 1):
    +                        X_batch = np.insert(X_batch, v_ind, 0, axis=height_index)
    +                    v_ind += self.v_stride
    +
    +            if self.h_stride > 1:
    +                h_ind = 1
    +                for i in range(X_batch.shape[width_index]):
    +                    for k in range(self.h_stride - 1):
    +                        X_batch = np.insert(X_batch, h_ind, 0, axis=width_index)
    +                    h_ind += self.h_stride
    +
    +            # Since the insertion of zero-filled rows and columns isn't perfect, we have
    +            # to assure that the resulting feature maps will have the expected upsampled height
    +            # and width by cutting them og at desired dimensions.
    +
    +            X_batch = X_batch[:, :, :upsampled_height, :upsampled_width]
    +
    +            X_batch_padded = self._padding(X_batch, batch_type="grad")
    +
    +            # initialize list of windows
    +            windows = []
    +
    +            # For each location in the image...
    +            for h in range(
    +                0,
    +                X_batch.shape[height_index],
    +                self.v_stride,
    +            ):
    +                for w in range(
    +                    0,
    +                    X_batch.shape[width_index],
    +                    self.h_stride,
    +                ):
    +                    # ...obtain an image patch of the original size (strided)
    +
    +                    # get window
    +                    window = X_batch_padded[
    +                        :, :, h : h + self.kernel_height, w : w + self.kernel_width
    +                    ]
    +
    +                    # append window to list
    +                    windows.append(window)
    +
    +            # return numpy array, unsampled dimensions
    +            return np.stack(windows), upsampled_height, upsampled_width
    +
    +    def _check_for_errors(self):
    +        # compares input channels of data to input channels of Convolution2DLayer
    +        if self.X_batch_feedforward.shape[input_channel_index] != self.input_channels:
    +            raise AssertionError(
    +                f"ERROR: Number of input channels in data ({self.X_batch_feedforward.shape[input_channel_index]}) is not equal to input channels in Convolution2DLayerOPT ({self.input_channels})! Please change the number of input channels of the Convolution2DLayer such that they are equal"
    +            )
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    The Convolutional Neural Network (CNN)

    + +

    Finally, we present the code for the CNN. The CNN class organizes all the layers, and allows for training on image data.

    + + + +
    +
    +
    +
    +
    +
    import math
    +import autograd.numpy as np
    +import sys
    +import warnings
    +from autograd import grad, elementwise_grad
    +from random import random, seed
    +from copy import deepcopy
    +from typing import Tuple, Callable
    +from sklearn.utils import resample
    +
    +warnings.simplefilter("error")
    +
    +
    +class CNN:
    +    def __init__(
    +        self,
    +        cost_func: Callable = CostCrossEntropy,
    +        scheduler: Scheduler = Adam(eta=1e-4, rho=0.9, rho2=0.999),
    +        seed: int = None,
    +    ):
    +        """
    +        Description:
    +        ------------
    +            Instantiates CNN object
    +
    +        Parameters:
    +        ------------
    +            I   output_func (costFunctions) cost function for feed forward neural network part of CNN,
    +                such as "CostLogReg", "CostOLS" or "CostCrossEntropy"
    +
    +            II  scheduler (Scheduler) optional parameter, default set to Adam. Can also be set to other
    +                schedulers such as AdaGrad, Momentum, RMS_prop and Constant. Note that schedulers have
    +                to be instantiated first with proper parameters (for example eta, rho and rho2 for Adam)
    +
    +            III seed (int) used for seeding all random operations
    +        """
    +        self.layers = list()
    +        self.cost_func = cost_func
    +        self.scheduler = scheduler
    +        self.schedulers_weight = list()
    +        self.schedulers_bias = list()
    +        self.seed = seed
    +        self.pred_format = None
    +
    +    def add_FullyConnectedLayer(
    +        self, nodes: int, act_func=LRELU, scheduler=None
    +    ) -> None:
    +        """
    +        Description:
    +        ------------
    +            Add a FullyConnectedLayer to the CNN, i.e. a hidden layer in the feed forward neural
    +            network part of the CNN. Often called a Dense layer in literature
    +
    +        Parameters:
    +        ------------
    +            I   nodes (int) number of nodes in FullyConnectedLayer
    +            II  act_func (activationFunctions) activation function of FullyConnectedLayer,
    +                such as "sigmoid", "RELU", "LRELU", "softmax" or "identity"
    +            III scheduler (Scheduler) optional parameter, default set to Adam. Can also be set to other
    +                schedulers such as AdaGrad, Momentum, RMS_prop and Constant
    +        """
    +        assert self.layers, "FullyConnectedLayer should follow FlattenLayer in CNN"
    +
    +        if scheduler is None:
    +            scheduler = self.scheduler
    +
    +        layer = FullyConnectedLayer(nodes, act_func, scheduler, self.seed)
    +        self.layers.append(layer)
    +
    +    def add_OutputLayer(self, nodes: int, output_func=sigmoid, scheduler=None) -> None:
    +        """
    +        Description:
    +        ------------
    +            Add an OutputLayer to the CNN, i.e. a the final layer in the feed forward neural
    +            network part of the CNN
    +
    +        Parameters:
    +        ------------
    +            I   nodes (int) number of nodes in OutputLayer. Set nodes=1 for binary classification and
    +                nodes = number of classes for multi-class classification
    +            II  output_func (activationFunctions) activation function for the output layer, such as
    +                "identity" for regression, "sigmoid" for binary classification and "softmax" for multi-class
    +                classification
    +            III scheduler (Scheduler) optional parameter, default set to Adam. Can also be set to other
    +                schedulers such as AdaGrad, Momentum, RMS_prop and Constant
    +        """
    +        assert self.layers, "OutputLayer should follow FullyConnectedLayer in CNN"
    +
    +        if scheduler is None:
    +            scheduler = self.scheduler
    +
    +        output_layer = OutputLayer(
    +            nodes, output_func, self.cost_func, scheduler, self.seed
    +        )
    +        self.layers.append(output_layer)
    +        self.pred_format = output_layer.get_pred_format()
    +
    +    def add_FlattenLayer(self, act_func=LRELU) -> None:
    +        """
    +        Description:
    +        ------------
    +            Add a FlattenLayer to the CNN, which flattens the image data such that it is formatted to
    +            be used in the feed forward neural network part of the CNN
    +        """
    +        self.layers.append(FlattenLayer(act_func=act_func, seed=self.seed))
    +
    +    def add_Convolution2DLayer(
    +        self,
    +        input_channels=1,
    +        feature_maps=1,
    +        kernel_height=3,
    +        kernel_width=3,
    +        v_stride=1,
    +        h_stride=1,
    +        pad="same",
    +        act_func=LRELU,
    +        optimized=True,
    +    ) -> None:
    +        """
    +        Description:
    +        ------------
    +            Add a Convolution2DLayer to the CNN, i.e. a convolutional layer with a 2 dimensional kernel. Should be
    +            the first layer added to the CNN
    +
    +        Parameters:
    +        ------------
    +            I   input_channels (int) specifies amount of input channels. For monochrome images, use input_channels
    +                = 1, and input_channels = 3 for colored images, where each channel represents one of R, G and B
    +            II  feature_maps (int) amount of feature maps in CNN
    +            III kernel_height (int) height of the kernel, also called 'convolutional filter' in literature
    +            IV  kernel_width (int) width of the kernel, also called 'convolutional filter' in literature
    +            V   v_stride (int) value of vertical stride for dimentionality reduction
    +            VI  h_stride (int) value of horizontal stride for dimentionality reduction
    +            VII pad (str) default = "same" ensures output size is the same as input size (given stride=1)
    +           VIII act_func (activationFunctions) default = "LRELU", nonlinear activation function
    +             IX optimized (bool) default = True, uses Convolution2DLayerOPT if True which is much faster when
    +                compared to Convolution2DLayer, which is a more straightforward, understandable implementation
    +        """
    +        if optimized:
    +            conv_layer = Convolution2DLayerOPT(
    +                input_channels,
    +                feature_maps,
    +                kernel_height,
    +                kernel_width,
    +                v_stride,
    +                h_stride,
    +                pad,
    +                act_func,
    +                self.seed,
    +                reset_weights_independently=False,
    +            )
    +        else:
    +            conv_layer = Convolution2DLayer(
    +                input_channels,
    +                feature_maps,
    +                kernel_height,
    +                kernel_width,
    +                v_stride,
    +                h_stride,
    +                pad,
    +                act_func,
    +                self.seed,
    +                reset_weights_independently=False,
    +            )
    +        self.layers.append(conv_layer)
    +
    +    def add_PoolingLayer(
    +        self, kernel_height=2, kernel_width=2, v_stride=1, h_stride=1, pooling="max"
    +    ) -> None:
    +        """
    +        Description:
    +        ------------
    +            Add a Pooling2DLayer to the CNN, i.e. a pooling layer that reduces the dimentionality of
    +            the image data. It is not necessary to use a Pooling2DLayer when creating a CNN, but it
    +            can be used to speed up the training
    +
    +        Parameters:
    +        ------------
    +            I   kernel_height (int) height of the kernel used for pooling
    +            II  kernel_width (int) width of the kernel used for pooling
    +            III v_stride (int) value of vertical stride for dimentionality reduction
    +            IV  h_stride (int) value of horizontal stride for dimentionality reduction
    +            V   pooling (str) either "max" or "average", describes type of pooling performed
    +        """
    +        pooling_layer = Pooling2DLayer(
    +            kernel_height, kernel_width, v_stride, h_stride, pooling, self.seed
    +        )
    +        self.layers.append(pooling_layer)
    +
    +    def fit(
    +        self,
    +        X: np.ndarray,
    +        t: np.ndarray,
    +        epochs: int = 100,
    +        lam: float = 0,
    +        batches: int = 1,
    +        X_val: np.ndarray = None,
    +        t_val: np.ndarray = None,
    +    ) -> dict:
    +        """
    +        Description:
    +        ------------
    +            Fits the CNN to input X for a given amount of epochs. Performs feedforward and backpropagation passes,
    +            can utilize batches, regulariziation and validation if desired.
    +
    +        Parameters:
    +        ------------
    +            X (numpy array) with input data in format [images, input channels,
    +            image height, image_width]
    +            t (numpy array) target labels for input data
    +            epochs (int) amount of epochs
    +            lam (float) regulariziation term lambda
    +            batches (int) amount of batches input data splits into
    +            X_val (numpy array) validation data
    +            t_val (numpy array) target labels for validation data
    +
    +        Returns:
    +        ------------
    +            scores (dict) a dictionary with "train_error", "train_acc", "val_error", val_acc" keys
    +            that contain numpy arrays with float values of all accuracies/errors over all epochs.
    +            Can be used to create plots. Also used to update the progress bar during training
    +        """
    +
    +        # setup
    +        if self.seed is not None:
    +            np.random.seed(self.seed)
    +
    +        # initialize weights
    +        self._initialize_weights(X)
    +
    +        # create arrays for score metrics
    +        scores = self._initialize_scores(epochs)
    +
    +        assert batches <= t.shape[0]
    +        batch_size = X.shape[0] // batches
    +
    +        try:
    +            for epoch in range(epochs):
    +                for batch in range(batches):
    +                    # minibatch gradient descent
    +                    # If the for loop has reached the last batch, take all thats left
    +                    if batch == batches - 1:
    +                        X_batch = X[batch * batch_size :, :, :, :]
    +                        t_batch = t[batch * batch_size :, :]
    +                    else:
    +                        X_batch = X[
    +                            batch * batch_size : (batch + 1) * batch_size, :, :, :
    +                        ]
    +                        t_batch = t[batch * batch_size : (batch + 1) * batch_size, :]
    +
    +                    self._feedforward(X_batch)
    +                    self._backpropagate(t_batch, lam)
    +
    +                # reset schedulers for each epoch (some schedulers pass in this call)
    +                for layer in self.layers:
    +                    if isinstance(layer, FullyConnectedLayer):
    +                        layer._reset_scheduler()
    +
    +                # computing performance metrics
    +                scores = self._compute_scores(scores, epoch, X, t, X_val, t_val)
    +
    +                # printing progress bar
    +                print_length = self._progress_bar(
    +                    epoch,
    +                    epochs,
    +                    scores,
    +                )
    +        # allows for stopping training at any point and seeing the result
    +        except KeyboardInterrupt:
    +            pass
    +
    +        # visualization of training progression (similiar to tensorflow progression bar)
    +        sys.stdout.write("\r" + " " * print_length)
    +        sys.stdout.flush()
    +        self._progress_bar(
    +            epochs,
    +            epochs,
    +            scores,
    +        )
    +        sys.stdout.write("")
    +
    +        return scores
    +
    +    def _feedforward(self, X_batch) -> np.ndarray:
    +        """
    +        Description:
    +        ------------
    +            Performs the feedforward pass for all layers in the CNN. Called from fit()
    +        """
    +        a = X_batch
    +        for layer in self.layers:
    +            a = layer._feedforward(a)
    +
    +        return a
    +
    +    def _backpropagate(self, t_batch, lam) -> None:
    +        """
    +        Description:
    +        ------------
    +            Performs backpropagation for all layers in the CNN. Called from fit()
    +        """
    +        assert len(self.layers) >= 2
    +        reversed_layers = self.layers[::-1]
    +
    +        # for every layer, backwards
    +        for i in range(len(reversed_layers) - 1):
    +            layer = reversed_layers[i]
    +            prev_layer = reversed_layers[i + 1]
    +
    +            # OutputLayer
    +            if isinstance(layer, OutputLayer):
    +                prev_a = prev_layer.get_prev_a()
    +                weights_next, delta_next = layer._backpropagate(t_batch, prev_a, lam)
    +
    +            # FullyConnectedLayer
    +            elif isinstance(layer, FullyConnectedLayer):
    +                assert (
    +                    delta_next is not None
    +                ), "No OutputLayer to follow FullyConnectedLayer"
    +                assert (
    +                    weights_next is not None
    +                ), "No OutputLayer to follow FullyConnectedLayer"
    +                prev_a = prev_layer.get_prev_a()
    +                weights_next, delta_next = layer._backpropagate(
    +                    weights_next, delta_next, prev_a, lam
    +                )
    +
    +            # FlattenLayer
    +            elif isinstance(layer, FlattenLayer):
    +                assert (
    +                    delta_next is not None
    +                ), "No FullyConnectedLayer to follow FlattenLayer"
    +                assert (
    +                    weights_next is not None
    +                ), "No FullyConnectedLayer to follow FlattenLayer"
    +                delta_next = layer._backpropagate(weights_next, delta_next)
    +
    +            # Convolution2DLayer and Convolution2DLayerOPT
    +            elif isinstance(layer, Convolution2DLayer):
    +                assert (
    +                    delta_next is not None
    +                ), "No FlattenLayer to follow Convolution2DLayer"
    +                delta_next = layer._backpropagate(delta_next)
    +
    +            # Pooling2DLayer
    +            elif isinstance(layer, Pooling2DLayer):
    +                assert delta_next is not None, "No Layer to follow Pooling2DLayer"
    +                delta_next = layer._backpropagate(delta_next)
    +
    +            # Catch error
    +            else:
    +                raise NotImplementedError
    +
    +    def _compute_scores(
    +        self,
    +        scores: dict,
    +        epoch: int,
    +        X: np.ndarray,
    +        t: np.ndarray,
    +        X_val: np.ndarray,
    +        t_val: np.ndarray,
    +    ) -> dict:
    +        """
    +        Description:
    +        ------------
    +            Computes scores such as training error, training accuracy, validation error
    +            and validation accuracy for the CNN depending on if a validation set is used
    +            and if the CNN performs classification or regression
    +
    +        Returns:
    +        ------------
    +            scores (dict) a dictionary with "train_error", "train_acc", "val_error", val_acc" keys
    +            that contain numpy arrays with float values of all accuracies/errors over all epochs.
    +            Can be used to create plots. Also used to update the progress bar during training
    +        """
    +
    +        pred_train = self.predict(X)
    +        cost_function_train = self.cost_func(t)
    +        train_error = cost_function_train(pred_train)
    +        scores["train_error"][epoch] = train_error
    +
    +        if X_val is not None and t_val is not None:
    +            cost_function_val = self.cost_func(t_val)
    +            pred_val = self.predict(X_val)
    +            val_error = cost_function_val(pred_val)
    +            scores["val_error"][epoch] = val_error
    +
    +        if self.pred_format != "Regression":
    +            train_acc = self._accuracy(pred_train, t)
    +            scores["train_acc"][epoch] = train_acc
    +            if X_val is not None and t_val is not None:
    +                val_acc = self._accuracy(pred_val, t_val)
    +                scores["val_acc"][epoch] = val_acc
    +
    +        return scores
    +
    +    def _initialize_scores(self, epochs) -> dict:
    +        """
    +        Description:
    +        ------------
    +            Initializes scores such as training error, training accuracy, validation error
    +            and validation accuracy for the CNN
    +
    +        Returns:
    +        ------------
    +            A dictionary with "train_error", "train_acc", "val_error", val_acc" keys that
    +            will contain numpy arrays with float values of all accuracies/errors over all epochs
    +            when passed through the _compute_scores() function during fit()
    +        """
    +        scores = dict()
    +
    +        train_errors = np.empty(epochs)
    +        train_errors.fill(np.nan)
    +        val_errors = np.empty(epochs)
    +        val_errors.fill(np.nan)
    +
    +        train_accs = np.empty(epochs)
    +        train_accs.fill(np.nan)
    +        val_accs = np.empty(epochs)
    +        val_accs.fill(np.nan)
    +
    +        scores["train_error"] = train_errors
    +        scores["val_error"] = val_errors
    +        scores["train_acc"] = train_accs
    +        scores["val_acc"] = val_accs
    +
    +        return scores
    +
    +    def _initialize_weights(self, X: np.ndarray) -> None:
    +        """
    +        Description:
    +        ------------
    +            Initializes weights for all layers in CNN
    +
    +        Parameters:
    +        ------------
    +            I   X (np.ndarray) input of format [img, feature_maps, height, width]
    +        """
    +        prev_nodes = X
    +        for layer in self.layers:
    +            prev_nodes = layer._reset_weights(prev_nodes)
    +
    +    def predict(self, X: np.ndarray, *, threshold=0.5) -> np.ndarray:
    +        """
    +        Description:
    +        ------------
    +            Predicts output of input X
    +
    +        Parameters:
    +        ------------
    +            I   X (np.ndarray) input [img, feature_maps, height, width]
    +        """
    +
    +        prediction = self._feedforward(X)
    +
    +        if self.pred_format == "Binary":
    +            return np.where(prediction > threshold, 1, 0)
    +        elif self.pred_format == "Multi-class":
    +            class_prediction = np.zeros(prediction.shape)
    +            for i in range(prediction.shape[0]):
    +                class_prediction[i, np.argmax(prediction[i, :])] = 1
    +            return class_prediction
    +        else:
    +            return prediction
    +
    +    def _accuracy(self, prediction: np.ndarray, target: np.ndarray) -> float:
    +        """
    +        Description:
    +        ------------
    +            Calculates accuracy of given prediction to target
    +
    +        Parameters:
    +        ------------
    +            I   prediction (np.ndarray): output of predict() fuction
    +            (1s and 0s in case of classification, and real numbers in case of regression)
    +            II  target (np.ndarray): vector of true values (What the network should predict)
    +
    +        Returns:
    +        ------------
    +            A floating point number representing the percentage of correctly classified instances.
    +        """
    +        assert prediction.size == target.size
    +        return np.average((target == prediction))
    +
    +    def _progress_bar(self, epoch: int, epochs: int, scores: dict) -> int:
    +        """
    +        Description:
    +        ------------
    +            Displays progress of training
    +        """
    +        progression = epoch / epochs
    +        epoch -= 1
    +        print_length = 40
    +        num_equals = int(progression * print_length)
    +        num_not = print_length - num_equals
    +        arrow = ">" if num_equals > 0 else ""
    +        bar = "[" + "=" * (num_equals - 1) + arrow + "-" * num_not + "]"
    +        perc_print = self._fmt(progression * 100, N=5)
    +        line = f"  {bar} {perc_print}% "
    +
    +        for key, score in scores.items():
    +            if np.isnan(score[epoch]) == False:
    +                value = self._fmt(score[epoch], N=4)
    +                line += f"| {key}: {value} "
    +        print(line, end="\r")
    +        return len(line)
    +
    +    def _fmt(self, value: int, N=4) -> str:
    +        """
    +        Description:
    +        ------------
    +            Formats decimal numbers for progress bar
    +        """
    +        if value > 0:
    +            v = value
    +        elif value < 0:
    +            v = -10 * value
    +        else:
    +            v = 1
    +        n = 1 + math.floor(math.log10(v))
    +        if n >= N - 1:
    +            return str(round(value))
    +            # or overflow
    +        return f"{value:.{N-n-1}f}"
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    Usage of CNN code

    + +

    Using the CNN codebase is very simple. We begin by initiating a CNN +object, which takes a cost function, a scheduler and a seed as its +arguments. If a scheduler is not provided, it will per default +initiate an Adam scheduler with eta=1e-4, and if a seed is not +provided, the CNN will not be seeded, meaning it will run with a +different random seed every run. Below we demonstrate an initiation of +our CNN. +

    + + + +
    +
    +
    +
    +
    +
    adam_scheduler = Adam(eta=1e-3, rho=0.9, rho2=0.999)
    +cnn = CNN(cost_func=CostCrossEntropy, scheduler=adam_scheduler, seed=2023)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    Now that we have our CNN object, we can begin to add layers to it! +Many of the add_layer functions have default values, for example +add_Convolution2DLayer() has a default v_stride and h_stride of +1. However, these can of course be set to any value you please. Note +that the input channels of a subsequent convolutional layer must equal +the previous convolutional layer's feature maps. +

    + + + +
    +
    +
    +
    +
    +
    cnn.add_Convolution2DLayer(
    +    input_channels=1,
    +    feature_maps=1,
    +    kernel_height=3,
    +    kernel_width=3,
    +    act_func=LRELU,
    +)
    +
    +cnn.add_FlattenLayer()
    +
    +cnn.add_FullyConnectedLayer(30, LRELU)
    +
    +cnn.add_FullyConnectedLayer(20, LRELU)
    +
    +cnn.add_OutputLayer(10, softmax)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    Here we have created a CNN with the following architecture:

    + +
      +
    1. A convolutional layer with 1 input channel, with a kernel height of 2 and a width of 2, which uses LRELU as its non-linearity function. This layer outputs 1 feature map, which feed into the subsequent layer.
    2. +
    3. A flatten layer
    4. +
    5. A hidden layer with 30 nodes, with LRELU as its activation function
    6. +
    7. Another hidden layer but with 20 nodes
    8. +
    9. The output layer, with softmax as its activation function and 10 nodes. We use 10 nodes because we will be using a dataset with 10 classes.
    10. +
    +

    Now, before we can train the model, we need to load in our data. We +will use the MNIST dataset and use 10000 \( 28 \times 28 images \). +

    + + + +
    +
    +
    +
    +
    +
    from sklearn.datasets import fetch_openml
    +from sklearn.model_selection import train_test_split
    +
    +def onehot(target: np.ndarray):
    +    onehot = np.zeros((target.size, target.max() + 1))
    +    onehot[np.arange(target.size), target] = 1
    +    return onehot
    +
    +# get dataset
    +dataset = fetch_openml("mnist_784", parser="auto")
    +mnist = dataset.data.to_numpy(dtype="float")[:10000, :]
    +
    +# scale data
    +for i in range(mnist.shape[1]):
    +    mnist[:, i] /= 255
    +    
    +# reshape to add single input channel to data shape [inputs, input_channels, height, width]
    +mnist = mnist.reshape(mnist.shape[0], 1, 28, 28)
    +
    +# one hot encode target as we are doing multi-class classification
    +target = onehot(np.array([int(i) for i in dataset.target.to_numpy()[:10000]]))
    +
    +# split into training and validation data
    +x_train, x_val, y_train, y_val = train_test_split(mnist, target)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    Now we may train our model. Note that we can utilize regularization in +the CNN by using the lam (lambda) parameter in fit(), and utilize +different types of gradient descent by specifying the amount of +batches via the batches parameter as shown below. +

    + +

    The functionfit() returns a score dictionary of the training error and +accuracy (and validation error and accuracy if a validation set is +provided) which can be used to plot the error and accuracy of the +model over epochs. +

    + + + +
    +
    +
    +
    +
    +
    scores = cnn.fit(
    +    x_train,
    +    y_train,
    +    lam=1e-5,
    +    batches=10,
    +    epochs=100,
    +    X_val=x_val,
    +    t_val=y_val,
    +)
    +
    +plt.plot(scores["train_acc"], label="Training")
    +plt.plot(scores["val_acc"], label="Validation")
    +plt.ylim([0.8,1])
    +plt.xlabel("Epochs")
    +plt.ylabel("Accuracy")
    +plt.legend()
    +plt.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    Considering we only trained the model for 100 epochs without any tuning of the hyperparameters, this result is pretty good.

    + +

    The codebase allows for great flexibility in CNN +architectures. Pooling layers can be added before, inbetween or after +convolutional layers, but due to the great optimizations made within +Convolution2DLayerOPT, we recommend using the v_stride and h_stride +parameters in add_Convolution2DLayer() to reduce the dimentionality of +the problem as the pooling layer is slow in comparison. To use the +unoptimized version of Convolution2DLayer, simply pass optimized=False +as an argument in add_Convolution2DLayer(). +

    + +

    If one wishes to perform binary classification using the CNN, simply +use the cost function 'CostLogReg' when initializing the CNN and use 1 +node at the OutputLayer. +

    + +

    Below we have created another, more untraditional architecture using +our code to demonstrate its flexibility and different attributes such +as asymmetric stride that might become useful when constructing your +own CNN. +

    + + + +
    +
    +
    +
    +
    +
    adam_scheduler = Adam(eta=1e-3, rho=0.9, rho2=0.999)
    +cnn = CNN(cost_func=CostCrossEntropy, scheduler=adam_scheduler, seed=2023)
    +
    +cnn.add_Convolution2DLayer(
    +    input_channels=1,
    +    feature_maps=7,
    +    kernel_height=7,
    +    kernel_width=1,
    +    act_func=LRELU,
    +)
    +
    +cnn.add_PoolingLayer(
    +    kernel_height=2,
    +    kernel_width=2,
    +    pooling="average",
    +)
    +
    +cnn.add_PoolingLayer(
    +    kernel_height=2,
    +    kernel_width=2,
    +    pooling="max",
    +)
    +
    +cnn.add_Convolution2DLayer(
    +    input_channels=7,
    +    feature_maps=1,
    +    kernel_height=4,
    +    kernel_width=4,
    +    v_stride=2,
    +    h_stride=3,
    +    act_func=LRELU,
    +    optimized=False,
    +)
    +
    +cnn.add_Convolution2DLayer(
    +    input_channels=1,
    +    feature_maps=1,
    +    kernel_height=2,
    +    kernel_width=2,
    +    act_func=sigmoid,
    +    optimized=True,
    +)
    +
    +cnn.add_PoolingLayer(
    +    kernel_height=2,
    +    kernel_width=2,
    +    pooling="max"
    +)
    +
    +cnn.add_FlattenLayer()
    +
    +cnn.add_FullyConnectedLayer(100, LRELU)
    +
    +cnn.add_FullyConnectedLayer(10, sigmoid)
    +
    +cnn.add_FullyConnectedLayer(101, identity)
    +
    +cnn.add_OutputLayer(10, softmax)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    Here we see the use of asymmetrical 1D kernels such as the \( 7 \times +1 \) kernel in the first convolutional layer, both max and average +pooling, asymmetric stride in the unoptimized convolutional layer, +more pooling, a flatten layer, a hidden layer with 100 nodes using +LRELU, another hidden layer with 10 hidden nodes that uses the sigmoid +activation function, and another hidden layer with 101 nodes which +utilizes no activation function (identity). Finally, we arrive at the +output layer with 10 nodes, which uses softmax as its activation +function. +

    +

    Additional Remarks

    + +

    The stride parameter controls the distance between each convolution +and the kernel/filter. If our image is padded, stride is the only +parameter that determines the size of the output from a convolutional +layer. However, if we decide not to perform any padding, the size of +the output feature map depends on both the stride and kernel size. It +is important to note that neither the stride nor the kernel has to be +symmetrical. This means that we can use a rectangular filter if we +choose, and the stride in the vertical direction (axis=0 in Python) +does not need to be the same as the stride in the horizontal direction +(axis=1 in Python). It may even be the case that asymmetric +combinations of stride or kernel dimensions, or both, yield better +results than symmetric values for these parameters. +

    + + + +
    +
    +
    +
    +
    +
    def convolve(image, kernel, stride=1):
    +    for i in range(2):
    +        kernel = np.rot90(kernel)
    +
    +    k_half_height = kernel.shape[0] // 2
    +    k_half_width = kernel.shape[0] // 2
    +
    +    conv_image = np.zeros(image.shape)
    +    pad_image = padding(image, kernel)
    +
    +    for i in range(k_half_height, conv_image.shape[0] + k_half_height, stride):
    +        for j in range(k_half_width, conv_image.shape[1] + k_half_width, stride):
    +            conv_image[i - k_half_height, j - k_half_width] = np.sum(
    +                pad_image[
    +                    i - k_half_height : i + k_half_height + 1, j - k_half_width : j + k_half_width + 1
    +                ]
    +                * kernel
    +            )
    +
    +    return conv_image
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    Remarks on the speed

    + +

    Despite the naive convolution algorithm shown above working finely, it +is extremely slow, requiring approximately 20-30 seconds to process a +single image. The time complexity of 2D convolution, which is O(NMnm), +rapidly becomes a constraint and may, at worst, make computations +infeasible. Consequently, optimizing the naive 2D convolution +algorithm is a necessity, as the execution time of the algorithm +significantly increases as the input data size expands. This can pose +a bottleneck in applications that necessitate real-time processing of +large data volumes, such as image and video processing, deep learning, +and scientific simulations. +

    + +

    To address this issue, we shall present two widely used optimization +techniques: the separable kernel approach and Fast Fourier Transform +(FFT). Both of these methods can drastically reduce the computational +complexity of convolution and enhance the overall efficiency of +processing substantial data quantities. While we shall refrain from +delving into the intricacies of these algorithms, we strongly +encourage you to examine at least the application of FFT to optimize +computations. +

    +

    Convolution using separable kernels

    + + + +
    +
    +
    +
    +
    +
    def conv2DSep(image, kernel, coef, stride=1, pad="zero"):
    +    for i in range(2):
    +        kernel = np.rot90(kernel)
    +
    +    # The kernel is quadratic, thus we only need one of its dimensions
    +    half_dim = kernel.shape[0] // 2
    +
    +    ker1 = np.array(kernel[0, :])
    +    ker2 = np.array(kernel[:, 0])
    +
    +    if pad == "zero":
    +        conv_image = np.zeros(image.shape)
    +        pad_image = padding(image, kernel)
    +    else:
    +        conv_image = np.zeros(
    +            (image.shape[0] - kernel.shape[0], image.shape[1] - kernel.shape[1])
    +        )
    +        pad_image = image[:, :]
    +
    +    for i in range(half_dim, conv_image.shape[0] + half_dim, stride):
    +        for j in range(half_dim, conv_image.shape[1] + half_dim, stride):
    +            conv_image[i - half_dim, j - half_dim] = (
    +                pad_image[
    +                    i - half_dim : i + half_dim + 1, j - half_dim : j + half_dim + 1
    +                ]
    +                @ ker1
    +                @ ker2.T
    +                * coef
    +            )
    +
    +    return conv_image
    +
    +img_path = img_path = "../data/IMG-2167.JPG"
    +image_of_cute_dog = imageio.imread(img_path, mode="L")
    +start_time = time.time()
    +filtered_image = conv2DSep(image_of_cute_dog, kernel=sobel_kernel, coef=1)
    +print(f'Time taken for convolution with seperated kernel on 128x128 image {time.time() - start_time}')
    +plt.imshow(filtered_image, cmap="gray", vmin=0, vmax=255, aspect="auto")
    +plt.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    By taking advantage of the capabilities of separable kernels, we can +effectively cut the computational expense of filtering an image in +half. Yet, if we seek even more rapid processing, we can turn to the +Fast Fourier Transform (FFT) algorithm provided by the numpy +library. By utilizing FFT to transform the input image and filter into +the frequency domain, we can perform convolution in this domain. This +approach significantly reduces the number of operations needed and +results in a marked speedup relative to other convolution +techniques. In addition, it is worth noting that the FFT is widely +regarded as one of the most critical algorithms developed to date, +with applications ranging from digital signal processing to scientific +computing. +

    +

    Convolution in the Fourier domain

    + + +
    +
    +
    +
    +
    +
    start_time = time.time()
    +img_fft = np.fft.fft2(image_of_cute_dog)
    +kernel_fft = np.fft.fft2(sobel_kernel, s=image_of_cute_dog.shape)
    +
    +conv_image = img_fft * kernel_fft
    +
    +filtered_image = np.fft.ifft2(conv_image)
    +print(f'Time take for convolution in the fourier domain: {time.time() - start_time}')
    +plt.imshow(filtered_image.real, cmap="gray", vmin=0, vmax=255, aspect="auto")
    +plt.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    It is evident that executing convolution in the Fourier domain yields +the quickest computation time. Nonetheless, one should exercise +caution, particularly when dealing with images of relatively small +dimensions, as one of the other methods may prove to be more +expeditious than FFT-enhanced convolution. The overhead involved in +transferring both the image and filter into the Fourier domain, +followed by their subsequent transformation back into the spatial +domain, results in a minor inconvenience. Therefore, it is imperative +to remain cognizant of this fact when utilizing FFT as the primary +optimization technique. +

    © 1999-2023, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license diff --git a/doc/pub/week44/ipynb/ipynb-week44-src.tar.gz b/doc/pub/week44/ipynb/ipynb-week44-src.tar.gz index 8ec528d54..5f17830d0 100644 Binary files a/doc/pub/week44/ipynb/ipynb-week44-src.tar.gz and b/doc/pub/week44/ipynb/ipynb-week44-src.tar.gz differ diff --git a/doc/pub/week44/ipynb/week44.ipynb b/doc/pub/week44/ipynb/week44.ipynb index 3f8f3f16f..3836b8722 100644 --- a/doc/pub/week44/ipynb/week44.ipynb +++ b/doc/pub/week44/ipynb/week44.ipynb @@ -2,7 +2,7 @@ "cells": [ { "cell_type": "markdown", - "id": "17a59a38", + "id": "32b868e8", "metadata": { "editable": true }, @@ -14,7 +14,7 @@ }, { "cell_type": "markdown", - "id": "e84b3a73", + "id": "f49ca0a8", "metadata": { "editable": true }, @@ -27,7 +27,7 @@ }, { "cell_type": "markdown", - "id": "dfee3388", + "id": "18b6439b", "metadata": { "editable": true }, @@ -75,7 +75,7 @@ }, { "cell_type": "markdown", - "id": "ebc1e521", + "id": "4d15ec9a", "metadata": { "editable": true }, @@ -85,7 +85,7 @@ }, { "cell_type": "markdown", - "id": "5fa9a7f1", + "id": "d059dfe4", "metadata": { "editable": true }, @@ -112,7 +112,7 @@ }, { "cell_type": "markdown", - "id": "4f2578cc", + "id": "11298ed6", "metadata": { "editable": true }, @@ -134,7 +134,7 @@ }, { "cell_type": "markdown", - "id": "8053992e", + "id": "adf7491b", "metadata": { "editable": true }, @@ -152,7 +152,7 @@ }, { "cell_type": "markdown", - "id": "7491ab94", + "id": "0c91aae7", "metadata": { "editable": true }, @@ -182,7 +182,7 @@ }, { "cell_type": "markdown", - "id": "be67a938", + "id": "44f4900f", "metadata": { "editable": true }, @@ -212,7 +212,7 @@ }, { "cell_type": "markdown", - "id": "b3f5ac1d", + "id": "65dfc36c", "metadata": { "editable": true }, @@ -252,7 +252,7 @@ }, { "cell_type": "markdown", - "id": "ab56ef75", + "id": "9cc13745", "metadata": { "editable": true }, @@ -281,7 +281,7 @@ }, { "cell_type": "markdown", - "id": "58f02d37", + "id": "2b29f8fd", "metadata": { "editable": true }, @@ -303,7 +303,7 @@ }, { "cell_type": "markdown", - "id": "441ee7fb", + "id": "b863e7a7", "metadata": { "editable": true }, @@ -332,7 +332,7 @@ }, { "cell_type": "markdown", - "id": "5f7920f8", + "id": "d00f2c70", "metadata": { "editable": true }, @@ -349,7 +349,7 @@ }, { "cell_type": "markdown", - "id": "ea2ea529", + "id": "b449a003", "metadata": { "editable": true }, @@ -369,7 +369,7 @@ }, { "cell_type": "markdown", - "id": "18a81c49", + "id": "cc14fe57", "metadata": { "editable": true }, @@ -381,7 +381,7 @@ }, { "cell_type": "markdown", - "id": "5a3c2f1a", + "id": "756045db", "metadata": { "editable": true }, @@ -393,7 +393,7 @@ }, { "cell_type": "markdown", - "id": "651caa4b", + "id": "ce837df3", "metadata": { "editable": true }, @@ -405,7 +405,7 @@ }, { "cell_type": "markdown", - "id": "07b35396", + "id": "9783d27c", "metadata": { "editable": true }, @@ -415,7 +415,7 @@ }, { "cell_type": "markdown", - "id": "66dd28db", + "id": "ab5e9780", "metadata": { "editable": true }, @@ -427,7 +427,7 @@ }, { "cell_type": "markdown", - "id": "08486386", + "id": "464f7836", "metadata": { "editable": true }, @@ -439,7 +439,7 @@ }, { "cell_type": "markdown", - "id": "2890951e", + "id": "154be50a", "metadata": { "editable": true }, @@ -454,7 +454,7 @@ }, { "cell_type": "markdown", - "id": "c900af57", + "id": "b4d21b2f", "metadata": { "editable": true }, @@ -466,7 +466,7 @@ }, { "cell_type": "markdown", - "id": "0c6b9f27", + "id": "ff44d22a", "metadata": { "editable": true }, @@ -476,7 +476,7 @@ }, { "cell_type": "markdown", - "id": "c49cca1f", + "id": "1c7d0d6e", "metadata": { "editable": true }, @@ -488,7 +488,7 @@ }, { "cell_type": "markdown", - "id": "2cc13706", + "id": "214f4775", "metadata": { "editable": true }, @@ -498,7 +498,7 @@ }, { "cell_type": "markdown", - "id": "27775d39", + "id": "e2d3411d", "metadata": { "editable": true }, @@ -510,7 +510,7 @@ }, { "cell_type": "markdown", - "id": "93206df8", + "id": "2ddb06e5", "metadata": { "editable": true }, @@ -523,7 +523,7 @@ }, { "cell_type": "markdown", - "id": "369507c7", + "id": "6c188f5d", "metadata": { "editable": true }, @@ -542,7 +542,7 @@ }, { "cell_type": "markdown", - "id": "cde3b451", + "id": "0b315303", "metadata": { "editable": true }, @@ -554,7 +554,7 @@ }, { "cell_type": "markdown", - "id": "b51b8235", + "id": "69576ac3", "metadata": { "editable": true }, @@ -566,7 +566,7 @@ }, { "cell_type": "markdown", - "id": "0b07fce2", + "id": "2613b8a5", "metadata": { "editable": true }, @@ -576,7 +576,7 @@ }, { "cell_type": "markdown", - "id": "859be638", + "id": "d41c3500", "metadata": { "editable": true }, @@ -588,7 +588,7 @@ }, { "cell_type": "markdown", - "id": "979f02d6", + "id": "1568b770", "metadata": { "editable": true }, @@ -598,7 +598,7 @@ }, { "cell_type": "markdown", - "id": "eeb775d7", + "id": "a1a0651f", "metadata": { "editable": true }, @@ -612,7 +612,7 @@ }, { "cell_type": "markdown", - "id": "be95becd", + "id": "86a7a43b", "metadata": { "editable": true }, @@ -630,7 +630,7 @@ }, { "cell_type": "markdown", - "id": "207b6d2d", + "id": "683b8af2", "metadata": { "editable": true }, @@ -641,7 +641,7 @@ }, { "cell_type": "markdown", - "id": "d462dc7e", + "id": "6137c505", "metadata": { "editable": true }, @@ -659,7 +659,7 @@ }, { "cell_type": "markdown", - "id": "982ab75a", + "id": "eb91fb37", "metadata": { "editable": true }, @@ -673,7 +673,7 @@ }, { "cell_type": "markdown", - "id": "f5e6967f", + "id": "aabbac3a", "metadata": { "editable": true }, @@ -685,7 +685,7 @@ }, { "cell_type": "markdown", - "id": "06812fcb", + "id": "4fe1f6a7", "metadata": { "editable": true }, @@ -697,7 +697,7 @@ }, { "cell_type": "markdown", - "id": "2637c4eb", + "id": "44c67471", "metadata": { "editable": true }, @@ -711,7 +711,7 @@ }, { "cell_type": "markdown", - "id": "b885a58d", + "id": "76d28174", "metadata": { "editable": true }, @@ -729,7 +729,7 @@ }, { "cell_type": "markdown", - "id": "0a6c3b4e", + "id": "e86171f0", "metadata": { "editable": true }, @@ -750,7 +750,7 @@ }, { "cell_type": "markdown", - "id": "4a5b6f5d", + "id": "680dd1f2", "metadata": { "editable": true }, @@ -764,7 +764,7 @@ }, { "cell_type": "markdown", - "id": "69cedbbf", + "id": "513afa38", "metadata": { "editable": true }, @@ -777,7 +777,7 @@ }, { "cell_type": "markdown", - "id": "9a06d7b5", + "id": "ae689c51", "metadata": { "editable": true }, @@ -790,7 +790,7 @@ { "cell_type": "code", "execution_count": 1, - "id": "3e1b8360", + "id": "f555270a", "metadata": { "collapsed": false, "editable": true @@ -820,7 +820,7 @@ }, { "cell_type": "markdown", - "id": "8e9c7169", + "id": "16b8d140", "metadata": { "editable": true }, @@ -834,7 +834,7 @@ }, { "cell_type": "markdown", - "id": "a9a1a7cd", + "id": "ad49e93d", "metadata": { "editable": true }, @@ -852,7 +852,7 @@ }, { "cell_type": "markdown", - "id": "15d2720f", + "id": "3eece618", "metadata": { "editable": true }, @@ -867,7 +867,7 @@ }, { "cell_type": "markdown", - "id": "19b996db", + "id": "d7d5881a", "metadata": { "editable": true }, @@ -885,7 +885,7 @@ }, { "cell_type": "markdown", - "id": "87a41d0b", + "id": "83b03221", "metadata": { "editable": true }, @@ -896,7 +896,7 @@ }, { "cell_type": "markdown", - "id": "c4beae12", + "id": "010f1781", "metadata": { "editable": true }, @@ -916,7 +916,7 @@ }, { "cell_type": "markdown", - "id": "1b2775b5", + "id": "f02aa278", "metadata": { "editable": true }, @@ -935,7 +935,7 @@ }, { "cell_type": "markdown", - "id": "24bd8f24", + "id": "b11ae77a", "metadata": { "editable": true }, @@ -955,7 +955,7 @@ }, { "cell_type": "markdown", - "id": "30a9e4e0", + "id": "f874de4b", "metadata": { "editable": true }, @@ -968,7 +968,7 @@ }, { "cell_type": "markdown", - "id": "32e9d669", + "id": "597579d6", "metadata": { "editable": true }, @@ -984,7 +984,7 @@ }, { "cell_type": "markdown", - "id": "1a7ee9e5", + "id": "4e055320", "metadata": { "editable": true }, @@ -1001,7 +1001,7 @@ }, { "cell_type": "markdown", - "id": "3947f32a", + "id": "a133e3b1", "metadata": { "editable": true }, @@ -1019,7 +1019,7 @@ }, { "cell_type": "markdown", - "id": "a8003937", + "id": "c14919a7", "metadata": { "editable": true }, @@ -1029,7 +1029,7 @@ }, { "cell_type": "markdown", - "id": "11aa8fc2", + "id": "5650b08e", "metadata": { "editable": true }, @@ -1045,7 +1045,7 @@ }, { "cell_type": "markdown", - "id": "86b86a37", + "id": "91006368", "metadata": { "editable": true }, @@ -1055,7 +1055,7 @@ }, { "cell_type": "markdown", - "id": "53038ae4", + "id": "c1b5a978", "metadata": { "editable": true }, @@ -1074,7 +1074,7 @@ { "cell_type": "code", "execution_count": 2, - "id": "75d656f0", + "id": "021490c8", "metadata": { "collapsed": false, "editable": true @@ -1114,7 +1114,7 @@ }, { "cell_type": "markdown", - "id": "a87f2c20", + "id": "b8006631", "metadata": { "editable": true }, @@ -1128,7 +1128,7 @@ }, { "cell_type": "markdown", - "id": "b6a4c5b3", + "id": "de188b6b", "metadata": { "editable": true }, @@ -1140,7 +1140,7 @@ }, { "cell_type": "markdown", - "id": "4c558e34", + "id": "ca5e4985", "metadata": { "editable": true }, @@ -1150,7 +1150,7 @@ }, { "cell_type": "markdown", - "id": "00bb19ef", + "id": "e3baf95c", "metadata": { "editable": true }, @@ -1162,7 +1162,7 @@ }, { "cell_type": "markdown", - "id": "25c286e3", + "id": "b1aff500", "metadata": { "editable": true }, @@ -1172,7 +1172,7 @@ }, { "cell_type": "markdown", - "id": "beb8376f", + "id": "0adf4a73", "metadata": { "editable": true }, @@ -1184,7 +1184,7 @@ }, { "cell_type": "markdown", - "id": "2b435e43", + "id": "943b3641", "metadata": { "editable": true }, @@ -1196,7 +1196,7 @@ }, { "cell_type": "markdown", - "id": "05fd9661", + "id": "d4a4565f", "metadata": { "editable": true }, @@ -1223,7 +1223,7 @@ }, { "cell_type": "markdown", - "id": "fafb0593", + "id": "90c5983f", "metadata": { "editable": true }, @@ -1235,7 +1235,7 @@ }, { "cell_type": "markdown", - "id": "7bf42d02", + "id": "b9dc706b", "metadata": { "editable": true }, @@ -1245,7 +1245,7 @@ }, { "cell_type": "markdown", - "id": "262180ae", + "id": "4e700e3b", "metadata": { "editable": true }, @@ -1271,7 +1271,7 @@ }, { "cell_type": "markdown", - "id": "93448f3b", + "id": "76a62fa2", "metadata": { "editable": true }, @@ -1283,7 +1283,7 @@ }, { "cell_type": "markdown", - "id": "fda74a57", + "id": "f70c1ce4", "metadata": { "editable": true }, @@ -1302,7 +1302,7 @@ }, { "cell_type": "markdown", - "id": "d3b4dbd8", + "id": "8ad25ed3", "metadata": { "editable": true }, @@ -1315,7 +1315,7 @@ }, { "cell_type": "markdown", - "id": "52f497d3", + "id": "5a56eff1", "metadata": { "editable": true }, @@ -1327,7 +1327,7 @@ }, { "cell_type": "markdown", - "id": "aaa4bc29", + "id": "2302c58c", "metadata": { "editable": true }, @@ -1348,7 +1348,7 @@ }, { "cell_type": "markdown", - "id": "84510c2c", + "id": "b24c6544", "metadata": { "editable": true }, @@ -1369,7 +1369,7 @@ }, { "cell_type": "markdown", - "id": "2738b23d", + "id": "1e4682a2", "metadata": { "editable": true }, @@ -1394,7 +1394,7 @@ }, { "cell_type": "markdown", - "id": "da148657", + "id": "317a594e", "metadata": { "editable": true }, @@ -1413,7 +1413,7 @@ }, { "cell_type": "markdown", - "id": "c0c9268b", + "id": "5bcbc7de", "metadata": { "editable": true }, @@ -1424,7 +1424,7 @@ { "cell_type": "code", "execution_count": 3, - "id": "80213e1a", + "id": "32c6d683", "metadata": { "collapsed": false, "editable": true @@ -1475,7 +1475,7 @@ }, { "cell_type": "markdown", - "id": "fef4cb65", + "id": "10efc6e2", "metadata": { "editable": true }, @@ -1486,7 +1486,7 @@ { "cell_type": "code", "execution_count": 4, - "id": "acd42baa", + "id": "d8b243fe", "metadata": { "collapsed": false, "editable": true @@ -1519,7 +1519,7 @@ }, { "cell_type": "markdown", - "id": "d5607150", + "id": "8231a073", "metadata": { "editable": true }, @@ -1530,7 +1530,7 @@ { "cell_type": "code", "execution_count": 5, - "id": "15f11301", + "id": "e2d8b11c", "metadata": { "collapsed": false, "editable": true @@ -1567,7 +1567,7 @@ }, { "cell_type": "markdown", - "id": "35f52da1", + "id": "1c599535", "metadata": { "editable": true }, @@ -1578,7 +1578,7 @@ { "cell_type": "code", "execution_count": 6, - "id": "d59b5af9", + "id": "c7718d55", "metadata": { "collapsed": false, "editable": true @@ -1605,7 +1605,7 @@ }, { "cell_type": "markdown", - "id": "9ce2618f", + "id": "b02c6452", "metadata": { "editable": true }, @@ -1616,7 +1616,7 @@ { "cell_type": "code", "execution_count": 7, - "id": "3ee7773f", + "id": "ba14f397", "metadata": { "collapsed": false, "editable": true @@ -1657,7 +1657,7 @@ }, { "cell_type": "markdown", - "id": "a1e6e893", + "id": "8f433eb8", "metadata": { "editable": true }, @@ -1673,7 +1673,7 @@ { "cell_type": "code", "execution_count": 8, - "id": "1ef1f0f4", + "id": "ab03b0e5", "metadata": { "collapsed": false, "editable": true @@ -1694,7 +1694,7 @@ }, { "cell_type": "markdown", - "id": "c14d36db", + "id": "bfba77ad", "metadata": { "editable": true }, @@ -1707,7 +1707,7 @@ { "cell_type": "code", "execution_count": 9, - "id": "51200962", + "id": "bcde11c7", "metadata": { "collapsed": false, "editable": true @@ -1732,7 +1732,7 @@ }, { "cell_type": "markdown", - "id": "6efce5c0", + "id": "cf5bc34e", "metadata": { "editable": true }, @@ -1747,7 +1747,7 @@ { "cell_type": "code", "execution_count": 10, - "id": "bbc0fe1d", + "id": "e0ded37d", "metadata": { "collapsed": false, "editable": true @@ -1768,7 +1768,7 @@ }, { "cell_type": "markdown", - "id": "4544c57b", + "id": "6eb288a2", "metadata": { "editable": true }, @@ -1778,7 +1778,7 @@ }, { "cell_type": "markdown", - "id": "59677754", + "id": "ff6eb6ef", "metadata": { "editable": true }, @@ -1797,7 +1797,7 @@ { "cell_type": "code", "execution_count": 11, - "id": "c7851eae", + "id": "a2b050dc", "metadata": { "collapsed": false, "editable": true @@ -1814,7 +1814,7 @@ }, { "cell_type": "markdown", - "id": "955527b2", + "id": "01af49fe", "metadata": { "editable": true }, @@ -1824,7 +1824,7 @@ }, { "cell_type": "markdown", - "id": "98a6c3da", + "id": "5293bdae", "metadata": { "editable": true }, @@ -1835,7 +1835,7 @@ { "cell_type": "code", "execution_count": 12, - "id": "09e274b7", + "id": "4adcb51c", "metadata": { "collapsed": false, "editable": true @@ -1852,7 +1852,7 @@ }, { "cell_type": "markdown", - "id": "75005c72", + "id": "60534f56", "metadata": { "editable": true }, @@ -1863,7 +1863,7 @@ { "cell_type": "code", "execution_count": 13, - "id": "095db594", + "id": "396b9a0a", "metadata": { "collapsed": false, "editable": true @@ -1881,6 +1881,3421 @@ "\n", "print(test_acc)" ] + }, + { + "cell_type": "markdown", + "id": "117079e0", + "metadata": { + "editable": true + }, + "source": [ + "## Building our own CNN code\n", + "\n", + "Here we present a flexible and readable python code for a CNN\n", + "implemented with NumPy. We will present the code, showcase how to use\n", + "the codebase and fit a CNN that yields a 99% accuracy on the 28x28\n", + "MNIST dataset within reasonable time.\n", + "\n", + "The CNN is compatible with all schedulers, cost functions and\n", + "activation functions discussed in constructing our neural network\n", + "codes.\n", + "\n", + " The CNN code consists of different types of Layer classes, including\n", + "Convolution2DLayer, Pooling2DLayer, FlattenLayer, FullyConnectedLayer\n", + "and OutputLayer, which can be added to the CNN object using the\n", + "interface of the CNN class. This allows you to easily construct your\n", + "own CNN, as well as allowing you to get used to an interface similar\n", + "to that of TensorFlow which is used for real world applications. \n", + "\n", + "Another important feature of this code is that it throws errors if\n", + "unreasonable decisions are made (for example using a kernel that is\n", + "larger than the image, not using a FlattenLayer, etc), and provides\n", + "the user with an informative error message." + ] + }, + { + "cell_type": "markdown", + "id": "4387296c", + "metadata": { + "editable": true + }, + "source": [ + "### List of contents:\n", + "\n", + "1. Schedulers\n", + "\n", + "2. Activation Functions\n", + "\n", + "3. Cost Functions \n", + "\n", + "4. Convolution\n", + "\n", + "5. Layers\n", + "\n", + "6. CNN \n", + "\n", + "7. Some final remarks" + ] + }, + { + "cell_type": "markdown", + "id": "6051bce6", + "metadata": { + "editable": true + }, + "source": [ + "### Schedulers\n", + "\n", + "The code below shows object oriented implementations of the Constant,\n", + "Momentum, Adagrad, AdagradMomentum, RMS prop and Adam schedulers. All\n", + "of the classes belong to the shared abstract Scheduler class, and\n", + "share the update_change() and reset() methods allowing for any of the\n", + "schedulers to be seamlessly used during the training stage, as will\n", + "later be shown in the fit() method of the neural\n", + "network. Update_change() only has one parameter, the gradient\n", + "($\\delta^{l}_{j}a^{l-1}_k$), and returns the change which will be\n", + "subtracted from the weights. The reset() function takes no parameters,\n", + "and resets the desired variables. For Constant and Momentum, reset\n", + "does nothing." + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "id": "b687d5af", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "import autograd.numpy as np\n", + "\n", + "class Scheduler:\n", + " \"\"\"\n", + " Abstract class for Schedulers\n", + " \"\"\"\n", + "\n", + " def __init__(self, eta):\n", + " self.eta = eta\n", + "\n", + " # should be overwritten\n", + " def update_change(self, gradient):\n", + " raise NotImplementedError\n", + "\n", + " # overwritten if needed\n", + " def reset(self):\n", + " pass\n", + "\n", + "\n", + "class Constant(Scheduler):\n", + " def __init__(self, eta):\n", + " super().__init__(eta)\n", + "\n", + " def update_change(self, gradient):\n", + " return self.eta * gradient\n", + " \n", + " def reset(self):\n", + " pass\n", + "\n", + "\n", + "class Momentum(Scheduler):\n", + " def __init__(self, eta: float, momentum: float):\n", + " super().__init__(eta)\n", + " self.momentum = momentum\n", + " self.change = 0\n", + "\n", + " def update_change(self, gradient):\n", + " self.change = self.momentum * self.change + self.eta * gradient\n", + " return self.change\n", + "\n", + " def reset(self):\n", + " pass\n", + "\n", + "\n", + "class Adagrad(Scheduler):\n", + " def __init__(self, eta):\n", + " super().__init__(eta)\n", + " self.G_t = None\n", + "\n", + " def update_change(self, gradient):\n", + " delta = 1e-8 # avoid division ny zero\n", + "\n", + " if self.G_t is None:\n", + " self.G_t = np.zeros((gradient.shape[0], gradient.shape[0]))\n", + "\n", + " self.G_t += gradient @ gradient.T\n", + "\n", + " G_t_inverse = 1 / (\n", + " delta + np.sqrt(np.reshape(np.diagonal(self.G_t), (self.G_t.shape[0], 1)))\n", + " )\n", + " return self.eta * gradient * G_t_inverse\n", + "\n", + " def reset(self):\n", + " self.G_t = None\n", + "\n", + "\n", + "class AdagradMomentum(Scheduler):\n", + " def __init__(self, eta, momentum):\n", + " super().__init__(eta)\n", + " self.G_t = None\n", + " self.momentum = momentum\n", + " self.change = 0\n", + "\n", + " def update_change(self, gradient):\n", + " delta = 1e-8 # avoid division ny zero\n", + "\n", + " if self.G_t is None:\n", + " self.G_t = np.zeros((gradient.shape[0], gradient.shape[0]))\n", + "\n", + " self.G_t += gradient @ gradient.T\n", + "\n", + " G_t_inverse = 1 / (\n", + " delta + np.sqrt(np.reshape(np.diagonal(self.G_t), (self.G_t.shape[0], 1)))\n", + " )\n", + " self.change = self.change * self.momentum + self.eta * gradient * G_t_inverse\n", + " return self.change\n", + "\n", + " def reset(self):\n", + " self.G_t = None\n", + "\n", + "\n", + "class RMS_prop(Scheduler):\n", + " def __init__(self, eta, rho):\n", + " super().__init__(eta)\n", + " self.rho = rho\n", + " self.second = 0.0\n", + "\n", + " def update_change(self, gradient):\n", + " delta = 1e-8 # avoid division ny zero\n", + " self.second = self.rho * self.second + (1 - self.rho) * gradient * gradient\n", + " return self.eta * gradient / (np.sqrt(self.second + delta))\n", + "\n", + " def reset(self):\n", + " self.second = 0.0\n", + "\n", + "\n", + "class Adam(Scheduler):\n", + " def __init__(self, eta, rho, rho2):\n", + " super().__init__(eta)\n", + " self.rho = rho\n", + " self.rho2 = rho2\n", + " self.moment = 0\n", + " self.second = 0\n", + " self.n_epochs = 1\n", + "\n", + " def update_change(self, gradient):\n", + " delta = 1e-8 # avoid division ny zero\n", + "\n", + " self.moment = self.rho * self.moment + (1 - self.rho) * gradient\n", + " self.second = self.rho2 * self.second + (1 - self.rho2) * gradient * gradient\n", + "\n", + " moment_corrected = self.moment / (1 - self.rho**self.n_epochs)\n", + " second_corrected = self.second / (1 - self.rho2**self.n_epochs)\n", + "\n", + " return self.eta * moment_corrected / (np.sqrt(second_corrected + delta))\n", + "\n", + " def reset(self):\n", + " self.n_epochs += 1\n", + " self.moment = 0\n", + " self.second = 0" + ] + }, + { + "cell_type": "markdown", + "id": "ab9955ee", + "metadata": { + "editable": true + }, + "source": [ + "### Usage of schedulers\n", + "\n", + "To initalize a scheduler, simply create the object and pass in the necessary parameters such as the learning rate and the momentum as shown below. As the Scheduler class is an abstract class it should not called directly, and will raise an error upon usage." + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "id": "99c69ccb", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "momentum_scheduler = Momentum(eta=1e-3, momentum=0.9)\n", + "adam_scheduler = Adam(eta=1e-3, rho=0.9, rho2=0.999)" + ] + }, + { + "cell_type": "markdown", + "id": "02508975", + "metadata": { + "editable": true + }, + "source": [ + "Here is a small example for how a segment of code using schedulers could look. Switching out the schedulers is simple." + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "id": "5ac22cfd", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "weights = np.ones((3,3))\n", + "print(f\"Before scheduler:\\n{weights=}\")\n", + "\n", + "epochs = 10\n", + "for e in range(epochs):\n", + " gradient = np.random.rand(3, 3)\n", + " change = adam_scheduler.update_change(gradient)\n", + " weights = weights - change\n", + " adam_scheduler.reset()\n", + "\n", + "print(f\"\\nAfter scheduler:\\n{weights=}\")" + ] + }, + { + "cell_type": "markdown", + "id": "233c256f", + "metadata": { + "editable": true + }, + "source": [ + "### Cost functions\n", + "\n", + "In this section we will quickly look at cost functions that can be\n", + "used when creating the neural network. Every cost function takes the\n", + "target vector as its parameter, and returns a function valued only at\n", + "X such that it may easily be differentiated." + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "id": "27a2af46", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "def CostOLS(target):\n", + " \"\"\"\n", + " Return OLS function valued only at X, so\n", + " that it may be easily differentiated\n", + " \"\"\"\n", + "\n", + " def func(X):\n", + " return (1.0 / target.shape[0]) * np.sum((target - X) ** 2)\n", + "\n", + " return func\n", + "\n", + "\n", + "def CostLogReg(target):\n", + " \"\"\"\n", + " Return Logistic Regression cost function\n", + " valued only at X, so that it may be easily differentiated\n", + " \"\"\"\n", + "\n", + " def func(X):\n", + " return -(1.0 / target.shape[0]) * np.sum(\n", + " (target * np.log(X + 10e-10)) + ((1 - target) * np.log(1 - X + 10e-10))\n", + " )\n", + "\n", + " return func\n", + "\n", + "\n", + "def CostCrossEntropy(target):\n", + " \"\"\"\n", + " Return cross entropy cost function valued only at X, so\n", + " that it may be easily differentiated\n", + " \"\"\"\n", + " \n", + " def func(X):\n", + " return -(1.0 / target.size) * np.sum(target * np.log(X + 10e-10))\n", + "\n", + " return func" + ] + }, + { + "cell_type": "markdown", + "id": "48ae2ab4", + "metadata": { + "editable": true + }, + "source": [ + "### Usage of cost functions\n", + "\n", + "Below we will provide a short example of how these cost function may\n", + "be used to obtain results if you wish to test them out on your own\n", + "using AutoGrad's automatic differentiation." + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "id": "99302d7b", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "from autograd import grad\n", + "\n", + "target = np.array([[1, 2, 3]]).T\n", + "a = np.array([[4, 5, 6]]).T\n", + "\n", + "cost_func = CostCrossEntropy\n", + "cost_func_derivative = grad(cost_func(target))\n", + "\n", + "valued_at_a = cost_func_derivative(a)\n", + "print(f\"Derivative of cost function {cost_func.__name__} valued at a:\\n{valued_at_a}\")" + ] + }, + { + "cell_type": "markdown", + "id": "beb76a0e", + "metadata": { + "editable": true + }, + "source": [ + "### Activation functions\n", + "\n", + "Finally, before we look at the layers that make up the neural network,\n", + "we will look at the activation functions which can be specified\n", + "between the hidden layers and as the output function. Each function\n", + "can be valued for any given vector or matrix X, and can be\n", + "differentiated via derivate()." + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "id": "057b4aac", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "\n", + "import autograd.numpy as np\n", + "from autograd import elementwise_grad\n", + "\n", + "def identity(X):\n", + " return X\n", + "\n", + "\n", + "def sigmoid(X):\n", + " try:\n", + " return 1.0 / (1 + np.exp(-X))\n", + " except FloatingPointError:\n", + " return np.where(X > np.zeros(X.shape), np.ones(X.shape), np.zeros(X.shape))\n", + "\n", + "\n", + "def softmax(X):\n", + " X = X - np.max(X, axis=-1, keepdims=True)\n", + " delta = 10e-10\n", + " return np.exp(X) / (np.sum(np.exp(X), axis=-1, keepdims=True) + delta)\n", + "\n", + "\n", + "def RELU(X):\n", + " return np.where(X > np.zeros(X.shape), X, np.zeros(X.shape))\n", + "\n", + "\n", + "def LRELU(X):\n", + " delta = 10e-4\n", + " return np.where(X > np.zeros(X.shape), X, delta * X)\n", + "\n", + "\n", + "def derivate(func):\n", + " if func.__name__ == \"RELU\":\n", + "\n", + " def func(X):\n", + " return np.where(X > 0, 1, 0)\n", + "\n", + " return func\n", + "\n", + " elif func.__name__ == \"LRELU\":\n", + "\n", + " def func(X):\n", + " delta = 10e-4\n", + " return np.where(X > 0, 1, delta)\n", + "\n", + " return func\n", + "\n", + " else:\n", + " return elementwise_grad(func)" + ] + }, + { + "cell_type": "markdown", + "id": "e5e39beb", + "metadata": { + "editable": true + }, + "source": [ + "### Usage of activation functions\n", + "\n", + "Below we present a short demonstration of how to use an activation\n", + "function. The derivative of the activation function will be important\n", + "when calculating the output delta term during backpropagation. Note\n", + "that derivate() can also be used for cost functions for a more\n", + "generalized approach." + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "id": "dca3e6a9", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "z = np.array([[4, 5, 6]]).T\n", + "print(f\"Input to activation function:\\n{z}\")\n", + "\n", + "act_func = sigmoid\n", + "a = act_func(z)\n", + "print(f\"\\nOutput from {act_func.__name__} activation function:\\n{a}\")\n", + "\n", + "act_func_derivative = derivate(act_func)\n", + "valued_at_z = act_func_derivative(a)\n", + "print(f\"\\nDerivative of {act_func.__name__} activation function valued at z:\\n{valued_at_z}\")" + ] + }, + { + "cell_type": "markdown", + "id": "41430661", + "metadata": { + "editable": true + }, + "source": [ + "### Convolution\n", + "\n", + "In order to construct a convolutional neural network (CNN), it is\n", + "crucial to comprehend the fundamental principles of convolution and\n", + "how it aids in extracting information from images. Convolution, at its\n", + "core, is merely a mathematical operation between two functions that\n", + "yields another function. It is represented by an integral between two\n", + "functions, which is typically expressed as:" + ] + }, + { + "cell_type": "markdown", + "id": "815920b5", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "(f \\ast g)(t):=\\int_{-\\infty}^{\\infty} f(\\tau) g(t-\\tau) d \\tau.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "826ae26d", + "metadata": { + "editable": true + }, + "source": [ + "Here, f and g are the two functions on which we want to perform an\n", + "operation. The outcome of the convolution operation is represented by\n", + "$(f \\ast g)$, and it is derived by sliding the function g over f and\n", + "computing the integral of their product at each position. If both\n", + "functions are continuous, convolution takes the form shown\n", + "above. However, if we discretize both f and g, the convolution\n", + "operation will take the form of a sum between the elements of f and g:" + ] + }, + { + "cell_type": "markdown", + "id": "ae984b90", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "(f \\ast g)[n]=\\sum_{m=0}^{n-1} f[m] g[n-m].\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "c74ad806", + "metadata": { + "editable": true + }, + "source": [ + "The key idea we utilize to extract the information contained in an\n", + "image is to slide an $m \\times n$ matrix *g* over an $m \\times n$\n", + "matrix *f*. In our case, *f* represents the image, while *g*\n", + "represents the kernel, oftentimes called a filter. However, since our\n", + "convolution will be a two-dimensional variant, we need to extend our\n", + "mathematical formula with an additional summation:" + ] + }, + { + "cell_type": "markdown", + "id": "91b53f99", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "(f \\ast g)[i, j]\\sum_{m=0}^{M-1}\\sum_{n=0}^{N-1} f[m,n] g[i-m, j-n].\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "404c8cac", + "metadata": { + "editable": true + }, + "source": [ + "It is imperative to note that the size of the kernel g is\n", + "significantly smaller than the size of the input image f, thereby\n", + "reducing the amount of computation necessary for feature\n", + "extraction. Furthermore, the kernel is usually a trainable parameter\n", + "in a convolutional neural network, allowing the network to learn\n", + "appropriate kernels for specific tasks.\n", + "\n", + "To give you an example of how 2D convolution works in practice,\n", + "suppose we have an image *f* of dimension $6 \\times 6$" + ] + }, + { + "cell_type": "markdown", + "id": "dcbbd719", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "f = \\begin{bmatrix}\n", + "4 & 1 & 2 & 9 & 8 & 6 \\\\\n", + "9 & 5 & 9 & 5 & 8 & 5 \\\\\n", + "1 & 5 & 9 & 7 & 6 & 4 \\\\\n", + "2 & 9 & 8 & 3 & 7 & 1 \\\\\n", + "8 & 1 & 6 & 4 & 2 & 2 \\\\\n", + "1 & 0 & 5 & 7 & 8 & 2 \\\\\n", + "\\end{bmatrix}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "823269cb", + "metadata": { + "editable": true + }, + "source": [ + "and a $3 \\times 3$ kernel *g* called a low-pass filter. Note that the\n", + "kernel is usually rotated by 180 degrees during convolution, however\n", + "this has no effect on this kernel." + ] + }, + { + "cell_type": "markdown", + "id": "c251f583", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "g = \\frac{1}{9}\n", + "\\begin{bmatrix}\n", + "1 & 1 & 1 \\\\\n", + "1 & 1 & 1 \\\\\n", + "1 & 1 & 1 \\\\\n", + "\\end{bmatrix}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "41218fa0", + "metadata": { + "editable": true + }, + "source": [ + "In order to filter the image, we have to extract a $3 \\times 3$\n", + "element from the upper left corner of *f*, and perform element-wise\n", + "multiplication of the extracted image pixels with the elements of the\n", + "kernel *g*:" + ] + }, + { + "cell_type": "markdown", + "id": "fd6333be", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\begin{bmatrix}\n", + "4 & 1 & 2 \\\\\n", + "9 & 5 & 9 \\\\\n", + "1 & 5 & 9 \\\\\n", + "\\end{bmatrix}\n", + "\\cdot\n", + "\\begin{bmatrix}\n", + "\\frac{1}{9} & \\frac{1}{9} & \\frac{1}{9} \\\\\n", + "\\frac{1}{9} & \\frac{1}{9} & \\frac{1}{9} \\\\\n", + "\\frac{1}{9} & \\frac{1}{9} & \\frac{1}{9} \\\\\n", + "\\end{bmatrix}\n", + "=\n", + "\\begin{bmatrix}\n", + "\\frac{4}{9} & \\frac{1}{9} & \\frac{2}{9} \\\\\n", + "\\frac{9}{9} & \\frac{5}{9} & \\frac{9}{9} \\\\\n", + "\\frac{1}{9} & \\frac{5}{9} & \\frac{9}{9} \\\\\n", + "\\end {bmatrix}\n", + "= \\textbf{A}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "990703e2", + "metadata": { + "editable": true + }, + "source": [ + "Then, following the multiplication, we summarize all the elements of the resulting matrix A:" + ] + }, + { + "cell_type": "markdown", + "id": "9f2e335f", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "(f \\ast g)[0, 0]= \\sum_{i=0}^{2} \\sum_{j=0}^{2} a_{i,j} = 5\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "7e6ceca6", + "metadata": { + "editable": true + }, + "source": [ + "Which corresponds to the first element of the filtered image $(f \\ast g)$.\n", + "\n", + "Here we use a stride of 1, a parameter denoted *s* which describes how\n", + "many indexes we move the kernel *g* to the right before repeating the\n", + "calculations above for the next $3 \\times 3$ element of the image\n", + "*f*. It is usually presumed that *s*=1, however, larger values for *s*\n", + "can be used to reduce the dimentionality of the filtered image such\n", + "that the convolution operation is more computationally efficient. In\n", + "the context of a convolutional neural network, this will become very\n", + "useful.\n", + "\n", + "The full result of the convolution is:" + ] + }, + { + "cell_type": "markdown", + "id": "023394e0", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "(f \\ast g) =\n", + "\\begin{bmatrix}\n", + "5 & 5.78 & 7 & 6.44 \\\\\n", + "6.33 & 6.67 & 6.89 & 5.11 \\\\\n", + "5.44 & 5.78 & 5.78 & 4 \\\\\n", + "4.44 & 4.78 & 5.56 & 4 \\\\\n", + "\\end{bmatrix}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "9a974887", + "metadata": { + "editable": true + }, + "source": [ + "The result is markedly smaller in shape than the original image. This occurs when using convolution without first padding the image with additional columns and rows, allowing us to keep the original image shape after sliding the kernel over the image.\n", + "How many rows and columns we wish to pad the image with depends strictly on the shape of the kernel, as we wish to pad the image with *r* additional rows and *c* additional columns." + ] + }, + { + "cell_type": "markdown", + "id": "d0fcdb54", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "r =\\lfloor \\frac{kernel\\ height}{2} \\rfloor \\cdot 2 \\\\\n", + "c =\\lfloor \\frac{kernel\\ width}{2} \\rfloor \\cdot 2\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "70eeff71", + "metadata": { + "editable": true + }, + "source": [ + "Note the notation $\\lfloor \\frac{kernel width}{2} \\rfloor$ means that\n", + "we floor the result of the division, meaning we round down to a whole\n", + "number in case $\\frac{kernel width}{2}$ results in a floating point\n", + "number.\n", + "\n", + "Using those simple equations, we find out by how much we have to\n", + "extend the dimensions of the original image. Before proceeding,\n", + "however, we might ask what we shall fill the additional rows and\n", + "columns with? One of the most common approaches to padding is\n", + "zero-padding, which as the name suggest, involves filling the rows and\n", + "columns with zeros. This is the approach that we will be using for\n", + "this demonstration. If we apply this padding to out original $6 \\times 6$\n", + "image, the result will be an $8 \\times 8$ image as the kernel has a width and\n", + "height of 3. Note that the original image is encapsuled by the\n", + "zero-padded rows and columns:" + ] + }, + { + "cell_type": "markdown", + "id": "da8af146", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\begin{bmatrix}\n", + "0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\\\\n", + "0 & 4 & 1 & 2 & 9 & 8 & 6 & 0 \\\\\n", + "0 & 9 & 5 & 9 & 5 & 8 & 5 & 0 \\\\\n", + "0 & 1 & 5 & 9 & 7 & 6 & 4 & 0 \\\\\n", + "0 & 2 & 9 & 8 & 3 & 7 & 1 & 0 \\\\\n", + "0 & 8 & 1 & 6 & 4 & 2 & 2 & 0 \\\\\n", + "0 & 1 & 0 & 5 & 7 & 8 & 2 & 0 \\\\\n", + "0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\\\\n", + "\n", + "\\end{bmatrix}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "ae69a9ad", + "metadata": { + "editable": true + }, + "source": [ + "Below we have provided code that demonstrates padding and convolution. As you will see when we run the code, the size of the image will remain unchanged when using padding.~" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "id": "e6bf3cc7", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "import numpy as np\n", + "\n", + "def padding(image, kernel):\n", + " # calculate r and c\n", + " r = (kernel.shape[0] // 2) * 2\n", + " c = (kernel.shape[1] // 2) * 2\n", + " \n", + " # padded image dimensions\n", + " padded_height = image.shape[0] + r\n", + " padded_width = image.shape[1] + c\n", + " \n", + " # for more readable code\n", + " k_half_height = kernel.shape[0] // 2\n", + " k_half_width = kernel.shape[1] // 2\n", + "\n", + " # zero matrix with padded dimensions\n", + " padded_img = np.zeros((padded_height, padded_width))\n", + "\n", + " # place image into zero matrix\n", + " padded_img[k_half_height : padded_height - k_half_height,\n", + " k_half_width : padded_width - k_half_width] = image[:, :]\n", + "\n", + " return padded_img\n", + "\n", + "def convolve(original_image, padded_image, kernel, stride=1):\n", + " # rotate kernel by 180 degrees\n", + " kernel = np.rot90(np.rot90(kernel))\n", + "\n", + " # note that kernel height // 2 is written as 'm'\n", + " # and kernel width // 2 as 'n' in the mathematical notation\n", + " m = kernel.shape[0] // 2\n", + " n = kernel.shape[1] // 2\n", + " \n", + " r = (kernel.shape[0] // 2) * 2\n", + " c = (kernel.shape[1] // 2) * 2\n", + " \n", + " # initialize output array\n", + " convolved_image = np.zeros(original_image.shape)\n", + " image_height = original_image.shape[0]\n", + " image_width = original_image.shape[1]\n", + "\n", + " # the convolution\n", + " for i in range(m, image_height + m, stride):\n", + " for j in range(n, image_width + n, stride):\n", + " convolved_image[i-m, j-n] = np.sum(\n", + " padded_image[i : i + m, j : j + n]\n", + " * kernel\n", + " )\n", + " \n", + " return convolved_image\n", + "\n", + "def convolve(image, kernel, stride=1):\n", + " for i in range(2):\n", + " kernel = np.rot90(kernel)\n", + "\n", + " k_half_height = kernel.shape[0] // 2\n", + " k_half_width = kernel.shape[0] // 2\n", + "\n", + " conv_image = np.zeros(image.shape)\n", + " pad_image = padding(image, kernel)\n", + "\n", + " for i in range(k_half_height, conv_image.shape[0] + k_half_height, stride):\n", + " for j in range(k_half_width, conv_image.shape[1] + k_half_width, stride):\n", + " conv_image[i - k_half_height, j - k_half_width] = np.sum(\n", + " pad_image[\n", + " i - k_half_height : i + k_half_height + 1, j - k_half_width : j + k_half_width + 1\n", + " ]\n", + " * kernel\n", + " )\n", + "\n", + " return conv_image" + ] + }, + { + "cell_type": "markdown", + "id": "2f4eeaae", + "metadata": { + "editable": true + }, + "source": [ + "Fun fact: When filtering images, you will see that convolution involves rotating the kernel by 180 degrees. \n", + "However, this is not the case when applying convolution in a CNN, where the same operation not rotated by 180 degrees is called \n", + "cross-correlation." + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "id": "97f47d4f", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "\n", + "original_image = np.array([[4, 1, 2, 9, 8, 6],\n", + " [9, 5, 9, 5, 8, 5],\n", + " [1, 5, 9, 7, 6, 4],\n", + " [2, 9, 8, 3, 7, 1],\n", + " [8, 1, 6, 4, 2, 2],\n", + " [1, 0, 5, 7, 8, 2]])\n", + "\n", + "kernel = (1/9)*np.ones((3,3))\n", + "\n", + "print(f\"{original_image.shape=}\")\n", + "\n", + "# note that convolve() performs padding\n", + "convolved_image = convolve(original_image, kernel, stride=1)\n", + "\n", + "print(f\"{convolved_image.shape=}\")" + ] + }, + { + "cell_type": "markdown", + "id": "31222f43", + "metadata": { + "editable": true + }, + "source": [ + "As you can see, the resulting image is of the same size as the\n", + "original image. To round of our demonstration of convolution, we will\n", + "present the results of convolution using commonly used kernels. In a\n", + "CNN, the values of the kernels are randomly initialized, and then\n", + "learned during training. These kernels will extract information\n", + "regarding the picture, such as for example the edge detection filter\n", + "demonstrated below extracts the edges present in the picture. Of\n", + "course, there is no guarantee that the CNN will learn an edge\n", + "detection filter, but this should provide some intuiton as to how the\n", + "CNN is able to use kernels to make better predictions than a regular\n", + "feed forward neural network." + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "id": "430389e0", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "# Now an example using a real image and first a gaussian low-pass filter and then a sobel filter\n", + "import numpy as np\n", + "import imageio.v3 as imageio\n", + "import matplotlib.pyplot as plt\n", + "import time\n", + "\n", + "def generate_gauss_mask(sigma, K=1):\n", + " side = np.ceil(1 + 8 * sigma)\n", + " y, x = np.mgrid[-side // 2 + 1 : (side // 2) + 1, -side // 2 + 1 : (side // 2) + 1]\n", + " ker_coef = K / (2 * np.pi * sigma**2)\n", + " g = np.exp(-((x**2 + y**2) / (2.0 * sigma**2)))\n", + "\n", + " return g, ker_coef\n", + "\n", + "\n", + "img_path = \"../data/IMG-2167.JPG\"\n", + "image_of_cute_dog = imageio.imread(img_path, mode='L')\n", + "\n", + "plt.imshow(image_of_cute_dog, cmap=\"gray\", vmin=0, vmax=255, aspect=\"auto\")\n", + "plt.title(\"Original image\")\n", + "plt.show()\n", + "\n", + "gauss, kernel = generate_gauss_mask(sigma=6)\n", + "gauss_kernel = gauss*kernel\n", + "\n", + "filtered_image = convolve(image_of_cute_dog, gauss_kernel)\n", + "plt.imshow(filtered_image, cmap=\"gray\", vmin=0, vmax=255, aspect=\"auto\")\n", + "plt.title(\"Result of convolution with gauss kernel (blurring filter)\")\n", + "plt.show()\n", + "\n", + "sobel_kernel = np.array([[1, 2, 1],\n", + " [0, 0, 0], \n", + " [-1, -2, -1]])\n", + "\n", + "filtered_image = convolve(image_of_cute_dog, sobel_kernel)\n", + "\n", + "plt.imshow(filtered_image, cmap=\"gray\", vmin=0, vmax=255, aspect=\"auto\")\n", + "plt.title(\"Result of convolution with sobel kernel (edge detection filter)\")\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "5df25adc", + "metadata": { + "editable": true + }, + "source": [ + "### Layers\n", + "\n", + "The code below initialises global variables for readability and\n", + "describes the abstract class Layers. This is not important in order to\n", + "understand the CNN, but is benefitial for organizing the code neatly." + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "id": "96ef1a9d", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "import math\n", + "import autograd.numpy as np\n", + "from copy import deepcopy, copy\n", + "from autograd import grad\n", + "from typing import Callable\n", + "\n", + "# global variables for index readability\n", + "input_index = 0\n", + "node_index = 1\n", + "bias_index = 1\n", + "input_channel_index = 1\n", + "feature_maps_index = 1\n", + "height_index = 2\n", + "width_index = 3\n", + "kernel_feature_maps_index = 1\n", + "kernel_input_channels_index = 0\n", + "\n", + "\n", + "class Layer:\n", + " def __init__(self, seed):\n", + " self.seed = seed\n", + "\n", + " def _feedforward(self):\n", + " raise NotImplementedError\n", + "\n", + " def _backpropagate(self):\n", + " raise NotImplementedError\n", + "\n", + " def _reset_weights(self, previous_nodes):\n", + " raise NotImplementedError" + ] + }, + { + "cell_type": "markdown", + "id": "7b3820e4", + "metadata": { + "editable": true + }, + "source": [ + "### Convolution2DLayer: convolution in a hidden layer\n", + "\n", + "After establishing the foundational understanding of applying\n", + "convolution to spatial data, let us delve into the intricate workings\n", + "of a convolutional layer in a Convolutional Neural Network (CNN). The\n", + "primary function of convolution, as previously discussed, is to\n", + "extract pertinent information from images while simultaneously\n", + "decreasing the scale of our data. To initiate the image processing, we\n", + "shall begin by partitioning the images into color channels (unless the\n", + "image is grayscale), comprising three primary colors: red, green, and\n", + "blue. We will subsequently utilize trainable kernels to construct a\n", + "higher-dimensional encoding of each channel called feature\n", + "maps. Successive layers will receive these feature maps as inputs,\n", + "generating further encodings, albeit with reduced dimensions. The term\n", + "trainable kernels denotes the initialization of pre-defined\n", + "kernel-shaped weights, which we will then train via backpropagation,\n", + "similar to how weights are trained in a Feedforward Neural Network.\n", + "\n", + "To ensure seamless integration between our implementation of the\n", + "convolutional layer and popular machine learning frameworks like\n", + "Tensorflow (Keras) and PyTorch, we have adopted a design pattern that\n", + "mirrors the construction of models using these APIs. This involves\n", + "implementing our convolutional layer as a Python class or object,\n", + "which allows for a more modular and flexible approach to building\n", + "neural networks. By structuring our code in this way, users can easily\n", + "incorporate our implementation into their existing machine learning\n", + "pipelines without having to make significant changes to their\n", + "codebase. Additionally, this design pattern promotes code reusability\n", + "and makes it easier to maintain and update our convolutional layer\n", + "implementation over time.\n", + "\n", + "Note that the Convolution2DLayer takes in an activation function as a parameter, as it also performs non-linearity." + ] + }, + { + "cell_type": "code", + "execution_count": 25, + "id": "8775922b", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "class Convolution2DLayer(Layer):\n", + " def __init__(\n", + " self,\n", + " input_channels,\n", + " feature_maps,\n", + " kernel_height,\n", + " kernel_width,\n", + " v_stride,\n", + " h_stride,\n", + " pad,\n", + " act_func: Callable,\n", + " seed=None,\n", + " reset_weights_independently=True,\n", + " ):\n", + " super().__init__(seed)\n", + " self.input_channels = input_channels\n", + " self.feature_maps = feature_maps\n", + " self.kernel_height = kernel_height\n", + " self.kernel_width = kernel_width\n", + " self.v_stride = v_stride\n", + " self.h_stride = h_stride\n", + " self.pad = pad\n", + " self.act_func = act_func\n", + "\n", + " # such that the layer can be used on its own\n", + " # outside of the CNN module\n", + " if reset_weights_independently == True:\n", + " self._reset_weights_independently()\n", + "\n", + " def _feedforward(self, X_batch):\n", + " # note that the shape of X_batch = [inputs, input_maps, img_height, img_width]\n", + "\n", + " # pad the input batch\n", + " X_batch_padded = self._padding(X_batch)\n", + "\n", + " # calculate height_index and width_index after stride\n", + " strided_height = int(np.ceil(X_batch.shape[height_index] / self.v_stride))\n", + " strided_width = int(np.ceil(X_batch.shape[width_index] / self.h_stride))\n", + "\n", + " # create output array\n", + " output = np.ndarray(\n", + " (\n", + " X_batch.shape[input_index],\n", + " self.feature_maps,\n", + " strided_height,\n", + " strided_width,\n", + " )\n", + " )\n", + "\n", + " # save input and output for backpropagation\n", + " self.X_batch_feedforward = X_batch\n", + " self.output_shape = output.shape\n", + "\n", + " # checking for errors, no need to look here :)\n", + " self._check_for_errors()\n", + "\n", + " # convolve input with kernel\n", + " for img in range(X_batch.shape[input_index]):\n", + " for chin in range(self.input_channels):\n", + " for fmap in range(self.feature_maps):\n", + " out_h = 0\n", + " for h in range(0, X_batch.shape[height_index], self.v_stride):\n", + " out_w = 0\n", + " for w in range(0, X_batch.shape[width_index], self.h_stride):\n", + " output[img, fmap, out_h, out_w] = np.sum(\n", + " X_batch_padded[\n", + " img,\n", + " chin,\n", + " h : h + self.kernel_height,\n", + " w : w + self.kernel_width,\n", + " ]\n", + " * self.kernel[chin, fmap, :, :]\n", + " )\n", + " out_w += 1\n", + " out_h += 1\n", + "\n", + " # Pay attention to the fact that we're not rotating the kernel by 180 degrees when filtering the image in\n", + " # the convolutional layer, as convolution in terms of Machine Learning is a procedure known as cross-correlation\n", + " # in image processing and signal processing\n", + "\n", + " # return a\n", + " return self.act_func(output / (self.kernel_height))\n", + "\n", + " def _backpropagate(self, delta_term_next):\n", + " # intiate matrices\n", + " delta_term = np.zeros((self.X_batch_feedforward.shape))\n", + " gradient_kernel = np.zeros((self.kernel.shape))\n", + "\n", + " # pad input for convolution\n", + " X_batch_padded = self._padding(self.X_batch_feedforward)\n", + "\n", + " # Since an activation function is used at the output of the convolution layer, its derivative\n", + " # has to be accounted for in the backpropagation -> as if ReLU was a layer on its own.\n", + " act_derivative = derivate(self.act_func)\n", + " delta_term_next = act_derivative(delta_term_next)\n", + "\n", + " # fill in 0's for values removed by vertical stride in feedforward\n", + " if self.v_stride > 1:\n", + " v_ind = 1\n", + " for i in range(delta_term_next.shape[height_index]):\n", + " for j in range(self.v_stride - 1):\n", + " delta_term_next = np.insert(\n", + " delta_term_next, v_ind, 0, axis=height_index\n", + " )\n", + " v_ind += self.v_stride\n", + "\n", + " # fill in 0's for values removed by horizontal stride in feedforward\n", + " if self.h_stride > 1:\n", + " h_ind = 1\n", + " for i in range(delta_term_next.shape[width_index]):\n", + " for k in range(self.h_stride - 1):\n", + " delta_term_next = np.insert(\n", + " delta_term_next, h_ind, 0, axis=width_index\n", + " )\n", + " h_ind += self.h_stride\n", + "\n", + " # crops out 0-rows and 0-columns\n", + " delta_term_next = delta_term_next[\n", + " :,\n", + " :,\n", + " : self.X_batch_feedforward.shape[height_index],\n", + " : self.X_batch_feedforward.shape[width_index],\n", + " ]\n", + "\n", + " # the gradient received from the next layer also needs to be padded\n", + " delta_term_next = self._padding(delta_term_next)\n", + "\n", + " # calculate delta term by convolving next delta term with kernel\n", + " for img in range(self.X_batch_feedforward.shape[input_index]):\n", + " for chin in range(self.input_channels):\n", + " for fmap in range(self.feature_maps):\n", + " for h in range(self.X_batch_feedforward.shape[height_index]):\n", + " for w in range(self.X_batch_feedforward.shape[width_index]):\n", + " delta_term[img, chin, h, w] = np.sum(\n", + " delta_term_next[\n", + " img,\n", + " fmap,\n", + " h : h + self.kernel_height,\n", + " w : w + self.kernel_width,\n", + " ]\n", + " * np.rot90(np.rot90(self.kernel[chin, fmap, :, :]))\n", + " )\n", + "\n", + " # calculate gradient for kernel for weight update\n", + " # also via convolution\n", + " for chin in range(self.input_channels):\n", + " for fmap in range(self.feature_maps):\n", + " for k_x in range(self.kernel_height):\n", + " for k_y in range(self.kernel_width):\n", + " gradient_kernel[chin, fmap, k_x, k_y] = np.sum(\n", + " X_batch_padded[\n", + " img,\n", + " chin,\n", + " h : h + self.kernel_height,\n", + " w : w + self.kernel_width,\n", + " ]\n", + " * delta_term_next[\n", + " img,\n", + " fmap,\n", + " h : h + self.kernel_height,\n", + " w : w + self.kernel_width,\n", + " ]\n", + " )\n", + " # all kernels are updated with weight gradient of kernel\n", + " self.kernel -= gradient_kernel\n", + "\n", + " # return delta term\n", + " return delta_term\n", + "\n", + " def _padding(self, X_batch, batch_type=\"image\"):\n", + "\n", + " # same padding for images\n", + " if self.pad == \"same\" and batch_type == \"image\":\n", + " padded_height = X_batch.shape[height_index] + (self.kernel_height // 2) * 2\n", + " padded_width = X_batch.shape[width_index] + (self.kernel_width // 2) * 2\n", + " half_kernel_height = self.kernel_height // 2\n", + " half_kernel_width = self.kernel_width // 2\n", + "\n", + " # initialize padded array\n", + " X_batch_padded = np.ndarray(\n", + " (\n", + " X_batch.shape[input_index],\n", + " X_batch.shape[feature_maps_index],\n", + " padded_height,\n", + " padded_width,\n", + " )\n", + " )\n", + "\n", + " # zero pad all images in X_batch\n", + " for img in range(X_batch.shape[input_index]):\n", + " padded_img = np.zeros(\n", + " (X_batch.shape[feature_maps_index], padded_height, padded_width)\n", + " )\n", + " padded_img[\n", + " :,\n", + " half_kernel_height : padded_height - half_kernel_height,\n", + " half_kernel_width : padded_width - half_kernel_width,\n", + " ] = X_batch[img, :, :, :]\n", + " X_batch_padded[img, :, :, :] = padded_img[:, :, :]\n", + "\n", + " return X_batch_padded\n", + "\n", + " # same padding for gradients\n", + " elif self.pad == \"same\" and batch_type == \"grad\":\n", + " padded_height = X_batch.shape[height_index] + (self.kernel_height // 2) * 2\n", + " padded_width = X_batch.shape[width_index] + (self.kernel_width // 2) * 2\n", + " half_kernel_height = self.kernel_height // 2\n", + " half_kernel_width = self.kernel_width // 2\n", + "\n", + " # initialize padded array\n", + " delta_term_padded = np.zeros(\n", + " (\n", + " X_batch.shape[input_index],\n", + " X_batch.shape[feature_maps_index],\n", + " padded_height,\n", + " padded_width,\n", + " )\n", + " )\n", + "\n", + " # zero pad delta term\n", + " delta_term_padded[\n", + " :, :, : X_batch.shape[height_index], : X_batch.shape[width_index]\n", + " ] = X_batch[:, :, :, :]\n", + "\n", + " return delta_term_padded\n", + "\n", + " else:\n", + " return X_batch\n", + "\n", + " def _reset_weights_independently(self):\n", + " # sets seed to remove randomness inbetween runs\n", + " if self.seed is not None:\n", + " np.random.seed(self.seed)\n", + "\n", + " # initializes kernel matrix\n", + " self.kernel = np.ndarray(\n", + " (\n", + " self.input_channels,\n", + " self.feature_maps,\n", + " self.kernel_height,\n", + " self.kernel_width,\n", + " )\n", + " )\n", + "\n", + " # randomly initializes weights\n", + " for chin in range(self.kernel.shape[kernel_input_channels_index]):\n", + " for fmap in range(self.kernel.shape[kernel_feature_maps_index]):\n", + " self.kernel[chin, fmap, :, :] = np.random.rand(\n", + " self.kernel_height, self.kernel_width\n", + " )\n", + "\n", + " def _reset_weights(self, previous_nodes):\n", + " # sets weights\n", + " self._reset_weights_independently()\n", + "\n", + " # returns shape of output used for subsequent layer's weight initiation\n", + " strided_height = int(\n", + " np.ceil(previous_nodes.shape[height_index] / self.v_stride)\n", + " )\n", + " strided_width = int(np.ceil(previous_nodes.shape[width_index] / self.h_stride))\n", + " next_nodes = np.ones(\n", + " (\n", + " previous_nodes.shape[input_index],\n", + " self.feature_maps,\n", + " strided_height,\n", + " strided_width,\n", + " )\n", + " )\n", + " return next_nodes / self.kernel_height\n", + "\n", + " def _check_for_errors(self):\n", + " if self.X_batch_feedforward.shape[input_channel_index] != self.input_channels:\n", + " raise AssertionError(\n", + " f\"ERROR: Number of input channels in data ({self.X_batch_feedforward.shape[input_channel_index]}) is not equal to input channels in Convolution2DLayerOPT ({self.input_channels})! Please change the number of input channels of the Convolution2DLayer such that they are equal\"\n", + " )" + ] + }, + { + "cell_type": "markdown", + "id": "730b8338", + "metadata": { + "editable": true + }, + "source": [ + "### Backpropagation in the convolutional layer\n", + "\n", + "As you may have noticed, we have not yet explained how the\n", + "backpropagation algorithm works in a convolutional layer. However,\n", + "having covered all other major details about convolutional layers, we\n", + "are now prepared to do so. It should come as no surprise that the\n", + "calculation of delta terms at each convolutional layer takes the form\n", + "of convolution. After the gradient has been propagated backwards\n", + "through the flattening layer, where it was reshaped into an\n", + "appropriate form, calculating the update value for the kernel is\n", + "simply a matter of convolving the output gradient with the input of\n", + "the layer for which we are updating the weights. For more detail, this\n", + "article serves as an excellent resource, see\n", + "" + ] + }, + { + "cell_type": "markdown", + "id": "54d1a07d", + "metadata": { + "editable": true + }, + "source": [ + "### Demonstration\n", + "\n", + "We can use the convolutional layer above to perform a simple convolution on an image of the now familiar cute dog." + ] + }, + { + "cell_type": "code", + "execution_count": 26, + "id": "ac10f107", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "import numpy as np\n", + "import imageio.v3 as imageio\n", + "import matplotlib.pyplot as plt\n", + "\n", + "def plot_convolution_result(X, layer):\n", + " plt.imshow(X[0, 0, :, :], vmin=0, vmax=255, cmap=\"gray\")\n", + " plt.title(\"Original image\")\n", + " plt.colorbar()\n", + " plt.show()\n", + " conv_result = layer._feedforward(X)\n", + " plt.title(\"Result of convolutional layer\")\n", + " plt.imshow(conv_result[0, 0, :, :], vmin=0, vmax=255, cmap=\"gray\")\n", + " plt.colorbar()\n", + " plt.show()\n", + "\n", + "# create layer\n", + "layer = Convolution2DLayer(\n", + " input_channels=3,\n", + " feature_maps=1,\n", + " kernel_height=4,\n", + " kernel_width=4,\n", + " v_stride=2,\n", + " h_stride=2,\n", + " pad=\"same\",\n", + " act_func=identity,\n", + " seed=2023,\n", + " )\n", + "\n", + "# read in image path, make data correct format\n", + "img_path = img_path = \"../data/IMG-2167.JPG\"\n", + "image_of_cute_dog = imageio.imread(img_path)\n", + "image_shape = image_of_cute_dog.shape\n", + "image_of_cute_dog = image_of_cute_dog.reshape(1, image_shape[0], image_shape[1], image_shape[2])\n", + "image_of_cute_dog = image_of_cute_dog.transpose(0, 3, 1, 2)\n", + "\n", + "# plot the result of the convolution\n", + "plot_convolution_result(image_of_cute_dog, layer)" + ] + }, + { + "cell_type": "markdown", + "id": "cf95bae4", + "metadata": { + "editable": true + }, + "source": [ + "We cobserve that the result has half the pixels on each axis due to\n", + "the fact that we've used a horizontal and vertical stride of 2. The\n", + "result of this convolution is not very insightfull, as the kernel has\n", + "completely random values for the first feedforward pass. However, as\n", + "we perform multiple forward and backward passes, the results of the\n", + "convolution should provide identifying features of the image it uses\n", + "for classification.\n", + "\n", + "Note that image data usually comes in many different shapes and sizes,\n", + "but for our CNN we require the input data be formatted as \\[Number of\n", + "inputs, input channels, input height, input width\\]. Occasionally, the\n", + "data you come accross use will be formatted like this, but on many\n", + "occasions reshaping and transposing the dimensions is sadly necessary." + ] + }, + { + "cell_type": "markdown", + "id": "d02b9c44", + "metadata": { + "editable": true + }, + "source": [ + "### Pooling Layer\n", + "\n", + "The pooling layer is another widely used type of layer in\n", + "convolutional neural networks that enables data downsampling to a more\n", + "manageable size. Despite recent technological advancements that allow\n", + "for convolution without excessive size reduction of the data, the\n", + "pooling layer still remains a fundamental component of convolutional\n", + "neural networks. It can be used before, after, or in between\n", + "convolutional layers, although finding the optimal placement of layers\n", + "and network depth requires experimentation to achieve the best\n", + "performance for a given problem. The code we provide allows you to\n", + "perform two types of pooling known as max pooling and average pooling." + ] + }, + { + "cell_type": "code", + "execution_count": 27, + "id": "f53d233d", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "class Pooling2DLayer(Layer):\n", + " def __init__(\n", + " self,\n", + " kernel_height,\n", + " kernel_width,\n", + " v_stride,\n", + " h_stride,\n", + " pooling=\"max\",\n", + " seed=None,\n", + " ):\n", + " super().__init__(seed)\n", + " self.kernel_height = kernel_height\n", + " self.kernel_width = kernel_width\n", + " self.v_stride = v_stride\n", + " self.h_stride = h_stride\n", + " self.pooling = pooling\n", + "\n", + " def _feedforward(self, X_batch):\n", + " # Saving the input for use in the backwardpass\n", + " self.X_batch_feedforward = X_batch\n", + "\n", + " # check if user is silly\n", + " self._check_for_errors()\n", + "\n", + " # Computing the size of the feature maps based on kernel size and the stride parameter\n", + " strided_height = (\n", + " X_batch.shape[height_index] - self.kernel_height\n", + " ) // self.v_stride + 1\n", + " if X_batch.shape[height_index] == X_batch.shape[width_index]:\n", + " strided_width = strided_height\n", + " else:\n", + " strided_width = (\n", + " X_batch.shape[width_index] - self.kernel_width\n", + " ) // self.h_stride + 1\n", + "\n", + " # initialize output array\n", + " output = np.ndarray(\n", + " (\n", + " X_batch.shape[input_index],\n", + " X_batch.shape[feature_maps_index],\n", + " strided_height,\n", + " strided_width,\n", + " )\n", + " )\n", + "\n", + " # select pooling action, either max or average pooling\n", + " if self.pooling == \"max\":\n", + " self.pooling_action = np.max\n", + " elif self.pooling == \"average\":\n", + " self.pooling_action = np.mean\n", + "\n", + " # pool based on kernel size and stride\n", + " for img in range(output.shape[input_index]):\n", + " for fmap in range(output.shape[feature_maps_index]):\n", + " for h in range(strided_height):\n", + " for w in range(strided_width):\n", + " output[img, fmap, h, w] = self.pooling_action(\n", + " X_batch[\n", + " img,\n", + " fmap,\n", + " (h * self.v_stride) : (h * self.v_stride)\n", + " + self.kernel_height,\n", + " (w * self.h_stride) : (w * self.h_stride)\n", + " + self.kernel_width,\n", + " ]\n", + " )\n", + "\n", + " # output for feedforward in next layer\n", + " return output\n", + "\n", + " def _backpropagate(self, delta_term_next):\n", + " # initiate delta term array\n", + " delta_term = np.zeros((self.X_batch_feedforward.shape))\n", + "\n", + " for img in range(delta_term_next.shape[input_index]):\n", + " for fmap in range(delta_term_next.shape[feature_maps_index]):\n", + " for h in range(0, delta_term_next.shape[height_index], self.v_stride):\n", + " for w in range(\n", + " 0, delta_term_next.shape[width_index], self.h_stride\n", + " ):\n", + " # max pooling\n", + " if self.pooling == \"max\":\n", + " # get window\n", + " window = self.X_batch_feedforward[\n", + " img,\n", + " fmap,\n", + " h : h + self.kernel_height,\n", + " w : w + self.kernel_width,\n", + " ]\n", + "\n", + " # find max values indices in window\n", + " max_h, max_w = np.unravel_index(\n", + " window.argmax(), window.shape\n", + " )\n", + "\n", + " # set values in new, upsampled delta term\n", + " delta_term[\n", + " img,\n", + " fmap,\n", + " (h + max_h),\n", + " (w + max_w),\n", + " ] += delta_term_next[img, fmap, h, w]\n", + "\n", + " # average pooling\n", + " if self.pooling == \"average\":\n", + " delta_term[\n", + " img,\n", + " fmap,\n", + " h : h + self.kernel_height,\n", + " w : w + self.kernel_width,\n", + " ] = (\n", + " delta_term_next[img, fmap, h, w]\n", + " / self.kernel_height\n", + " / self.kernel_width\n", + " )\n", + " # returns input to backpropagation in previous layer\n", + " return delta_term\n", + "\n", + " def _reset_weights(self, previous_nodes):\n", + " # calculate strided height, strided width\n", + " strided_height = (\n", + " previous_nodes.shape[height_index] - self.kernel_height\n", + " ) // self.v_stride + 1\n", + " if previous_nodes.shape[height_index] == previous_nodes.shape[width_index]:\n", + " strided_width = strided_height\n", + " else:\n", + " strided_width = (\n", + " previous_nodes.shape[width_index] - self.kernel_width\n", + " ) // self.h_stride + 1\n", + "\n", + " # initiate output array\n", + " output = np.ones(\n", + " (\n", + " previous_nodes.shape[input_index],\n", + " previous_nodes.shape[feature_maps_index],\n", + " strided_height,\n", + " strided_width,\n", + " )\n", + " )\n", + "\n", + " # returns output with shape used for reset weights in next layer\n", + " return output\n", + "\n", + " def _check_for_errors(self):\n", + " # check if input is smaller than kernel size -> error\n", + " assert (\n", + " self.X_batch_feedforward.shape[width_index] >= self.kernel_width\n", + " ), f\"ERROR: Pooling kernel width_index ({self.kernel_width}) larger than data width_index ({self.X_batch_feedforward.input.shape[2]}), please lower the kernel width_index of the Pooling2DLayer\"\n", + " assert (\n", + " self.X_batch_feedforward.shape[height_index] >= self.kernel_height\n", + " ), f\"ERROR: Pooling kernel height_index ({self.kernel_height}) larger than data height_index ({self.X_batch_feedforward.input.shape[3]}), please lower the kernel height_index of the Pooling2DLayer\"" + ] + }, + { + "cell_type": "markdown", + "id": "d6d73c7c", + "metadata": { + "editable": true + }, + "source": [ + "### Flattening Layer\n", + "\n", + "Before we can begin building our first CNN model, we need to introduce\n", + "the flattening layer. As its name suggests, the flattening layer\n", + "transforms the data into a one-dimensional vector that can be fed into\n", + "the feedforward layers of our network. This layer plays a crucial role\n", + "in preparing the data for further processing in the\n", + "network. Additionally, the flattening layer is responsible for\n", + "reshaping the gradient to the proper shape during\n", + "backpropagation. This ensures that the kernels are correctly updated,\n", + "allowing for effective learning in the network." + ] + }, + { + "cell_type": "code", + "execution_count": 28, + "id": "c5ae6332", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "class FlattenLayer(Layer):\n", + " def __init__(self, act_func=LRELU, seed=None):\n", + " super().__init__(seed)\n", + " self.act_func = act_func\n", + "\n", + " def _feedforward(self, X_batch):\n", + " # save input for backpropagation\n", + " self.X_batch_feedforward_shape = X_batch.shape\n", + " # Remember, the data has the following shape: (I, FM, H, W, ) in the convolutional layers\n", + " # whilst the data has the shape (I, FM * H * W) in the fully connected layers\n", + " # I = Inputs, FM = Feature Maps, H = Height and W = Width.\n", + " X_batch = X_batch.reshape(\n", + " X_batch.shape[input_index],\n", + " X_batch.shape[feature_maps_index]\n", + " * X_batch.shape[height_index]\n", + " * X_batch.shape[width_index],\n", + " )\n", + "\n", + " # add bias to a\n", + " self.z_matrix = X_batch\n", + " bias = np.ones((X_batch.shape[input_index], 1)) * 0.01\n", + " self.a_matrix = np.hstack([bias, X_batch])\n", + "\n", + " # return a, the input to feedforward in next layer\n", + " return self.a_matrix\n", + "\n", + " def _backpropagate(self, weights_next, delta_term_next):\n", + " activation_derivative = derivate(self.act_func)\n", + "\n", + " # calculate delta term\n", + " delta_term = (\n", + " weights_next[bias_index:, :] @ delta_term_next.T\n", + " ).T * activation_derivative(self.z_matrix)\n", + "\n", + " # FlattenLayer does not update weights\n", + " # reshapes delta layer to convolutional layer data format [Input, Feature_Maps, Height, Width]\n", + " return delta_term.reshape(self.X_batch_feedforward_shape)\n", + "\n", + " def _reset_weights(self, previous_nodes):\n", + " # note that the previous nodes to the FlattenLayer are from the convolutional layers\n", + " previous_nodes = previous_nodes.reshape(\n", + " previous_nodes.shape[input_index],\n", + " previous_nodes.shape[feature_maps_index]\n", + " * previous_nodes.shape[height_index]\n", + " * previous_nodes.shape[width_index],\n", + " )\n", + "\n", + " # return shape used in reset_weights in next layer\n", + " return previous_nodes.shape[node_index]\n", + "\n", + " def get_prev_a(self):\n", + " return self.a_matrix" + ] + }, + { + "cell_type": "markdown", + "id": "09dc88fd", + "metadata": { + "editable": true + }, + "source": [ + "### Fully Connected Layers\n", + "\n", + "Finally, the result from the flatten layer will pass to a series of\n", + "fully connected layers, which function as a normal feed forward neural\n", + "network. The fully connected layers are split into two classes;\n", + "FullyConnectedLayer which acts as a hidden layer, and OutputLayer,\n", + "which acts as the single output layer at the end of the CNN. If one\n", + "wishes to use this codebase to construct a normal feed forward neural\n", + "network, it must start with a FlattenLayer due to techincal details\n", + "regarding weight intitialization. However many FullyConnectedLayers\n", + "can be added to the CNN, and in each layer the amount of nodes, which\n", + "activation function and scheduler to use can be specified. In\n", + "practice, the scheduler will be specified in the CNN object\n", + "initialization, and inherited if no other scheduler is specified." + ] + }, + { + "cell_type": "code", + "execution_count": 29, + "id": "00672cce", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "class FullyConnectedLayer(Layer):\n", + " # FullyConnectedLayer per default uses LRELU and Adam scheduler\n", + " # with an eta of 0.0001, rho of 0.9 and rho2 of 0.999\n", + " def __init__(\n", + " self,\n", + " nodes: int,\n", + " act_func: Callable = LRELU,\n", + " scheduler: Scheduler = Adam(eta=1e-4, rho=0.9, rho2=0.999),\n", + " seed: int = None,\n", + " ):\n", + " super().__init__(seed)\n", + " self.nodes = nodes\n", + " self.act_func = act_func\n", + " self.scheduler_weight = copy(scheduler)\n", + " self.scheduler_bias = copy(scheduler)\n", + "\n", + " # initiate matrices for later\n", + " self.weights = None\n", + " self.a_matrix = None\n", + " self.z_matrix = None\n", + "\n", + " def _feedforward(self, X_batch):\n", + " # calculate z\n", + " self.z_matrix = X_batch @ self.weights\n", + "\n", + " # calculate a, add bias\n", + " bias = np.ones((X_batch.shape[input_index], 1)) * 0.01\n", + " self.a_matrix = self.act_func(self.z_matrix)\n", + " self.a_matrix = np.hstack([bias, self.a_matrix])\n", + "\n", + " # return a, the input for feedforward in next layer\n", + " return self.a_matrix\n", + "\n", + " def _backpropagate(self, weights_next, delta_term_next, a_previous, lam):\n", + " # take the derivative of the activation function\n", + " activation_derivative = derivate(self.act_func)\n", + "\n", + " # calculate the delta term\n", + " delta_term = (\n", + " weights_next[bias_index:, :] @ delta_term_next.T\n", + " ).T * activation_derivative(self.z_matrix)\n", + "\n", + " # intitiate matrix to store gradient\n", + " # note that we exclude the bias term, which we will calculate later\n", + " gradient_weights = np.zeros(\n", + " (\n", + " a_previous.shape[input_index],\n", + " a_previous.shape[node_index] - bias_index,\n", + " delta_term.shape[node_index],\n", + " )\n", + " )\n", + "\n", + " # calculate gradient = delta term * previous a\n", + " for i in range(len(delta_term)):\n", + " gradient_weights[i, :, :] = np.outer(\n", + " a_previous[i, bias_index:], delta_term[i, :]\n", + " )\n", + "\n", + " # sum the gradient, divide by input_index\n", + " gradient_weights = np.mean(gradient_weights, axis=input_index)\n", + " # for the bias gradient we do not multiply by previous a\n", + " gradient_bias = np.mean(delta_term, axis=input_index).reshape(\n", + " 1, delta_term.shape[node_index]\n", + " )\n", + "\n", + " # regularization term\n", + " gradient_weights += self.weights[bias_index:, :] * lam\n", + "\n", + " # send gradients into scheduler\n", + " # returns update matrix which will be used to update the weights and bias\n", + " update_matrix = np.vstack(\n", + " [\n", + " self.scheduler_bias.update_change(gradient_bias),\n", + " self.scheduler_weight.update_change(gradient_weights),\n", + " ]\n", + " )\n", + "\n", + " # update weights\n", + " self.weights -= update_matrix\n", + "\n", + " # return weights and delta term, input for backpropagation in previous layer\n", + " return self.weights, delta_term\n", + "\n", + " def _reset_weights(self, previous_nodes):\n", + " # sets seed to remove randomness inbetween runs\n", + " if self.seed is not None:\n", + " np.random.seed(self.seed)\n", + "\n", + " # add bias, initiate random weights\n", + " bias = 1\n", + " self.weights = np.random.randn(previous_nodes + bias, self.nodes)\n", + "\n", + " # returns number of nodes, used for reset_weights in next layer\n", + " return self.nodes\n", + "\n", + " def _reset_scheduler(self):\n", + " # resets scheduler per epoch\n", + " self.scheduler_weight.reset()\n", + " self.scheduler_bias.reset()\n", + "\n", + " def get_prev_a(self):\n", + " # returns a matrix, used in backpropagation\n", + " return self.a_matrix\n", + "\n", + "\n", + "class OutputLayer(FullyConnectedLayer):\n", + " def __init__(\n", + " self,\n", + " nodes: int,\n", + " output_func: Callable = LRELU,\n", + " cost_func: Callable = CostCrossEntropy,\n", + " scheduler: Scheduler = Adam(eta=1e-4, rho=0.9, rho2=0.999),\n", + " seed: int = None,\n", + " ):\n", + " super().__init__(nodes, output_func, copy(scheduler), seed)\n", + " self.cost_func = cost_func\n", + "\n", + " # initiate matrices for later\n", + " self.weights = None\n", + " self.a_matrix = None\n", + " self.z_matrix = None\n", + "\n", + " # decides if the output layer performs binary or multi-class classification\n", + " self._set_pred_format()\n", + "\n", + " def _feedforward(self, X_batch: np.ndarray):\n", + " # calculate a, z\n", + " # note that bias is not added as this would create an extra output class\n", + " self.z_matrix = X_batch @ self.weights\n", + " self.a_matrix = self.act_func(self.z_matrix)\n", + "\n", + " # returns prediction\n", + " return self.a_matrix\n", + "\n", + " def _backpropagate(self, target, a_previous, lam):\n", + " # note that in the OutputLayer the activation function is the output function\n", + " activation_derivative = derivate(self.act_func)\n", + "\n", + " # calculate output delta terms\n", + " # for multi-class or binary classification\n", + " if self.pred_format == \"Multi-class\":\n", + " delta_term = self.a_matrix - target\n", + " else:\n", + " cost_func_derivative = grad(self.cost_func(target))\n", + " delta_term = activation_derivative(self.z_matrix) * cost_func_derivative(\n", + " self.a_matrix\n", + " )\n", + "\n", + " # intiate matrix that stores gradient\n", + " gradient_weights = np.zeros(\n", + " (\n", + " a_previous.shape[input_index],\n", + " a_previous.shape[node_index] - bias_index,\n", + " delta_term.shape[node_index],\n", + " )\n", + " )\n", + "\n", + " # calculate gradient = delta term * previous a\n", + " for i in range(len(delta_term)):\n", + " gradient_weights[i, :, :] = np.outer(\n", + " a_previous[i, bias_index:], delta_term[i, :]\n", + " )\n", + "\n", + " # sum the gradient, divide by input_index\n", + " gradient_weights = np.mean(gradient_weights, axis=input_index)\n", + " # for the bias gradient we do not multiply by previous a\n", + " gradient_bias = np.mean(delta_term, axis=input_index).reshape(\n", + " 1, delta_term.shape[node_index]\n", + " )\n", + "\n", + " # regularization term\n", + " gradient_weights += self.weights[bias_index:, :] * lam\n", + "\n", + " # send gradients into scheduler\n", + " # returns update matrix which will be used to update the weights and bias\n", + " update_matrix = np.vstack(\n", + " [\n", + " self.scheduler_bias.update_change(gradient_bias),\n", + " self.scheduler_weight.update_change(gradient_weights),\n", + " ]\n", + " )\n", + "\n", + " # update weights\n", + " self.weights -= update_matrix\n", + "\n", + " # return weights and delta term, input for backpropagation in previous layer\n", + " return self.weights, delta_term\n", + "\n", + " def _reset_weights(self, previous_nodes):\n", + " # sets seed to remove randomness inbetween runs\n", + " if self.seed is not None:\n", + " np.random.seed(self.seed)\n", + "\n", + " # add bias, initiate random weights\n", + " bias = 1\n", + " self.weights = np.random.rand(previous_nodes + bias, self.nodes)\n", + "\n", + " # returns number of nodes, used for reset_weights in next layer\n", + " return self.nodes\n", + "\n", + " def _reset_scheduler(self):\n", + " # resets scheduler per epoch\n", + " self.scheduler_weight.reset()\n", + " self.scheduler_bias.reset()\n", + "\n", + " def _set_pred_format(self):\n", + " # sets prediction format to either regression, binary or multi-class classification\n", + " if self.act_func.__name__ is None or self.act_func.__name__ == \"identity\":\n", + " self.pred_format = \"Regression\"\n", + " elif self.act_func.__name__ == \"sigmoid\" or self.act_func.__name__ == \"tanh\":\n", + " self.pred_format = \"Binary\"\n", + " else:\n", + " self.pred_format = \"Multi-class\"\n", + "\n", + " def get_pred_format(self):\n", + " # returns format of prediction\n", + " return self.pred_format" + ] + }, + { + "cell_type": "markdown", + "id": "d12f3649", + "metadata": { + "editable": true + }, + "source": [ + "### Optimized Convolution2DLayer\n", + "\n", + "For our CNN, we have also implemented an optimized version of the\n", + "Convolution2DLayer, Convolution2DLayerOPT, which runs much faster. See\n", + "VII. Remarks for discussion. This layer will per default be used by\n", + "the CNN due to its computational advantages, but is much less\n", + "readable. We've documented it such that specially interested students\n", + "can understand the principles behind it, but it is not recommended to\n", + "read. In short, we reshape and transpose parts of the image such that\n", + "the convolutional operation can be swapped out for a simple matrix\n", + "multiplication." + ] + }, + { + "cell_type": "code", + "execution_count": 30, + "id": "53a308e9", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "class Convolution2DLayerOPT(Convolution2DLayer):\n", + " \"\"\"\n", + " Am optimized version of the convolution layer above which\n", + " utilizes an approach of extracting windows of size equivalent\n", + " in size to the filter. The convoution is then performed on those\n", + " windows instead of a full feature map.\n", + " \"\"\"\n", + "\n", + " def __init__(\n", + " self,\n", + " input_channels,\n", + " feature_maps,\n", + " kernel_height,\n", + " kernel_width,\n", + " v_stride,\n", + " h_stride,\n", + " pad,\n", + " act_func: Callable,\n", + " seed=None,\n", + " reset_weights_independently=True,\n", + " ):\n", + " super().__init__(\n", + " input_channels,\n", + " feature_maps,\n", + " kernel_height,\n", + " kernel_width,\n", + " v_stride,\n", + " h_stride,\n", + " pad,\n", + " act_func,\n", + " seed,\n", + " )\n", + " # true if layer is used outside of CNN\n", + " if reset_weights_independently == True:\n", + " self._reset_weights_independently()\n", + "\n", + " def _feedforward(self, X_batch):\n", + " # The optimized _feedforward method is difficult to understand but computationally more efficient\n", + " # for a more \"by the book\" approach, please look at the _feedforward method of Convolution2DLayer\n", + "\n", + " # save the input for backpropagation\n", + " self.X_batch_feedforward = X_batch\n", + "\n", + " # check that there are the correct amount of input channels\n", + " self._check_for_errors()\n", + "\n", + " # calculate new shape after stride\n", + " strided_height = int(np.ceil(X_batch.shape[height_index] / self.v_stride))\n", + " strided_width = int(np.ceil(X_batch.shape[width_index] / self.h_stride))\n", + "\n", + " # get windows of the image for more computationally efficient convolution\n", + " # the idea is that we want to align the dimensions that we wish to matrix\n", + " # multiply, then use a simple matrix multiplication instead of convolution.\n", + " # then, we reshape the size back to its intended shape\n", + " windows = self._extract_windows(X_batch)\n", + " windows = windows.transpose(1, 0, 2, 3, 4).reshape(\n", + " X_batch.shape[input_index],\n", + " strided_height * strided_width,\n", + " -1,\n", + " )\n", + "\n", + " # reshape the kernel for more computationally efficient convolution\n", + " kernel = self.kernel\n", + " kernel = kernel.transpose(0, 2, 3, 1).reshape(\n", + " kernel.shape[kernel_input_channels_index]\n", + " * kernel.shape[height_index]\n", + " * kernel.shape[width_index],\n", + " -1,\n", + " )\n", + "\n", + " # use simple matrix calculation to obtain output\n", + " output = (\n", + " (windows @ kernel)\n", + " .reshape(\n", + " X_batch.shape[input_index],\n", + " strided_height,\n", + " strided_width,\n", + " -1,\n", + " )\n", + " .transpose(0, 3, 1, 2)\n", + " )\n", + "\n", + " # The output is reshaped and rearranged to appropriate shape\n", + " return self.act_func(\n", + " output / (self.kernel_height * X_batch.shape[feature_maps_index])\n", + " )\n", + "\n", + " def _backpropagate(self, delta_term_next):\n", + " # The optimized _backpropagate method is difficult to understand but computationally more efficient\n", + " # for a more \"by the book\" approach, please look at the _backpropagate method of Convolution2DLayer\n", + " act_derivative = derivate(self.act_func)\n", + " delta_term_next = act_derivative(delta_term_next)\n", + "\n", + " # calculate strided dimensions\n", + " strided_height = int(\n", + " np.ceil(self.X_batch_feedforward.shape[height_index] / self.v_stride)\n", + " )\n", + " strided_width = int(\n", + " np.ceil(self.X_batch_feedforward.shape[width_index] / self.h_stride)\n", + " )\n", + "\n", + " # copy kernel\n", + " kernel = self.kernel\n", + "\n", + " # get windows, reshape for matrix multiplication\n", + " windows = self._extract_windows(self.X_batch_feedforward, \"image\").reshape(\n", + " self.X_batch_feedforward.shape[input_index]\n", + " * strided_height\n", + " * strided_width,\n", + " -1,\n", + " )\n", + "\n", + " # initialize output gradient, reshape and transpose into correct shape\n", + " # for matrix multiplication\n", + " output_grad_tr = delta_term_next.transpose(0, 2, 3, 1).reshape(\n", + " self.X_batch_feedforward.shape[input_index]\n", + " * strided_height\n", + " * strided_width,\n", + " -1,\n", + " )\n", + "\n", + " # calculate gradient kernel via simple matrix multiplication and reshaping\n", + " gradient_kernel = (\n", + " (windows.T @ output_grad_tr)\n", + " .reshape(\n", + " kernel.shape[kernel_input_channels_index],\n", + " kernel.shape[height_index],\n", + " kernel.shape[width_index],\n", + " kernel.shape[kernel_feature_maps_index],\n", + " )\n", + " .transpose(0, 3, 1, 2)\n", + " )\n", + "\n", + " # for computing the input gradient\n", + " windows_out, upsampled_height, upsampled_width = self._extract_windows(\n", + " delta_term_next, \"grad\"\n", + " )\n", + "\n", + " # calculate new window dimensions\n", + " new_windows_first_dim = (\n", + " self.X_batch_feedforward.shape[input_index]\n", + " * upsampled_height\n", + " * upsampled_width\n", + " )\n", + " # ceil allows for various asymmetric kernels\n", + " new_windows_sec_dim = int(np.ceil(windows_out.size / new_windows_first_dim))\n", + "\n", + " # reshape for matrix multiplication\n", + " windows_out = windows_out.transpose(1, 0, 2, 3, 4).reshape(\n", + " new_windows_first_dim, new_windows_sec_dim\n", + " )\n", + "\n", + " # reshape for matrix multiplication\n", + " kernel_reshaped = kernel.reshape(self.input_channels, -1)\n", + "\n", + " # calculating input gradient for next convolutional layer\n", + " input_grad = (windows_out @ kernel_reshaped.T).reshape(\n", + " self.X_batch_feedforward.shape[input_index],\n", + " upsampled_height,\n", + " upsampled_width,\n", + " kernel.shape[kernel_input_channels_index],\n", + " )\n", + " input_grad = input_grad.transpose(0, 3, 1, 2)\n", + "\n", + " # Update the weights in the kernel\n", + " self.kernel -= gradient_kernel\n", + "\n", + " # Output the gradient to propagate backwards\n", + " return input_grad\n", + "\n", + " def _extract_windows(self, X_batch, batch_type=\"image\"):\n", + " \"\"\"\n", + " Receives as input the X_batch with shape (inputs, feature_maps, image_height, image_width)\n", + " and extract windows of size kernel_height * kernel_width for every image and every feature_map.\n", + " It then returns an np.ndarray of shape (image_height * image_width, inputs, feature_maps, kernel_height, kernel_width)\n", + " which will be used either to filter the images in feedforward or to calculate the gradient.\n", + " \"\"\"\n", + "\n", + " # initialize list of windows\n", + " windows = []\n", + "\n", + " if batch_type == \"image\":\n", + " # pad the images\n", + " X_batch_padded = self._padding(X_batch, batch_type=\"image\")\n", + " img_height, img_width = X_batch_padded.shape[2:]\n", + " # For each location in the image...\n", + " for h in range(\n", + " 0,\n", + " X_batch.shape[height_index],\n", + " self.v_stride,\n", + " ):\n", + " for w in range(\n", + " 0,\n", + " X_batch.shape[width_index],\n", + " self.h_stride,\n", + " ):\n", + " # ...obtain an image patch of the original size (strided)\n", + "\n", + " # get window\n", + " window = X_batch_padded[\n", + " :,\n", + " :,\n", + " h : h + self.kernel_height,\n", + " w : w + self.kernel_width,\n", + " ]\n", + "\n", + " # append to list of windows\n", + " windows.append(window)\n", + "\n", + " # return numpy array instead of list\n", + " return np.stack(windows)\n", + "\n", + " # In order to be able to perform backprogagation by the method of window extraction,\n", + " # here is a modified approach to extracting the windows which allow for the necessary\n", + " # upsampling of the gradient in case the on of the stride parameters is larger than one.\n", + "\n", + " if batch_type == \"grad\":\n", + "\n", + " # In the case of one of the stride parameters being odd, we have to take some\n", + " # extra care in calculating the upsampled size of X_batch. We solve this\n", + " # by simply flooring the result of dividing stride by 2.\n", + " if self.v_stride < 2 or self.v_stride % 2 == 0:\n", + " v_stride = 0\n", + " else:\n", + " v_stride = int(np.floor(self.v_stride / 2))\n", + "\n", + " if self.h_stride < 2 or self.h_stride % 2 == 0:\n", + " h_stride = 0\n", + " else:\n", + " h_stride = int(np.floor(self.h_stride / 2))\n", + "\n", + " upsampled_height = (X_batch.shape[height_index] * self.v_stride) - v_stride\n", + " upsampled_width = (X_batch.shape[width_index] * self.h_stride) - h_stride\n", + "\n", + " # When upsampling, we need to insert rows and columns filled with zeros\n", + " # into each feature map. How many of those we have to insert is purely\n", + " # dependant on the value of stride parameter in the vertical and horizontal\n", + " # direction.\n", + " if self.v_stride > 1:\n", + " v_ind = 1\n", + " for i in range(X_batch.shape[height_index]):\n", + " for j in range(self.v_stride - 1):\n", + " X_batch = np.insert(X_batch, v_ind, 0, axis=height_index)\n", + " v_ind += self.v_stride\n", + "\n", + " if self.h_stride > 1:\n", + " h_ind = 1\n", + " for i in range(X_batch.shape[width_index]):\n", + " for k in range(self.h_stride - 1):\n", + " X_batch = np.insert(X_batch, h_ind, 0, axis=width_index)\n", + " h_ind += self.h_stride\n", + "\n", + " # Since the insertion of zero-filled rows and columns isn't perfect, we have\n", + " # to assure that the resulting feature maps will have the expected upsampled height\n", + " # and width by cutting them og at desired dimensions.\n", + "\n", + " X_batch = X_batch[:, :, :upsampled_height, :upsampled_width]\n", + "\n", + " X_batch_padded = self._padding(X_batch, batch_type=\"grad\")\n", + "\n", + " # initialize list of windows\n", + " windows = []\n", + "\n", + " # For each location in the image...\n", + " for h in range(\n", + " 0,\n", + " X_batch.shape[height_index],\n", + " self.v_stride,\n", + " ):\n", + " for w in range(\n", + " 0,\n", + " X_batch.shape[width_index],\n", + " self.h_stride,\n", + " ):\n", + " # ...obtain an image patch of the original size (strided)\n", + "\n", + " # get window\n", + " window = X_batch_padded[\n", + " :, :, h : h + self.kernel_height, w : w + self.kernel_width\n", + " ]\n", + "\n", + " # append window to list\n", + " windows.append(window)\n", + "\n", + " # return numpy array, unsampled dimensions\n", + " return np.stack(windows), upsampled_height, upsampled_width\n", + "\n", + " def _check_for_errors(self):\n", + " # compares input channels of data to input channels of Convolution2DLayer\n", + " if self.X_batch_feedforward.shape[input_channel_index] != self.input_channels:\n", + " raise AssertionError(\n", + " f\"ERROR: Number of input channels in data ({self.X_batch_feedforward.shape[input_channel_index]}) is not equal to input channels in Convolution2DLayerOPT ({self.input_channels})! Please change the number of input channels of the Convolution2DLayer such that they are equal\"\n", + " )" + ] + }, + { + "cell_type": "markdown", + "id": "3729d0f3", + "metadata": { + "editable": true + }, + "source": [ + "### The Convolutional Neural Network (CNN)\n", + "\n", + "Finally, we present the code for the CNN. The CNN class organizes all the layers, and allows for training on image data." + ] + }, + { + "cell_type": "code", + "execution_count": 31, + "id": "4c63d821", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "import math\n", + "import autograd.numpy as np\n", + "import sys\n", + "import warnings\n", + "from autograd import grad, elementwise_grad\n", + "from random import random, seed\n", + "from copy import deepcopy\n", + "from typing import Tuple, Callable\n", + "from sklearn.utils import resample\n", + "\n", + "warnings.simplefilter(\"error\")\n", + "\n", + "\n", + "class CNN:\n", + " def __init__(\n", + " self,\n", + " cost_func: Callable = CostCrossEntropy,\n", + " scheduler: Scheduler = Adam(eta=1e-4, rho=0.9, rho2=0.999),\n", + " seed: int = None,\n", + " ):\n", + " \"\"\"\n", + " Description:\n", + " ------------\n", + " Instantiates CNN object\n", + "\n", + " Parameters:\n", + " ------------\n", + " I output_func (costFunctions) cost function for feed forward neural network part of CNN,\n", + " such as \"CostLogReg\", \"CostOLS\" or \"CostCrossEntropy\"\n", + "\n", + " II scheduler (Scheduler) optional parameter, default set to Adam. Can also be set to other\n", + " schedulers such as AdaGrad, Momentum, RMS_prop and Constant. Note that schedulers have\n", + " to be instantiated first with proper parameters (for example eta, rho and rho2 for Adam)\n", + "\n", + " III seed (int) used for seeding all random operations\n", + " \"\"\"\n", + " self.layers = list()\n", + " self.cost_func = cost_func\n", + " self.scheduler = scheduler\n", + " self.schedulers_weight = list()\n", + " self.schedulers_bias = list()\n", + " self.seed = seed\n", + " self.pred_format = None\n", + "\n", + " def add_FullyConnectedLayer(\n", + " self, nodes: int, act_func=LRELU, scheduler=None\n", + " ) -> None:\n", + " \"\"\"\n", + " Description:\n", + " ------------\n", + " Add a FullyConnectedLayer to the CNN, i.e. a hidden layer in the feed forward neural\n", + " network part of the CNN. Often called a Dense layer in literature\n", + "\n", + " Parameters:\n", + " ------------\n", + " I nodes (int) number of nodes in FullyConnectedLayer\n", + " II act_func (activationFunctions) activation function of FullyConnectedLayer,\n", + " such as \"sigmoid\", \"RELU\", \"LRELU\", \"softmax\" or \"identity\"\n", + " III scheduler (Scheduler) optional parameter, default set to Adam. Can also be set to other\n", + " schedulers such as AdaGrad, Momentum, RMS_prop and Constant\n", + " \"\"\"\n", + " assert self.layers, \"FullyConnectedLayer should follow FlattenLayer in CNN\"\n", + "\n", + " if scheduler is None:\n", + " scheduler = self.scheduler\n", + "\n", + " layer = FullyConnectedLayer(nodes, act_func, scheduler, self.seed)\n", + " self.layers.append(layer)\n", + "\n", + " def add_OutputLayer(self, nodes: int, output_func=sigmoid, scheduler=None) -> None:\n", + " \"\"\"\n", + " Description:\n", + " ------------\n", + " Add an OutputLayer to the CNN, i.e. a the final layer in the feed forward neural\n", + " network part of the CNN\n", + "\n", + " Parameters:\n", + " ------------\n", + " I nodes (int) number of nodes in OutputLayer. Set nodes=1 for binary classification and\n", + " nodes = number of classes for multi-class classification\n", + " II output_func (activationFunctions) activation function for the output layer, such as\n", + " \"identity\" for regression, \"sigmoid\" for binary classification and \"softmax\" for multi-class\n", + " classification\n", + " III scheduler (Scheduler) optional parameter, default set to Adam. Can also be set to other\n", + " schedulers such as AdaGrad, Momentum, RMS_prop and Constant\n", + " \"\"\"\n", + " assert self.layers, \"OutputLayer should follow FullyConnectedLayer in CNN\"\n", + "\n", + " if scheduler is None:\n", + " scheduler = self.scheduler\n", + "\n", + " output_layer = OutputLayer(\n", + " nodes, output_func, self.cost_func, scheduler, self.seed\n", + " )\n", + " self.layers.append(output_layer)\n", + " self.pred_format = output_layer.get_pred_format()\n", + "\n", + " def add_FlattenLayer(self, act_func=LRELU) -> None:\n", + " \"\"\"\n", + " Description:\n", + " ------------\n", + " Add a FlattenLayer to the CNN, which flattens the image data such that it is formatted to\n", + " be used in the feed forward neural network part of the CNN\n", + " \"\"\"\n", + " self.layers.append(FlattenLayer(act_func=act_func, seed=self.seed))\n", + "\n", + " def add_Convolution2DLayer(\n", + " self,\n", + " input_channels=1,\n", + " feature_maps=1,\n", + " kernel_height=3,\n", + " kernel_width=3,\n", + " v_stride=1,\n", + " h_stride=1,\n", + " pad=\"same\",\n", + " act_func=LRELU,\n", + " optimized=True,\n", + " ) -> None:\n", + " \"\"\"\n", + " Description:\n", + " ------------\n", + " Add a Convolution2DLayer to the CNN, i.e. a convolutional layer with a 2 dimensional kernel. Should be\n", + " the first layer added to the CNN\n", + "\n", + " Parameters:\n", + " ------------\n", + " I input_channels (int) specifies amount of input channels. For monochrome images, use input_channels\n", + " = 1, and input_channels = 3 for colored images, where each channel represents one of R, G and B\n", + " II feature_maps (int) amount of feature maps in CNN\n", + " III kernel_height (int) height of the kernel, also called 'convolutional filter' in literature\n", + " IV kernel_width (int) width of the kernel, also called 'convolutional filter' in literature\n", + " V v_stride (int) value of vertical stride for dimentionality reduction\n", + " VI h_stride (int) value of horizontal stride for dimentionality reduction\n", + " VII pad (str) default = \"same\" ensures output size is the same as input size (given stride=1)\n", + " VIII act_func (activationFunctions) default = \"LRELU\", nonlinear activation function\n", + " IX optimized (bool) default = True, uses Convolution2DLayerOPT if True which is much faster when\n", + " compared to Convolution2DLayer, which is a more straightforward, understandable implementation\n", + " \"\"\"\n", + " if optimized:\n", + " conv_layer = Convolution2DLayerOPT(\n", + " input_channels,\n", + " feature_maps,\n", + " kernel_height,\n", + " kernel_width,\n", + " v_stride,\n", + " h_stride,\n", + " pad,\n", + " act_func,\n", + " self.seed,\n", + " reset_weights_independently=False,\n", + " )\n", + " else:\n", + " conv_layer = Convolution2DLayer(\n", + " input_channels,\n", + " feature_maps,\n", + " kernel_height,\n", + " kernel_width,\n", + " v_stride,\n", + " h_stride,\n", + " pad,\n", + " act_func,\n", + " self.seed,\n", + " reset_weights_independently=False,\n", + " )\n", + " self.layers.append(conv_layer)\n", + "\n", + " def add_PoolingLayer(\n", + " self, kernel_height=2, kernel_width=2, v_stride=1, h_stride=1, pooling=\"max\"\n", + " ) -> None:\n", + " \"\"\"\n", + " Description:\n", + " ------------\n", + " Add a Pooling2DLayer to the CNN, i.e. a pooling layer that reduces the dimentionality of\n", + " the image data. It is not necessary to use a Pooling2DLayer when creating a CNN, but it\n", + " can be used to speed up the training\n", + "\n", + " Parameters:\n", + " ------------\n", + " I kernel_height (int) height of the kernel used for pooling\n", + " II kernel_width (int) width of the kernel used for pooling\n", + " III v_stride (int) value of vertical stride for dimentionality reduction\n", + " IV h_stride (int) value of horizontal stride for dimentionality reduction\n", + " V pooling (str) either \"max\" or \"average\", describes type of pooling performed\n", + " \"\"\"\n", + " pooling_layer = Pooling2DLayer(\n", + " kernel_height, kernel_width, v_stride, h_stride, pooling, self.seed\n", + " )\n", + " self.layers.append(pooling_layer)\n", + "\n", + " def fit(\n", + " self,\n", + " X: np.ndarray,\n", + " t: np.ndarray,\n", + " epochs: int = 100,\n", + " lam: float = 0,\n", + " batches: int = 1,\n", + " X_val: np.ndarray = None,\n", + " t_val: np.ndarray = None,\n", + " ) -> dict:\n", + " \"\"\"\n", + " Description:\n", + " ------------\n", + " Fits the CNN to input X for a given amount of epochs. Performs feedforward and backpropagation passes,\n", + " can utilize batches, regulariziation and validation if desired.\n", + "\n", + " Parameters:\n", + " ------------\n", + " X (numpy array) with input data in format [images, input channels,\n", + " image height, image_width]\n", + " t (numpy array) target labels for input data\n", + " epochs (int) amount of epochs\n", + " lam (float) regulariziation term lambda\n", + " batches (int) amount of batches input data splits into\n", + " X_val (numpy array) validation data\n", + " t_val (numpy array) target labels for validation data\n", + "\n", + " Returns:\n", + " ------------\n", + " scores (dict) a dictionary with \"train_error\", \"train_acc\", \"val_error\", val_acc\" keys\n", + " that contain numpy arrays with float values of all accuracies/errors over all epochs.\n", + " Can be used to create plots. Also used to update the progress bar during training\n", + " \"\"\"\n", + "\n", + " # setup\n", + " if self.seed is not None:\n", + " np.random.seed(self.seed)\n", + "\n", + " # initialize weights\n", + " self._initialize_weights(X)\n", + "\n", + " # create arrays for score metrics\n", + " scores = self._initialize_scores(epochs)\n", + "\n", + " assert batches <= t.shape[0]\n", + " batch_size = X.shape[0] // batches\n", + "\n", + " try:\n", + " for epoch in range(epochs):\n", + " for batch in range(batches):\n", + " # minibatch gradient descent\n", + " # If the for loop has reached the last batch, take all thats left\n", + " if batch == batches - 1:\n", + " X_batch = X[batch * batch_size :, :, :, :]\n", + " t_batch = t[batch * batch_size :, :]\n", + " else:\n", + " X_batch = X[\n", + " batch * batch_size : (batch + 1) * batch_size, :, :, :\n", + " ]\n", + " t_batch = t[batch * batch_size : (batch + 1) * batch_size, :]\n", + "\n", + " self._feedforward(X_batch)\n", + " self._backpropagate(t_batch, lam)\n", + "\n", + " # reset schedulers for each epoch (some schedulers pass in this call)\n", + " for layer in self.layers:\n", + " if isinstance(layer, FullyConnectedLayer):\n", + " layer._reset_scheduler()\n", + "\n", + " # computing performance metrics\n", + " scores = self._compute_scores(scores, epoch, X, t, X_val, t_val)\n", + "\n", + " # printing progress bar\n", + " print_length = self._progress_bar(\n", + " epoch,\n", + " epochs,\n", + " scores,\n", + " )\n", + " # allows for stopping training at any point and seeing the result\n", + " except KeyboardInterrupt:\n", + " pass\n", + "\n", + " # visualization of training progression (similiar to tensorflow progression bar)\n", + " sys.stdout.write(\"\\r\" + \" \" * print_length)\n", + " sys.stdout.flush()\n", + " self._progress_bar(\n", + " epochs,\n", + " epochs,\n", + " scores,\n", + " )\n", + " sys.stdout.write(\"\")\n", + "\n", + " return scores\n", + "\n", + " def _feedforward(self, X_batch) -> np.ndarray:\n", + " \"\"\"\n", + " Description:\n", + " ------------\n", + " Performs the feedforward pass for all layers in the CNN. Called from fit()\n", + " \"\"\"\n", + " a = X_batch\n", + " for layer in self.layers:\n", + " a = layer._feedforward(a)\n", + "\n", + " return a\n", + "\n", + " def _backpropagate(self, t_batch, lam) -> None:\n", + " \"\"\"\n", + " Description:\n", + " ------------\n", + " Performs backpropagation for all layers in the CNN. Called from fit()\n", + " \"\"\"\n", + " assert len(self.layers) >= 2\n", + " reversed_layers = self.layers[::-1]\n", + "\n", + " # for every layer, backwards\n", + " for i in range(len(reversed_layers) - 1):\n", + " layer = reversed_layers[i]\n", + " prev_layer = reversed_layers[i + 1]\n", + "\n", + " # OutputLayer\n", + " if isinstance(layer, OutputLayer):\n", + " prev_a = prev_layer.get_prev_a()\n", + " weights_next, delta_next = layer._backpropagate(t_batch, prev_a, lam)\n", + "\n", + " # FullyConnectedLayer\n", + " elif isinstance(layer, FullyConnectedLayer):\n", + " assert (\n", + " delta_next is not None\n", + " ), \"No OutputLayer to follow FullyConnectedLayer\"\n", + " assert (\n", + " weights_next is not None\n", + " ), \"No OutputLayer to follow FullyConnectedLayer\"\n", + " prev_a = prev_layer.get_prev_a()\n", + " weights_next, delta_next = layer._backpropagate(\n", + " weights_next, delta_next, prev_a, lam\n", + " )\n", + "\n", + " # FlattenLayer\n", + " elif isinstance(layer, FlattenLayer):\n", + " assert (\n", + " delta_next is not None\n", + " ), \"No FullyConnectedLayer to follow FlattenLayer\"\n", + " assert (\n", + " weights_next is not None\n", + " ), \"No FullyConnectedLayer to follow FlattenLayer\"\n", + " delta_next = layer._backpropagate(weights_next, delta_next)\n", + "\n", + " # Convolution2DLayer and Convolution2DLayerOPT\n", + " elif isinstance(layer, Convolution2DLayer):\n", + " assert (\n", + " delta_next is not None\n", + " ), \"No FlattenLayer to follow Convolution2DLayer\"\n", + " delta_next = layer._backpropagate(delta_next)\n", + "\n", + " # Pooling2DLayer\n", + " elif isinstance(layer, Pooling2DLayer):\n", + " assert delta_next is not None, \"No Layer to follow Pooling2DLayer\"\n", + " delta_next = layer._backpropagate(delta_next)\n", + "\n", + " # Catch error\n", + " else:\n", + " raise NotImplementedError\n", + "\n", + " def _compute_scores(\n", + " self,\n", + " scores: dict,\n", + " epoch: int,\n", + " X: np.ndarray,\n", + " t: np.ndarray,\n", + " X_val: np.ndarray,\n", + " t_val: np.ndarray,\n", + " ) -> dict:\n", + " \"\"\"\n", + " Description:\n", + " ------------\n", + " Computes scores such as training error, training accuracy, validation error\n", + " and validation accuracy for the CNN depending on if a validation set is used\n", + " and if the CNN performs classification or regression\n", + "\n", + " Returns:\n", + " ------------\n", + " scores (dict) a dictionary with \"train_error\", \"train_acc\", \"val_error\", val_acc\" keys\n", + " that contain numpy arrays with float values of all accuracies/errors over all epochs.\n", + " Can be used to create plots. Also used to update the progress bar during training\n", + " \"\"\"\n", + "\n", + " pred_train = self.predict(X)\n", + " cost_function_train = self.cost_func(t)\n", + " train_error = cost_function_train(pred_train)\n", + " scores[\"train_error\"][epoch] = train_error\n", + "\n", + " if X_val is not None and t_val is not None:\n", + " cost_function_val = self.cost_func(t_val)\n", + " pred_val = self.predict(X_val)\n", + " val_error = cost_function_val(pred_val)\n", + " scores[\"val_error\"][epoch] = val_error\n", + "\n", + " if self.pred_format != \"Regression\":\n", + " train_acc = self._accuracy(pred_train, t)\n", + " scores[\"train_acc\"][epoch] = train_acc\n", + " if X_val is not None and t_val is not None:\n", + " val_acc = self._accuracy(pred_val, t_val)\n", + " scores[\"val_acc\"][epoch] = val_acc\n", + "\n", + " return scores\n", + "\n", + " def _initialize_scores(self, epochs) -> dict:\n", + " \"\"\"\n", + " Description:\n", + " ------------\n", + " Initializes scores such as training error, training accuracy, validation error\n", + " and validation accuracy for the CNN\n", + "\n", + " Returns:\n", + " ------------\n", + " A dictionary with \"train_error\", \"train_acc\", \"val_error\", val_acc\" keys that\n", + " will contain numpy arrays with float values of all accuracies/errors over all epochs\n", + " when passed through the _compute_scores() function during fit()\n", + " \"\"\"\n", + " scores = dict()\n", + "\n", + " train_errors = np.empty(epochs)\n", + " train_errors.fill(np.nan)\n", + " val_errors = np.empty(epochs)\n", + " val_errors.fill(np.nan)\n", + "\n", + " train_accs = np.empty(epochs)\n", + " train_accs.fill(np.nan)\n", + " val_accs = np.empty(epochs)\n", + " val_accs.fill(np.nan)\n", + "\n", + " scores[\"train_error\"] = train_errors\n", + " scores[\"val_error\"] = val_errors\n", + " scores[\"train_acc\"] = train_accs\n", + " scores[\"val_acc\"] = val_accs\n", + "\n", + " return scores\n", + "\n", + " def _initialize_weights(self, X: np.ndarray) -> None:\n", + " \"\"\"\n", + " Description:\n", + " ------------\n", + " Initializes weights for all layers in CNN\n", + "\n", + " Parameters:\n", + " ------------\n", + " I X (np.ndarray) input of format [img, feature_maps, height, width]\n", + " \"\"\"\n", + " prev_nodes = X\n", + " for layer in self.layers:\n", + " prev_nodes = layer._reset_weights(prev_nodes)\n", + "\n", + " def predict(self, X: np.ndarray, *, threshold=0.5) -> np.ndarray:\n", + " \"\"\"\n", + " Description:\n", + " ------------\n", + " Predicts output of input X\n", + "\n", + " Parameters:\n", + " ------------\n", + " I X (np.ndarray) input [img, feature_maps, height, width]\n", + " \"\"\"\n", + "\n", + " prediction = self._feedforward(X)\n", + "\n", + " if self.pred_format == \"Binary\":\n", + " return np.where(prediction > threshold, 1, 0)\n", + " elif self.pred_format == \"Multi-class\":\n", + " class_prediction = np.zeros(prediction.shape)\n", + " for i in range(prediction.shape[0]):\n", + " class_prediction[i, np.argmax(prediction[i, :])] = 1\n", + " return class_prediction\n", + " else:\n", + " return prediction\n", + "\n", + " def _accuracy(self, prediction: np.ndarray, target: np.ndarray) -> float:\n", + " \"\"\"\n", + " Description:\n", + " ------------\n", + " Calculates accuracy of given prediction to target\n", + "\n", + " Parameters:\n", + " ------------\n", + " I prediction (np.ndarray): output of predict() fuction\n", + " (1s and 0s in case of classification, and real numbers in case of regression)\n", + " II target (np.ndarray): vector of true values (What the network should predict)\n", + "\n", + " Returns:\n", + " ------------\n", + " A floating point number representing the percentage of correctly classified instances.\n", + " \"\"\"\n", + " assert prediction.size == target.size\n", + " return np.average((target == prediction))\n", + "\n", + " def _progress_bar(self, epoch: int, epochs: int, scores: dict) -> int:\n", + " \"\"\"\n", + " Description:\n", + " ------------\n", + " Displays progress of training\n", + " \"\"\"\n", + " progression = epoch / epochs\n", + " epoch -= 1\n", + " print_length = 40\n", + " num_equals = int(progression * print_length)\n", + " num_not = print_length - num_equals\n", + " arrow = \">\" if num_equals > 0 else \"\"\n", + " bar = \"[\" + \"=\" * (num_equals - 1) + arrow + \"-\" * num_not + \"]\"\n", + " perc_print = self._fmt(progression * 100, N=5)\n", + " line = f\" {bar} {perc_print}% \"\n", + "\n", + " for key, score in scores.items():\n", + " if np.isnan(score[epoch]) == False:\n", + " value = self._fmt(score[epoch], N=4)\n", + " line += f\"| {key}: {value} \"\n", + " print(line, end=\"\\r\")\n", + " return len(line)\n", + "\n", + " def _fmt(self, value: int, N=4) -> str:\n", + " \"\"\"\n", + " Description:\n", + " ------------\n", + " Formats decimal numbers for progress bar\n", + " \"\"\"\n", + " if value > 0:\n", + " v = value\n", + " elif value < 0:\n", + " v = -10 * value\n", + " else:\n", + " v = 1\n", + " n = 1 + math.floor(math.log10(v))\n", + " if n >= N - 1:\n", + " return str(round(value))\n", + " # or overflow\n", + " return f\"{value:.{N-n-1}f}\"" + ] + }, + { + "cell_type": "markdown", + "id": "6b0ce5da", + "metadata": { + "editable": true + }, + "source": [ + "### Usage of CNN code\n", + "\n", + "Using the CNN codebase is very simple. We begin by initiating a CNN\n", + "object, which takes a cost function, a scheduler and a seed as its\n", + "arguments. If a scheduler is not provided, it will per default\n", + "initiate an Adam scheduler with eta=1e-4, and if a seed is not\n", + "provided, the CNN will not be seeded, meaning it will run with a\n", + "different random seed every run. Below we demonstrate an initiation of\n", + "our CNN." + ] + }, + { + "cell_type": "code", + "execution_count": 32, + "id": "ebb4b539", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "adam_scheduler = Adam(eta=1e-3, rho=0.9, rho2=0.999)\n", + "cnn = CNN(cost_func=CostCrossEntropy, scheduler=adam_scheduler, seed=2023)" + ] + }, + { + "cell_type": "markdown", + "id": "a530c013", + "metadata": { + "editable": true + }, + "source": [ + "Now that we have our CNN object, we can begin to add layers to it!\n", + "Many of the add_layer functions have default values, for example\n", + "add_Convolution2DLayer() has a default v_stride and h_stride of\n", + "1. However, these can of course be set to any value you please. Note\n", + "that the input channels of a subsequent convolutional layer must equal\n", + "the previous convolutional layer's feature maps." + ] + }, + { + "cell_type": "code", + "execution_count": 33, + "id": "a0dea1a7", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "cnn.add_Convolution2DLayer(\n", + " input_channels=1,\n", + " feature_maps=1,\n", + " kernel_height=3,\n", + " kernel_width=3,\n", + " act_func=LRELU,\n", + ")\n", + "\n", + "cnn.add_FlattenLayer()\n", + "\n", + "cnn.add_FullyConnectedLayer(30, LRELU)\n", + "\n", + "cnn.add_FullyConnectedLayer(20, LRELU)\n", + "\n", + "cnn.add_OutputLayer(10, softmax)" + ] + }, + { + "cell_type": "markdown", + "id": "82fbc808", + "metadata": { + "editable": true + }, + "source": [ + "Here we have created a CNN with the following architecture:\n", + "\n", + "1. A convolutional layer with 1 input channel, with a kernel height of 2 and a width of 2, which uses LRELU as its non-linearity function. This layer outputs 1 feature map, which feed into the subsequent layer.\n", + "\n", + "2. A flatten layer\n", + "\n", + "3. A hidden layer with 30 nodes, with LRELU as its activation function\n", + "\n", + "4. Another hidden layer but with 20 nodes\n", + "\n", + "5. The output layer, with softmax as its activation function and 10 nodes. We use 10 nodes because we will be using a dataset with 10 classes.\n", + "\n", + "Now, before we can train the model, we need to load in our data. We\n", + "will use the MNIST dataset and use 10000 $28 \\times 28 images$." + ] + }, + { + "cell_type": "code", + "execution_count": 34, + "id": "ff126b57", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "from sklearn.datasets import fetch_openml\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "def onehot(target: np.ndarray):\n", + " onehot = np.zeros((target.size, target.max() + 1))\n", + " onehot[np.arange(target.size), target] = 1\n", + " return onehot\n", + "\n", + "# get dataset\n", + "dataset = fetch_openml(\"mnist_784\", parser=\"auto\")\n", + "mnist = dataset.data.to_numpy(dtype=\"float\")[:10000, :]\n", + "\n", + "# scale data\n", + "for i in range(mnist.shape[1]):\n", + " mnist[:, i] /= 255\n", + " \n", + "# reshape to add single input channel to data shape [inputs, input_channels, height, width]\n", + "mnist = mnist.reshape(mnist.shape[0], 1, 28, 28)\n", + "\n", + "# one hot encode target as we are doing multi-class classification\n", + "target = onehot(np.array([int(i) for i in dataset.target.to_numpy()[:10000]]))\n", + "\n", + "# split into training and validation data\n", + "x_train, x_val, y_train, y_val = train_test_split(mnist, target)" + ] + }, + { + "cell_type": "markdown", + "id": "8bd37284", + "metadata": { + "editable": true + }, + "source": [ + "Now we may train our model. Note that we can utilize regularization in\n", + "the CNN by using the lam (lambda) parameter in fit(), and utilize\n", + "different types of gradient descent by specifying the amount of\n", + "batches via the batches parameter as shown below.\n", + "\n", + "The functionfit() returns a score dictionary of the training error and\n", + "accuracy (and validation error and accuracy if a validation set is\n", + "provided) which can be used to plot the error and accuracy of the\n", + "model over epochs." + ] + }, + { + "cell_type": "code", + "execution_count": 35, + "id": "b273c240", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "scores = cnn.fit(\n", + " x_train,\n", + " y_train,\n", + " lam=1e-5,\n", + " batches=10,\n", + " epochs=100,\n", + " X_val=x_val,\n", + " t_val=y_val,\n", + ")\n", + "\n", + "plt.plot(scores[\"train_acc\"], label=\"Training\")\n", + "plt.plot(scores[\"val_acc\"], label=\"Validation\")\n", + "plt.ylim([0.8,1])\n", + "plt.xlabel(\"Epochs\")\n", + "plt.ylabel(\"Accuracy\")\n", + "plt.legend()\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "9f246cc2", + "metadata": { + "editable": true + }, + "source": [ + "Considering we only trained the model for 100 epochs without any tuning of the hyperparameters, this result is pretty good.\n", + "\n", + "The codebase allows for great flexibility in CNN\n", + "architectures. Pooling layers can be added before, inbetween or after\n", + "convolutional layers, but due to the great optimizations made within\n", + "Convolution2DLayerOPT, we recommend using the v_stride and h_stride\n", + "parameters in add_Convolution2DLayer() to reduce the dimentionality of\n", + "the problem as the pooling layer is slow in comparison. To use the\n", + "unoptimized version of Convolution2DLayer, simply pass optimized=False\n", + "as an argument in add_Convolution2DLayer().\n", + "\n", + "If one wishes to perform binary classification using the CNN, simply\n", + "use the cost function 'CostLogReg' when initializing the CNN and use 1\n", + "node at the OutputLayer.\n", + "\n", + "Below we have created another, more untraditional architecture using\n", + "our code to demonstrate its flexibility and different attributes such\n", + "as asymmetric stride that might become useful when constructing your\n", + "own CNN." + ] + }, + { + "cell_type": "code", + "execution_count": 36, + "id": "6684df44", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "adam_scheduler = Adam(eta=1e-3, rho=0.9, rho2=0.999)\n", + "cnn = CNN(cost_func=CostCrossEntropy, scheduler=adam_scheduler, seed=2023)\n", + "\n", + "cnn.add_Convolution2DLayer(\n", + " input_channels=1,\n", + " feature_maps=7,\n", + " kernel_height=7,\n", + " kernel_width=1,\n", + " act_func=LRELU,\n", + ")\n", + "\n", + "cnn.add_PoolingLayer(\n", + " kernel_height=2,\n", + " kernel_width=2,\n", + " pooling=\"average\",\n", + ")\n", + "\n", + "cnn.add_PoolingLayer(\n", + " kernel_height=2,\n", + " kernel_width=2,\n", + " pooling=\"max\",\n", + ")\n", + "\n", + "cnn.add_Convolution2DLayer(\n", + " input_channels=7,\n", + " feature_maps=1,\n", + " kernel_height=4,\n", + " kernel_width=4,\n", + " v_stride=2,\n", + " h_stride=3,\n", + " act_func=LRELU,\n", + " optimized=False,\n", + ")\n", + "\n", + "cnn.add_Convolution2DLayer(\n", + " input_channels=1,\n", + " feature_maps=1,\n", + " kernel_height=2,\n", + " kernel_width=2,\n", + " act_func=sigmoid,\n", + " optimized=True,\n", + ")\n", + "\n", + "cnn.add_PoolingLayer(\n", + " kernel_height=2,\n", + " kernel_width=2,\n", + " pooling=\"max\"\n", + ")\n", + "\n", + "cnn.add_FlattenLayer()\n", + "\n", + "cnn.add_FullyConnectedLayer(100, LRELU)\n", + "\n", + "cnn.add_FullyConnectedLayer(10, sigmoid)\n", + "\n", + "cnn.add_FullyConnectedLayer(101, identity)\n", + "\n", + "cnn.add_OutputLayer(10, softmax)" + ] + }, + { + "cell_type": "markdown", + "id": "a20d9002", + "metadata": { + "editable": true + }, + "source": [ + "Here we see the use of asymmetrical 1D kernels such as the $7 \\times\n", + "1$ kernel in the first convolutional layer, both max and average\n", + "pooling, asymmetric stride in the unoptimized convolutional layer,\n", + "more pooling, a flatten layer, a hidden layer with 100 nodes using\n", + "LRELU, another hidden layer with 10 hidden nodes that uses the sigmoid\n", + "activation function, and another hidden layer with 101 nodes which\n", + "utilizes no activation function (identity). Finally, we arrive at the\n", + "output layer with 10 nodes, which uses softmax as its activation\n", + "function." + ] + }, + { + "cell_type": "markdown", + "id": "2eac2c7e", + "metadata": { + "editable": true + }, + "source": [ + "### Additional Remarks\n", + "\n", + "The stride parameter controls the distance between each convolution\n", + "and the kernel/filter. If our image is padded, stride is the only\n", + "parameter that determines the size of the output from a convolutional\n", + "layer. However, if we decide not to perform any padding, the size of\n", + "the output feature map depends on both the stride and kernel size. It\n", + "is important to note that neither the stride nor the kernel has to be\n", + "symmetrical. This means that we can use a rectangular filter if we\n", + "choose, and the stride in the vertical direction (axis=0 in Python)\n", + "does not need to be the same as the stride in the horizontal direction\n", + "(axis=1 in Python). It may even be the case that asymmetric\n", + "combinations of stride or kernel dimensions, or both, yield better\n", + "results than symmetric values for these parameters." + ] + }, + { + "cell_type": "code", + "execution_count": 37, + "id": "12387ab5", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "def convolve(image, kernel, stride=1):\n", + " for i in range(2):\n", + " kernel = np.rot90(kernel)\n", + "\n", + " k_half_height = kernel.shape[0] // 2\n", + " k_half_width = kernel.shape[0] // 2\n", + "\n", + " conv_image = np.zeros(image.shape)\n", + " pad_image = padding(image, kernel)\n", + "\n", + " for i in range(k_half_height, conv_image.shape[0] + k_half_height, stride):\n", + " for j in range(k_half_width, conv_image.shape[1] + k_half_width, stride):\n", + " conv_image[i - k_half_height, j - k_half_width] = np.sum(\n", + " pad_image[\n", + " i - k_half_height : i + k_half_height + 1, j - k_half_width : j + k_half_width + 1\n", + " ]\n", + " * kernel\n", + " )\n", + "\n", + " return conv_image" + ] + }, + { + "cell_type": "markdown", + "id": "0a08b11f", + "metadata": { + "editable": true + }, + "source": [ + "### Remarks on the speed\n", + "\n", + "Despite the naive convolution algorithm shown above working finely, it\n", + "is extremely slow, requiring approximately 20-30 seconds to process a\n", + "single image. The time complexity of 2D convolution, which is O(NMnm),\n", + "rapidly becomes a constraint and may, at worst, make computations\n", + "infeasible. Consequently, optimizing the naive 2D convolution\n", + "algorithm is a necessity, as the execution time of the algorithm\n", + "significantly increases as the input data size expands. This can pose\n", + "a bottleneck in applications that necessitate real-time processing of\n", + "large data volumes, such as image and video processing, deep learning,\n", + "and scientific simulations.\n", + "\n", + "To address this issue, we shall present two widely used optimization\n", + "techniques: the separable kernel approach and Fast Fourier Transform\n", + "(FFT). Both of these methods can drastically reduce the computational\n", + "complexity of convolution and enhance the overall efficiency of\n", + "processing substantial data quantities. While we shall refrain from\n", + "delving into the intricacies of these algorithms, we strongly\n", + "encourage you to examine at least the application of FFT to optimize\n", + "computations." + ] + }, + { + "cell_type": "markdown", + "id": "596d27ad", + "metadata": { + "editable": true + }, + "source": [ + "### Convolution using separable kernels" + ] + }, + { + "cell_type": "code", + "execution_count": 38, + "id": "0ab0cb35", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "def conv2DSep(image, kernel, coef, stride=1, pad=\"zero\"):\n", + " for i in range(2):\n", + " kernel = np.rot90(kernel)\n", + "\n", + " # The kernel is quadratic, thus we only need one of its dimensions\n", + " half_dim = kernel.shape[0] // 2\n", + "\n", + " ker1 = np.array(kernel[0, :])\n", + " ker2 = np.array(kernel[:, 0])\n", + "\n", + " if pad == \"zero\":\n", + " conv_image = np.zeros(image.shape)\n", + " pad_image = padding(image, kernel)\n", + " else:\n", + " conv_image = np.zeros(\n", + " (image.shape[0] - kernel.shape[0], image.shape[1] - kernel.shape[1])\n", + " )\n", + " pad_image = image[:, :]\n", + "\n", + " for i in range(half_dim, conv_image.shape[0] + half_dim, stride):\n", + " for j in range(half_dim, conv_image.shape[1] + half_dim, stride):\n", + " conv_image[i - half_dim, j - half_dim] = (\n", + " pad_image[\n", + " i - half_dim : i + half_dim + 1, j - half_dim : j + half_dim + 1\n", + " ]\n", + " @ ker1\n", + " @ ker2.T\n", + " * coef\n", + " )\n", + "\n", + " return conv_image\n", + "\n", + "img_path = img_path = \"../data/IMG-2167.JPG\"\n", + "image_of_cute_dog = imageio.imread(img_path, mode=\"L\")\n", + "start_time = time.time()\n", + "filtered_image = conv2DSep(image_of_cute_dog, kernel=sobel_kernel, coef=1)\n", + "print(f'Time taken for convolution with seperated kernel on 128x128 image {time.time() - start_time}')\n", + "plt.imshow(filtered_image, cmap=\"gray\", vmin=0, vmax=255, aspect=\"auto\")\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "8896f1b3", + "metadata": { + "editable": true + }, + "source": [ + "By taking advantage of the capabilities of separable kernels, we can\n", + "effectively cut the computational expense of filtering an image in\n", + "half. Yet, if we seek even more rapid processing, we can turn to the\n", + "Fast Fourier Transform (FFT) algorithm provided by the numpy\n", + "library. By utilizing FFT to transform the input image and filter into\n", + "the frequency domain, we can perform convolution in this domain. This\n", + "approach significantly reduces the number of operations needed and\n", + "results in a marked speedup relative to other convolution\n", + "techniques. In addition, it is worth noting that the FFT is widely\n", + "regarded as one of the most critical algorithms developed to date,\n", + "with applications ranging from digital signal processing to scientific\n", + "computing." + ] + }, + { + "cell_type": "markdown", + "id": "2021cf7f", + "metadata": { + "editable": true + }, + "source": [ + "### Convolution in the Fourier domain" + ] + }, + { + "cell_type": "code", + "execution_count": 39, + "id": "27aee28e", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "start_time = time.time()\n", + "img_fft = np.fft.fft2(image_of_cute_dog)\n", + "kernel_fft = np.fft.fft2(sobel_kernel, s=image_of_cute_dog.shape)\n", + "\n", + "conv_image = img_fft * kernel_fft\n", + "\n", + "filtered_image = np.fft.ifft2(conv_image)\n", + "print(f'Time take for convolution in the fourier domain: {time.time() - start_time}')\n", + "plt.imshow(filtered_image.real, cmap=\"gray\", vmin=0, vmax=255, aspect=\"auto\")\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "0b4ae049", + "metadata": { + "editable": true + }, + "source": [ + "It is evident that executing convolution in the Fourier domain yields\n", + "the quickest computation time. Nonetheless, one should exercise\n", + "caution, particularly when dealing with images of relatively small\n", + "dimensions, as one of the other methods may prove to be more\n", + "expeditious than FFT-enhanced convolution. The overhead involved in\n", + "transferring both the image and filter into the Fourier domain,\n", + "followed by their subsequent transformation back into the spatial\n", + "domain, results in a minor inconvenience. Therefore, it is imperative\n", + "to remain cognizant of this fact when utilizing FFT as the primary\n", + "optimization technique." + ] } ], "metadata": {}, diff --git a/doc/src/week44/week44.do.txt b/doc/src/week44/week44.do.txt index 7b5dcdea1..ab239c653 100644 --- a/doc/src/week44/week44.do.txt +++ b/doc/src/week44/week44.do.txt @@ -1053,30 +1053,52 @@ print(test_acc) !split ===== Building our own CNN code ===== -# -# In this notebook we present flexible and readable python code for a CNN implemented with NumPy. We will present the code, showcase how to use the codebase and fit a CNN that yields a 99% accuracy on the 28x28 MNIST dataset within reasonable time. -# -# The CNN is compatible with all schedulers, cost functions and activation functions presented in https://github.com/EricEReber/Neural-Network, which we will also showcase in this notebook before the CNN. -# -# The CNN code consists of different types of Layer classes, including Convolution2DLayer, Pooling2DLayer, FlattenLayer, FullyConnectedLayer and OutputLayer, which can be added to the CNN object using the interface of the CNN class. This allows students to easily construct their own CNN, as well as allowing students to get used to an interface similar to that of TensorFlow which is used for real world applications. -# -# Another important feature of this code is that it throws errors if unreasonable decisions are made (for example using a kernel that is larger than the image, not using a FlattenLayer, etc), and provides the user with an informative error message. -# -# List of contents: \ -# I. Schedulers \ -# II. Activation Functions \ -# III. Cost Functions \ -# IV. Convolution \ -# V. Layers \ -# VI. CNN \ -# VII. Remarks -# ## I. Schedulers -# The code below shows object oriented implementations of the Constant, Momentum, Adagrad, AdagradMomentum, RMS prop and Adam schedulers. All of the classes belong to the shared abstract Scheduler class, and share the update_change() and reset() methods allowing for any of the schedulers to be seamlessly used during the training stage, as will later be shown in the fit() method of the neural network. Update_change() only has one parameter, the gradient ($\delta^{l}_{j}a^{l-1}_k$), and returns the change which will be subtracted from the weights. The reset() function takes no parameters, and resets the desired variables. For Constant and Momentum, reset does nothing. +Here we present a flexible and readable python code for a CNN +implemented with NumPy. We will present the code, showcase how to use +the codebase and fit a CNN that yields a 99% accuracy on the 28x28 +MNIST dataset within reasonable time. -# In[1]: +The CNN is compatible with all schedulers, cost functions and +activation functions discussed in constructing our neural network +codes. + + The CNN code consists of different types of Layer classes, including +Convolution2DLayer, Pooling2DLayer, FlattenLayer, FullyConnectedLayer +and OutputLayer, which can be added to the CNN object using the +interface of the CNN class. This allows you to easily construct your +own CNN, as well as allowing you to get used to an interface similar +to that of TensorFlow which is used for real world applications. +Another important feature of this code is that it throws errors if +unreasonable decisions are made (for example using a kernel that is +larger than the image, not using a FlattenLayer, etc), and provides +the user with an informative error message. +=== List of contents: === +o Schedulers +o Activation Functions +o Cost Functions +o Convolution +o Layers +o CNN +o Some final remarks + +=== Schedulers === + +The code below shows object oriented implementations of the Constant, +Momentum, Adagrad, AdagradMomentum, RMS prop and Adam schedulers. All +of the classes belong to the shared abstract Scheduler class, and +share the update_change() and reset() methods allowing for any of the +schedulers to be seamlessly used during the training stage, as will +later be shown in the fit() method of the neural +network. Update_change() only has one parameter, the gradient +($\delta^{l}_{j}a^{l-1}_k$), and returns the change which will be +subtracted from the weights. The reset() function takes no parameters, +and resets the desired variables. For Constant and Momentum, reset +does nothing. + +!bc pycod import autograd.numpy as np class Scheduler: @@ -1208,24 +1230,20 @@ class Adam(Scheduler): self.moment = 0 self.second = 0 +!ec -# ## Usage of schedulers -# -# To initalize a scheduler, simply create the object and pass in the necessary parameters such as the learning rate and the momentum as shown below. As the Scheduler class is an abstract class it should not called directly, and will raise an error upon usage. -# - -# In[2]: +=== Usage of schedulers === +To initalize a scheduler, simply create the object and pass in the necessary parameters such as the learning rate and the momentum as shown below. As the Scheduler class is an abstract class it should not called directly, and will raise an error upon usage. +!bc pycod momentum_scheduler = Momentum(eta=1e-3, momentum=0.9) adam_scheduler = Adam(eta=1e-3, rho=0.9, rho2=0.999) +!ec +Here is a small example for how a segment of code using schedulers could look. Switching out the schedulers is simple. -# Here is a small example for how a segment of code using schedulers could look. Switching out the schedulers is simple. - -# In[3]: - - +!bc pycod weights = np.ones((3,3)) print(f"Before scheduler:\n{weights=}") @@ -1237,16 +1255,17 @@ for e in range(epochs): adam_scheduler.reset() print(f"\nAfter scheduler:\n{weights=}") +!ec + +=== Cost functions === + +In this section we will quickly look at cost functions that can be +used when creating the neural network. Every cost function takes the +target vector as its parameter, and returns a function valued only at +X such that it may easily be differentiated. -# ## II. Cost functions -# -# In this section we will quickly look at cost functions that can be used when creating the neural network. Every cost function takes the target vector as its parameter, and returns a function valued only at X such that it may easily be differentiated. -# - -# In[4]: - - +!bc pycod def CostOLS(target): """ Return OLS function valued only at X, so @@ -1284,15 +1303,15 @@ def CostCrossEntropy(target): return func +!ec -# ## Usage of cost functions -# -# Below we will provide a short example of how these cost function may be used to obtain results if you wish to test them out on your own using AutoGrad's automatic differentiation. -# - -# In[5]: +=== Usage of cost functions === +Below we will provide a short example of how these cost function may +be used to obtain results if you wish to test them out on your own +using AutoGrad's automatic differentiation. +!bc pycod from autograd import grad target = np.array([[1, 2, 3]]).T @@ -1303,15 +1322,18 @@ cost_func_derivative = grad(cost_func(target)) valued_at_a = cost_func_derivative(a) print(f"Derivative of cost function {cost_func.__name__} valued at a:\n{valued_at_a}") +!ec + +=== Activation functions === + +Finally, before we look at the layers that make up the neural network, +we will look at the activation functions which can be specified +between the hidden layers and as the output function. Each function +can be valued for any given vector or matrix X, and can be +differentiated via derivate(). -# ## III. Activation functions -# -# Finally, before we look at the layers that make up the neural network, we will look at the activation functions which can be specified between the hidden layers and as the output function. Each function can be valued for any given vector or matrix X, and can be differentiated via derivate(). -# - -# In[6]: - +!bc pycod import autograd.numpy as np from autograd import elementwise_grad @@ -1360,17 +1382,19 @@ def derivate(func): else: return elementwise_grad(func) +!ec -# -# ## Usage of activation functions -# -# Below is a short demonstration of how to use an activation function. The derivative of the activation function will be important when calculating the output delta term during backpropagation. Note that derivate() can also be used for cost functions for a more generalized approach. -# +=== Usage of activation functions === -# In[7]: +Below we present a short demonstration of how to use an activation +function. The derivative of the activation function will be important +when calculating the output delta term during backpropagation. Note +that derivate() can also be used for cost functions for a more +generalized approach. +!bc pycod z = np.array([[4, 5, 6]]).T print(f"Input to activation function:\n{z}") @@ -1381,120 +1405,190 @@ print(f"\nOutput from {act_func.__name__} activation function:\n{a}") act_func_derivative = derivate(act_func) valued_at_z = act_func_derivative(a) print(f"\nDerivative of {act_func.__name__} activation function valued at z:\n{valued_at_z}") +!ec +=== Convolution === -# ## IV. Convolution -# -# In order to construct a convolutional neural network (CNN), it is crucial to comprehend the fundamental principles of convolution and how it aids in extracting information from images. Convolution, at its core, is merely a mathematical operation between two functions that yields another function. It is represented by an integral between two functions, which is typically expressed as: -# -# $$(f \ast g)(t):=\int_{-\infty}^{\infty} f(\tau) g(t-\tau) d \tau$$ -# -# Here, f and g are the two functions on which we want to perform an operation. The outcome of the convolution operation is represented by $(f \ast g)$, and it is derived by sliding the function g over f and computing the integral of their product at each position. If both functions are continuous, convolution takes the form shown above. However, if we discretize both f and g, the convolution operation will take the form of a sum between the elements of f and g: -# -# -# $$(f \ast g)[n]=\sum_{m=0}^{n-1} f[m] g[n-m]$$ -# -# The key idea we utilize to extract the information contained in an image is to slide an $m \times n$ matrix *g* over an $m \times n$ matrix *f*. In our case, *f* represents the image, while *g* represents the kernel, oftentimes called a filter. However, since our convolution will be a two-dimensional variant, we need to extend our mathematical formula with an additional summation: -# -# -# $$(f \ast g)[i, j]\sum_{m=0}^{M-1}\sum_{n=0}^{N-1} f[m,n] g[i-m, j-n]$$ -# -# It is imperative to note that the size of the kernel g is significantly smaller than the size of the input image f, thereby reducing the amount of computation necessary for feature extraction. Furthermore, the kernel is usually a trainable parameter in a convolutional neural network, allowing the network to learn appropriate kernels for specific tasks. -# -# Now to give you an example of how 2D convolution works in practice, suppose we have an image *f* of dimension $6 \times 6$ -# -# $$ -# f = \begin{bmatrix} -# 4 & 1 & 2 & 9 & 8 & 6 \\ -# 9 & 5 & 9 & 5 & 8 & 5 \\ -# 1 & 5 & 9 & 7 & 6 & 4 \\ -# 2 & 9 & 8 & 3 & 7 & 1 \\ -# 8 & 1 & 6 & 4 & 2 & 2 \\ -# 1 & 0 & 5 & 7 & 8 & 2 \\ -# \end{bmatrix} -# $$ -# -# and a $3 \times 3$ kernel *g* called a low-pass filter. Note that the kernel is usually rotated by 180 degrees during convolution, however this has no effect on this kernel. -# -# $$g = \frac{1}{9} -# \begin{bmatrix} -# 1 & 1 & 1 \\ -# 1 & 1 & 1 \\ -# 1 & 1 & 1 \\ -# \end{bmatrix} -# $$ -# -# In order to filter the image, we have to extract a $3 \times 3$ element from the upper left corner of *f*, and perform element-wise multiplication of the extracted image pixels with the elements of the kernel *g*: -# -# $$ -# \begin{bmatrix} -# 4 & 1 & 2 \\ -# 9 & 5 & 9 \\ -# 1 & 5 & 9 \\ -# \end{bmatrix} -# \cdot -# \begin{bmatrix} -# \frac{1}{9} & \frac{1}{9} & \frac{1}{9} \\ -# \frac{1}{9} & \frac{1}{9} & \frac{1}{9} \\ -# \frac{1}{9} & \frac{1}{9} & \frac{1}{9} \\ -# \end{bmatrix} -# = -# \begin{bmatrix} -# \frac{4}{9} & \frac{1}{9} & \frac{2}{9} \\ -# \frac{9}{9} & \frac{5}{9} & \frac{9}{9} \\ -# \frac{1}{9} & \frac{5}{9} & \frac{9}{9} \\ -# \end {bmatrix} -# = \textbf{A} -# $$ -# -# Then, following the multiplication, we summarize all the elements of the resulting matrix A: -# -# $$ -# (f \ast g)[0, 0]= \sum_{i=0}^{2} \sum_{j=0}^{2} a_{i,j} = 5 -# $$ -# -# Which corresponds to the first element of the filtered image $(f \ast g)$. -# -# Here we use a stride of 1, a parameter denoted *s* which describes how many indexes we move the kernel *g* to the right before repeating the calculations above for the next $3 \times 3$ element of the image *f*. It is usually presumed that *s*=1, however, larger values for *s* can be used to reduce the dimentionality of the filtered image such that the convolution operation is more computationally efficient. In the context of a convolutional neural network, this will become very useful. -# -# The full result of the convolution is: -# -# $$ -# (f \ast g) = -# \begin{bmatrix} -# 5 & 5.78 & 7 & 6.44 \\ -# 6.33 & 6.67 & 6.89 & 5.11 \\ -# 5.44 & 5.78 & 5.78 & 4 \\ -# 4.44 & 4.78 & 5.56 & 4 \\ -# \end{bmatrix} -# $$ -# -# The result is markedly smaller in shape than the original image. This occurs when using convolution without first padding the image with additional columns and rows, allowing us to keep the original image shape after sliding the kernel over the image. -# How many rows and columns we wish to pad the image with depends strictly on the shape of the kernel, as we wish to pad the image with *r* additional rows and *c* additional columns. -# -# $$r =\lfloor \frac{kernel\ height}{2} \rfloor \cdot 2 \\ -# c =\lfloor \frac{kernel\ width}{2} \rfloor \cdot 2$$ -# -# Note the notation $\lfloor \frac{kernel width}{2} \rfloor$ means that we floor the result of the division, meaning we round down to a whole number in case $\frac{kernel width}{2}$ results in a floating point number. -# -# Using those simple equations, we find out by how much we have to extend the dimensions of the original image. Before proceeding, however, we might ask what we shall fill the additional rows and columns with? One of the most common approaches to padding is zero-padding, which as the name suggest, involves filling the rows and columns with zeros. This is the approach that we will be using for this demonstration. If we apply this padding to out original 6 x 6 image, the result will we an 8 x 8 image as the kernel has a width and height of 3. Note that the original image is encapsuled by the zero-padded rows and columns: -# -# \begin{bmatrix} -# 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ -# 0 & 4 & 1 & 2 & 9 & 8 & 6 & 0 \\ -# 0 & 9 & 5 & 9 & 5 & 8 & 5 & 0 \\ -# 0 & 1 & 5 & 9 & 7 & 6 & 4 & 0 \\ -# 0 & 2 & 9 & 8 & 3 & 7 & 1 & 0 \\ -# 0 & 8 & 1 & 6 & 4 & 2 & 2 & 0 \\ -# 0 & 1 & 0 & 5 & 7 & 8 & 2 & 0 \\ -# 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ -# \end{bmatrix} -# -# Below we have provided code that demonstrates padding and convolution. As you will see when we run the code, the size of the image will remain unchanged when using padding. +In order to construct a convolutional neural network (CNN), it is +crucial to comprehend the fundamental principles of convolution and +how it aids in extracting information from images. Convolution, at its +core, is merely a mathematical operation between two functions that +yields another function. It is represented by an integral between two +functions, which is typically expressed as: -# In[8]: +!bt +\[ +(f \ast g)(t):=\int_{-\infty}^{\infty} f(\tau) g(t-\tau) d \tau. +\] +!et +Here, f and g are the two functions on which we want to perform an +operation. The outcome of the convolution operation is represented by +$(f \ast g)$, and it is derived by sliding the function g over f and +computing the integral of their product at each position. If both +functions are continuous, convolution takes the form shown +above. However, if we discretize both f and g, the convolution +operation will take the form of a sum between the elements of f and g: +!bt +\[ +(f \ast g)[n]=\sum_{m=0}^{n-1} f[m] g[n-m]. +\] +!et +The key idea we utilize to extract the information contained in an +image is to slide an $m \times n$ matrix *g* over an $m \times n$ +matrix *f*. In our case, *f* represents the image, while *g* +represents the kernel, oftentimes called a filter. However, since our +convolution will be a two-dimensional variant, we need to extend our +mathematical formula with an additional summation: + +!bt +\[ +(f \ast g)[i, j]\sum_{m=0}^{M-1}\sum_{n=0}^{N-1} f[m,n] g[i-m, j-n]. +\] +!et + +It is imperative to note that the size of the kernel g is +significantly smaller than the size of the input image f, thereby +reducing the amount of computation necessary for feature +extraction. Furthermore, the kernel is usually a trainable parameter +in a convolutional neural network, allowing the network to learn +appropriate kernels for specific tasks. + +To give you an example of how 2D convolution works in practice, +suppose we have an image *f* of dimension $6 \times 6$ + +!bt +\[ +f = \begin{bmatrix} +4 & 1 & 2 & 9 & 8 & 6 \\ +9 & 5 & 9 & 5 & 8 & 5 \\ +1 & 5 & 9 & 7 & 6 & 4 \\ +2 & 9 & 8 & 3 & 7 & 1 \\ +8 & 1 & 6 & 4 & 2 & 2 \\ +1 & 0 & 5 & 7 & 8 & 2 \\ +\end{bmatrix} +\] +!et + +and a $3 \times 3$ kernel *g* called a low-pass filter. Note that the +kernel is usually rotated by 180 degrees during convolution, however +this has no effect on this kernel. + +!bt +\[ +g = \frac{1}{9} +\begin{bmatrix} +1 & 1 & 1 \\ +1 & 1 & 1 \\ +1 & 1 & 1 \\ +\end{bmatrix} +\] +!et + +In order to filter the image, we have to extract a $3 \times 3$ +element from the upper left corner of *f*, and perform element-wise +multiplication of the extracted image pixels with the elements of the +kernel *g*: + +!bt +\[ +\begin{bmatrix} +4 & 1 & 2 \\ +9 & 5 & 9 \\ +1 & 5 & 9 \\ +\end{bmatrix} +\cdot +\begin{bmatrix} +\frac{1}{9} & \frac{1}{9} & \frac{1}{9} \\ +\frac{1}{9} & \frac{1}{9} & \frac{1}{9} \\ +\frac{1}{9} & \frac{1}{9} & \frac{1}{9} \\ +\end{bmatrix} += +\begin{bmatrix} +\frac{4}{9} & \frac{1}{9} & \frac{2}{9} \\ +\frac{9}{9} & \frac{5}{9} & \frac{9}{9} \\ +\frac{1}{9} & \frac{5}{9} & \frac{9}{9} \\ +\end {bmatrix} += \textbf{A} +\] +!et + +Then, following the multiplication, we summarize all the elements of the resulting matrix A: + +!bt +\[ +(f \ast g)[0, 0]= \sum_{i=0}^{2} \sum_{j=0}^{2} a_{i,j} = 5 +\] +!et + +Which corresponds to the first element of the filtered image $(f \ast g)$. + +Here we use a stride of 1, a parameter denoted *s* which describes how +many indexes we move the kernel *g* to the right before repeating the +calculations above for the next $3 \times 3$ element of the image +*f*. It is usually presumed that *s*=1, however, larger values for *s* +can be used to reduce the dimentionality of the filtered image such +that the convolution operation is more computationally efficient. In +the context of a convolutional neural network, this will become very +useful. + +The full result of the convolution is: + +!bt +\[ +(f \ast g) = +\begin{bmatrix} +5 & 5.78 & 7 & 6.44 \\ +6.33 & 6.67 & 6.89 & 5.11 \\ +5.44 & 5.78 & 5.78 & 4 \\ +4.44 & 4.78 & 5.56 & 4 \\ +\end{bmatrix} +\] +!et +The result is markedly smaller in shape than the original image. This occurs when using convolution without first padding the image with additional columns and rows, allowing us to keep the original image shape after sliding the kernel over the image. +How many rows and columns we wish to pad the image with depends strictly on the shape of the kernel, as we wish to pad the image with *r* additional rows and *c* additional columns. + +!bt +\[ +r =\lfloor \frac{kernel\ height}{2} \rfloor \cdot 2 \\ +c =\lfloor \frac{kernel\ width}{2} \rfloor \cdot 2 +\] +!et + +Note the notation $\lfloor \frac{kernel width}{2} \rfloor$ means that +we floor the result of the division, meaning we round down to a whole +number in case $\frac{kernel width}{2}$ results in a floating point +number. + +Using those simple equations, we find out by how much we have to +extend the dimensions of the original image. Before proceeding, +however, we might ask what we shall fill the additional rows and +columns with? One of the most common approaches to padding is +zero-padding, which as the name suggest, involves filling the rows and +columns with zeros. This is the approach that we will be using for +this demonstration. If we apply this padding to out original $6 \times 6$ +image, the result will be an $8 \times 8$ image as the kernel has a width and +height of 3. Note that the original image is encapsuled by the +zero-padded rows and columns: + +!bt +\[ +\begin{bmatrix} +0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ +0 & 4 & 1 & 2 & 9 & 8 & 6 & 0 \\ +0 & 9 & 5 & 9 & 5 & 8 & 5 & 0 \\ +0 & 1 & 5 & 9 & 7 & 6 & 4 & 0 \\ +0 & 2 & 9 & 8 & 3 & 7 & 1 & 0 \\ +0 & 8 & 1 & 6 & 4 & 2 & 2 & 0 \\ +0 & 1 & 0 & 5 & 7 & 8 & 2 & 0 \\ +0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ +\] +\end{bmatrix} +!et +Below we have provided code that demonstrates padding and convolution. As you will see when we run the code, the size of the image will remain unchanged when using padding.~ + +!bc pycod import numpy as np def padding(image, kernel): @@ -1566,14 +1660,13 @@ def convolve(image, kernel, stride=1): ) return conv_image +!ec +Fun fact: When filtering images, you will see that convolution involves rotating the kernel by 180 degrees. +However, this is not the case when applying convolution in a CNN, where the same operation not rotated by 180 degrees is called +cross-correlation. -# Fun fact: When filtering images, you will see that convolution involves rotating the kernel by 180 degrees. -# However, this is not the case when applying convolution in a CNN, where the same operation not rotated by 180 degrees is called -# cross-correlation. - -# In[9]: - +!bc pycod original_image = np.array([[4, 1, 2, 9, 8, 6], [9, 5, 9, 5, 8, 5], @@ -1590,13 +1683,21 @@ print(f"{original_image.shape=}") convolved_image = convolve(original_image, kernel, stride=1) print(f"{convolved_image.shape=}") +!ec +As you can see, the resulting image is of the same size as the +original image. To round of our demonstration of convolution, we will +present the results of convolution using commonly used kernels. In a +CNN, the values of the kernels are randomly initialized, and then +learned during training. These kernels will extract information +regarding the picture, such as for example the edge detection filter +demonstrated below extracts the edges present in the picture. Of +course, there is no guarantee that the CNN will learn an edge +detection filter, but this should provide some intuiton as to how the +CNN is able to use kernels to make better predictions than a regular +feed forward neural network. -# As you can see, the resulting image is of the same size as the original image. To round of our demonstration of convolution, we will present the results of convolution using commonly used kernels. In a CNN, the values of the kernels are randomly initialized, and then learned during training. These kernels will extract information regarding the picture, such as for example the edge detection filter demonstrated below extracts the edges present in the picture. Of course, there is no guarantee that the CNN will learn an edge detection filter, but this should provide some intuiton as to how the CNN is able to use kernels to make better predictions than a regular feed forward neural network. - -# In[10]: - - +!bc pycod # Now an example using a real image and first a gaussian low-pass filter and then a sobel filter import numpy as np import imageio.v3 as imageio @@ -1636,15 +1737,15 @@ filtered_image = convolve(image_of_cute_dog, sobel_kernel) plt.imshow(filtered_image, cmap="gray", vmin=0, vmax=255, aspect="auto") plt.title("Result of convolution with sobel kernel (edge detection filter)") plt.show() +!ec +=== Layers === -# ## V. Layers -# -# The code below initialises global variables for readability and describes the abstract class Layers. This is not important in order to understand the CNN, but is benefitial for organizing the code neatly. - -# In[11]: - +The code below initialises global variables for readability and +describes the abstract class Layers. This is not important in order to +understand the CNN, but is benefitial for organizing the code neatly. +!bc pycod import math import autograd.numpy as np from copy import deepcopy, copy @@ -1675,19 +1776,44 @@ class Layer: def _reset_weights(self, previous_nodes): raise NotImplementedError +!ec +=== Convolution2DLayer: convolution in a hidden layer === -# ### Convolution2DLayer: convolution in a hidden layer -# -# After establishing the foundational understanding of applying convolution to spatial data, let us delve into the intricate workings of a convolutional layer in a Convolutional Neural Network (CNN). The primary function of convolution, as previously discussed, is to extract pertinent information from images while simultaneously decreasing the scale of our data. To initiate the image processing, we shall begin by partitioning the images into color channels (unless the image is grayscale), comprising three primary colors: red, green, and blue. We will subsequently utilize trainable kernels to construct a higher-dimensional encoding of each channel called feature maps. Successive layers will receive these feature maps as inputs, generating further encodings, albeit with reduced dimensions. The term trainable kernels denotes the initialization of pre-defined kernel-shaped weights, which we will then train via backpropagation, similar to how weights are trained in a Feedforward Neural Network. -# -# To ensure seamless integration between our implementation of the convolutional layer and popular machine learning frameworks like Tensorflow (Keras) and PyTorch, we have adopted a design pattern that mirrors the construction of models using these APIs. This involves implementing our convolutional layer as a Python class or object, which allows for a more modular and flexible approach to building neural networks. By structuring our code in this way, users can easily incorporate our implementation into their existing machine learning pipelines without having to make significant changes to their codebase. Additionally, this design pattern promotes code reusability and makes it easier to maintain and update our convolutional layer implementation over time. -# -# Note that the Convolution2DLayer takes in an activation function as a parameter, as it also performs non-linearity. +After establishing the foundational understanding of applying +convolution to spatial data, let us delve into the intricate workings +of a convolutional layer in a Convolutional Neural Network (CNN). The +primary function of convolution, as previously discussed, is to +extract pertinent information from images while simultaneously +decreasing the scale of our data. To initiate the image processing, we +shall begin by partitioning the images into color channels (unless the +image is grayscale), comprising three primary colors: red, green, and +blue. We will subsequently utilize trainable kernels to construct a +higher-dimensional encoding of each channel called feature +maps. Successive layers will receive these feature maps as inputs, +generating further encodings, albeit with reduced dimensions. The term +trainable kernels denotes the initialization of pre-defined +kernel-shaped weights, which we will then train via backpropagation, +similar to how weights are trained in a Feedforward Neural Network. -# In[12]: + +To ensure seamless integration between our implementation of the +convolutional layer and popular machine learning frameworks like +Tensorflow (Keras) and PyTorch, we have adopted a design pattern that +mirrors the construction of models using these APIs. This involves +implementing our convolutional layer as a Python class or object, +which allows for a more modular and flexible approach to building +neural networks. By structuring our code in this way, users can easily +incorporate our implementation into their existing machine learning +pipelines without having to make significant changes to their +codebase. Additionally, this design pattern promotes code reusability +and makes it easier to maintain and update our convolutional layer +implementation over time. + +Note that the Convolution2DLayer takes in an activation function as a parameter, as it also performs non-linearity. +!bc pycod class Convolution2DLayer(Layer): def __init__( self, @@ -1963,18 +2089,28 @@ class Convolution2DLayer(Layer): raise AssertionError( f"ERROR: Number of input channels in data ({self.X_batch_feedforward.shape[input_channel_index]}) is not equal to input channels in Convolution2DLayerOPT ({self.input_channels})! Please change the number of input channels of the Convolution2DLayer such that they are equal" ) +!ec +=== Backpropagation in the convolutional layer === -# ### Backpropagation in the convolutional layer -# -# As you may have noticed, we have not yet explained how the backpropagation algorithm works in a convolutional layer. However, having covered all other major details about convolutional layers, we are now prepared to do so. It should come as no surprise that the calculation of delta terms at each convolutional layer takes the form of convolution. After the gradient has been propagated backwards through the flattening layer, where it was reshaped into an appropriate form, calculating the update value for the kernel is simply a matter of convolving the output gradient with the input of the layer for which we are updating the weights. For more detail, this article serves as an excellent resource https://pavisj.medium.com/convolutions-and-backpropagations-46026a8f5d2c +As you may have noticed, we have not yet explained how the +backpropagation algorithm works in a convolutional layer. However, +having covered all other major details about convolutional layers, we +are now prepared to do so. It should come as no surprise that the +calculation of delta terms at each convolutional layer takes the form +of convolution. After the gradient has been propagated backwards +through the flattening layer, where it was reshaped into an +appropriate form, calculating the update value for the kernel is +simply a matter of convolving the output gradient with the input of +the layer for which we are updating the weights. For more detail, this +article serves as an excellent resource, see +URL:"https://pavisj.medium.com/convolutions-and-backpropagations-46026a8f5d2c" -# ### Demonstration -# We can use the convolutional layer above to perform a simple convolution on an image of the now familiar cute dog. - -# In[13]: +=== Demonstration === +We can use the convolutional layer above to perform a simple convolution on an image of the now familiar cute dog. +!bc pycod import numpy as np import imageio.v3 as imageio import matplotlib.pyplot as plt @@ -2012,21 +2148,37 @@ image_of_cute_dog = image_of_cute_dog.transpose(0, 3, 1, 2) # plot the result of the convolution plot_convolution_result(image_of_cute_dog, layer) +!ec + +We cobserve that the result has half the pixels on each axis due to +the fact that we've used a horizontal and vertical stride of 2. The +result of this convolution is not very insightfull, as the kernel has +completely random values for the first feedforward pass. However, as +we perform multiple forward and backward passes, the results of the +convolution should provide identifying features of the image it uses +for classification. -# We can observe that the result has half the pixels on each axis due to the fact that we've used a horizontal and vertical stride of 2. The result of this convolution is not very insightfull, as the kernel has completely random values for the first feedforward pass. However, as we perform multiple forward and backward passes, the results of the convolution should provide identifying features of the image it uses for classification. -# -# Note that image data usually comes in many different shapes and sizes, but for our CNN we require the input data be formatted as \[Number of inputs, input channels, input height, input width\]. Occasionally, the data you come accross use will be formatted like this, but on many occasions reshaping and transposing the dimensions is sadly necessary. +Note that image data usually comes in many different shapes and sizes, +but for our CNN we require the input data be formatted as \[Number of +inputs, input channels, input height, input width\]. Occasionally, the +data you come accross use will be formatted like this, but on many +occasions reshaping and transposing the dimensions is sadly necessary. -# ## Pooling Layer -# -# The pooling layer is another widely used type of layer in convolutional neural networks that enables data downsampling to a more manageable size. Despite recent technological advancements that allow for convolution without excessive size reduction of the data, the pooling layer still remains a fundamental component of convolutional neural networks. It can be used before, after, or in between convolutional layers, although finding the optimal placement of layers and network depth requires experimentation to achieve the best performance for a given problem. The code we provide allows you to perform two types of pooling known as max pooling and average pooling. -# -# Below is the code for the pooling layer: - -# In[14]: +=== Pooling Layer === +The pooling layer is another widely used type of layer in +convolutional neural networks that enables data downsampling to a more +manageable size. Despite recent technological advancements that allow +for convolution without excessive size reduction of the data, the +pooling layer still remains a fundamental component of convolutional +neural networks. It can be used before, after, or in between +convolutional layers, although finding the optimal placement of layers +and network depth requires experimentation to achieve the best +performance for a given problem. The code we provide allows you to +perform two types of pooling known as max pooling and average pooling. +!bc pycod class Pooling2DLayer(Layer): def __init__( self, @@ -2178,15 +2330,21 @@ class Pooling2DLayer(Layer): assert ( self.X_batch_feedforward.shape[height_index] >= self.kernel_height ), f"ERROR: Pooling kernel height_index ({self.kernel_height}) larger than data height_index ({self.X_batch_feedforward.input.shape[3]}), please lower the kernel height_index of the Pooling2DLayer" +!ec +=== Flattening Layer === -# ## Flattening Layer -# -# Before we can begin building our first CNN model, we need to introduce the flattening layer. As its name suggests, the flattening layer transforms the data into a one-dimensional vector that can be fed into the feedforward layers of our network. This layer plays a crucial role in preparing the data for further processing in the network. Additionally, the flattening layer is responsible for reshaping the gradient to the proper shape during backpropagation. This ensures that the kernels are correctly updated, allowing for effective learning in the network. - -# In[15]: - +Before we can begin building our first CNN model, we need to introduce +the flattening layer. As its name suggests, the flattening layer +transforms the data into a one-dimensional vector that can be fed into +the feedforward layers of our network. This layer plays a crucial role +in preparing the data for further processing in the +network. Additionally, the flattening layer is responsible for +reshaping the gradient to the proper shape during +backpropagation. This ensures that the kernels are correctly updated, +allowing for effective learning in the network. +!bc pycod class FlattenLayer(Layer): def __init__(self, act_func=LRELU, seed=None): super().__init__(seed) @@ -2239,15 +2397,24 @@ class FlattenLayer(Layer): def get_prev_a(self): return self.a_matrix +!ec +=== Fully Connected Layers === -# ## Fully Connected Layers -# -# Finally, the result from the flatten layer will pass to a series of fully connected layers, which function as a normal feed forward neural network. The fully connected layers are split into two classes; FullyConnectedLayer which acts as a hidden layer, and OutputLayer, which acts as the single output layer at the end of the CNN. If one wishes to use this codebase to construct a normal feed forward neural network, it must start with a FlattenLayer due to techincal details regarding weight intitialization. However many FullyConnectedLayers can be added to the CNN, and in each layer the amount of nodes, which activation function and scheduler to use can be specified. In practice, the scheduler will be specified in the CNN object initialization, and inherited if no other scheduler is specified. - -# In[16]: - +Finally, the result from the flatten layer will pass to a series of +fully connected layers, which function as a normal feed forward neural +network. The fully connected layers are split into two classes; +FullyConnectedLayer which acts as a hidden layer, and OutputLayer, +which acts as the single output layer at the end of the CNN. If one +wishes to use this codebase to construct a normal feed forward neural +network, it must start with a FlattenLayer due to techincal details +regarding weight intitialization. However many FullyConnectedLayers +can be added to the CNN, and in each layer the amount of nodes, which +activation function and scheduler to use can be specified. In +practice, the scheduler will be specified in the CNN object +initialization, and inherited if no other scheduler is specified. +!bc pycod class FullyConnectedLayer(Layer): # FullyConnectedLayer per default uses LRELU and Adam scheduler # with an eta of 0.0001, rho of 0.9 and rho2 of 0.999 @@ -2465,15 +2632,22 @@ class OutputLayer(FullyConnectedLayer): def get_pred_format(self): # returns format of prediction return self.pred_format +!ec + +=== Optimized Convolution2DLayer === + +For our CNN, we have also implemented an optimized version of the +Convolution2DLayer, Convolution2DLayerOPT, which runs much faster. See +VII. Remarks for discussion. This layer will per default be used by +the CNN due to its computational advantages, but is much less +readable. We've documented it such that specially interested students +can understand the principles behind it, but it is not recommended to +read. In short, we reshape and transpose parts of the image such that +the convolutional operation can be swapped out for a simple matrix +multiplication. -# ## BONUS: Optimized Convolution2DLayer -# -# For our CNN, we have also implemented an optimized version of the Convolution2DLayer, Convolution2DLayerOPT, which runs much faster. See VII. Remarks for discussion. This layer will per default be used by the CNN due to its computational advantages, but is much less readable. We've documented it such that specially interested students can understand the principles behind it, but it is not recommended to read. In short, we reshape and transpose parts of the image such that the convolutional operation can be swapped out for a simple matrix multiplication. - -# In[17]: - - +!bc pycod class Convolution2DLayerOPT(Convolution2DLayer): """ Am optimized version of the convolution layer above which @@ -2767,15 +2941,13 @@ class Convolution2DLayerOPT(Convolution2DLayer): raise AssertionError( f"ERROR: Number of input channels in data ({self.X_batch_feedforward.shape[input_channel_index]}) is not equal to input channels in Convolution2DLayerOPT ({self.input_channels})! Please change the number of input channels of the Convolution2DLayer such that they are equal" ) +!ec +=== The Convolutional Neural Network (CNN) === -# ## VI. The Convolutional Neural Network (CNN) -# -# Finally, we will present the code for the CNN. The CNN class organizes all the layers, and allows for training on image data. - -# In[18]: - +Finally, we present the code for the CNN. The CNN class organizes all the layers, and allows for training on image data. +!bc pycod import math import autograd.numpy as np import sys @@ -3300,24 +3472,31 @@ class CNN: return str(round(value)) # or overflow return f"{value:.{N-n-1}f}" +!ec +=== Usage of CNN code === -# ## Usage of CNN -# -# Using the CNN codebase is very simple. We begin by initiating a CNN object, which takes a cost function, a scheduler and a seed as its arguments. If a scheduler is not provided, it will per default initiate an Adam scheduler with eta=1e-4, and if a seed is not provided, the CNN will not be seeded, meaning it will run with a different random seed every run. Below we demonstrate an initiation of our CNN. - -# In[19]: - +Using the CNN codebase is very simple. We begin by initiating a CNN +object, which takes a cost function, a scheduler and a seed as its +arguments. If a scheduler is not provided, it will per default +initiate an Adam scheduler with eta=1e-4, and if a seed is not +provided, the CNN will not be seeded, meaning it will run with a +different random seed every run. Below we demonstrate an initiation of +our CNN. +!bc pycod adam_scheduler = Adam(eta=1e-3, rho=0.9, rho2=0.999) cnn = CNN(cost_func=CostCrossEntropy, scheduler=adam_scheduler, seed=2023) +!ec +Now that we have our CNN object, we can begin to add layers to it! +Many of the add_layer functions have default values, for example +add_Convolution2DLayer() has a default v_stride and h_stride of +1. However, these can of course be set to any value you please. Note +that the input channels of a subsequent convolutional layer must equal +the previous convolutional layer's feature maps. -# Now that we have our CNN object, we can begin to add layers to it! Many of the add_layer functions have default values, for example add_Convolution2DLayer() has a default v_stride and h_stride of 1. However, these can of course be set to any value you please. Note that the input channels of a subsequent convolutional layer must equal the previous convolutional layer's feature maps. - -# In[20]: - - +!bc pycod cnn.add_Convolution2DLayer( input_channels=1, feature_maps=1, @@ -3333,25 +3512,24 @@ cnn.add_FullyConnectedLayer(30, LRELU) cnn.add_FullyConnectedLayer(20, LRELU) cnn.add_OutputLayer(10, softmax) +!ec +Here we have created a CNN with the following architecture: + +o A convolutional layer with 1 input channel, with a kernel height of 2 and a width of 2, which uses LRELU as its non-linearity function. This layer outputs 1 feature map, which feed into the subsequent layer. -# Here we have created a CNN with the following architecture: -# -# (1) A convolutional layer with 1 input channel, with a kernel height of 2 and a width of 2, which uses LRELU as its non-linearity function. This layer outputs 1 feature map, which feed into the subsequent layer. -# -# (2) A flatten layer -# -# (3) A hidden layer with 30 nodes, with LRELU as its activation function -# -# (4) Another hidden layer but with 20 nodes -# -# (5) The output layer, with softmax as its activation function and 10 nodes. We use 10 nodes because we will be using a dataset with 10 classes. -# -# Now, before we can train the model, we need to load in our data. We will use the MNIST dataset and use 10000 28 x 28 images. +o A flatten layer -# In[21]: +o A hidden layer with 30 nodes, with LRELU as its activation function +o Another hidden layer but with 20 nodes +o The output layer, with softmax as its activation function and 10 nodes. We use 10 nodes because we will be using a dataset with 10 classes. + +Now, before we can train the model, we need to load in our data. We +will use the MNIST dataset and use 10000 $28 \times 28 images$. + +!bc pycod from sklearn.datasets import fetch_openml from sklearn.model_selection import train_test_split @@ -3376,15 +3554,19 @@ target = onehot(np.array([int(i) for i in dataset.target.to_numpy()[:10000]])) # split into training and validation data x_train, x_val, y_train, y_val = train_test_split(mnist, target) +!ec +Now we may train our model. Note that we can utilize regularization in +the CNN by using the lam (lambda) parameter in fit(), and utilize +different types of gradient descent by specifying the amount of +batches via the batches parameter as shown below. + +The functionfit() returns a score dictionary of the training error and +accuracy (and validation error and accuracy if a validation set is +provided) which can be used to plot the error and accuracy of the +model over epochs. -# Now we may train our model. Note that we can utilize regularization in the CNN by using the lam (lambda) parameter in fit(), and utilize different types of gradient descent by specifying the amount of batches via the batches parameter as shown below. -# -# fit() returns a score dictionary of the training error and accuracy (and validation error and accuracy if a validation set is provided) which can be used to plot the error and accuracy of the model over epochs. - -# In[22]: - - +!bc pycod scores = cnn.fit( x_train, y_train, @@ -3395,10 +3577,6 @@ scores = cnn.fit( t_val=y_val, ) - -# In[30]: - - plt.plot(scores["train_acc"], label="Training") plt.plot(scores["val_acc"], label="Validation") plt.ylim([0.8,1]) @@ -3406,19 +3584,29 @@ plt.xlabel("Epochs") plt.ylabel("Accuracy") plt.legend() plt.show() +!ec +Considering we only trained the model for 100 epochs without any tuning of the hyperparameters, this result is pretty good. + +The codebase allows for great flexibility in CNN +architectures. Pooling layers can be added before, inbetween or after +convolutional layers, but due to the great optimizations made within +Convolution2DLayerOPT, we recommend using the v_stride and h_stride +parameters in add_Convolution2DLayer() to reduce the dimentionality of +the problem as the pooling layer is slow in comparison. To use the +unoptimized version of Convolution2DLayer, simply pass optimized=False +as an argument in add_Convolution2DLayer(). -# Considering we only trained the model for 100 epochs without any tuning of the hyperparameters, this result is pretty good. -# -# The codebase allows for great flexibility in CNN architectures. Pooling layers can be added before, inbetween or after convolutional layers, but due to the great optimizations made within Convolution2DLayerOPT, we recommend using the v_stride and h_stride parameters in add_Convolution2DLayer() to reduce the dimentionality of the problem as the pooling layer is slow in comparison. To use the unoptimized version of Convolution2DLayer, simply pass optimized=False as an argument in add_Convolution2DLayer(). This will however, make us sad. -# -# If one wishes to perform binary classification using the CNN, simply use the cost function 'CostLogReg' when initializing the CNN and use 1 node at the OutputLayer. -# -# Below we have created another, more untraditional architecture using our code to demonstrate its flexibility and different attributes such as asymmetric stride that might become useful when constructing your own CNN. - -# In[24]: - +If one wishes to perform binary classification using the CNN, simply +use the cost function 'CostLogReg' when initializing the CNN and use 1 +node at the OutputLayer. + +Below we have created another, more untraditional architecture using +our code to demonstrate its flexibility and different attributes such +as asymmetric stride that might become useful when constructing your +own CNN. +!bc pycod adam_scheduler = Adam(eta=1e-3, rho=0.9, rho2=0.999) cnn = CNN(cost_func=CostCrossEntropy, scheduler=adam_scheduler, seed=2023) @@ -3477,19 +3665,35 @@ cnn.add_FullyConnectedLayer(10, sigmoid) cnn.add_FullyConnectedLayer(101, identity) cnn.add_OutputLayer(10, softmax) +!ec + +Here we see the use of asymmetrical 1D kernels such as the $7 \times +1$ kernel in the first convolutional layer, both max and average +pooling, asymmetric stride in the unoptimized convolutional layer, +more pooling, a flatten layer, a hidden layer with 100 nodes using +LRELU, another hidden layer with 10 hidden nodes that uses the sigmoid +activation function, and another hidden layer with 101 nodes which +utilizes no activation function (identity). Finally, we arrive at the +output layer with 10 nodes, which uses softmax as its activation +function. + +=== Additional Remarks === -# Here we see the use of asymmetrical 1D kernels such as the $7 \times 1$ kernel in the first convolutional layer, both max and average pooling, asymmetric stride in the unoptimized convolutional layer, more pooling, a flatten layer, a hidden layer with 100 nodes using LRELU, another hidden layer with 10 hidden nodes that uses the sigmoid activation function, and another hidden layer with 101 nodes which utilizes no activation function (identity). Finally, we arrive at the output layer with 10 nodes, which uses softmax as its activation function. - -# ## VII. Remarks (Extra) - -# ### Remarks about stride and kernel size -# -# The stride parameter controls the distance between each convolution and the kernel/filter. If our image is padded, stride is the only parameter that determines the size of the output from a convolutional layer. However, if we decide not to perform any padding, the size of the output feature map depends on both the stride and kernel size. It is important to note that neither the stride nor the kernel has to be symmetrical. This means that we can use a rectangular filter if we choose, and the stride in the vertical direction (axis=0 in Python) does not need to be the same as the stride in the horizontal direction (axis=1 in Python). It may even be the case that asymmetric combinations of stride or kernel dimensions, or both, yield better results than symmetric values for these parameters. - -# In[25]: - +The stride parameter controls the distance between each convolution +and the kernel/filter. If our image is padded, stride is the only +parameter that determines the size of the output from a convolutional +layer. However, if we decide not to perform any padding, the size of +the output feature map depends on both the stride and kernel size. It +is important to note that neither the stride nor the kernel has to be +symmetrical. This means that we can use a rectangular filter if we +choose, and the stride in the vertical direction (axis=0 in Python) +does not need to be the same as the stride in the horizontal direction +(axis=1 in Python). It may even be the case that asymmetric +combinations of stride or kernel dimensions, or both, yield better +results than symmetric values for these parameters. +!bc pycod def convolve(image, kernel, stride=1): for i in range(2): kernel = np.rot90(kernel) @@ -3510,19 +3714,33 @@ def convolve(image, kernel, stride=1): ) return conv_image +!ec +=== Remarks on the speed === -# ### Remarks on the speed -# -# Despite the naive convolution algorithm shown above working finely, it is extremely slow, requiring approximately 20-30 seconds to process a single image. The time complexity of 2D convolution, which is O(NMnm), rapidly becomes a constraint and may, at worst, make computations infeasible. Consequently, optimizing the naive 2D convolution algorithm is a necessity, as the execution time of the algorithm significantly increases as the input data size expands. This can pose a bottleneck in applications that necessitate real-time processing of large data volumes, such as image and video processing, deep learning, and scientific simulations. -# -# To address this issue, we shall present two widely used optimization techniques: the separable kernel approach and Fast Fourier Transform (FFT). Both of these methods can drastically reduce the computational complexity of convolution and enhance the overall efficiency of processing substantial data quantities. While we shall refrain from delving into the intricacies of these algorithms, we strongly encourage you to examine at least the application of FFT to optimize computations. +Despite the naive convolution algorithm shown above working finely, it +is extremely slow, requiring approximately 20-30 seconds to process a +single image. The time complexity of 2D convolution, which is O(NMnm), +rapidly becomes a constraint and may, at worst, make computations +infeasible. Consequently, optimizing the naive 2D convolution +algorithm is a necessity, as the execution time of the algorithm +significantly increases as the input data size expands. This can pose +a bottleneck in applications that necessitate real-time processing of +large data volumes, such as image and video processing, deep learning, +and scientific simulations. -# ### Convolution using separable kernels - -# In[26]: +To address this issue, we shall present two widely used optimization +techniques: the separable kernel approach and Fast Fourier Transform +(FFT). Both of these methods can drastically reduce the computational +complexity of convolution and enhance the overall efficiency of +processing substantial data quantities. While we shall refrain from +delving into the intricacies of these algorithms, we strongly +encourage you to examine at least the application of FFT to optimize +computations. +=== Convolution using separable kernels === +!bc pycod def conv2DSep(image, kernel, coef, stride=1, pad="zero"): for i in range(2): kernel = np.rot90(kernel) @@ -3562,15 +3780,23 @@ filtered_image = conv2DSep(image_of_cute_dog, kernel=sobel_kernel, coef=1) print(f'Time taken for convolution with seperated kernel on 128x128 image {time.time() - start_time}') plt.imshow(filtered_image, cmap="gray", vmin=0, vmax=255, aspect="auto") plt.show() +!ec +By taking advantage of the capabilities of separable kernels, we can +effectively cut the computational expense of filtering an image in +half. Yet, if we seek even more rapid processing, we can turn to the +Fast Fourier Transform (FFT) algorithm provided by the numpy +library. By utilizing FFT to transform the input image and filter into +the frequency domain, we can perform convolution in this domain. This +approach significantly reduces the number of operations needed and +results in a marked speedup relative to other convolution +techniques. In addition, it is worth noting that the FFT is widely +regarded as one of the most critical algorithms developed to date, +with applications ranging from digital signal processing to scientific +computing. -# By taking advantage of the capabilities of separable kernels, we can effectively cut the computational expense of filtering an image in half. Yet, if we seek even more rapid processing, we can turn to the Fast Fourier Transform (FFT) algorithm provided by the numpy library. By utilizing FFT to transform the input image and filter into the frequency domain, we can perform convolution in this domain. This approach significantly reduces the number of operations needed and results in a marked speedup relative to other convolution techniques. In addition, it is worth noting that the FFT is widely regarded as one of the most critical algorithms developed to date, with applications ranging from digital signal processing to scientific computing. - -# ### Convolution in the Fourier domain - -# In[27]: - - +=== Convolution in the Fourier domain === +!bc pycod start_time = time.time() img_fft = np.fft.fft2(image_of_cute_dog) kernel_fft = np.fft.fft2(sobel_kernel, s=image_of_cute_dog.shape) @@ -3581,9 +3807,16 @@ filtered_image = np.fft.ifft2(conv_image) print(f'Time take for convolution in the fourier domain: {time.time() - start_time}') plt.imshow(filtered_image.real, cmap="gray", vmin=0, vmax=255, aspect="auto") plt.show() +!ec - -# It is evident that executing convolution in the Fourier domain yields the quickest computation time. Nonetheless, one should exercise caution, particularly when dealing with images of relatively small dimensions, as one of the other methods may prove to be more expeditious than FFT-enhanced convolution. The overhead involved in transferring both the image and filter into the Fourier domain, followed by their subsequent transformation back into the spatial domain, results in a minor inconvenience. Therefore, it is imperative to remain cognizant of this fact when utilizing FFT as the primary optimization technique. - -# +It is evident that executing convolution in the Fourier domain yields +the quickest computation time. Nonetheless, one should exercise +caution, particularly when dealing with images of relatively small +dimensions, as one of the other methods may prove to be more +expeditious than FFT-enhanced convolution. The overhead involved in +transferring both the image and filter into the Fourier domain, +followed by their subsequent transformation back into the spatial +domain, results in a minor inconvenience. Therefore, it is imperative +to remain cognizant of this fact when utilizing FFT as the primary +optimization technique.