diff --git a/doc/pub/week44/html/._week44-bs000.html b/doc/pub/week44/html/._week44-bs000.html index c696978c2..e73a75127 100644 --- a/doc/pub/week44/html/._week44-bs000.html +++ b/doc/pub/week44/html/._week44-bs000.html @@ -75,6 +75,12 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d None, 'a-deep-cnn-model-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Key Idea', 2, None, 'key-idea'), + ('How to do image compression before the era of deep learning', + 2, + None, + 'how-to-do-image-compression-before-the-era-of-deep-learning'), + ('The SVD example', 2, None, 'the-svd-example'), + ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Convolution Examples: Polynomial multiplication', 2, @@ -89,6 +95,8 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'a-more-efficient-way-of-coding-the-above-convolution'), + ('Commutative process', 2, None, 'commutative-process'), + ('Toeplitz matrices', 2, None, 'toeplitz-matrices'), ('Fourier series and Toeplitz matrices', 2, None, @@ -97,36 +105,75 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'generalizing-the-above-one-dimensional-case'), - ('Two-dimensional Objects', 2, None, 'two-dimensional-objects'), - ('CNNs in more detail', 2, None, 'cnns-in-more-detail'), - ('Performing a discrete convolution with padding ("From Raschka ' - 'et al":"https://github.com/rasbt/machine-learning-book")', + ('Memory considerations', 2, None, 'memory-considerations'), + ('Padding', 2, None, 'padding'), + ('New vector', 2, None, 'new-vector'), + ('Rewriting as dot products', 2, None, - 'performing-a-discrete-convolution-with-padding-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Performing a general discrete convolution ("From Raschka et ' + 'rewriting-as-dot-products'), + ('Cross correlation', 2, None, 'cross-correlation'), + ('Two-dimensional objects', 2, None, 'two-dimensional-objects'), + ('CNNs in more detail, simple example', + 2, + None, + 'cnns-in-more-detail-simple-example'), + ('The convolution stage', 2, None, 'the-convolution-stage'), + ('Finding the number of parameters', + 2, + None, + 'finding-the-number-of-parameters'), + ('New image (or volume)', 2, None, 'new-image-or-volume'), + ('Parameters to train, common settings', + 2, + None, + 'parameters-to-train-common-settings'), + ('Examples of CNN setups', 2, None, 'examples-of-cnn-setups'), + ('Summarizing: Performing a general discrete convolution ("From ' + 'Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, - 'performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Set of filters', 2, None, 'set-of-filters'), + 'summarizing-performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Pooling', 2, None, 'pooling'), - ('No zero padding, unit strides', - 2, - None, - 'no-zero-padding-unit-strides'), - ('Zero padding, unit strides', - 2, - None, - 'zero-padding-unit-strides'), - ('Half (same) padding', 2, None, 'half-same-padding'), - ('Full padding', 2, None, 'full-padding'), ('Pooling arithmetic', 2, None, 'pooling-arithmetic'), ('Pooling types ("From Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, 'pooling-types-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), + ('Building convolutional neural networks in Tensorflow and Keras', + 2, + None, + 'building-convolutional-neural-networks-in-tensorflow-and-keras'), + ('Setting it up', 2, None, 'setting-it-up'), + ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), + ('Strong correlations', 2, None, 'strong-correlations'), + ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), + ('Systematic reduction', 2, None, 'systematic-reduction'), + ('Prerequisites: Collect and pre-process data', + 2, + None, + 'prerequisites-collect-and-pre-process-data'), + ('Importing Keras and Tensorflow', + 2, + None, + 'importing-keras-and-tensorflow'), + ('Running with Keras', 2, None, 'running-with-keras'), + ('Final part', 2, None, 'final-part'), + ('Final visualization', 2, None, 'final-visualization'), + ('The CIFAR01 data set', 2, None, 'the-cifar01-data-set'), + ('Verifying the data set', 2, None, 'verifying-the-data-set'), + ('Set up the model', 2, None, 'set-up-the-model'), + ('Add Dense layers on top', 2, None, 'add-dense-layers-on-top'), + ('Compile and train the model', + 2, + None, + 'compile-and-train-the-model'), + ('Finally, evaluate the model', + 2, + None, + 'finally-evaluate-the-model'), ('Building our own CNN code', 2, None, @@ -173,27 +220,7 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Convolution in the Fourier domain', 3, None, - 'convolution-in-the-fourier-domain'), - ('Building convolutional neural networks in Tensorflow and Keras', - 2, - None, - 'building-convolutional-neural-networks-in-tensorflow-and-keras'), - ('Setting it up', 2, None, 'setting-it-up'), - ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), - ('Strong correlations', 2, None, 'strong-correlations'), - ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), - ('Systematic reduction', 2, None, 'systematic-reduction'), - ('Prerequisites: Collect and pre-process data', - 2, - None, - 'prerequisites-collect-and-pre-process-data'), - ('Importing Keras and Tensorflow', - 2, - None, - 'importing-keras-and-tensorflow'), - ('Running with Keras', 2, None, 'running-with-keras'), - ('Final part', 2, None, 'final-part'), - ('Final visualization', 2, None, 'final-visualization')]} + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -244,59 +271,74 @@ MathJax.Hub.Config({
  • CNNs in brief
  • A deep CNN model ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • Key Idea
  • -
  • Mathematics of CNNs
  • -
  • Convolution Examples: Polynomial multiplication
  • -
  • Efficient Polynomial Multiplication
  • -
  • Further simplification
  • -
  • A more efficient way of coding the above Convolution
  • -
  • Fourier series and Toeplitz matrices
  • -
  • Generalizing the above one-dimensional case
  • -
  • Two-dimensional Objects
  • -
  • CNNs in more detail
  • -
  • Performing a discrete convolution with padding ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Set of filters
  • -
  • Pooling
  • -
  • No zero padding, unit strides
  • -
  • Zero padding, unit strides
  • -
  • Half (same) padding
  • -
  • Full padding
  • -
  • Pooling arithmetic
  • -
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Building our own CNN code
  • -
  •    List of contents:
  • -
  •    Schedulers
  • -
  •    Usage of schedulers
  • -
  •    Cost functions
  • -
  •    Usage of cost functions
  • -
  •    Activation functions
  • -
  •    Usage of activation functions
  • -
  •    Convolution
  • -
  •    Layers
  • -
  •    Convolution2DLayer: convolution in a hidden layer
  • -
  •    Backpropagation in the convolutional layer
  • -
  •    Demonstration
  • -
  •    Pooling Layer
  • -
  •    Flattening Layer
  • -
  •    Fully Connected Layers
  • -
  •    Optimized Convolution2DLayer
  • -
  •    The Convolutional Neural Network (CNN)
  • -
  •    Usage of CNN code
  • -
  •    Additional Remarks
  • -
  •    Remarks on the speed
  • -
  •    Convolution using separable kernels
  • -
  •    Convolution in the Fourier domain
  • -
  • Building convolutional neural networks in Tensorflow and Keras
  • -
  • Setting it up
  • -
  • The MNIST dataset again
  • -
  • Strong correlations
  • -
  • Layers of a CNN
  • -
  • Systematic reduction
  • -
  • Prerequisites: Collect and pre-process data
  • -
  • Importing Keras and Tensorflow
  • -
  • Running with Keras
  • -
  • Final part
  • -
  • Final visualization
  • +
  • How to do image compression before the era of deep learning
  • +
  • The SVD example
  • +
  • Mathematics of CNNs
  • +
  • Mathematics of CNNs
  • +
  • Convolution Examples: Polynomial multiplication
  • +
  • Efficient Polynomial Multiplication
  • +
  • Further simplification
  • +
  • A more efficient way of coding the above Convolution
  • +
  • Commutative process
  • +
  • Toeplitz matrices
  • +
  • Fourier series and Toeplitz matrices
  • +
  • Generalizing the above one-dimensional case
  • +
  • Memory considerations
  • +
  • Padding
  • +
  • New vector
  • +
  • Rewriting as dot products
  • +
  • Cross correlation
  • +
  • Two-dimensional objects
  • +
  • CNNs in more detail, simple example
  • +
  • The convolution stage
  • +
  • Finding the number of parameters
  • +
  • New image (or volume)
  • +
  • Parameters to train, common settings
  • +
  • Examples of CNN setups
  • +
  • Summarizing: Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Pooling
  • +
  • Pooling arithmetic
  • +
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Building convolutional neural networks in Tensorflow and Keras
  • +
  • Setting it up
  • +
  • The MNIST dataset again
  • +
  • Strong correlations
  • +
  • Layers of a CNN
  • +
  • Systematic reduction
  • +
  • Prerequisites: Collect and pre-process data
  • +
  • Importing Keras and Tensorflow
  • +
  • Running with Keras
  • +
  • Final part
  • +
  • Final visualization
  • +
  • The CIFAR01 data set
  • +
  • Verifying the data set
  • +
  • Set up the model
  • +
  • Add Dense layers on top
  • +
  • Compile and train the model
  • +
  • Finally, evaluate the model
  • +
  • Building our own CNN code
  • +
  •    List of contents:
  • +
  •    Schedulers
  • +
  •    Usage of schedulers
  • +
  •    Cost functions
  • +
  •    Usage of cost functions
  • +
  •    Activation functions
  • +
  •    Usage of activation functions
  • +
  •    Convolution
  • +
  •    Layers
  • +
  •    Convolution2DLayer: convolution in a hidden layer
  • +
  •    Backpropagation in the convolutional layer
  • +
  •    Demonstration
  • +
  •    Pooling Layer
  • +
  •    Flattening Layer
  • +
  •    Fully Connected Layers
  • +
  •    Optimized Convolution2DLayer
  • +
  •    The Convolutional Neural Network (CNN)
  • +
  •    Usage of CNN code
  • +
  •    Additional Remarks
  • +
  •    Remarks on the speed
  • +
  •    Convolution using separable kernels
  • +
  •    Convolution in the Fourier domain
  • @@ -351,7 +393,7 @@ MathJax.Hub.Config({
  • 9
  • 10
  • ...
  • -
  • 47
  • +
  • 62
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs001.html b/doc/pub/week44/html/._week44-bs001.html index c47f506e6..5555f64c1 100644 --- a/doc/pub/week44/html/._week44-bs001.html +++ b/doc/pub/week44/html/._week44-bs001.html @@ -75,6 +75,12 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d None, 'a-deep-cnn-model-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Key Idea', 2, None, 'key-idea'), + ('How to do image compression before the era of deep learning', + 2, + None, + 'how-to-do-image-compression-before-the-era-of-deep-learning'), + ('The SVD example', 2, None, 'the-svd-example'), + ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Convolution Examples: Polynomial multiplication', 2, @@ -89,6 +95,8 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'a-more-efficient-way-of-coding-the-above-convolution'), + ('Commutative process', 2, None, 'commutative-process'), + ('Toeplitz matrices', 2, None, 'toeplitz-matrices'), ('Fourier series and Toeplitz matrices', 2, None, @@ -97,36 +105,75 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'generalizing-the-above-one-dimensional-case'), - ('Two-dimensional Objects', 2, None, 'two-dimensional-objects'), - ('CNNs in more detail', 2, None, 'cnns-in-more-detail'), - ('Performing a discrete convolution with padding ("From Raschka ' - 'et al":"https://github.com/rasbt/machine-learning-book")', + ('Memory considerations', 2, None, 'memory-considerations'), + ('Padding', 2, None, 'padding'), + ('New vector', 2, None, 'new-vector'), + ('Rewriting as dot products', 2, None, - 'performing-a-discrete-convolution-with-padding-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Performing a general discrete convolution ("From Raschka et ' + 'rewriting-as-dot-products'), + ('Cross correlation', 2, None, 'cross-correlation'), + ('Two-dimensional objects', 2, None, 'two-dimensional-objects'), + ('CNNs in more detail, simple example', + 2, + None, + 'cnns-in-more-detail-simple-example'), + ('The convolution stage', 2, None, 'the-convolution-stage'), + ('Finding the number of parameters', + 2, + None, + 'finding-the-number-of-parameters'), + ('New image (or volume)', 2, None, 'new-image-or-volume'), + ('Parameters to train, common settings', + 2, + None, + 'parameters-to-train-common-settings'), + ('Examples of CNN setups', 2, None, 'examples-of-cnn-setups'), + ('Summarizing: Performing a general discrete convolution ("From ' + 'Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, - 'performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Set of filters', 2, None, 'set-of-filters'), + 'summarizing-performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Pooling', 2, None, 'pooling'), - ('No zero padding, unit strides', - 2, - None, - 'no-zero-padding-unit-strides'), - ('Zero padding, unit strides', - 2, - None, - 'zero-padding-unit-strides'), - ('Half (same) padding', 2, None, 'half-same-padding'), - ('Full padding', 2, None, 'full-padding'), ('Pooling arithmetic', 2, None, 'pooling-arithmetic'), ('Pooling types ("From Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, 'pooling-types-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), + ('Building convolutional neural networks in Tensorflow and Keras', + 2, + None, + 'building-convolutional-neural-networks-in-tensorflow-and-keras'), + ('Setting it up', 2, None, 'setting-it-up'), + ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), + ('Strong correlations', 2, None, 'strong-correlations'), + ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), + ('Systematic reduction', 2, None, 'systematic-reduction'), + ('Prerequisites: Collect and pre-process data', + 2, + None, + 'prerequisites-collect-and-pre-process-data'), + ('Importing Keras and Tensorflow', + 2, + None, + 'importing-keras-and-tensorflow'), + ('Running with Keras', 2, None, 'running-with-keras'), + ('Final part', 2, None, 'final-part'), + ('Final visualization', 2, None, 'final-visualization'), + ('The CIFAR01 data set', 2, None, 'the-cifar01-data-set'), + ('Verifying the data set', 2, None, 'verifying-the-data-set'), + ('Set up the model', 2, None, 'set-up-the-model'), + ('Add Dense layers on top', 2, None, 'add-dense-layers-on-top'), + ('Compile and train the model', + 2, + None, + 'compile-and-train-the-model'), + ('Finally, evaluate the model', + 2, + None, + 'finally-evaluate-the-model'), ('Building our own CNN code', 2, None, @@ -173,27 +220,7 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Convolution in the Fourier domain', 3, None, - 'convolution-in-the-fourier-domain'), - ('Building convolutional neural networks in Tensorflow and Keras', - 2, - None, - 'building-convolutional-neural-networks-in-tensorflow-and-keras'), - ('Setting it up', 2, None, 'setting-it-up'), - ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), - ('Strong correlations', 2, None, 'strong-correlations'), - ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), - ('Systematic reduction', 2, None, 'systematic-reduction'), - ('Prerequisites: Collect and pre-process data', - 2, - None, - 'prerequisites-collect-and-pre-process-data'), - ('Importing Keras and Tensorflow', - 2, - None, - 'importing-keras-and-tensorflow'), - ('Running with Keras', 2, None, 'running-with-keras'), - ('Final part', 2, None, 'final-part'), - ('Final visualization', 2, None, 'final-visualization')]} + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -244,59 +271,74 @@ MathJax.Hub.Config({
  • CNNs in brief
  • A deep CNN model ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • Key Idea
  • -
  • Mathematics of CNNs
  • -
  • Convolution Examples: Polynomial multiplication
  • -
  • Efficient Polynomial Multiplication
  • -
  • Further simplification
  • -
  • A more efficient way of coding the above Convolution
  • -
  • Fourier series and Toeplitz matrices
  • -
  • Generalizing the above one-dimensional case
  • -
  • Two-dimensional Objects
  • -
  • CNNs in more detail
  • -
  • Performing a discrete convolution with padding ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Set of filters
  • -
  • Pooling
  • -
  • No zero padding, unit strides
  • -
  • Zero padding, unit strides
  • -
  • Half (same) padding
  • -
  • Full padding
  • -
  • Pooling arithmetic
  • -
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Building our own CNN code
  • -
  •    List of contents:
  • -
  •    Schedulers
  • -
  •    Usage of schedulers
  • -
  •    Cost functions
  • -
  •    Usage of cost functions
  • -
  •    Activation functions
  • -
  •    Usage of activation functions
  • -
  •    Convolution
  • -
  •    Layers
  • -
  •    Convolution2DLayer: convolution in a hidden layer
  • -
  •    Backpropagation in the convolutional layer
  • -
  •    Demonstration
  • -
  •    Pooling Layer
  • -
  •    Flattening Layer
  • -
  •    Fully Connected Layers
  • -
  •    Optimized Convolution2DLayer
  • -
  •    The Convolutional Neural Network (CNN)
  • -
  •    Usage of CNN code
  • -
  •    Additional Remarks
  • -
  •    Remarks on the speed
  • -
  •    Convolution using separable kernels
  • -
  •    Convolution in the Fourier domain
  • -
  • Building convolutional neural networks in Tensorflow and Keras
  • -
  • Setting it up
  • -
  • The MNIST dataset again
  • -
  • Strong correlations
  • -
  • Layers of a CNN
  • -
  • Systematic reduction
  • -
  • Prerequisites: Collect and pre-process data
  • -
  • Importing Keras and Tensorflow
  • -
  • Running with Keras
  • -
  • Final part
  • -
  • Final visualization
  • +
  • How to do image compression before the era of deep learning
  • +
  • The SVD example
  • +
  • Mathematics of CNNs
  • +
  • Mathematics of CNNs
  • +
  • Convolution Examples: Polynomial multiplication
  • +
  • Efficient Polynomial Multiplication
  • +
  • Further simplification
  • +
  • A more efficient way of coding the above Convolution
  • +
  • Commutative process
  • +
  • Toeplitz matrices
  • +
  • Fourier series and Toeplitz matrices
  • +
  • Generalizing the above one-dimensional case
  • +
  • Memory considerations
  • +
  • Padding
  • +
  • New vector
  • +
  • Rewriting as dot products
  • +
  • Cross correlation
  • +
  • Two-dimensional objects
  • +
  • CNNs in more detail, simple example
  • +
  • The convolution stage
  • +
  • Finding the number of parameters
  • +
  • New image (or volume)
  • +
  • Parameters to train, common settings
  • +
  • Examples of CNN setups
  • +
  • Summarizing: Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Pooling
  • +
  • Pooling arithmetic
  • +
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Building convolutional neural networks in Tensorflow and Keras
  • +
  • Setting it up
  • +
  • The MNIST dataset again
  • +
  • Strong correlations
  • +
  • Layers of a CNN
  • +
  • Systematic reduction
  • +
  • Prerequisites: Collect and pre-process data
  • +
  • Importing Keras and Tensorflow
  • +
  • Running with Keras
  • +
  • Final part
  • +
  • Final visualization
  • +
  • The CIFAR01 data set
  • +
  • Verifying the data set
  • +
  • Set up the model
  • +
  • Add Dense layers on top
  • +
  • Compile and train the model
  • +
  • Finally, evaluate the model
  • +
  • Building our own CNN code
  • +
  •    List of contents:
  • +
  •    Schedulers
  • +
  •    Usage of schedulers
  • +
  •    Cost functions
  • +
  •    Usage of cost functions
  • +
  •    Activation functions
  • +
  •    Usage of activation functions
  • +
  •    Convolution
  • +
  •    Layers
  • +
  •    Convolution2DLayer: convolution in a hidden layer
  • +
  •    Backpropagation in the convolutional layer
  • +
  •    Demonstration
  • +
  •    Pooling Layer
  • +
  •    Flattening Layer
  • +
  •    Fully Connected Layers
  • +
  •    Optimized Convolution2DLayer
  • +
  •    The Convolutional Neural Network (CNN)
  • +
  •    Usage of CNN code
  • +
  •    Additional Remarks
  • +
  •    Remarks on the speed
  • +
  •    Convolution using separable kernels
  • +
  •    Convolution in the Fourier domain
  • @@ -345,7 +387,7 @@ MathJax.Hub.Config({
  • 10
  • 11
  • ...
  • -
  • 47
  • +
  • 62
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs002.html b/doc/pub/week44/html/._week44-bs002.html index 8fed3c827..6c07203a5 100644 --- a/doc/pub/week44/html/._week44-bs002.html +++ b/doc/pub/week44/html/._week44-bs002.html @@ -75,6 +75,12 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d None, 'a-deep-cnn-model-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Key Idea', 2, None, 'key-idea'), + ('How to do image compression before the era of deep learning', + 2, + None, + 'how-to-do-image-compression-before-the-era-of-deep-learning'), + ('The SVD example', 2, None, 'the-svd-example'), + ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Convolution Examples: Polynomial multiplication', 2, @@ -89,6 +95,8 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'a-more-efficient-way-of-coding-the-above-convolution'), + ('Commutative process', 2, None, 'commutative-process'), + ('Toeplitz matrices', 2, None, 'toeplitz-matrices'), ('Fourier series and Toeplitz matrices', 2, None, @@ -97,36 +105,75 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'generalizing-the-above-one-dimensional-case'), - ('Two-dimensional Objects', 2, None, 'two-dimensional-objects'), - ('CNNs in more detail', 2, None, 'cnns-in-more-detail'), - ('Performing a discrete convolution with padding ("From Raschka ' - 'et al":"https://github.com/rasbt/machine-learning-book")', + ('Memory considerations', 2, None, 'memory-considerations'), + ('Padding', 2, None, 'padding'), + ('New vector', 2, None, 'new-vector'), + ('Rewriting as dot products', 2, None, - 'performing-a-discrete-convolution-with-padding-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Performing a general discrete convolution ("From Raschka et ' + 'rewriting-as-dot-products'), + ('Cross correlation', 2, None, 'cross-correlation'), + ('Two-dimensional objects', 2, None, 'two-dimensional-objects'), + ('CNNs in more detail, simple example', + 2, + None, + 'cnns-in-more-detail-simple-example'), + ('The convolution stage', 2, None, 'the-convolution-stage'), + ('Finding the number of parameters', + 2, + None, + 'finding-the-number-of-parameters'), + ('New image (or volume)', 2, None, 'new-image-or-volume'), + ('Parameters to train, common settings', + 2, + None, + 'parameters-to-train-common-settings'), + ('Examples of CNN setups', 2, None, 'examples-of-cnn-setups'), + ('Summarizing: Performing a general discrete convolution ("From ' + 'Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, - 'performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Set of filters', 2, None, 'set-of-filters'), + 'summarizing-performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Pooling', 2, None, 'pooling'), - ('No zero padding, unit strides', - 2, - None, - 'no-zero-padding-unit-strides'), - ('Zero padding, unit strides', - 2, - None, - 'zero-padding-unit-strides'), - ('Half (same) padding', 2, None, 'half-same-padding'), - ('Full padding', 2, None, 'full-padding'), ('Pooling arithmetic', 2, None, 'pooling-arithmetic'), ('Pooling types ("From Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, 'pooling-types-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), + ('Building convolutional neural networks in Tensorflow and Keras', + 2, + None, + 'building-convolutional-neural-networks-in-tensorflow-and-keras'), + ('Setting it up', 2, None, 'setting-it-up'), + ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), + ('Strong correlations', 2, None, 'strong-correlations'), + ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), + ('Systematic reduction', 2, None, 'systematic-reduction'), + ('Prerequisites: Collect and pre-process data', + 2, + None, + 'prerequisites-collect-and-pre-process-data'), + ('Importing Keras and Tensorflow', + 2, + None, + 'importing-keras-and-tensorflow'), + ('Running with Keras', 2, None, 'running-with-keras'), + ('Final part', 2, None, 'final-part'), + ('Final visualization', 2, None, 'final-visualization'), + ('The CIFAR01 data set', 2, None, 'the-cifar01-data-set'), + ('Verifying the data set', 2, None, 'verifying-the-data-set'), + ('Set up the model', 2, None, 'set-up-the-model'), + ('Add Dense layers on top', 2, None, 'add-dense-layers-on-top'), + ('Compile and train the model', + 2, + None, + 'compile-and-train-the-model'), + ('Finally, evaluate the model', + 2, + None, + 'finally-evaluate-the-model'), ('Building our own CNN code', 2, None, @@ -173,27 +220,7 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Convolution in the Fourier domain', 3, None, - 'convolution-in-the-fourier-domain'), - ('Building convolutional neural networks in Tensorflow and Keras', - 2, - None, - 'building-convolutional-neural-networks-in-tensorflow-and-keras'), - ('Setting it up', 2, None, 'setting-it-up'), - ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), - ('Strong correlations', 2, None, 'strong-correlations'), - ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), - ('Systematic reduction', 2, None, 'systematic-reduction'), - ('Prerequisites: Collect and pre-process data', - 2, - None, - 'prerequisites-collect-and-pre-process-data'), - ('Importing Keras and Tensorflow', - 2, - None, - 'importing-keras-and-tensorflow'), - ('Running with Keras', 2, None, 'running-with-keras'), - ('Final part', 2, None, 'final-part'), - ('Final visualization', 2, None, 'final-visualization')]} + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -244,59 +271,74 @@ MathJax.Hub.Config({
  • CNNs in brief
  • A deep CNN model ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • Key Idea
  • -
  • Mathematics of CNNs
  • -
  • Convolution Examples: Polynomial multiplication
  • -
  • Efficient Polynomial Multiplication
  • -
  • Further simplification
  • -
  • A more efficient way of coding the above Convolution
  • -
  • Fourier series and Toeplitz matrices
  • -
  • Generalizing the above one-dimensional case
  • -
  • Two-dimensional Objects
  • -
  • CNNs in more detail
  • -
  • Performing a discrete convolution with padding ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Set of filters
  • -
  • Pooling
  • -
  • No zero padding, unit strides
  • -
  • Zero padding, unit strides
  • -
  • Half (same) padding
  • -
  • Full padding
  • -
  • Pooling arithmetic
  • -
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Building our own CNN code
  • -
  •    List of contents:
  • -
  •    Schedulers
  • -
  •    Usage of schedulers
  • -
  •    Cost functions
  • -
  •    Usage of cost functions
  • -
  •    Activation functions
  • -
  •    Usage of activation functions
  • -
  •    Convolution
  • -
  •    Layers
  • -
  •    Convolution2DLayer: convolution in a hidden layer
  • -
  •    Backpropagation in the convolutional layer
  • -
  •    Demonstration
  • -
  •    Pooling Layer
  • -
  •    Flattening Layer
  • -
  •    Fully Connected Layers
  • -
  •    Optimized Convolution2DLayer
  • -
  •    The Convolutional Neural Network (CNN)
  • -
  •    Usage of CNN code
  • -
  •    Additional Remarks
  • -
  •    Remarks on the speed
  • -
  •    Convolution using separable kernels
  • -
  •    Convolution in the Fourier domain
  • -
  • Building convolutional neural networks in Tensorflow and Keras
  • -
  • Setting it up
  • -
  • The MNIST dataset again
  • -
  • Strong correlations
  • -
  • Layers of a CNN
  • -
  • Systematic reduction
  • -
  • Prerequisites: Collect and pre-process data
  • -
  • Importing Keras and Tensorflow
  • -
  • Running with Keras
  • -
  • Final part
  • -
  • Final visualization
  • +
  • How to do image compression before the era of deep learning
  • +
  • The SVD example
  • +
  • Mathematics of CNNs
  • +
  • Mathematics of CNNs
  • +
  • Convolution Examples: Polynomial multiplication
  • +
  • Efficient Polynomial Multiplication
  • +
  • Further simplification
  • +
  • A more efficient way of coding the above Convolution
  • +
  • Commutative process
  • +
  • Toeplitz matrices
  • +
  • Fourier series and Toeplitz matrices
  • +
  • Generalizing the above one-dimensional case
  • +
  • Memory considerations
  • +
  • Padding
  • +
  • New vector
  • +
  • Rewriting as dot products
  • +
  • Cross correlation
  • +
  • Two-dimensional objects
  • +
  • CNNs in more detail, simple example
  • +
  • The convolution stage
  • +
  • Finding the number of parameters
  • +
  • New image (or volume)
  • +
  • Parameters to train, common settings
  • +
  • Examples of CNN setups
  • +
  • Summarizing: Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Pooling
  • +
  • Pooling arithmetic
  • +
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Building convolutional neural networks in Tensorflow and Keras
  • +
  • Setting it up
  • +
  • The MNIST dataset again
  • +
  • Strong correlations
  • +
  • Layers of a CNN
  • +
  • Systematic reduction
  • +
  • Prerequisites: Collect and pre-process data
  • +
  • Importing Keras and Tensorflow
  • +
  • Running with Keras
  • +
  • Final part
  • +
  • Final visualization
  • +
  • The CIFAR01 data set
  • +
  • Verifying the data set
  • +
  • Set up the model
  • +
  • Add Dense layers on top
  • +
  • Compile and train the model
  • +
  • Finally, evaluate the model
  • +
  • Building our own CNN code
  • +
  •    List of contents:
  • +
  •    Schedulers
  • +
  •    Usage of schedulers
  • +
  •    Cost functions
  • +
  •    Usage of cost functions
  • +
  •    Activation functions
  • +
  •    Usage of activation functions
  • +
  •    Convolution
  • +
  •    Layers
  • +
  •    Convolution2DLayer: convolution in a hidden layer
  • +
  •    Backpropagation in the convolutional layer
  • +
  •    Demonstration
  • +
  •    Pooling Layer
  • +
  •    Flattening Layer
  • +
  •    Fully Connected Layers
  • +
  •    Optimized Convolution2DLayer
  • +
  •    The Convolutional Neural Network (CNN)
  • +
  •    Usage of CNN code
  • +
  •    Additional Remarks
  • +
  •    Remarks on the speed
  • +
  •    Convolution using separable kernels
  • +
  •    Convolution in the Fourier domain
  • @@ -340,7 +382,7 @@ MathJax.Hub.Config({
  • 11
  • 12
  • ...
  • -
  • 47
  • +
  • 62
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs003.html b/doc/pub/week44/html/._week44-bs003.html index fbe640a9f..c283b9feb 100644 --- a/doc/pub/week44/html/._week44-bs003.html +++ b/doc/pub/week44/html/._week44-bs003.html @@ -75,6 +75,12 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d None, 'a-deep-cnn-model-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Key Idea', 2, None, 'key-idea'), + ('How to do image compression before the era of deep learning', + 2, + None, + 'how-to-do-image-compression-before-the-era-of-deep-learning'), + ('The SVD example', 2, None, 'the-svd-example'), + ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Convolution Examples: Polynomial multiplication', 2, @@ -89,6 +95,8 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'a-more-efficient-way-of-coding-the-above-convolution'), + ('Commutative process', 2, None, 'commutative-process'), + ('Toeplitz matrices', 2, None, 'toeplitz-matrices'), ('Fourier series and Toeplitz matrices', 2, None, @@ -97,36 +105,75 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'generalizing-the-above-one-dimensional-case'), - ('Two-dimensional Objects', 2, None, 'two-dimensional-objects'), - ('CNNs in more detail', 2, None, 'cnns-in-more-detail'), - ('Performing a discrete convolution with padding ("From Raschka ' - 'et al":"https://github.com/rasbt/machine-learning-book")', + ('Memory considerations', 2, None, 'memory-considerations'), + ('Padding', 2, None, 'padding'), + ('New vector', 2, None, 'new-vector'), + ('Rewriting as dot products', 2, None, - 'performing-a-discrete-convolution-with-padding-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Performing a general discrete convolution ("From Raschka et ' + 'rewriting-as-dot-products'), + ('Cross correlation', 2, None, 'cross-correlation'), + ('Two-dimensional objects', 2, None, 'two-dimensional-objects'), + ('CNNs in more detail, simple example', + 2, + None, + 'cnns-in-more-detail-simple-example'), + ('The convolution stage', 2, None, 'the-convolution-stage'), + ('Finding the number of parameters', + 2, + None, + 'finding-the-number-of-parameters'), + ('New image (or volume)', 2, None, 'new-image-or-volume'), + ('Parameters to train, common settings', + 2, + None, + 'parameters-to-train-common-settings'), + ('Examples of CNN setups', 2, None, 'examples-of-cnn-setups'), + ('Summarizing: Performing a general discrete convolution ("From ' + 'Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, - 'performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Set of filters', 2, None, 'set-of-filters'), + 'summarizing-performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Pooling', 2, None, 'pooling'), - ('No zero padding, unit strides', - 2, - None, - 'no-zero-padding-unit-strides'), - ('Zero padding, unit strides', - 2, - None, - 'zero-padding-unit-strides'), - ('Half (same) padding', 2, None, 'half-same-padding'), - ('Full padding', 2, None, 'full-padding'), ('Pooling arithmetic', 2, None, 'pooling-arithmetic'), ('Pooling types ("From Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, 'pooling-types-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), + ('Building convolutional neural networks in Tensorflow and Keras', + 2, + None, + 'building-convolutional-neural-networks-in-tensorflow-and-keras'), + ('Setting it up', 2, None, 'setting-it-up'), + ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), + ('Strong correlations', 2, None, 'strong-correlations'), + ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), + ('Systematic reduction', 2, None, 'systematic-reduction'), + ('Prerequisites: Collect and pre-process data', + 2, + None, + 'prerequisites-collect-and-pre-process-data'), + ('Importing Keras and Tensorflow', + 2, + None, + 'importing-keras-and-tensorflow'), + ('Running with Keras', 2, None, 'running-with-keras'), + ('Final part', 2, None, 'final-part'), + ('Final visualization', 2, None, 'final-visualization'), + ('The CIFAR01 data set', 2, None, 'the-cifar01-data-set'), + ('Verifying the data set', 2, None, 'verifying-the-data-set'), + ('Set up the model', 2, None, 'set-up-the-model'), + ('Add Dense layers on top', 2, None, 'add-dense-layers-on-top'), + ('Compile and train the model', + 2, + None, + 'compile-and-train-the-model'), + ('Finally, evaluate the model', + 2, + None, + 'finally-evaluate-the-model'), ('Building our own CNN code', 2, None, @@ -173,27 +220,7 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Convolution in the Fourier domain', 3, None, - 'convolution-in-the-fourier-domain'), - ('Building convolutional neural networks in Tensorflow and Keras', - 2, - None, - 'building-convolutional-neural-networks-in-tensorflow-and-keras'), - ('Setting it up', 2, None, 'setting-it-up'), - ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), - ('Strong correlations', 2, None, 'strong-correlations'), - ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), - ('Systematic reduction', 2, None, 'systematic-reduction'), - ('Prerequisites: Collect and pre-process data', - 2, - None, - 'prerequisites-collect-and-pre-process-data'), - ('Importing Keras and Tensorflow', - 2, - None, - 'importing-keras-and-tensorflow'), - ('Running with Keras', 2, None, 'running-with-keras'), - ('Final part', 2, None, 'final-part'), - ('Final visualization', 2, None, 'final-visualization')]} + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -244,59 +271,74 @@ MathJax.Hub.Config({
  • CNNs in brief
  • A deep CNN model ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • Key Idea
  • -
  • Mathematics of CNNs
  • -
  • Convolution Examples: Polynomial multiplication
  • -
  • Efficient Polynomial Multiplication
  • -
  • Further simplification
  • -
  • A more efficient way of coding the above Convolution
  • -
  • Fourier series and Toeplitz matrices
  • -
  • Generalizing the above one-dimensional case
  • -
  • Two-dimensional Objects
  • -
  • CNNs in more detail
  • -
  • Performing a discrete convolution with padding ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Set of filters
  • -
  • Pooling
  • -
  • No zero padding, unit strides
  • -
  • Zero padding, unit strides
  • -
  • Half (same) padding
  • -
  • Full padding
  • -
  • Pooling arithmetic
  • -
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Building our own CNN code
  • -
  •    List of contents:
  • -
  •    Schedulers
  • -
  •    Usage of schedulers
  • -
  •    Cost functions
  • -
  •    Usage of cost functions
  • -
  •    Activation functions
  • -
  •    Usage of activation functions
  • -
  •    Convolution
  • -
  •    Layers
  • -
  •    Convolution2DLayer: convolution in a hidden layer
  • -
  •    Backpropagation in the convolutional layer
  • -
  •    Demonstration
  • -
  •    Pooling Layer
  • -
  •    Flattening Layer
  • -
  •    Fully Connected Layers
  • -
  •    Optimized Convolution2DLayer
  • -
  •    The Convolutional Neural Network (CNN)
  • -
  •    Usage of CNN code
  • -
  •    Additional Remarks
  • -
  •    Remarks on the speed
  • -
  •    Convolution using separable kernels
  • -
  •    Convolution in the Fourier domain
  • -
  • Building convolutional neural networks in Tensorflow and Keras
  • -
  • Setting it up
  • -
  • The MNIST dataset again
  • -
  • Strong correlations
  • -
  • Layers of a CNN
  • -
  • Systematic reduction
  • -
  • Prerequisites: Collect and pre-process data
  • -
  • Importing Keras and Tensorflow
  • -
  • Running with Keras
  • -
  • Final part
  • -
  • Final visualization
  • +
  • How to do image compression before the era of deep learning
  • +
  • The SVD example
  • +
  • Mathematics of CNNs
  • +
  • Mathematics of CNNs
  • +
  • Convolution Examples: Polynomial multiplication
  • +
  • Efficient Polynomial Multiplication
  • +
  • Further simplification
  • +
  • A more efficient way of coding the above Convolution
  • +
  • Commutative process
  • +
  • Toeplitz matrices
  • +
  • Fourier series and Toeplitz matrices
  • +
  • Generalizing the above one-dimensional case
  • +
  • Memory considerations
  • +
  • Padding
  • +
  • New vector
  • +
  • Rewriting as dot products
  • +
  • Cross correlation
  • +
  • Two-dimensional objects
  • +
  • CNNs in more detail, simple example
  • +
  • The convolution stage
  • +
  • Finding the number of parameters
  • +
  • New image (or volume)
  • +
  • Parameters to train, common settings
  • +
  • Examples of CNN setups
  • +
  • Summarizing: Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Pooling
  • +
  • Pooling arithmetic
  • +
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Building convolutional neural networks in Tensorflow and Keras
  • +
  • Setting it up
  • +
  • The MNIST dataset again
  • +
  • Strong correlations
  • +
  • Layers of a CNN
  • +
  • Systematic reduction
  • +
  • Prerequisites: Collect and pre-process data
  • +
  • Importing Keras and Tensorflow
  • +
  • Running with Keras
  • +
  • Final part
  • +
  • Final visualization
  • +
  • The CIFAR01 data set
  • +
  • Verifying the data set
  • +
  • Set up the model
  • +
  • Add Dense layers on top
  • +
  • Compile and train the model
  • +
  • Finally, evaluate the model
  • +
  • Building our own CNN code
  • +
  •    List of contents:
  • +
  •    Schedulers
  • +
  •    Usage of schedulers
  • +
  •    Cost functions
  • +
  •    Usage of cost functions
  • +
  •    Activation functions
  • +
  •    Usage of activation functions
  • +
  •    Convolution
  • +
  •    Layers
  • +
  •    Convolution2DLayer: convolution in a hidden layer
  • +
  •    Backpropagation in the convolutional layer
  • +
  •    Demonstration
  • +
  •    Pooling Layer
  • +
  •    Flattening Layer
  • +
  •    Fully Connected Layers
  • +
  •    Optimized Convolution2DLayer
  • +
  •    The Convolutional Neural Network (CNN)
  • +
  •    Usage of CNN code
  • +
  •    Additional Remarks
  • +
  •    Remarks on the speed
  • +
  •    Convolution using separable kernels
  • +
  •    Convolution in the Fourier domain
  • @@ -328,7 +370,7 @@ MathJax.Hub.Config({
  • 12
  • 13
  • ...
  • -
  • 47
  • +
  • 62
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs004.html b/doc/pub/week44/html/._week44-bs004.html index f67228f65..e726d59b6 100644 --- a/doc/pub/week44/html/._week44-bs004.html +++ b/doc/pub/week44/html/._week44-bs004.html @@ -75,6 +75,12 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d None, 'a-deep-cnn-model-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Key Idea', 2, None, 'key-idea'), + ('How to do image compression before the era of deep learning', + 2, + None, + 'how-to-do-image-compression-before-the-era-of-deep-learning'), + ('The SVD example', 2, None, 'the-svd-example'), + ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Convolution Examples: Polynomial multiplication', 2, @@ -89,6 +95,8 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'a-more-efficient-way-of-coding-the-above-convolution'), + ('Commutative process', 2, None, 'commutative-process'), + ('Toeplitz matrices', 2, None, 'toeplitz-matrices'), ('Fourier series and Toeplitz matrices', 2, None, @@ -97,36 +105,75 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'generalizing-the-above-one-dimensional-case'), - ('Two-dimensional Objects', 2, None, 'two-dimensional-objects'), - ('CNNs in more detail', 2, None, 'cnns-in-more-detail'), - ('Performing a discrete convolution with padding ("From Raschka ' - 'et al":"https://github.com/rasbt/machine-learning-book")', + ('Memory considerations', 2, None, 'memory-considerations'), + ('Padding', 2, None, 'padding'), + ('New vector', 2, None, 'new-vector'), + ('Rewriting as dot products', 2, None, - 'performing-a-discrete-convolution-with-padding-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Performing a general discrete convolution ("From Raschka et ' + 'rewriting-as-dot-products'), + ('Cross correlation', 2, None, 'cross-correlation'), + ('Two-dimensional objects', 2, None, 'two-dimensional-objects'), + ('CNNs in more detail, simple example', + 2, + None, + 'cnns-in-more-detail-simple-example'), + ('The convolution stage', 2, None, 'the-convolution-stage'), + ('Finding the number of parameters', + 2, + None, + 'finding-the-number-of-parameters'), + ('New image (or volume)', 2, None, 'new-image-or-volume'), + ('Parameters to train, common settings', + 2, + None, + 'parameters-to-train-common-settings'), + ('Examples of CNN setups', 2, None, 'examples-of-cnn-setups'), + ('Summarizing: Performing a general discrete convolution ("From ' + 'Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, - 'performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Set of filters', 2, None, 'set-of-filters'), + 'summarizing-performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Pooling', 2, None, 'pooling'), - ('No zero padding, unit strides', - 2, - None, - 'no-zero-padding-unit-strides'), - ('Zero padding, unit strides', - 2, - None, - 'zero-padding-unit-strides'), - ('Half (same) padding', 2, None, 'half-same-padding'), - ('Full padding', 2, None, 'full-padding'), ('Pooling arithmetic', 2, None, 'pooling-arithmetic'), ('Pooling types ("From Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, 'pooling-types-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), + ('Building convolutional neural networks in Tensorflow and Keras', + 2, + None, + 'building-convolutional-neural-networks-in-tensorflow-and-keras'), + ('Setting it up', 2, None, 'setting-it-up'), + ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), + ('Strong correlations', 2, None, 'strong-correlations'), + ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), + ('Systematic reduction', 2, None, 'systematic-reduction'), + ('Prerequisites: Collect and pre-process data', + 2, + None, + 'prerequisites-collect-and-pre-process-data'), + ('Importing Keras and Tensorflow', + 2, + None, + 'importing-keras-and-tensorflow'), + ('Running with Keras', 2, None, 'running-with-keras'), + ('Final part', 2, None, 'final-part'), + ('Final visualization', 2, None, 'final-visualization'), + ('The CIFAR01 data set', 2, None, 'the-cifar01-data-set'), + ('Verifying the data set', 2, None, 'verifying-the-data-set'), + ('Set up the model', 2, None, 'set-up-the-model'), + ('Add Dense layers on top', 2, None, 'add-dense-layers-on-top'), + ('Compile and train the model', + 2, + None, + 'compile-and-train-the-model'), + ('Finally, evaluate the model', + 2, + None, + 'finally-evaluate-the-model'), ('Building our own CNN code', 2, None, @@ -173,27 +220,7 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Convolution in the Fourier domain', 3, None, - 'convolution-in-the-fourier-domain'), - ('Building convolutional neural networks in Tensorflow and Keras', - 2, - None, - 'building-convolutional-neural-networks-in-tensorflow-and-keras'), - ('Setting it up', 2, None, 'setting-it-up'), - ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), - ('Strong correlations', 2, None, 'strong-correlations'), - ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), - ('Systematic reduction', 2, None, 'systematic-reduction'), - ('Prerequisites: Collect and pre-process data', - 2, - None, - 'prerequisites-collect-and-pre-process-data'), - ('Importing Keras and Tensorflow', - 2, - None, - 'importing-keras-and-tensorflow'), - ('Running with Keras', 2, None, 'running-with-keras'), - ('Final part', 2, None, 'final-part'), - ('Final visualization', 2, None, 'final-visualization')]} + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -244,59 +271,74 @@ MathJax.Hub.Config({
  • CNNs in brief
  • A deep CNN model ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • Key Idea
  • -
  • Mathematics of CNNs
  • -
  • Convolution Examples: Polynomial multiplication
  • -
  • Efficient Polynomial Multiplication
  • -
  • Further simplification
  • -
  • A more efficient way of coding the above Convolution
  • -
  • Fourier series and Toeplitz matrices
  • -
  • Generalizing the above one-dimensional case
  • -
  • Two-dimensional Objects
  • -
  • CNNs in more detail
  • -
  • Performing a discrete convolution with padding ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Set of filters
  • -
  • Pooling
  • -
  • No zero padding, unit strides
  • -
  • Zero padding, unit strides
  • -
  • Half (same) padding
  • -
  • Full padding
  • -
  • Pooling arithmetic
  • -
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Building our own CNN code
  • -
  •    List of contents:
  • -
  •    Schedulers
  • -
  •    Usage of schedulers
  • -
  •    Cost functions
  • -
  •    Usage of cost functions
  • -
  •    Activation functions
  • -
  •    Usage of activation functions
  • -
  •    Convolution
  • -
  •    Layers
  • -
  •    Convolution2DLayer: convolution in a hidden layer
  • -
  •    Backpropagation in the convolutional layer
  • -
  •    Demonstration
  • -
  •    Pooling Layer
  • -
  •    Flattening Layer
  • -
  •    Fully Connected Layers
  • -
  •    Optimized Convolution2DLayer
  • -
  •    The Convolutional Neural Network (CNN)
  • -
  •    Usage of CNN code
  • -
  •    Additional Remarks
  • -
  •    Remarks on the speed
  • -
  •    Convolution using separable kernels
  • -
  •    Convolution in the Fourier domain
  • -
  • Building convolutional neural networks in Tensorflow and Keras
  • -
  • Setting it up
  • -
  • The MNIST dataset again
  • -
  • Strong correlations
  • -
  • Layers of a CNN
  • -
  • Systematic reduction
  • -
  • Prerequisites: Collect and pre-process data
  • -
  • Importing Keras and Tensorflow
  • -
  • Running with Keras
  • -
  • Final part
  • -
  • Final visualization
  • +
  • How to do image compression before the era of deep learning
  • +
  • The SVD example
  • +
  • Mathematics of CNNs
  • +
  • Mathematics of CNNs
  • +
  • Convolution Examples: Polynomial multiplication
  • +
  • Efficient Polynomial Multiplication
  • +
  • Further simplification
  • +
  • A more efficient way of coding the above Convolution
  • +
  • Commutative process
  • +
  • Toeplitz matrices
  • +
  • Fourier series and Toeplitz matrices
  • +
  • Generalizing the above one-dimensional case
  • +
  • Memory considerations
  • +
  • Padding
  • +
  • New vector
  • +
  • Rewriting as dot products
  • +
  • Cross correlation
  • +
  • Two-dimensional objects
  • +
  • CNNs in more detail, simple example
  • +
  • The convolution stage
  • +
  • Finding the number of parameters
  • +
  • New image (or volume)
  • +
  • Parameters to train, common settings
  • +
  • Examples of CNN setups
  • +
  • Summarizing: Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Pooling
  • +
  • Pooling arithmetic
  • +
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Building convolutional neural networks in Tensorflow and Keras
  • +
  • Setting it up
  • +
  • The MNIST dataset again
  • +
  • Strong correlations
  • +
  • Layers of a CNN
  • +
  • Systematic reduction
  • +
  • Prerequisites: Collect and pre-process data
  • +
  • Importing Keras and Tensorflow
  • +
  • Running with Keras
  • +
  • Final part
  • +
  • Final visualization
  • +
  • The CIFAR01 data set
  • +
  • Verifying the data set
  • +
  • Set up the model
  • +
  • Add Dense layers on top
  • +
  • Compile and train the model
  • +
  • Finally, evaluate the model
  • +
  • Building our own CNN code
  • +
  •    List of contents:
  • +
  •    Schedulers
  • +
  •    Usage of schedulers
  • +
  •    Cost functions
  • +
  •    Usage of cost functions
  • +
  •    Activation functions
  • +
  •    Usage of activation functions
  • +
  •    Convolution
  • +
  •    Layers
  • +
  •    Convolution2DLayer: convolution in a hidden layer
  • +
  •    Backpropagation in the convolutional layer
  • +
  •    Demonstration
  • +
  •    Pooling Layer
  • +
  •    Flattening Layer
  • +
  •    Fully Connected Layers
  • +
  •    Optimized Convolution2DLayer
  • +
  •    The Convolutional Neural Network (CNN)
  • +
  •    Usage of CNN code
  • +
  •    Additional Remarks
  • +
  •    Remarks on the speed
  • +
  •    Convolution using separable kernels
  • +
  •    Convolution in the Fourier domain
  • @@ -348,7 +390,7 @@ Networks still apply (back propagation, gradient descent etc etc).
  • 13
  • 14
  • ...
  • -
  • 47
  • +
  • 62
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs005.html b/doc/pub/week44/html/._week44-bs005.html index ea2689f94..8d49d3e88 100644 --- a/doc/pub/week44/html/._week44-bs005.html +++ b/doc/pub/week44/html/._week44-bs005.html @@ -75,6 +75,12 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d None, 'a-deep-cnn-model-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Key Idea', 2, None, 'key-idea'), + ('How to do image compression before the era of deep learning', + 2, + None, + 'how-to-do-image-compression-before-the-era-of-deep-learning'), + ('The SVD example', 2, None, 'the-svd-example'), + ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Convolution Examples: Polynomial multiplication', 2, @@ -89,6 +95,8 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'a-more-efficient-way-of-coding-the-above-convolution'), + ('Commutative process', 2, None, 'commutative-process'), + ('Toeplitz matrices', 2, None, 'toeplitz-matrices'), ('Fourier series and Toeplitz matrices', 2, None, @@ -97,36 +105,75 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'generalizing-the-above-one-dimensional-case'), - ('Two-dimensional Objects', 2, None, 'two-dimensional-objects'), - ('CNNs in more detail', 2, None, 'cnns-in-more-detail'), - ('Performing a discrete convolution with padding ("From Raschka ' - 'et al":"https://github.com/rasbt/machine-learning-book")', + ('Memory considerations', 2, None, 'memory-considerations'), + ('Padding', 2, None, 'padding'), + ('New vector', 2, None, 'new-vector'), + ('Rewriting as dot products', 2, None, - 'performing-a-discrete-convolution-with-padding-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Performing a general discrete convolution ("From Raschka et ' + 'rewriting-as-dot-products'), + ('Cross correlation', 2, None, 'cross-correlation'), + ('Two-dimensional objects', 2, None, 'two-dimensional-objects'), + ('CNNs in more detail, simple example', + 2, + None, + 'cnns-in-more-detail-simple-example'), + ('The convolution stage', 2, None, 'the-convolution-stage'), + ('Finding the number of parameters', + 2, + None, + 'finding-the-number-of-parameters'), + ('New image (or volume)', 2, None, 'new-image-or-volume'), + ('Parameters to train, common settings', + 2, + None, + 'parameters-to-train-common-settings'), + ('Examples of CNN setups', 2, None, 'examples-of-cnn-setups'), + ('Summarizing: Performing a general discrete convolution ("From ' + 'Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, - 'performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Set of filters', 2, None, 'set-of-filters'), + 'summarizing-performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Pooling', 2, None, 'pooling'), - ('No zero padding, unit strides', - 2, - None, - 'no-zero-padding-unit-strides'), - ('Zero padding, unit strides', - 2, - None, - 'zero-padding-unit-strides'), - ('Half (same) padding', 2, None, 'half-same-padding'), - ('Full padding', 2, None, 'full-padding'), ('Pooling arithmetic', 2, None, 'pooling-arithmetic'), ('Pooling types ("From Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, 'pooling-types-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), + ('Building convolutional neural networks in Tensorflow and Keras', + 2, + None, + 'building-convolutional-neural-networks-in-tensorflow-and-keras'), + ('Setting it up', 2, None, 'setting-it-up'), + ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), + ('Strong correlations', 2, None, 'strong-correlations'), + ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), + ('Systematic reduction', 2, None, 'systematic-reduction'), + ('Prerequisites: Collect and pre-process data', + 2, + None, + 'prerequisites-collect-and-pre-process-data'), + ('Importing Keras and Tensorflow', + 2, + None, + 'importing-keras-and-tensorflow'), + ('Running with Keras', 2, None, 'running-with-keras'), + ('Final part', 2, None, 'final-part'), + ('Final visualization', 2, None, 'final-visualization'), + ('The CIFAR01 data set', 2, None, 'the-cifar01-data-set'), + ('Verifying the data set', 2, None, 'verifying-the-data-set'), + ('Set up the model', 2, None, 'set-up-the-model'), + ('Add Dense layers on top', 2, None, 'add-dense-layers-on-top'), + ('Compile and train the model', + 2, + None, + 'compile-and-train-the-model'), + ('Finally, evaluate the model', + 2, + None, + 'finally-evaluate-the-model'), ('Building our own CNN code', 2, None, @@ -173,27 +220,7 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Convolution in the Fourier domain', 3, None, - 'convolution-in-the-fourier-domain'), - ('Building convolutional neural networks in Tensorflow and Keras', - 2, - None, - 'building-convolutional-neural-networks-in-tensorflow-and-keras'), - ('Setting it up', 2, None, 'setting-it-up'), - ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), - ('Strong correlations', 2, None, 'strong-correlations'), - ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), - ('Systematic reduction', 2, None, 'systematic-reduction'), - ('Prerequisites: Collect and pre-process data', - 2, - None, - 'prerequisites-collect-and-pre-process-data'), - ('Importing Keras and Tensorflow', - 2, - None, - 'importing-keras-and-tensorflow'), - ('Running with Keras', 2, None, 'running-with-keras'), - ('Final part', 2, None, 'final-part'), - ('Final visualization', 2, None, 'final-visualization')]} + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -244,59 +271,74 @@ MathJax.Hub.Config({
  • CNNs in brief
  • A deep CNN model ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • Key Idea
  • -
  • Mathematics of CNNs
  • -
  • Convolution Examples: Polynomial multiplication
  • -
  • Efficient Polynomial Multiplication
  • -
  • Further simplification
  • -
  • A more efficient way of coding the above Convolution
  • -
  • Fourier series and Toeplitz matrices
  • -
  • Generalizing the above one-dimensional case
  • -
  • Two-dimensional Objects
  • -
  • CNNs in more detail
  • -
  • Performing a discrete convolution with padding ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Set of filters
  • -
  • Pooling
  • -
  • No zero padding, unit strides
  • -
  • Zero padding, unit strides
  • -
  • Half (same) padding
  • -
  • Full padding
  • -
  • Pooling arithmetic
  • -
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Building our own CNN code
  • -
  •    List of contents:
  • -
  •    Schedulers
  • -
  •    Usage of schedulers
  • -
  •    Cost functions
  • -
  •    Usage of cost functions
  • -
  •    Activation functions
  • -
  •    Usage of activation functions
  • -
  •    Convolution
  • -
  •    Layers
  • -
  •    Convolution2DLayer: convolution in a hidden layer
  • -
  •    Backpropagation in the convolutional layer
  • -
  •    Demonstration
  • -
  •    Pooling Layer
  • -
  •    Flattening Layer
  • -
  •    Fully Connected Layers
  • -
  •    Optimized Convolution2DLayer
  • -
  •    The Convolutional Neural Network (CNN)
  • -
  •    Usage of CNN code
  • -
  •    Additional Remarks
  • -
  •    Remarks on the speed
  • -
  •    Convolution using separable kernels
  • -
  •    Convolution in the Fourier domain
  • -
  • Building convolutional neural networks in Tensorflow and Keras
  • -
  • Setting it up
  • -
  • The MNIST dataset again
  • -
  • Strong correlations
  • -
  • Layers of a CNN
  • -
  • Systematic reduction
  • -
  • Prerequisites: Collect and pre-process data
  • -
  • Importing Keras and Tensorflow
  • -
  • Running with Keras
  • -
  • Final part
  • -
  • Final visualization
  • +
  • How to do image compression before the era of deep learning
  • +
  • The SVD example
  • +
  • Mathematics of CNNs
  • +
  • Mathematics of CNNs
  • +
  • Convolution Examples: Polynomial multiplication
  • +
  • Efficient Polynomial Multiplication
  • +
  • Further simplification
  • +
  • A more efficient way of coding the above Convolution
  • +
  • Commutative process
  • +
  • Toeplitz matrices
  • +
  • Fourier series and Toeplitz matrices
  • +
  • Generalizing the above one-dimensional case
  • +
  • Memory considerations
  • +
  • Padding
  • +
  • New vector
  • +
  • Rewriting as dot products
  • +
  • Cross correlation
  • +
  • Two-dimensional objects
  • +
  • CNNs in more detail, simple example
  • +
  • The convolution stage
  • +
  • Finding the number of parameters
  • +
  • New image (or volume)
  • +
  • Parameters to train, common settings
  • +
  • Examples of CNN setups
  • +
  • Summarizing: Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Pooling
  • +
  • Pooling arithmetic
  • +
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Building convolutional neural networks in Tensorflow and Keras
  • +
  • Setting it up
  • +
  • The MNIST dataset again
  • +
  • Strong correlations
  • +
  • Layers of a CNN
  • +
  • Systematic reduction
  • +
  • Prerequisites: Collect and pre-process data
  • +
  • Importing Keras and Tensorflow
  • +
  • Running with Keras
  • +
  • Final part
  • +
  • Final visualization
  • +
  • The CIFAR01 data set
  • +
  • Verifying the data set
  • +
  • Set up the model
  • +
  • Add Dense layers on top
  • +
  • Compile and train the model
  • +
  • Finally, evaluate the model
  • +
  • Building our own CNN code
  • +
  •    List of contents:
  • +
  •    Schedulers
  • +
  •    Usage of schedulers
  • +
  •    Cost functions
  • +
  •    Usage of cost functions
  • +
  •    Activation functions
  • +
  •    Usage of activation functions
  • +
  •    Convolution
  • +
  •    Layers
  • +
  •    Convolution2DLayer: convolution in a hidden layer
  • +
  •    Backpropagation in the convolutional layer
  • +
  •    Demonstration
  • +
  •    Pooling Layer
  • +
  •    Flattening Layer
  • +
  •    Fully Connected Layers
  • +
  •    Optimized Convolution2DLayer
  • +
  •    The Convolutional Neural Network (CNN)
  • +
  •    Usage of CNN code
  • +
  •    Additional Remarks
  • +
  •    Remarks on the speed
  • +
  •    Convolution using separable kernels
  • +
  •    Convolution in the Fourier domain
  • @@ -337,7 +379,7 @@ the network.
  • 14
  • 15
  • ...
  • -
  • 47
  • +
  • 62
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs006.html b/doc/pub/week44/html/._week44-bs006.html index 21a6e67c9..edf65f635 100644 --- a/doc/pub/week44/html/._week44-bs006.html +++ b/doc/pub/week44/html/._week44-bs006.html @@ -75,6 +75,12 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d None, 'a-deep-cnn-model-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Key Idea', 2, None, 'key-idea'), + ('How to do image compression before the era of deep learning', + 2, + None, + 'how-to-do-image-compression-before-the-era-of-deep-learning'), + ('The SVD example', 2, None, 'the-svd-example'), + ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Convolution Examples: Polynomial multiplication', 2, @@ -89,6 +95,8 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'a-more-efficient-way-of-coding-the-above-convolution'), + ('Commutative process', 2, None, 'commutative-process'), + ('Toeplitz matrices', 2, None, 'toeplitz-matrices'), ('Fourier series and Toeplitz matrices', 2, None, @@ -97,36 +105,75 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'generalizing-the-above-one-dimensional-case'), - ('Two-dimensional Objects', 2, None, 'two-dimensional-objects'), - ('CNNs in more detail', 2, None, 'cnns-in-more-detail'), - ('Performing a discrete convolution with padding ("From Raschka ' - 'et al":"https://github.com/rasbt/machine-learning-book")', + ('Memory considerations', 2, None, 'memory-considerations'), + ('Padding', 2, None, 'padding'), + ('New vector', 2, None, 'new-vector'), + ('Rewriting as dot products', 2, None, - 'performing-a-discrete-convolution-with-padding-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Performing a general discrete convolution ("From Raschka et ' + 'rewriting-as-dot-products'), + ('Cross correlation', 2, None, 'cross-correlation'), + ('Two-dimensional objects', 2, None, 'two-dimensional-objects'), + ('CNNs in more detail, simple example', + 2, + None, + 'cnns-in-more-detail-simple-example'), + ('The convolution stage', 2, None, 'the-convolution-stage'), + ('Finding the number of parameters', + 2, + None, + 'finding-the-number-of-parameters'), + ('New image (or volume)', 2, None, 'new-image-or-volume'), + ('Parameters to train, common settings', + 2, + None, + 'parameters-to-train-common-settings'), + ('Examples of CNN setups', 2, None, 'examples-of-cnn-setups'), + ('Summarizing: Performing a general discrete convolution ("From ' + 'Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, - 'performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Set of filters', 2, None, 'set-of-filters'), + 'summarizing-performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Pooling', 2, None, 'pooling'), - ('No zero padding, unit strides', - 2, - None, - 'no-zero-padding-unit-strides'), - ('Zero padding, unit strides', - 2, - None, - 'zero-padding-unit-strides'), - ('Half (same) padding', 2, None, 'half-same-padding'), - ('Full padding', 2, None, 'full-padding'), ('Pooling arithmetic', 2, None, 'pooling-arithmetic'), ('Pooling types ("From Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, 'pooling-types-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), + ('Building convolutional neural networks in Tensorflow and Keras', + 2, + None, + 'building-convolutional-neural-networks-in-tensorflow-and-keras'), + ('Setting it up', 2, None, 'setting-it-up'), + ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), + ('Strong correlations', 2, None, 'strong-correlations'), + ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), + ('Systematic reduction', 2, None, 'systematic-reduction'), + ('Prerequisites: Collect and pre-process data', + 2, + None, + 'prerequisites-collect-and-pre-process-data'), + ('Importing Keras and Tensorflow', + 2, + None, + 'importing-keras-and-tensorflow'), + ('Running with Keras', 2, None, 'running-with-keras'), + ('Final part', 2, None, 'final-part'), + ('Final visualization', 2, None, 'final-visualization'), + ('The CIFAR01 data set', 2, None, 'the-cifar01-data-set'), + ('Verifying the data set', 2, None, 'verifying-the-data-set'), + ('Set up the model', 2, None, 'set-up-the-model'), + ('Add Dense layers on top', 2, None, 'add-dense-layers-on-top'), + ('Compile and train the model', + 2, + None, + 'compile-and-train-the-model'), + ('Finally, evaluate the model', + 2, + None, + 'finally-evaluate-the-model'), ('Building our own CNN code', 2, None, @@ -173,27 +220,7 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Convolution in the Fourier domain', 3, None, - 'convolution-in-the-fourier-domain'), - ('Building convolutional neural networks in Tensorflow and Keras', - 2, - None, - 'building-convolutional-neural-networks-in-tensorflow-and-keras'), - ('Setting it up', 2, None, 'setting-it-up'), - ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), - ('Strong correlations', 2, None, 'strong-correlations'), - ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), - ('Systematic reduction', 2, None, 'systematic-reduction'), - ('Prerequisites: Collect and pre-process data', - 2, - None, - 'prerequisites-collect-and-pre-process-data'), - ('Importing Keras and Tensorflow', - 2, - None, - 'importing-keras-and-tensorflow'), - ('Running with Keras', 2, None, 'running-with-keras'), - ('Final part', 2, None, 'final-part'), - ('Final visualization', 2, None, 'final-visualization')]} + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -244,59 +271,74 @@ MathJax.Hub.Config({
  • CNNs in brief
  • A deep CNN model ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • Key Idea
  • -
  • Mathematics of CNNs
  • -
  • Convolution Examples: Polynomial multiplication
  • -
  • Efficient Polynomial Multiplication
  • -
  • Further simplification
  • -
  • A more efficient way of coding the above Convolution
  • -
  • Fourier series and Toeplitz matrices
  • -
  • Generalizing the above one-dimensional case
  • -
  • Two-dimensional Objects
  • -
  • CNNs in more detail
  • -
  • Performing a discrete convolution with padding ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Set of filters
  • -
  • Pooling
  • -
  • No zero padding, unit strides
  • -
  • Zero padding, unit strides
  • -
  • Half (same) padding
  • -
  • Full padding
  • -
  • Pooling arithmetic
  • -
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Building our own CNN code
  • -
  •    List of contents:
  • -
  •    Schedulers
  • -
  •    Usage of schedulers
  • -
  •    Cost functions
  • -
  •    Usage of cost functions
  • -
  •    Activation functions
  • -
  •    Usage of activation functions
  • -
  •    Convolution
  • -
  •    Layers
  • -
  •    Convolution2DLayer: convolution in a hidden layer
  • -
  •    Backpropagation in the convolutional layer
  • -
  •    Demonstration
  • -
  •    Pooling Layer
  • -
  •    Flattening Layer
  • -
  •    Fully Connected Layers
  • -
  •    Optimized Convolution2DLayer
  • -
  •    The Convolutional Neural Network (CNN)
  • -
  •    Usage of CNN code
  • -
  •    Additional Remarks
  • -
  •    Remarks on the speed
  • -
  •    Convolution using separable kernels
  • -
  •    Convolution in the Fourier domain
  • -
  • Building convolutional neural networks in Tensorflow and Keras
  • -
  • Setting it up
  • -
  • The MNIST dataset again
  • -
  • Strong correlations
  • -
  • Layers of a CNN
  • -
  • Systematic reduction
  • -
  • Prerequisites: Collect and pre-process data
  • -
  • Importing Keras and Tensorflow
  • -
  • Running with Keras
  • -
  • Final part
  • -
  • Final visualization
  • +
  • How to do image compression before the era of deep learning
  • +
  • The SVD example
  • +
  • Mathematics of CNNs
  • +
  • Mathematics of CNNs
  • +
  • Convolution Examples: Polynomial multiplication
  • +
  • Efficient Polynomial Multiplication
  • +
  • Further simplification
  • +
  • A more efficient way of coding the above Convolution
  • +
  • Commutative process
  • +
  • Toeplitz matrices
  • +
  • Fourier series and Toeplitz matrices
  • +
  • Generalizing the above one-dimensional case
  • +
  • Memory considerations
  • +
  • Padding
  • +
  • New vector
  • +
  • Rewriting as dot products
  • +
  • Cross correlation
  • +
  • Two-dimensional objects
  • +
  • CNNs in more detail, simple example
  • +
  • The convolution stage
  • +
  • Finding the number of parameters
  • +
  • New image (or volume)
  • +
  • Parameters to train, common settings
  • +
  • Examples of CNN setups
  • +
  • Summarizing: Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Pooling
  • +
  • Pooling arithmetic
  • +
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Building convolutional neural networks in Tensorflow and Keras
  • +
  • Setting it up
  • +
  • The MNIST dataset again
  • +
  • Strong correlations
  • +
  • Layers of a CNN
  • +
  • Systematic reduction
  • +
  • Prerequisites: Collect and pre-process data
  • +
  • Importing Keras and Tensorflow
  • +
  • Running with Keras
  • +
  • Final part
  • +
  • Final visualization
  • +
  • The CIFAR01 data set
  • +
  • Verifying the data set
  • +
  • Set up the model
  • +
  • Add Dense layers on top
  • +
  • Compile and train the model
  • +
  • Finally, evaluate the model
  • +
  • Building our own CNN code
  • +
  •    List of contents:
  • +
  •    Schedulers
  • +
  •    Usage of schedulers
  • +
  •    Cost functions
  • +
  •    Usage of cost functions
  • +
  •    Activation functions
  • +
  •    Usage of activation functions
  • +
  •    Convolution
  • +
  •    Layers
  • +
  •    Convolution2DLayer: convolution in a hidden layer
  • +
  •    Backpropagation in the convolutional layer
  • +
  •    Demonstration
  • +
  •    Pooling Layer
  • +
  •    Flattening Layer
  • +
  •    Fully Connected Layers
  • +
  •    Optimized Convolution2DLayer
  • +
  •    The Convolutional Neural Network (CNN)
  • +
  •    Usage of CNN code
  • +
  •    Additional Remarks
  • +
  •    Remarks on the speed
  • +
  •    Convolution using separable kernels
  • +
  •    Convolution in the Fourier domain
  • @@ -340,7 +382,7 @@ before the transformation.
  • 15
  • 16
  • ...
  • -
  • 47
  • +
  • 62
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs007.html b/doc/pub/week44/html/._week44-bs007.html index 4c8ec3794..c3be604da 100644 --- a/doc/pub/week44/html/._week44-bs007.html +++ b/doc/pub/week44/html/._week44-bs007.html @@ -75,6 +75,12 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d None, 'a-deep-cnn-model-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Key Idea', 2, None, 'key-idea'), + ('How to do image compression before the era of deep learning', + 2, + None, + 'how-to-do-image-compression-before-the-era-of-deep-learning'), + ('The SVD example', 2, None, 'the-svd-example'), + ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Convolution Examples: Polynomial multiplication', 2, @@ -89,6 +95,8 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'a-more-efficient-way-of-coding-the-above-convolution'), + ('Commutative process', 2, None, 'commutative-process'), + ('Toeplitz matrices', 2, None, 'toeplitz-matrices'), ('Fourier series and Toeplitz matrices', 2, None, @@ -97,36 +105,75 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'generalizing-the-above-one-dimensional-case'), - ('Two-dimensional Objects', 2, None, 'two-dimensional-objects'), - ('CNNs in more detail', 2, None, 'cnns-in-more-detail'), - ('Performing a discrete convolution with padding ("From Raschka ' - 'et al":"https://github.com/rasbt/machine-learning-book")', + ('Memory considerations', 2, None, 'memory-considerations'), + ('Padding', 2, None, 'padding'), + ('New vector', 2, None, 'new-vector'), + ('Rewriting as dot products', 2, None, - 'performing-a-discrete-convolution-with-padding-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Performing a general discrete convolution ("From Raschka et ' + 'rewriting-as-dot-products'), + ('Cross correlation', 2, None, 'cross-correlation'), + ('Two-dimensional objects', 2, None, 'two-dimensional-objects'), + ('CNNs in more detail, simple example', + 2, + None, + 'cnns-in-more-detail-simple-example'), + ('The convolution stage', 2, None, 'the-convolution-stage'), + ('Finding the number of parameters', + 2, + None, + 'finding-the-number-of-parameters'), + ('New image (or volume)', 2, None, 'new-image-or-volume'), + ('Parameters to train, common settings', + 2, + None, + 'parameters-to-train-common-settings'), + ('Examples of CNN setups', 2, None, 'examples-of-cnn-setups'), + ('Summarizing: Performing a general discrete convolution ("From ' + 'Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, - 'performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Set of filters', 2, None, 'set-of-filters'), + 'summarizing-performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Pooling', 2, None, 'pooling'), - ('No zero padding, unit strides', - 2, - None, - 'no-zero-padding-unit-strides'), - ('Zero padding, unit strides', - 2, - None, - 'zero-padding-unit-strides'), - ('Half (same) padding', 2, None, 'half-same-padding'), - ('Full padding', 2, None, 'full-padding'), ('Pooling arithmetic', 2, None, 'pooling-arithmetic'), ('Pooling types ("From Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, 'pooling-types-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), + ('Building convolutional neural networks in Tensorflow and Keras', + 2, + None, + 'building-convolutional-neural-networks-in-tensorflow-and-keras'), + ('Setting it up', 2, None, 'setting-it-up'), + ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), + ('Strong correlations', 2, None, 'strong-correlations'), + ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), + ('Systematic reduction', 2, None, 'systematic-reduction'), + ('Prerequisites: Collect and pre-process data', + 2, + None, + 'prerequisites-collect-and-pre-process-data'), + ('Importing Keras and Tensorflow', + 2, + None, + 'importing-keras-and-tensorflow'), + ('Running with Keras', 2, None, 'running-with-keras'), + ('Final part', 2, None, 'final-part'), + ('Final visualization', 2, None, 'final-visualization'), + ('The CIFAR01 data set', 2, None, 'the-cifar01-data-set'), + ('Verifying the data set', 2, None, 'verifying-the-data-set'), + ('Set up the model', 2, None, 'set-up-the-model'), + ('Add Dense layers on top', 2, None, 'add-dense-layers-on-top'), + ('Compile and train the model', + 2, + None, + 'compile-and-train-the-model'), + ('Finally, evaluate the model', + 2, + None, + 'finally-evaluate-the-model'), ('Building our own CNN code', 2, None, @@ -173,27 +220,7 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Convolution in the Fourier domain', 3, None, - 'convolution-in-the-fourier-domain'), - ('Building convolutional neural networks in Tensorflow and Keras', - 2, - None, - 'building-convolutional-neural-networks-in-tensorflow-and-keras'), - ('Setting it up', 2, None, 'setting-it-up'), - ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), - ('Strong correlations', 2, None, 'strong-correlations'), - ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), - ('Systematic reduction', 2, None, 'systematic-reduction'), - ('Prerequisites: Collect and pre-process data', - 2, - None, - 'prerequisites-collect-and-pre-process-data'), - ('Importing Keras and Tensorflow', - 2, - None, - 'importing-keras-and-tensorflow'), - ('Running with Keras', 2, None, 'running-with-keras'), - ('Final part', 2, None, 'final-part'), - ('Final visualization', 2, None, 'final-visualization')]} + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -244,59 +271,74 @@ MathJax.Hub.Config({
  • CNNs in brief
  • A deep CNN model ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • Key Idea
  • -
  • Mathematics of CNNs
  • -
  • Convolution Examples: Polynomial multiplication
  • -
  • Efficient Polynomial Multiplication
  • -
  • Further simplification
  • -
  • A more efficient way of coding the above Convolution
  • -
  • Fourier series and Toeplitz matrices
  • -
  • Generalizing the above one-dimensional case
  • -
  • Two-dimensional Objects
  • -
  • CNNs in more detail
  • -
  • Performing a discrete convolution with padding ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Set of filters
  • -
  • Pooling
  • -
  • No zero padding, unit strides
  • -
  • Zero padding, unit strides
  • -
  • Half (same) padding
  • -
  • Full padding
  • -
  • Pooling arithmetic
  • -
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Building our own CNN code
  • -
  •    List of contents:
  • -
  •    Schedulers
  • -
  •    Usage of schedulers
  • -
  •    Cost functions
  • -
  •    Usage of cost functions
  • -
  •    Activation functions
  • -
  •    Usage of activation functions
  • -
  •    Convolution
  • -
  •    Layers
  • -
  •    Convolution2DLayer: convolution in a hidden layer
  • -
  •    Backpropagation in the convolutional layer
  • -
  •    Demonstration
  • -
  •    Pooling Layer
  • -
  •    Flattening Layer
  • -
  •    Fully Connected Layers
  • -
  •    Optimized Convolution2DLayer
  • -
  •    The Convolutional Neural Network (CNN)
  • -
  •    Usage of CNN code
  • -
  •    Additional Remarks
  • -
  •    Remarks on the speed
  • -
  •    Convolution using separable kernels
  • -
  •    Convolution in the Fourier domain
  • -
  • Building convolutional neural networks in Tensorflow and Keras
  • -
  • Setting it up
  • -
  • The MNIST dataset again
  • -
  • Strong correlations
  • -
  • Layers of a CNN
  • -
  • Systematic reduction
  • -
  • Prerequisites: Collect and pre-process data
  • -
  • Importing Keras and Tensorflow
  • -
  • Running with Keras
  • -
  • Final part
  • -
  • Final visualization
  • +
  • How to do image compression before the era of deep learning
  • +
  • The SVD example
  • +
  • Mathematics of CNNs
  • +
  • Mathematics of CNNs
  • +
  • Convolution Examples: Polynomial multiplication
  • +
  • Efficient Polynomial Multiplication
  • +
  • Further simplification
  • +
  • A more efficient way of coding the above Convolution
  • +
  • Commutative process
  • +
  • Toeplitz matrices
  • +
  • Fourier series and Toeplitz matrices
  • +
  • Generalizing the above one-dimensional case
  • +
  • Memory considerations
  • +
  • Padding
  • +
  • New vector
  • +
  • Rewriting as dot products
  • +
  • Cross correlation
  • +
  • Two-dimensional objects
  • +
  • CNNs in more detail, simple example
  • +
  • The convolution stage
  • +
  • Finding the number of parameters
  • +
  • New image (or volume)
  • +
  • Parameters to train, common settings
  • +
  • Examples of CNN setups
  • +
  • Summarizing: Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Pooling
  • +
  • Pooling arithmetic
  • +
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Building convolutional neural networks in Tensorflow and Keras
  • +
  • Setting it up
  • +
  • The MNIST dataset again
  • +
  • Strong correlations
  • +
  • Layers of a CNN
  • +
  • Systematic reduction
  • +
  • Prerequisites: Collect and pre-process data
  • +
  • Importing Keras and Tensorflow
  • +
  • Running with Keras
  • +
  • Final part
  • +
  • Final visualization
  • +
  • The CIFAR01 data set
  • +
  • Verifying the data set
  • +
  • Set up the model
  • +
  • Add Dense layers on top
  • +
  • Compile and train the model
  • +
  • Finally, evaluate the model
  • +
  • Building our own CNN code
  • +
  •    List of contents:
  • +
  •    Schedulers
  • +
  •    Usage of schedulers
  • +
  •    Cost functions
  • +
  •    Usage of cost functions
  • +
  •    Activation functions
  • +
  •    Usage of activation functions
  • +
  •    Convolution
  • +
  •    Layers
  • +
  •    Convolution2DLayer: convolution in a hidden layer
  • +
  •    Backpropagation in the convolutional layer
  • +
  •    Demonstration
  • +
  •    Pooling Layer
  • +
  •    Flattening Layer
  • +
  •    Fully Connected Layers
  • +
  •    Optimized Convolution2DLayer
  • +
  •    The Convolutional Neural Network (CNN)
  • +
  •    Usage of CNN code
  • +
  •    Additional Remarks
  • +
  •    Remarks on the speed
  • +
  •    Convolution using separable kernels
  • +
  •    Convolution in the Fourier domain
  • @@ -354,7 +396,7 @@ in the input).
  • 16
  • 17
  • ...
  • -
  • 47
  • +
  • 62
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs008.html b/doc/pub/week44/html/._week44-bs008.html index f94bd9e9c..68b5b92e8 100644 --- a/doc/pub/week44/html/._week44-bs008.html +++ b/doc/pub/week44/html/._week44-bs008.html @@ -75,6 +75,12 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d None, 'a-deep-cnn-model-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Key Idea', 2, None, 'key-idea'), + ('How to do image compression before the era of deep learning', + 2, + None, + 'how-to-do-image-compression-before-the-era-of-deep-learning'), + ('The SVD example', 2, None, 'the-svd-example'), + ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Convolution Examples: Polynomial multiplication', 2, @@ -89,6 +95,8 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'a-more-efficient-way-of-coding-the-above-convolution'), + ('Commutative process', 2, None, 'commutative-process'), + ('Toeplitz matrices', 2, None, 'toeplitz-matrices'), ('Fourier series and Toeplitz matrices', 2, None, @@ -97,36 +105,75 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'generalizing-the-above-one-dimensional-case'), - ('Two-dimensional Objects', 2, None, 'two-dimensional-objects'), - ('CNNs in more detail', 2, None, 'cnns-in-more-detail'), - ('Performing a discrete convolution with padding ("From Raschka ' - 'et al":"https://github.com/rasbt/machine-learning-book")', + ('Memory considerations', 2, None, 'memory-considerations'), + ('Padding', 2, None, 'padding'), + ('New vector', 2, None, 'new-vector'), + ('Rewriting as dot products', 2, None, - 'performing-a-discrete-convolution-with-padding-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Performing a general discrete convolution ("From Raschka et ' + 'rewriting-as-dot-products'), + ('Cross correlation', 2, None, 'cross-correlation'), + ('Two-dimensional objects', 2, None, 'two-dimensional-objects'), + ('CNNs in more detail, simple example', + 2, + None, + 'cnns-in-more-detail-simple-example'), + ('The convolution stage', 2, None, 'the-convolution-stage'), + ('Finding the number of parameters', + 2, + None, + 'finding-the-number-of-parameters'), + ('New image (or volume)', 2, None, 'new-image-or-volume'), + ('Parameters to train, common settings', + 2, + None, + 'parameters-to-train-common-settings'), + ('Examples of CNN setups', 2, None, 'examples-of-cnn-setups'), + ('Summarizing: Performing a general discrete convolution ("From ' + 'Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, - 'performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Set of filters', 2, None, 'set-of-filters'), + 'summarizing-performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Pooling', 2, None, 'pooling'), - ('No zero padding, unit strides', - 2, - None, - 'no-zero-padding-unit-strides'), - ('Zero padding, unit strides', - 2, - None, - 'zero-padding-unit-strides'), - ('Half (same) padding', 2, None, 'half-same-padding'), - ('Full padding', 2, None, 'full-padding'), ('Pooling arithmetic', 2, None, 'pooling-arithmetic'), ('Pooling types ("From Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, 'pooling-types-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), + ('Building convolutional neural networks in Tensorflow and Keras', + 2, + None, + 'building-convolutional-neural-networks-in-tensorflow-and-keras'), + ('Setting it up', 2, None, 'setting-it-up'), + ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), + ('Strong correlations', 2, None, 'strong-correlations'), + ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), + ('Systematic reduction', 2, None, 'systematic-reduction'), + ('Prerequisites: Collect and pre-process data', + 2, + None, + 'prerequisites-collect-and-pre-process-data'), + ('Importing Keras and Tensorflow', + 2, + None, + 'importing-keras-and-tensorflow'), + ('Running with Keras', 2, None, 'running-with-keras'), + ('Final part', 2, None, 'final-part'), + ('Final visualization', 2, None, 'final-visualization'), + ('The CIFAR01 data set', 2, None, 'the-cifar01-data-set'), + ('Verifying the data set', 2, None, 'verifying-the-data-set'), + ('Set up the model', 2, None, 'set-up-the-model'), + ('Add Dense layers on top', 2, None, 'add-dense-layers-on-top'), + ('Compile and train the model', + 2, + None, + 'compile-and-train-the-model'), + ('Finally, evaluate the model', + 2, + None, + 'finally-evaluate-the-model'), ('Building our own CNN code', 2, None, @@ -173,27 +220,7 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Convolution in the Fourier domain', 3, None, - 'convolution-in-the-fourier-domain'), - ('Building convolutional neural networks in Tensorflow and Keras', - 2, - None, - 'building-convolutional-neural-networks-in-tensorflow-and-keras'), - ('Setting it up', 2, None, 'setting-it-up'), - ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), - ('Strong correlations', 2, None, 'strong-correlations'), - ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), - ('Systematic reduction', 2, None, 'systematic-reduction'), - ('Prerequisites: Collect and pre-process data', - 2, - None, - 'prerequisites-collect-and-pre-process-data'), - ('Importing Keras and Tensorflow', - 2, - None, - 'importing-keras-and-tensorflow'), - ('Running with Keras', 2, None, 'running-with-keras'), - ('Final part', 2, None, 'final-part'), - ('Final visualization', 2, None, 'final-visualization')]} + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -244,59 +271,74 @@ MathJax.Hub.Config({
  • CNNs in brief
  • A deep CNN model ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • Key Idea
  • -
  • Mathematics of CNNs
  • -
  • Convolution Examples: Polynomial multiplication
  • -
  • Efficient Polynomial Multiplication
  • -
  • Further simplification
  • -
  • A more efficient way of coding the above Convolution
  • -
  • Fourier series and Toeplitz matrices
  • -
  • Generalizing the above one-dimensional case
  • -
  • Two-dimensional Objects
  • -
  • CNNs in more detail
  • -
  • Performing a discrete convolution with padding ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Set of filters
  • -
  • Pooling
  • -
  • No zero padding, unit strides
  • -
  • Zero padding, unit strides
  • -
  • Half (same) padding
  • -
  • Full padding
  • -
  • Pooling arithmetic
  • -
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Building our own CNN code
  • -
  •    List of contents:
  • -
  •    Schedulers
  • -
  •    Usage of schedulers
  • -
  •    Cost functions
  • -
  •    Usage of cost functions
  • -
  •    Activation functions
  • -
  •    Usage of activation functions
  • -
  •    Convolution
  • -
  •    Layers
  • -
  •    Convolution2DLayer: convolution in a hidden layer
  • -
  •    Backpropagation in the convolutional layer
  • -
  •    Demonstration
  • -
  •    Pooling Layer
  • -
  •    Flattening Layer
  • -
  •    Fully Connected Layers
  • -
  •    Optimized Convolution2DLayer
  • -
  •    The Convolutional Neural Network (CNN)
  • -
  •    Usage of CNN code
  • -
  •    Additional Remarks
  • -
  •    Remarks on the speed
  • -
  •    Convolution using separable kernels
  • -
  •    Convolution in the Fourier domain
  • -
  • Building convolutional neural networks in Tensorflow and Keras
  • -
  • Setting it up
  • -
  • The MNIST dataset again
  • -
  • Strong correlations
  • -
  • Layers of a CNN
  • -
  • Systematic reduction
  • -
  • Prerequisites: Collect and pre-process data
  • -
  • Importing Keras and Tensorflow
  • -
  • Running with Keras
  • -
  • Final part
  • -
  • Final visualization
  • +
  • How to do image compression before the era of deep learning
  • +
  • The SVD example
  • +
  • Mathematics of CNNs
  • +
  • Mathematics of CNNs
  • +
  • Convolution Examples: Polynomial multiplication
  • +
  • Efficient Polynomial Multiplication
  • +
  • Further simplification
  • +
  • A more efficient way of coding the above Convolution
  • +
  • Commutative process
  • +
  • Toeplitz matrices
  • +
  • Fourier series and Toeplitz matrices
  • +
  • Generalizing the above one-dimensional case
  • +
  • Memory considerations
  • +
  • Padding
  • +
  • New vector
  • +
  • Rewriting as dot products
  • +
  • Cross correlation
  • +
  • Two-dimensional objects
  • +
  • CNNs in more detail, simple example
  • +
  • The convolution stage
  • +
  • Finding the number of parameters
  • +
  • New image (or volume)
  • +
  • Parameters to train, common settings
  • +
  • Examples of CNN setups
  • +
  • Summarizing: Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Pooling
  • +
  • Pooling arithmetic
  • +
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Building convolutional neural networks in Tensorflow and Keras
  • +
  • Setting it up
  • +
  • The MNIST dataset again
  • +
  • Strong correlations
  • +
  • Layers of a CNN
  • +
  • Systematic reduction
  • +
  • Prerequisites: Collect and pre-process data
  • +
  • Importing Keras and Tensorflow
  • +
  • Running with Keras
  • +
  • Final part
  • +
  • Final visualization
  • +
  • The CIFAR01 data set
  • +
  • Verifying the data set
  • +
  • Set up the model
  • +
  • Add Dense layers on top
  • +
  • Compile and train the model
  • +
  • Finally, evaluate the model
  • +
  • Building our own CNN code
  • +
  •    List of contents:
  • +
  •    Schedulers
  • +
  •    Usage of schedulers
  • +
  •    Cost functions
  • +
  •    Usage of cost functions
  • +
  •    Activation functions
  • +
  •    Usage of activation functions
  • +
  •    Convolution
  • +
  •    Layers
  • +
  •    Convolution2DLayer: convolution in a hidden layer
  • +
  •    Backpropagation in the convolutional layer
  • +
  •    Demonstration
  • +
  •    Pooling Layer
  • +
  •    Flattening Layer
  • +
  •    Fully Connected Layers
  • +
  •    Optimized Convolution2DLayer
  • +
  •    The Convolutional Neural Network (CNN)
  • +
  •    Usage of CNN code
  • +
  •    Additional Remarks
  • +
  •    Remarks on the speed
  • +
  •    Convolution using separable kernels
  • +
  •    Convolution in the Fourier domain
  • @@ -357,7 +399,7 @@ would quickly lead to possible overfitting.
  • 17
  • 18
  • ...
  • -
  • 47
  • +
  • 62
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs009.html b/doc/pub/week44/html/._week44-bs009.html index 694d67abc..4800dc14e 100644 --- a/doc/pub/week44/html/._week44-bs009.html +++ b/doc/pub/week44/html/._week44-bs009.html @@ -75,6 +75,12 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d None, 'a-deep-cnn-model-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Key Idea', 2, None, 'key-idea'), + ('How to do image compression before the era of deep learning', + 2, + None, + 'how-to-do-image-compression-before-the-era-of-deep-learning'), + ('The SVD example', 2, None, 'the-svd-example'), + ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Convolution Examples: Polynomial multiplication', 2, @@ -89,6 +95,8 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'a-more-efficient-way-of-coding-the-above-convolution'), + ('Commutative process', 2, None, 'commutative-process'), + ('Toeplitz matrices', 2, None, 'toeplitz-matrices'), ('Fourier series and Toeplitz matrices', 2, None, @@ -97,36 +105,75 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'generalizing-the-above-one-dimensional-case'), - ('Two-dimensional Objects', 2, None, 'two-dimensional-objects'), - ('CNNs in more detail', 2, None, 'cnns-in-more-detail'), - ('Performing a discrete convolution with padding ("From Raschka ' - 'et al":"https://github.com/rasbt/machine-learning-book")', + ('Memory considerations', 2, None, 'memory-considerations'), + ('Padding', 2, None, 'padding'), + ('New vector', 2, None, 'new-vector'), + ('Rewriting as dot products', 2, None, - 'performing-a-discrete-convolution-with-padding-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Performing a general discrete convolution ("From Raschka et ' + 'rewriting-as-dot-products'), + ('Cross correlation', 2, None, 'cross-correlation'), + ('Two-dimensional objects', 2, None, 'two-dimensional-objects'), + ('CNNs in more detail, simple example', + 2, + None, + 'cnns-in-more-detail-simple-example'), + ('The convolution stage', 2, None, 'the-convolution-stage'), + ('Finding the number of parameters', + 2, + None, + 'finding-the-number-of-parameters'), + ('New image (or volume)', 2, None, 'new-image-or-volume'), + ('Parameters to train, common settings', + 2, + None, + 'parameters-to-train-common-settings'), + ('Examples of CNN setups', 2, None, 'examples-of-cnn-setups'), + ('Summarizing: Performing a general discrete convolution ("From ' + 'Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, - 'performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Set of filters', 2, None, 'set-of-filters'), + 'summarizing-performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Pooling', 2, None, 'pooling'), - ('No zero padding, unit strides', - 2, - None, - 'no-zero-padding-unit-strides'), - ('Zero padding, unit strides', - 2, - None, - 'zero-padding-unit-strides'), - ('Half (same) padding', 2, None, 'half-same-padding'), - ('Full padding', 2, None, 'full-padding'), ('Pooling arithmetic', 2, None, 'pooling-arithmetic'), ('Pooling types ("From Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, 'pooling-types-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), + ('Building convolutional neural networks in Tensorflow and Keras', + 2, + None, + 'building-convolutional-neural-networks-in-tensorflow-and-keras'), + ('Setting it up', 2, None, 'setting-it-up'), + ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), + ('Strong correlations', 2, None, 'strong-correlations'), + ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), + ('Systematic reduction', 2, None, 'systematic-reduction'), + ('Prerequisites: Collect and pre-process data', + 2, + None, + 'prerequisites-collect-and-pre-process-data'), + ('Importing Keras and Tensorflow', + 2, + None, + 'importing-keras-and-tensorflow'), + ('Running with Keras', 2, None, 'running-with-keras'), + ('Final part', 2, None, 'final-part'), + ('Final visualization', 2, None, 'final-visualization'), + ('The CIFAR01 data set', 2, None, 'the-cifar01-data-set'), + ('Verifying the data set', 2, None, 'verifying-the-data-set'), + ('Set up the model', 2, None, 'set-up-the-model'), + ('Add Dense layers on top', 2, None, 'add-dense-layers-on-top'), + ('Compile and train the model', + 2, + None, + 'compile-and-train-the-model'), + ('Finally, evaluate the model', + 2, + None, + 'finally-evaluate-the-model'), ('Building our own CNN code', 2, None, @@ -173,27 +220,7 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Convolution in the Fourier domain', 3, None, - 'convolution-in-the-fourier-domain'), - ('Building convolutional neural networks in Tensorflow and Keras', - 2, - None, - 'building-convolutional-neural-networks-in-tensorflow-and-keras'), - ('Setting it up', 2, None, 'setting-it-up'), - ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), - ('Strong correlations', 2, None, 'strong-correlations'), - ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), - ('Systematic reduction', 2, None, 'systematic-reduction'), - ('Prerequisites: Collect and pre-process data', - 2, - None, - 'prerequisites-collect-and-pre-process-data'), - ('Importing Keras and Tensorflow', - 2, - None, - 'importing-keras-and-tensorflow'), - ('Running with Keras', 2, None, 'running-with-keras'), - ('Final part', 2, None, 'final-part'), - ('Final visualization', 2, None, 'final-visualization')]} + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -244,59 +271,74 @@ MathJax.Hub.Config({
  • CNNs in brief
  • A deep CNN model ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • Key Idea
  • -
  • Mathematics of CNNs
  • -
  • Convolution Examples: Polynomial multiplication
  • -
  • Efficient Polynomial Multiplication
  • -
  • Further simplification
  • -
  • A more efficient way of coding the above Convolution
  • -
  • Fourier series and Toeplitz matrices
  • -
  • Generalizing the above one-dimensional case
  • -
  • Two-dimensional Objects
  • -
  • CNNs in more detail
  • -
  • Performing a discrete convolution with padding ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Set of filters
  • -
  • Pooling
  • -
  • No zero padding, unit strides
  • -
  • Zero padding, unit strides
  • -
  • Half (same) padding
  • -
  • Full padding
  • -
  • Pooling arithmetic
  • -
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Building our own CNN code
  • -
  •    List of contents:
  • -
  •    Schedulers
  • -
  •    Usage of schedulers
  • -
  •    Cost functions
  • -
  •    Usage of cost functions
  • -
  •    Activation functions
  • -
  •    Usage of activation functions
  • -
  •    Convolution
  • -
  •    Layers
  • -
  •    Convolution2DLayer: convolution in a hidden layer
  • -
  •    Backpropagation in the convolutional layer
  • -
  •    Demonstration
  • -
  •    Pooling Layer
  • -
  •    Flattening Layer
  • -
  •    Fully Connected Layers
  • -
  •    Optimized Convolution2DLayer
  • -
  •    The Convolutional Neural Network (CNN)
  • -
  •    Usage of CNN code
  • -
  •    Additional Remarks
  • -
  •    Remarks on the speed
  • -
  •    Convolution using separable kernels
  • -
  •    Convolution in the Fourier domain
  • -
  • Building convolutional neural networks in Tensorflow and Keras
  • -
  • Setting it up
  • -
  • The MNIST dataset again
  • -
  • Strong correlations
  • -
  • Layers of a CNN
  • -
  • Systematic reduction
  • -
  • Prerequisites: Collect and pre-process data
  • -
  • Importing Keras and Tensorflow
  • -
  • Running with Keras
  • -
  • Final part
  • -
  • Final visualization
  • +
  • How to do image compression before the era of deep learning
  • +
  • The SVD example
  • +
  • Mathematics of CNNs
  • +
  • Mathematics of CNNs
  • +
  • Convolution Examples: Polynomial multiplication
  • +
  • Efficient Polynomial Multiplication
  • +
  • Further simplification
  • +
  • A more efficient way of coding the above Convolution
  • +
  • Commutative process
  • +
  • Toeplitz matrices
  • +
  • Fourier series and Toeplitz matrices
  • +
  • Generalizing the above one-dimensional case
  • +
  • Memory considerations
  • +
  • Padding
  • +
  • New vector
  • +
  • Rewriting as dot products
  • +
  • Cross correlation
  • +
  • Two-dimensional objects
  • +
  • CNNs in more detail, simple example
  • +
  • The convolution stage
  • +
  • Finding the number of parameters
  • +
  • New image (or volume)
  • +
  • Parameters to train, common settings
  • +
  • Examples of CNN setups
  • +
  • Summarizing: Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Pooling
  • +
  • Pooling arithmetic
  • +
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Building convolutional neural networks in Tensorflow and Keras
  • +
  • Setting it up
  • +
  • The MNIST dataset again
  • +
  • Strong correlations
  • +
  • Layers of a CNN
  • +
  • Systematic reduction
  • +
  • Prerequisites: Collect and pre-process data
  • +
  • Importing Keras and Tensorflow
  • +
  • Running with Keras
  • +
  • Final part
  • +
  • Final visualization
  • +
  • The CIFAR01 data set
  • +
  • Verifying the data set
  • +
  • Set up the model
  • +
  • Add Dense layers on top
  • +
  • Compile and train the model
  • +
  • Finally, evaluate the model
  • +
  • Building our own CNN code
  • +
  •    List of contents:
  • +
  •    Schedulers
  • +
  •    Usage of schedulers
  • +
  •    Cost functions
  • +
  •    Usage of cost functions
  • +
  •    Activation functions
  • +
  •    Usage of activation functions
  • +
  •    Convolution
  • +
  •    Layers
  • +
  •    Convolution2DLayer: convolution in a hidden layer
  • +
  •    Backpropagation in the convolutional layer
  • +
  •    Demonstration
  • +
  •    Pooling Layer
  • +
  •    Flattening Layer
  • +
  •    Fully Connected Layers
  • +
  •    Optimized Convolution2DLayer
  • +
  •    The Convolutional Neural Network (CNN)
  • +
  •    Usage of CNN code
  • +
  •    Additional Remarks
  • +
  •    Remarks on the speed
  • +
  •    Convolution using separable kernels
  • +
  •    Convolution in the Fourier domain
  • @@ -370,7 +412,7 @@ dimension.
  • 18
  • 19
  • ...
  • -
  • 47
  • +
  • 62
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs010.html b/doc/pub/week44/html/._week44-bs010.html index 5e741911d..b36dfe10a 100644 --- a/doc/pub/week44/html/._week44-bs010.html +++ b/doc/pub/week44/html/._week44-bs010.html @@ -75,6 +75,12 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d None, 'a-deep-cnn-model-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Key Idea', 2, None, 'key-idea'), + ('How to do image compression before the era of deep learning', + 2, + None, + 'how-to-do-image-compression-before-the-era-of-deep-learning'), + ('The SVD example', 2, None, 'the-svd-example'), + ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Convolution Examples: Polynomial multiplication', 2, @@ -89,6 +95,8 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'a-more-efficient-way-of-coding-the-above-convolution'), + ('Commutative process', 2, None, 'commutative-process'), + ('Toeplitz matrices', 2, None, 'toeplitz-matrices'), ('Fourier series and Toeplitz matrices', 2, None, @@ -97,36 +105,75 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'generalizing-the-above-one-dimensional-case'), - ('Two-dimensional Objects', 2, None, 'two-dimensional-objects'), - ('CNNs in more detail', 2, None, 'cnns-in-more-detail'), - ('Performing a discrete convolution with padding ("From Raschka ' - 'et al":"https://github.com/rasbt/machine-learning-book")', + ('Memory considerations', 2, None, 'memory-considerations'), + ('Padding', 2, None, 'padding'), + ('New vector', 2, None, 'new-vector'), + ('Rewriting as dot products', 2, None, - 'performing-a-discrete-convolution-with-padding-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Performing a general discrete convolution ("From Raschka et ' + 'rewriting-as-dot-products'), + ('Cross correlation', 2, None, 'cross-correlation'), + ('Two-dimensional objects', 2, None, 'two-dimensional-objects'), + ('CNNs in more detail, simple example', + 2, + None, + 'cnns-in-more-detail-simple-example'), + ('The convolution stage', 2, None, 'the-convolution-stage'), + ('Finding the number of parameters', + 2, + None, + 'finding-the-number-of-parameters'), + ('New image (or volume)', 2, None, 'new-image-or-volume'), + ('Parameters to train, common settings', + 2, + None, + 'parameters-to-train-common-settings'), + ('Examples of CNN setups', 2, None, 'examples-of-cnn-setups'), + ('Summarizing: Performing a general discrete convolution ("From ' + 'Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, - 'performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Set of filters', 2, None, 'set-of-filters'), + 'summarizing-performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Pooling', 2, None, 'pooling'), - ('No zero padding, unit strides', - 2, - None, - 'no-zero-padding-unit-strides'), - ('Zero padding, unit strides', - 2, - None, - 'zero-padding-unit-strides'), - ('Half (same) padding', 2, None, 'half-same-padding'), - ('Full padding', 2, None, 'full-padding'), ('Pooling arithmetic', 2, None, 'pooling-arithmetic'), ('Pooling types ("From Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, 'pooling-types-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), + ('Building convolutional neural networks in Tensorflow and Keras', + 2, + None, + 'building-convolutional-neural-networks-in-tensorflow-and-keras'), + ('Setting it up', 2, None, 'setting-it-up'), + ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), + ('Strong correlations', 2, None, 'strong-correlations'), + ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), + ('Systematic reduction', 2, None, 'systematic-reduction'), + ('Prerequisites: Collect and pre-process data', + 2, + None, + 'prerequisites-collect-and-pre-process-data'), + ('Importing Keras and Tensorflow', + 2, + None, + 'importing-keras-and-tensorflow'), + ('Running with Keras', 2, None, 'running-with-keras'), + ('Final part', 2, None, 'final-part'), + ('Final visualization', 2, None, 'final-visualization'), + ('The CIFAR01 data set', 2, None, 'the-cifar01-data-set'), + ('Verifying the data set', 2, None, 'verifying-the-data-set'), + ('Set up the model', 2, None, 'set-up-the-model'), + ('Add Dense layers on top', 2, None, 'add-dense-layers-on-top'), + ('Compile and train the model', + 2, + None, + 'compile-and-train-the-model'), + ('Finally, evaluate the model', + 2, + None, + 'finally-evaluate-the-model'), ('Building our own CNN code', 2, None, @@ -173,27 +220,7 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Convolution in the Fourier domain', 3, None, - 'convolution-in-the-fourier-domain'), - ('Building convolutional neural networks in Tensorflow and Keras', - 2, - None, - 'building-convolutional-neural-networks-in-tensorflow-and-keras'), - ('Setting it up', 2, None, 'setting-it-up'), - ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), - ('Strong correlations', 2, None, 'strong-correlations'), - ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), - ('Systematic reduction', 2, None, 'systematic-reduction'), - ('Prerequisites: Collect and pre-process data', - 2, - None, - 'prerequisites-collect-and-pre-process-data'), - ('Importing Keras and Tensorflow', - 2, - None, - 'importing-keras-and-tensorflow'), - ('Running with Keras', 2, None, 'running-with-keras'), - ('Final part', 2, None, 'final-part'), - ('Final visualization', 2, None, 'final-visualization')]} + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -244,59 +271,74 @@ MathJax.Hub.Config({
  • CNNs in brief
  • A deep CNN model ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • Key Idea
  • -
  • Mathematics of CNNs
  • -
  • Convolution Examples: Polynomial multiplication
  • -
  • Efficient Polynomial Multiplication
  • -
  • Further simplification
  • -
  • A more efficient way of coding the above Convolution
  • -
  • Fourier series and Toeplitz matrices
  • -
  • Generalizing the above one-dimensional case
  • -
  • Two-dimensional Objects
  • -
  • CNNs in more detail
  • -
  • Performing a discrete convolution with padding ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Set of filters
  • -
  • Pooling
  • -
  • No zero padding, unit strides
  • -
  • Zero padding, unit strides
  • -
  • Half (same) padding
  • -
  • Full padding
  • -
  • Pooling arithmetic
  • -
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Building our own CNN code
  • -
  •    List of contents:
  • -
  •    Schedulers
  • -
  •    Usage of schedulers
  • -
  •    Cost functions
  • -
  •    Usage of cost functions
  • -
  •    Activation functions
  • -
  •    Usage of activation functions
  • -
  •    Convolution
  • -
  •    Layers
  • -
  •    Convolution2DLayer: convolution in a hidden layer
  • -
  •    Backpropagation in the convolutional layer
  • -
  •    Demonstration
  • -
  •    Pooling Layer
  • -
  •    Flattening Layer
  • -
  •    Fully Connected Layers
  • -
  •    Optimized Convolution2DLayer
  • -
  •    The Convolutional Neural Network (CNN)
  • -
  •    Usage of CNN code
  • -
  •    Additional Remarks
  • -
  •    Remarks on the speed
  • -
  •    Convolution using separable kernels
  • -
  •    Convolution in the Fourier domain
  • -
  • Building convolutional neural networks in Tensorflow and Keras
  • -
  • Setting it up
  • -
  • The MNIST dataset again
  • -
  • Strong correlations
  • -
  • Layers of a CNN
  • -
  • Systematic reduction
  • -
  • Prerequisites: Collect and pre-process data
  • -
  • Importing Keras and Tensorflow
  • -
  • Running with Keras
  • -
  • Final part
  • -
  • Final visualization
  • +
  • How to do image compression before the era of deep learning
  • +
  • The SVD example
  • +
  • Mathematics of CNNs
  • +
  • Mathematics of CNNs
  • +
  • Convolution Examples: Polynomial multiplication
  • +
  • Efficient Polynomial Multiplication
  • +
  • Further simplification
  • +
  • A more efficient way of coding the above Convolution
  • +
  • Commutative process
  • +
  • Toeplitz matrices
  • +
  • Fourier series and Toeplitz matrices
  • +
  • Generalizing the above one-dimensional case
  • +
  • Memory considerations
  • +
  • Padding
  • +
  • New vector
  • +
  • Rewriting as dot products
  • +
  • Cross correlation
  • +
  • Two-dimensional objects
  • +
  • CNNs in more detail, simple example
  • +
  • The convolution stage
  • +
  • Finding the number of parameters
  • +
  • New image (or volume)
  • +
  • Parameters to train, common settings
  • +
  • Examples of CNN setups
  • +
  • Summarizing: Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Pooling
  • +
  • Pooling arithmetic
  • +
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Building convolutional neural networks in Tensorflow and Keras
  • +
  • Setting it up
  • +
  • The MNIST dataset again
  • +
  • Strong correlations
  • +
  • Layers of a CNN
  • +
  • Systematic reduction
  • +
  • Prerequisites: Collect and pre-process data
  • +
  • Importing Keras and Tensorflow
  • +
  • Running with Keras
  • +
  • Final part
  • +
  • Final visualization
  • +
  • The CIFAR01 data set
  • +
  • Verifying the data set
  • +
  • Set up the model
  • +
  • Add Dense layers on top
  • +
  • Compile and train the model
  • +
  • Finally, evaluate the model
  • +
  • Building our own CNN code
  • +
  •    List of contents:
  • +
  •    Schedulers
  • +
  •    Usage of schedulers
  • +
  •    Cost functions
  • +
  •    Usage of cost functions
  • +
  •    Activation functions
  • +
  •    Usage of activation functions
  • +
  •    Convolution
  • +
  •    Layers
  • +
  •    Convolution2DLayer: convolution in a hidden layer
  • +
  •    Backpropagation in the convolutional layer
  • +
  •    Demonstration
  • +
  •    Pooling Layer
  • +
  •    Flattening Layer
  • +
  •    Fully Connected Layers
  • +
  •    Optimized Convolution2DLayer
  • +
  •    The Convolutional Neural Network (CNN)
  • +
  •    Usage of CNN code
  • +
  •    Additional Remarks
  • +
  •    Remarks on the speed
  • +
  •    Convolution using separable kernels
  • +
  •    Convolution in the Fourier domain
  • @@ -361,7 +403,7 @@ $$
  • 19
  • 20
  • ...
  • -
  • 47
  • +
  • 62
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs011.html b/doc/pub/week44/html/._week44-bs011.html index ea1ee1fd0..f5d4ca77f 100644 --- a/doc/pub/week44/html/._week44-bs011.html +++ b/doc/pub/week44/html/._week44-bs011.html @@ -75,6 +75,12 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d None, 'a-deep-cnn-model-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Key Idea', 2, None, 'key-idea'), + ('How to do image compression before the era of deep learning', + 2, + None, + 'how-to-do-image-compression-before-the-era-of-deep-learning'), + ('The SVD example', 2, None, 'the-svd-example'), + ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Convolution Examples: Polynomial multiplication', 2, @@ -89,6 +95,8 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'a-more-efficient-way-of-coding-the-above-convolution'), + ('Commutative process', 2, None, 'commutative-process'), + ('Toeplitz matrices', 2, None, 'toeplitz-matrices'), ('Fourier series and Toeplitz matrices', 2, None, @@ -97,36 +105,75 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'generalizing-the-above-one-dimensional-case'), - ('Two-dimensional Objects', 2, None, 'two-dimensional-objects'), - ('CNNs in more detail', 2, None, 'cnns-in-more-detail'), - ('Performing a discrete convolution with padding ("From Raschka ' - 'et al":"https://github.com/rasbt/machine-learning-book")', + ('Memory considerations', 2, None, 'memory-considerations'), + ('Padding', 2, None, 'padding'), + ('New vector', 2, None, 'new-vector'), + ('Rewriting as dot products', 2, None, - 'performing-a-discrete-convolution-with-padding-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Performing a general discrete convolution ("From Raschka et ' + 'rewriting-as-dot-products'), + ('Cross correlation', 2, None, 'cross-correlation'), + ('Two-dimensional objects', 2, None, 'two-dimensional-objects'), + ('CNNs in more detail, simple example', + 2, + None, + 'cnns-in-more-detail-simple-example'), + ('The convolution stage', 2, None, 'the-convolution-stage'), + ('Finding the number of parameters', + 2, + None, + 'finding-the-number-of-parameters'), + ('New image (or volume)', 2, None, 'new-image-or-volume'), + ('Parameters to train, common settings', + 2, + None, + 'parameters-to-train-common-settings'), + ('Examples of CNN setups', 2, None, 'examples-of-cnn-setups'), + ('Summarizing: Performing a general discrete convolution ("From ' + 'Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, - 'performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Set of filters', 2, None, 'set-of-filters'), + 'summarizing-performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Pooling', 2, None, 'pooling'), - ('No zero padding, unit strides', - 2, - None, - 'no-zero-padding-unit-strides'), - ('Zero padding, unit strides', - 2, - None, - 'zero-padding-unit-strides'), - ('Half (same) padding', 2, None, 'half-same-padding'), - ('Full padding', 2, None, 'full-padding'), ('Pooling arithmetic', 2, None, 'pooling-arithmetic'), ('Pooling types ("From Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, 'pooling-types-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), + ('Building convolutional neural networks in Tensorflow and Keras', + 2, + None, + 'building-convolutional-neural-networks-in-tensorflow-and-keras'), + ('Setting it up', 2, None, 'setting-it-up'), + ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), + ('Strong correlations', 2, None, 'strong-correlations'), + ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), + ('Systematic reduction', 2, None, 'systematic-reduction'), + ('Prerequisites: Collect and pre-process data', + 2, + None, + 'prerequisites-collect-and-pre-process-data'), + ('Importing Keras and Tensorflow', + 2, + None, + 'importing-keras-and-tensorflow'), + ('Running with Keras', 2, None, 'running-with-keras'), + ('Final part', 2, None, 'final-part'), + ('Final visualization', 2, None, 'final-visualization'), + ('The CIFAR01 data set', 2, None, 'the-cifar01-data-set'), + ('Verifying the data set', 2, None, 'verifying-the-data-set'), + ('Set up the model', 2, None, 'set-up-the-model'), + ('Add Dense layers on top', 2, None, 'add-dense-layers-on-top'), + ('Compile and train the model', + 2, + None, + 'compile-and-train-the-model'), + ('Finally, evaluate the model', + 2, + None, + 'finally-evaluate-the-model'), ('Building our own CNN code', 2, None, @@ -173,27 +220,7 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Convolution in the Fourier domain', 3, None, - 'convolution-in-the-fourier-domain'), - ('Building convolutional neural networks in Tensorflow and Keras', - 2, - None, - 'building-convolutional-neural-networks-in-tensorflow-and-keras'), - ('Setting it up', 2, None, 'setting-it-up'), - ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), - ('Strong correlations', 2, None, 'strong-correlations'), - ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), - ('Systematic reduction', 2, None, 'systematic-reduction'), - ('Prerequisites: Collect and pre-process data', - 2, - None, - 'prerequisites-collect-and-pre-process-data'), - ('Importing Keras and Tensorflow', - 2, - None, - 'importing-keras-and-tensorflow'), - ('Running with Keras', 2, None, 'running-with-keras'), - ('Final part', 2, None, 'final-part'), - ('Final visualization', 2, None, 'final-visualization')]} + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -244,59 +271,74 @@ MathJax.Hub.Config({
  • CNNs in brief
  • A deep CNN model ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • Key Idea
  • -
  • Mathematics of CNNs
  • -
  • Convolution Examples: Polynomial multiplication
  • -
  • Efficient Polynomial Multiplication
  • -
  • Further simplification
  • -
  • A more efficient way of coding the above Convolution
  • -
  • Fourier series and Toeplitz matrices
  • -
  • Generalizing the above one-dimensional case
  • -
  • Two-dimensional Objects
  • -
  • CNNs in more detail
  • -
  • Performing a discrete convolution with padding ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Set of filters
  • -
  • Pooling
  • -
  • No zero padding, unit strides
  • -
  • Zero padding, unit strides
  • -
  • Half (same) padding
  • -
  • Full padding
  • -
  • Pooling arithmetic
  • -
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Building our own CNN code
  • -
  •    List of contents:
  • -
  •    Schedulers
  • -
  •    Usage of schedulers
  • -
  •    Cost functions
  • -
  •    Usage of cost functions
  • -
  •    Activation functions
  • -
  •    Usage of activation functions
  • -
  •    Convolution
  • -
  •    Layers
  • -
  •    Convolution2DLayer: convolution in a hidden layer
  • -
  •    Backpropagation in the convolutional layer
  • -
  •    Demonstration
  • -
  •    Pooling Layer
  • -
  •    Flattening Layer
  • -
  •    Fully Connected Layers
  • -
  •    Optimized Convolution2DLayer
  • -
  •    The Convolutional Neural Network (CNN)
  • -
  •    Usage of CNN code
  • -
  •    Additional Remarks
  • -
  •    Remarks on the speed
  • -
  •    Convolution using separable kernels
  • -
  •    Convolution in the Fourier domain
  • -
  • Building convolutional neural networks in Tensorflow and Keras
  • -
  • Setting it up
  • -
  • The MNIST dataset again
  • -
  • Strong correlations
  • -
  • Layers of a CNN
  • -
  • Systematic reduction
  • -
  • Prerequisites: Collect and pre-process data
  • -
  • Importing Keras and Tensorflow
  • -
  • Running with Keras
  • -
  • Final part
  • -
  • Final visualization
  • +
  • How to do image compression before the era of deep learning
  • +
  • The SVD example
  • +
  • Mathematics of CNNs
  • +
  • Mathematics of CNNs
  • +
  • Convolution Examples: Polynomial multiplication
  • +
  • Efficient Polynomial Multiplication
  • +
  • Further simplification
  • +
  • A more efficient way of coding the above Convolution
  • +
  • Commutative process
  • +
  • Toeplitz matrices
  • +
  • Fourier series and Toeplitz matrices
  • +
  • Generalizing the above one-dimensional case
  • +
  • Memory considerations
  • +
  • Padding
  • +
  • New vector
  • +
  • Rewriting as dot products
  • +
  • Cross correlation
  • +
  • Two-dimensional objects
  • +
  • CNNs in more detail, simple example
  • +
  • The convolution stage
  • +
  • Finding the number of parameters
  • +
  • New image (or volume)
  • +
  • Parameters to train, common settings
  • +
  • Examples of CNN setups
  • +
  • Summarizing: Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Pooling
  • +
  • Pooling arithmetic
  • +
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Building convolutional neural networks in Tensorflow and Keras
  • +
  • Setting it up
  • +
  • The MNIST dataset again
  • +
  • Strong correlations
  • +
  • Layers of a CNN
  • +
  • Systematic reduction
  • +
  • Prerequisites: Collect and pre-process data
  • +
  • Importing Keras and Tensorflow
  • +
  • Running with Keras
  • +
  • Final part
  • +
  • Final visualization
  • +
  • The CIFAR01 data set
  • +
  • Verifying the data set
  • +
  • Set up the model
  • +
  • Add Dense layers on top
  • +
  • Compile and train the model
  • +
  • Finally, evaluate the model
  • +
  • Building our own CNN code
  • +
  •    List of contents:
  • +
  •    Schedulers
  • +
  •    Usage of schedulers
  • +
  •    Cost functions
  • +
  •    Usage of cost functions
  • +
  •    Activation functions
  • +
  •    Usage of activation functions
  • +
  •    Convolution
  • +
  •    Layers
  • +
  •    Convolution2DLayer: convolution in a hidden layer
  • +
  •    Backpropagation in the convolutional layer
  • +
  •    Demonstration
  • +
  •    Pooling Layer
  • +
  •    Flattening Layer
  • +
  •    Fully Connected Layers
  • +
  •    Optimized Convolution2DLayer
  • +
  •    The Convolutional Neural Network (CNN)
  • +
  •    Usage of CNN code
  • +
  •    Additional Remarks
  • +
  •    Remarks on the speed
  • +
  •    Convolution using separable kernels
  • +
  •    Convolution in the Fourier domain
  • @@ -344,7 +386,7 @@ principles then apply to images and other similar data.
  • 20
  • 21
  • ...
  • -
  • 47
  • +
  • 62
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs012.html b/doc/pub/week44/html/._week44-bs012.html index 4ec9c0617..470056884 100644 --- a/doc/pub/week44/html/._week44-bs012.html +++ b/doc/pub/week44/html/._week44-bs012.html @@ -75,6 +75,12 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d None, 'a-deep-cnn-model-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Key Idea', 2, None, 'key-idea'), + ('How to do image compression before the era of deep learning', + 2, + None, + 'how-to-do-image-compression-before-the-era-of-deep-learning'), + ('The SVD example', 2, None, 'the-svd-example'), + ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Convolution Examples: Polynomial multiplication', 2, @@ -89,6 +95,8 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'a-more-efficient-way-of-coding-the-above-convolution'), + ('Commutative process', 2, None, 'commutative-process'), + ('Toeplitz matrices', 2, None, 'toeplitz-matrices'), ('Fourier series and Toeplitz matrices', 2, None, @@ -97,36 +105,75 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'generalizing-the-above-one-dimensional-case'), - ('Two-dimensional Objects', 2, None, 'two-dimensional-objects'), - ('CNNs in more detail', 2, None, 'cnns-in-more-detail'), - ('Performing a discrete convolution with padding ("From Raschka ' - 'et al":"https://github.com/rasbt/machine-learning-book")', + ('Memory considerations', 2, None, 'memory-considerations'), + ('Padding', 2, None, 'padding'), + ('New vector', 2, None, 'new-vector'), + ('Rewriting as dot products', 2, None, - 'performing-a-discrete-convolution-with-padding-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Performing a general discrete convolution ("From Raschka et ' + 'rewriting-as-dot-products'), + ('Cross correlation', 2, None, 'cross-correlation'), + ('Two-dimensional objects', 2, None, 'two-dimensional-objects'), + ('CNNs in more detail, simple example', + 2, + None, + 'cnns-in-more-detail-simple-example'), + ('The convolution stage', 2, None, 'the-convolution-stage'), + ('Finding the number of parameters', + 2, + None, + 'finding-the-number-of-parameters'), + ('New image (or volume)', 2, None, 'new-image-or-volume'), + ('Parameters to train, common settings', + 2, + None, + 'parameters-to-train-common-settings'), + ('Examples of CNN setups', 2, None, 'examples-of-cnn-setups'), + ('Summarizing: Performing a general discrete convolution ("From ' + 'Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, - 'performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Set of filters', 2, None, 'set-of-filters'), + 'summarizing-performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Pooling', 2, None, 'pooling'), - ('No zero padding, unit strides', - 2, - None, - 'no-zero-padding-unit-strides'), - ('Zero padding, unit strides', - 2, - None, - 'zero-padding-unit-strides'), - ('Half (same) padding', 2, None, 'half-same-padding'), - ('Full padding', 2, None, 'full-padding'), ('Pooling arithmetic', 2, None, 'pooling-arithmetic'), ('Pooling types ("From Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, 'pooling-types-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), + ('Building convolutional neural networks in Tensorflow and Keras', + 2, + None, + 'building-convolutional-neural-networks-in-tensorflow-and-keras'), + ('Setting it up', 2, None, 'setting-it-up'), + ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), + ('Strong correlations', 2, None, 'strong-correlations'), + ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), + ('Systematic reduction', 2, None, 'systematic-reduction'), + ('Prerequisites: Collect and pre-process data', + 2, + None, + 'prerequisites-collect-and-pre-process-data'), + ('Importing Keras and Tensorflow', + 2, + None, + 'importing-keras-and-tensorflow'), + ('Running with Keras', 2, None, 'running-with-keras'), + ('Final part', 2, None, 'final-part'), + ('Final visualization', 2, None, 'final-visualization'), + ('The CIFAR01 data set', 2, None, 'the-cifar01-data-set'), + ('Verifying the data set', 2, None, 'verifying-the-data-set'), + ('Set up the model', 2, None, 'set-up-the-model'), + ('Add Dense layers on top', 2, None, 'add-dense-layers-on-top'), + ('Compile and train the model', + 2, + None, + 'compile-and-train-the-model'), + ('Finally, evaluate the model', + 2, + None, + 'finally-evaluate-the-model'), ('Building our own CNN code', 2, None, @@ -173,27 +220,7 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Convolution in the Fourier domain', 3, None, - 'convolution-in-the-fourier-domain'), - ('Building convolutional neural networks in Tensorflow and Keras', - 2, - None, - 'building-convolutional-neural-networks-in-tensorflow-and-keras'), - ('Setting it up', 2, None, 'setting-it-up'), - ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), - ('Strong correlations', 2, None, 'strong-correlations'), - ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), - ('Systematic reduction', 2, None, 'systematic-reduction'), - ('Prerequisites: Collect and pre-process data', - 2, - None, - 'prerequisites-collect-and-pre-process-data'), - ('Importing Keras and Tensorflow', - 2, - None, - 'importing-keras-and-tensorflow'), - ('Running with Keras', 2, None, 'running-with-keras'), - ('Final part', 2, None, 'final-part'), - ('Final visualization', 2, None, 'final-visualization')]} + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -244,59 +271,74 @@ MathJax.Hub.Config({
  • CNNs in brief
  • A deep CNN model ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • Key Idea
  • -
  • Mathematics of CNNs
  • -
  • Convolution Examples: Polynomial multiplication
  • -
  • Efficient Polynomial Multiplication
  • -
  • Further simplification
  • -
  • A more efficient way of coding the above Convolution
  • -
  • Fourier series and Toeplitz matrices
  • -
  • Generalizing the above one-dimensional case
  • -
  • Two-dimensional Objects
  • -
  • CNNs in more detail
  • -
  • Performing a discrete convolution with padding ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Set of filters
  • -
  • Pooling
  • -
  • No zero padding, unit strides
  • -
  • Zero padding, unit strides
  • -
  • Half (same) padding
  • -
  • Full padding
  • -
  • Pooling arithmetic
  • -
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Building our own CNN code
  • -
  •    List of contents:
  • -
  •    Schedulers
  • -
  •    Usage of schedulers
  • -
  •    Cost functions
  • -
  •    Usage of cost functions
  • -
  •    Activation functions
  • -
  •    Usage of activation functions
  • -
  •    Convolution
  • -
  •    Layers
  • -
  •    Convolution2DLayer: convolution in a hidden layer
  • -
  •    Backpropagation in the convolutional layer
  • -
  •    Demonstration
  • -
  •    Pooling Layer
  • -
  •    Flattening Layer
  • -
  •    Fully Connected Layers
  • -
  •    Optimized Convolution2DLayer
  • -
  •    The Convolutional Neural Network (CNN)
  • -
  •    Usage of CNN code
  • -
  •    Additional Remarks
  • -
  •    Remarks on the speed
  • -
  •    Convolution using separable kernels
  • -
  •    Convolution in the Fourier domain
  • -
  • Building convolutional neural networks in Tensorflow and Keras
  • -
  • Setting it up
  • -
  • The MNIST dataset again
  • -
  • Strong correlations
  • -
  • Layers of a CNN
  • -
  • Systematic reduction
  • -
  • Prerequisites: Collect and pre-process data
  • -
  • Importing Keras and Tensorflow
  • -
  • Running with Keras
  • -
  • Final part
  • -
  • Final visualization
  • +
  • How to do image compression before the era of deep learning
  • +
  • The SVD example
  • +
  • Mathematics of CNNs
  • +
  • Mathematics of CNNs
  • +
  • Convolution Examples: Polynomial multiplication
  • +
  • Efficient Polynomial Multiplication
  • +
  • Further simplification
  • +
  • A more efficient way of coding the above Convolution
  • +
  • Commutative process
  • +
  • Toeplitz matrices
  • +
  • Fourier series and Toeplitz matrices
  • +
  • Generalizing the above one-dimensional case
  • +
  • Memory considerations
  • +
  • Padding
  • +
  • New vector
  • +
  • Rewriting as dot products
  • +
  • Cross correlation
  • +
  • Two-dimensional objects
  • +
  • CNNs in more detail, simple example
  • +
  • The convolution stage
  • +
  • Finding the number of parameters
  • +
  • New image (or volume)
  • +
  • Parameters to train, common settings
  • +
  • Examples of CNN setups
  • +
  • Summarizing: Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Pooling
  • +
  • Pooling arithmetic
  • +
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Building convolutional neural networks in Tensorflow and Keras
  • +
  • Setting it up
  • +
  • The MNIST dataset again
  • +
  • Strong correlations
  • +
  • Layers of a CNN
  • +
  • Systematic reduction
  • +
  • Prerequisites: Collect and pre-process data
  • +
  • Importing Keras and Tensorflow
  • +
  • Running with Keras
  • +
  • Final part
  • +
  • Final visualization
  • +
  • The CIFAR01 data set
  • +
  • Verifying the data set
  • +
  • Set up the model
  • +
  • Add Dense layers on top
  • +
  • Compile and train the model
  • +
  • Finally, evaluate the model
  • +
  • Building our own CNN code
  • +
  •    List of contents:
  • +
  •    Schedulers
  • +
  •    Usage of schedulers
  • +
  •    Cost functions
  • +
  •    Usage of cost functions
  • +
  •    Activation functions
  • +
  •    Usage of activation functions
  • +
  •    Convolution
  • +
  •    Layers
  • +
  •    Convolution2DLayer: convolution in a hidden layer
  • +
  •    Backpropagation in the convolutional layer
  • +
  •    Demonstration
  • +
  •    Pooling Layer
  • +
  •    Flattening Layer
  • +
  •    Fully Connected Layers
  • +
  •    Optimized Convolution2DLayer
  • +
  •    The Convolutional Neural Network (CNN)
  • +
  •    Usage of CNN code
  • +
  •    Additional Remarks
  • +
  •    Remarks on the speed
  • +
  •    Convolution using separable kernels
  • +
  •    Convolution in the Fourier domain
  • @@ -352,7 +394,7 @@ will stack these layers to form a full CNN architecture.
  • 21
  • 22
  • ...
  • -
  • 47
  • +
  • 62
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs013.html b/doc/pub/week44/html/._week44-bs013.html index a5f7b2701..e1101b015 100644 --- a/doc/pub/week44/html/._week44-bs013.html +++ b/doc/pub/week44/html/._week44-bs013.html @@ -75,6 +75,12 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d None, 'a-deep-cnn-model-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Key Idea', 2, None, 'key-idea'), + ('How to do image compression before the era of deep learning', + 2, + None, + 'how-to-do-image-compression-before-the-era-of-deep-learning'), + ('The SVD example', 2, None, 'the-svd-example'), + ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Convolution Examples: Polynomial multiplication', 2, @@ -89,6 +95,8 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'a-more-efficient-way-of-coding-the-above-convolution'), + ('Commutative process', 2, None, 'commutative-process'), + ('Toeplitz matrices', 2, None, 'toeplitz-matrices'), ('Fourier series and Toeplitz matrices', 2, None, @@ -97,36 +105,75 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'generalizing-the-above-one-dimensional-case'), - ('Two-dimensional Objects', 2, None, 'two-dimensional-objects'), - ('CNNs in more detail', 2, None, 'cnns-in-more-detail'), - ('Performing a discrete convolution with padding ("From Raschka ' - 'et al":"https://github.com/rasbt/machine-learning-book")', + ('Memory considerations', 2, None, 'memory-considerations'), + ('Padding', 2, None, 'padding'), + ('New vector', 2, None, 'new-vector'), + ('Rewriting as dot products', 2, None, - 'performing-a-discrete-convolution-with-padding-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Performing a general discrete convolution ("From Raschka et ' + 'rewriting-as-dot-products'), + ('Cross correlation', 2, None, 'cross-correlation'), + ('Two-dimensional objects', 2, None, 'two-dimensional-objects'), + ('CNNs in more detail, simple example', + 2, + None, + 'cnns-in-more-detail-simple-example'), + ('The convolution stage', 2, None, 'the-convolution-stage'), + ('Finding the number of parameters', + 2, + None, + 'finding-the-number-of-parameters'), + ('New image (or volume)', 2, None, 'new-image-or-volume'), + ('Parameters to train, common settings', + 2, + None, + 'parameters-to-train-common-settings'), + ('Examples of CNN setups', 2, None, 'examples-of-cnn-setups'), + ('Summarizing: Performing a general discrete convolution ("From ' + 'Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, - 'performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Set of filters', 2, None, 'set-of-filters'), + 'summarizing-performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Pooling', 2, None, 'pooling'), - ('No zero padding, unit strides', - 2, - None, - 'no-zero-padding-unit-strides'), - ('Zero padding, unit strides', - 2, - None, - 'zero-padding-unit-strides'), - ('Half (same) padding', 2, None, 'half-same-padding'), - ('Full padding', 2, None, 'full-padding'), ('Pooling arithmetic', 2, None, 'pooling-arithmetic'), ('Pooling types ("From Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, 'pooling-types-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), + ('Building convolutional neural networks in Tensorflow and Keras', + 2, + None, + 'building-convolutional-neural-networks-in-tensorflow-and-keras'), + ('Setting it up', 2, None, 'setting-it-up'), + ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), + ('Strong correlations', 2, None, 'strong-correlations'), + ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), + ('Systematic reduction', 2, None, 'systematic-reduction'), + ('Prerequisites: Collect and pre-process data', + 2, + None, + 'prerequisites-collect-and-pre-process-data'), + ('Importing Keras and Tensorflow', + 2, + None, + 'importing-keras-and-tensorflow'), + ('Running with Keras', 2, None, 'running-with-keras'), + ('Final part', 2, None, 'final-part'), + ('Final visualization', 2, None, 'final-visualization'), + ('The CIFAR01 data set', 2, None, 'the-cifar01-data-set'), + ('Verifying the data set', 2, None, 'verifying-the-data-set'), + ('Set up the model', 2, None, 'set-up-the-model'), + ('Add Dense layers on top', 2, None, 'add-dense-layers-on-top'), + ('Compile and train the model', + 2, + None, + 'compile-and-train-the-model'), + ('Finally, evaluate the model', + 2, + None, + 'finally-evaluate-the-model'), ('Building our own CNN code', 2, None, @@ -173,27 +220,7 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Convolution in the Fourier domain', 3, None, - 'convolution-in-the-fourier-domain'), - ('Building convolutional neural networks in Tensorflow and Keras', - 2, - None, - 'building-convolutional-neural-networks-in-tensorflow-and-keras'), - ('Setting it up', 2, None, 'setting-it-up'), - ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), - ('Strong correlations', 2, None, 'strong-correlations'), - ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), - ('Systematic reduction', 2, None, 'systematic-reduction'), - ('Prerequisites: Collect and pre-process data', - 2, - None, - 'prerequisites-collect-and-pre-process-data'), - ('Importing Keras and Tensorflow', - 2, - None, - 'importing-keras-and-tensorflow'), - ('Running with Keras', 2, None, 'running-with-keras'), - ('Final part', 2, None, 'final-part'), - ('Final visualization', 2, None, 'final-visualization')]} + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -244,59 +271,74 @@ MathJax.Hub.Config({
  • CNNs in brief
  • A deep CNN model ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • Key Idea
  • -
  • Mathematics of CNNs
  • -
  • Convolution Examples: Polynomial multiplication
  • -
  • Efficient Polynomial Multiplication
  • -
  • Further simplification
  • -
  • A more efficient way of coding the above Convolution
  • -
  • Fourier series and Toeplitz matrices
  • -
  • Generalizing the above one-dimensional case
  • -
  • Two-dimensional Objects
  • -
  • CNNs in more detail
  • -
  • Performing a discrete convolution with padding ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Set of filters
  • -
  • Pooling
  • -
  • No zero padding, unit strides
  • -
  • Zero padding, unit strides
  • -
  • Half (same) padding
  • -
  • Full padding
  • -
  • Pooling arithmetic
  • -
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Building our own CNN code
  • -
  •    List of contents:
  • -
  •    Schedulers
  • -
  •    Usage of schedulers
  • -
  •    Cost functions
  • -
  •    Usage of cost functions
  • -
  •    Activation functions
  • -
  •    Usage of activation functions
  • -
  •    Convolution
  • -
  •    Layers
  • -
  •    Convolution2DLayer: convolution in a hidden layer
  • -
  •    Backpropagation in the convolutional layer
  • -
  •    Demonstration
  • -
  •    Pooling Layer
  • -
  •    Flattening Layer
  • -
  •    Fully Connected Layers
  • -
  •    Optimized Convolution2DLayer
  • -
  •    The Convolutional Neural Network (CNN)
  • -
  •    Usage of CNN code
  • -
  •    Additional Remarks
  • -
  •    Remarks on the speed
  • -
  •    Convolution using separable kernels
  • -
  •    Convolution in the Fourier domain
  • -
  • Building convolutional neural networks in Tensorflow and Keras
  • -
  • Setting it up
  • -
  • The MNIST dataset again
  • -
  • Strong correlations
  • -
  • Layers of a CNN
  • -
  • Systematic reduction
  • -
  • Prerequisites: Collect and pre-process data
  • -
  • Importing Keras and Tensorflow
  • -
  • Running with Keras
  • -
  • Final part
  • -
  • Final visualization
  • +
  • How to do image compression before the era of deep learning
  • +
  • The SVD example
  • +
  • Mathematics of CNNs
  • +
  • Mathematics of CNNs
  • +
  • Convolution Examples: Polynomial multiplication
  • +
  • Efficient Polynomial Multiplication
  • +
  • Further simplification
  • +
  • A more efficient way of coding the above Convolution
  • +
  • Commutative process
  • +
  • Toeplitz matrices
  • +
  • Fourier series and Toeplitz matrices
  • +
  • Generalizing the above one-dimensional case
  • +
  • Memory considerations
  • +
  • Padding
  • +
  • New vector
  • +
  • Rewriting as dot products
  • +
  • Cross correlation
  • +
  • Two-dimensional objects
  • +
  • CNNs in more detail, simple example
  • +
  • The convolution stage
  • +
  • Finding the number of parameters
  • +
  • New image (or volume)
  • +
  • Parameters to train, common settings
  • +
  • Examples of CNN setups
  • +
  • Summarizing: Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Pooling
  • +
  • Pooling arithmetic
  • +
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Building convolutional neural networks in Tensorflow and Keras
  • +
  • Setting it up
  • +
  • The MNIST dataset again
  • +
  • Strong correlations
  • +
  • Layers of a CNN
  • +
  • Systematic reduction
  • +
  • Prerequisites: Collect and pre-process data
  • +
  • Importing Keras and Tensorflow
  • +
  • Running with Keras
  • +
  • Final part
  • +
  • Final visualization
  • +
  • The CIFAR01 data set
  • +
  • Verifying the data set
  • +
  • Set up the model
  • +
  • Add Dense layers on top
  • +
  • Compile and train the model
  • +
  • Finally, evaluate the model
  • +
  • Building our own CNN code
  • +
  •    List of contents:
  • +
  •    Schedulers
  • +
  •    Usage of schedulers
  • +
  •    Cost functions
  • +
  •    Usage of cost functions
  • +
  •    Activation functions
  • +
  •    Usage of activation functions
  • +
  •    Convolution
  • +
  •    Layers
  • +
  •    Convolution2DLayer: convolution in a hidden layer
  • +
  •    Backpropagation in the convolutional layer
  • +
  •    Demonstration
  • +
  •    Pooling Layer
  • +
  •    Flattening Layer
  • +
  •    Fully Connected Layers
  • +
  •    Optimized Convolution2DLayer
  • +
  •    The Convolutional Neural Network (CNN)
  • +
  •    Usage of CNN code
  • +
  •    Additional Remarks
  • +
  •    Remarks on the speed
  • +
  •    Convolution using separable kernels
  • +
  •    Convolution in the Fourier domain
  • @@ -349,7 +391,7 @@ are consistent with the labels in the training set for each image.
  • 22
  • 23
  • ...
  • -
  • 47
  • +
  • 62
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs014.html b/doc/pub/week44/html/._week44-bs014.html index 8b3484795..a1eaa151e 100644 --- a/doc/pub/week44/html/._week44-bs014.html +++ b/doc/pub/week44/html/._week44-bs014.html @@ -75,6 +75,12 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d None, 'a-deep-cnn-model-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Key Idea', 2, None, 'key-idea'), + ('How to do image compression before the era of deep learning', + 2, + None, + 'how-to-do-image-compression-before-the-era-of-deep-learning'), + ('The SVD example', 2, None, 'the-svd-example'), + ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Convolution Examples: Polynomial multiplication', 2, @@ -89,6 +95,8 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'a-more-efficient-way-of-coding-the-above-convolution'), + ('Commutative process', 2, None, 'commutative-process'), + ('Toeplitz matrices', 2, None, 'toeplitz-matrices'), ('Fourier series and Toeplitz matrices', 2, None, @@ -97,36 +105,75 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'generalizing-the-above-one-dimensional-case'), - ('Two-dimensional Objects', 2, None, 'two-dimensional-objects'), - ('CNNs in more detail', 2, None, 'cnns-in-more-detail'), - ('Performing a discrete convolution with padding ("From Raschka ' - 'et al":"https://github.com/rasbt/machine-learning-book")', + ('Memory considerations', 2, None, 'memory-considerations'), + ('Padding', 2, None, 'padding'), + ('New vector', 2, None, 'new-vector'), + ('Rewriting as dot products', 2, None, - 'performing-a-discrete-convolution-with-padding-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Performing a general discrete convolution ("From Raschka et ' + 'rewriting-as-dot-products'), + ('Cross correlation', 2, None, 'cross-correlation'), + ('Two-dimensional objects', 2, None, 'two-dimensional-objects'), + ('CNNs in more detail, simple example', + 2, + None, + 'cnns-in-more-detail-simple-example'), + ('The convolution stage', 2, None, 'the-convolution-stage'), + ('Finding the number of parameters', + 2, + None, + 'finding-the-number-of-parameters'), + ('New image (or volume)', 2, None, 'new-image-or-volume'), + ('Parameters to train, common settings', + 2, + None, + 'parameters-to-train-common-settings'), + ('Examples of CNN setups', 2, None, 'examples-of-cnn-setups'), + ('Summarizing: Performing a general discrete convolution ("From ' + 'Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, - 'performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Set of filters', 2, None, 'set-of-filters'), + 'summarizing-performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Pooling', 2, None, 'pooling'), - ('No zero padding, unit strides', - 2, - None, - 'no-zero-padding-unit-strides'), - ('Zero padding, unit strides', - 2, - None, - 'zero-padding-unit-strides'), - ('Half (same) padding', 2, None, 'half-same-padding'), - ('Full padding', 2, None, 'full-padding'), ('Pooling arithmetic', 2, None, 'pooling-arithmetic'), ('Pooling types ("From Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, 'pooling-types-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), + ('Building convolutional neural networks in Tensorflow and Keras', + 2, + None, + 'building-convolutional-neural-networks-in-tensorflow-and-keras'), + ('Setting it up', 2, None, 'setting-it-up'), + ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), + ('Strong correlations', 2, None, 'strong-correlations'), + ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), + ('Systematic reduction', 2, None, 'systematic-reduction'), + ('Prerequisites: Collect and pre-process data', + 2, + None, + 'prerequisites-collect-and-pre-process-data'), + ('Importing Keras and Tensorflow', + 2, + None, + 'importing-keras-and-tensorflow'), + ('Running with Keras', 2, None, 'running-with-keras'), + ('Final part', 2, None, 'final-part'), + ('Final visualization', 2, None, 'final-visualization'), + ('The CIFAR01 data set', 2, None, 'the-cifar01-data-set'), + ('Verifying the data set', 2, None, 'verifying-the-data-set'), + ('Set up the model', 2, None, 'set-up-the-model'), + ('Add Dense layers on top', 2, None, 'add-dense-layers-on-top'), + ('Compile and train the model', + 2, + None, + 'compile-and-train-the-model'), + ('Finally, evaluate the model', + 2, + None, + 'finally-evaluate-the-model'), ('Building our own CNN code', 2, None, @@ -173,27 +220,7 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Convolution in the Fourier domain', 3, None, - 'convolution-in-the-fourier-domain'), - ('Building convolutional neural networks in Tensorflow and Keras', - 2, - None, - 'building-convolutional-neural-networks-in-tensorflow-and-keras'), - ('Setting it up', 2, None, 'setting-it-up'), - ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), - ('Strong correlations', 2, None, 'strong-correlations'), - ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), - ('Systematic reduction', 2, None, 'systematic-reduction'), - ('Prerequisites: Collect and pre-process data', - 2, - None, - 'prerequisites-collect-and-pre-process-data'), - ('Importing Keras and Tensorflow', - 2, - None, - 'importing-keras-and-tensorflow'), - ('Running with Keras', 2, None, 'running-with-keras'), - ('Final part', 2, None, 'final-part'), - ('Final visualization', 2, None, 'final-visualization')]} + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -244,59 +271,74 @@ MathJax.Hub.Config({
  • CNNs in brief
  • A deep CNN model ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • Key Idea
  • -
  • Mathematics of CNNs
  • -
  • Convolution Examples: Polynomial multiplication
  • -
  • Efficient Polynomial Multiplication
  • -
  • Further simplification
  • -
  • A more efficient way of coding the above Convolution
  • -
  • Fourier series and Toeplitz matrices
  • -
  • Generalizing the above one-dimensional case
  • -
  • Two-dimensional Objects
  • -
  • CNNs in more detail
  • -
  • Performing a discrete convolution with padding ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Set of filters
  • -
  • Pooling
  • -
  • No zero padding, unit strides
  • -
  • Zero padding, unit strides
  • -
  • Half (same) padding
  • -
  • Full padding
  • -
  • Pooling arithmetic
  • -
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Building our own CNN code
  • -
  •    List of contents:
  • -
  •    Schedulers
  • -
  •    Usage of schedulers
  • -
  •    Cost functions
  • -
  •    Usage of cost functions
  • -
  •    Activation functions
  • -
  •    Usage of activation functions
  • -
  •    Convolution
  • -
  •    Layers
  • -
  •    Convolution2DLayer: convolution in a hidden layer
  • -
  •    Backpropagation in the convolutional layer
  • -
  •    Demonstration
  • -
  •    Pooling Layer
  • -
  •    Flattening Layer
  • -
  •    Fully Connected Layers
  • -
  •    Optimized Convolution2DLayer
  • -
  •    The Convolutional Neural Network (CNN)
  • -
  •    Usage of CNN code
  • -
  •    Additional Remarks
  • -
  •    Remarks on the speed
  • -
  •    Convolution using separable kernels
  • -
  •    Convolution in the Fourier domain
  • -
  • Building convolutional neural networks in Tensorflow and Keras
  • -
  • Setting it up
  • -
  • The MNIST dataset again
  • -
  • Strong correlations
  • -
  • Layers of a CNN
  • -
  • Systematic reduction
  • -
  • Prerequisites: Collect and pre-process data
  • -
  • Importing Keras and Tensorflow
  • -
  • Running with Keras
  • -
  • Final part
  • -
  • Final visualization
  • +
  • How to do image compression before the era of deep learning
  • +
  • The SVD example
  • +
  • Mathematics of CNNs
  • +
  • Mathematics of CNNs
  • +
  • Convolution Examples: Polynomial multiplication
  • +
  • Efficient Polynomial Multiplication
  • +
  • Further simplification
  • +
  • A more efficient way of coding the above Convolution
  • +
  • Commutative process
  • +
  • Toeplitz matrices
  • +
  • Fourier series and Toeplitz matrices
  • +
  • Generalizing the above one-dimensional case
  • +
  • Memory considerations
  • +
  • Padding
  • +
  • New vector
  • +
  • Rewriting as dot products
  • +
  • Cross correlation
  • +
  • Two-dimensional objects
  • +
  • CNNs in more detail, simple example
  • +
  • The convolution stage
  • +
  • Finding the number of parameters
  • +
  • New image (or volume)
  • +
  • Parameters to train, common settings
  • +
  • Examples of CNN setups
  • +
  • Summarizing: Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Pooling
  • +
  • Pooling arithmetic
  • +
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Building convolutional neural networks in Tensorflow and Keras
  • +
  • Setting it up
  • +
  • The MNIST dataset again
  • +
  • Strong correlations
  • +
  • Layers of a CNN
  • +
  • Systematic reduction
  • +
  • Prerequisites: Collect and pre-process data
  • +
  • Importing Keras and Tensorflow
  • +
  • Running with Keras
  • +
  • Final part
  • +
  • Final visualization
  • +
  • The CIFAR01 data set
  • +
  • Verifying the data set
  • +
  • Set up the model
  • +
  • Add Dense layers on top
  • +
  • Compile and train the model
  • +
  • Finally, evaluate the model
  • +
  • Building our own CNN code
  • +
  •    List of contents:
  • +
  •    Schedulers
  • +
  •    Usage of schedulers
  • +
  •    Cost functions
  • +
  •    Usage of cost functions
  • +
  •    Activation functions
  • +
  •    Usage of activation functions
  • +
  •    Convolution
  • +
  •    Layers
  • +
  •    Convolution2DLayer: convolution in a hidden layer
  • +
  •    Backpropagation in the convolutional layer
  • +
  •    Demonstration
  • +
  •    Pooling Layer
  • +
  •    Flattening Layer
  • +
  •    Fully Connected Layers
  • +
  •    Optimized Convolution2DLayer
  • +
  •    The Convolutional Neural Network (CNN)
  • +
  •    Usage of CNN code
  • +
  •    Additional Remarks
  • +
  •    Remarks on the speed
  • +
  •    Convolution using separable kernels
  • +
  •    Convolution in the Fourier domain
  • @@ -344,7 +386,7 @@ MathJax.Hub.Config({
  • 23
  • 24
  • ...
  • -
  • 47
  • +
  • 62
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs015.html b/doc/pub/week44/html/._week44-bs015.html index ac6d05f64..9bee34d42 100644 --- a/doc/pub/week44/html/._week44-bs015.html +++ b/doc/pub/week44/html/._week44-bs015.html @@ -75,6 +75,12 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d None, 'a-deep-cnn-model-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Key Idea', 2, None, 'key-idea'), + ('How to do image compression before the era of deep learning', + 2, + None, + 'how-to-do-image-compression-before-the-era-of-deep-learning'), + ('The SVD example', 2, None, 'the-svd-example'), + ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Convolution Examples: Polynomial multiplication', 2, @@ -89,6 +95,8 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'a-more-efficient-way-of-coding-the-above-convolution'), + ('Commutative process', 2, None, 'commutative-process'), + ('Toeplitz matrices', 2, None, 'toeplitz-matrices'), ('Fourier series and Toeplitz matrices', 2, None, @@ -97,36 +105,75 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'generalizing-the-above-one-dimensional-case'), - ('Two-dimensional Objects', 2, None, 'two-dimensional-objects'), - ('CNNs in more detail', 2, None, 'cnns-in-more-detail'), - ('Performing a discrete convolution with padding ("From Raschka ' - 'et al":"https://github.com/rasbt/machine-learning-book")', + ('Memory considerations', 2, None, 'memory-considerations'), + ('Padding', 2, None, 'padding'), + ('New vector', 2, None, 'new-vector'), + ('Rewriting as dot products', 2, None, - 'performing-a-discrete-convolution-with-padding-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Performing a general discrete convolution ("From Raschka et ' + 'rewriting-as-dot-products'), + ('Cross correlation', 2, None, 'cross-correlation'), + ('Two-dimensional objects', 2, None, 'two-dimensional-objects'), + ('CNNs in more detail, simple example', + 2, + None, + 'cnns-in-more-detail-simple-example'), + ('The convolution stage', 2, None, 'the-convolution-stage'), + ('Finding the number of parameters', + 2, + None, + 'finding-the-number-of-parameters'), + ('New image (or volume)', 2, None, 'new-image-or-volume'), + ('Parameters to train, common settings', + 2, + None, + 'parameters-to-train-common-settings'), + ('Examples of CNN setups', 2, None, 'examples-of-cnn-setups'), + ('Summarizing: Performing a general discrete convolution ("From ' + 'Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, - 'performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Set of filters', 2, None, 'set-of-filters'), + 'summarizing-performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Pooling', 2, None, 'pooling'), - ('No zero padding, unit strides', - 2, - None, - 'no-zero-padding-unit-strides'), - ('Zero padding, unit strides', - 2, - None, - 'zero-padding-unit-strides'), - ('Half (same) padding', 2, None, 'half-same-padding'), - ('Full padding', 2, None, 'full-padding'), ('Pooling arithmetic', 2, None, 'pooling-arithmetic'), ('Pooling types ("From Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, 'pooling-types-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), + ('Building convolutional neural networks in Tensorflow and Keras', + 2, + None, + 'building-convolutional-neural-networks-in-tensorflow-and-keras'), + ('Setting it up', 2, None, 'setting-it-up'), + ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), + ('Strong correlations', 2, None, 'strong-correlations'), + ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), + ('Systematic reduction', 2, None, 'systematic-reduction'), + ('Prerequisites: Collect and pre-process data', + 2, + None, + 'prerequisites-collect-and-pre-process-data'), + ('Importing Keras and Tensorflow', + 2, + None, + 'importing-keras-and-tensorflow'), + ('Running with Keras', 2, None, 'running-with-keras'), + ('Final part', 2, None, 'final-part'), + ('Final visualization', 2, None, 'final-visualization'), + ('The CIFAR01 data set', 2, None, 'the-cifar01-data-set'), + ('Verifying the data set', 2, None, 'verifying-the-data-set'), + ('Set up the model', 2, None, 'set-up-the-model'), + ('Add Dense layers on top', 2, None, 'add-dense-layers-on-top'), + ('Compile and train the model', + 2, + None, + 'compile-and-train-the-model'), + ('Finally, evaluate the model', + 2, + None, + 'finally-evaluate-the-model'), ('Building our own CNN code', 2, None, @@ -173,27 +220,7 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Convolution in the Fourier domain', 3, None, - 'convolution-in-the-fourier-domain'), - ('Building convolutional neural networks in Tensorflow and Keras', - 2, - None, - 'building-convolutional-neural-networks-in-tensorflow-and-keras'), - ('Setting it up', 2, None, 'setting-it-up'), - ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), - ('Strong correlations', 2, None, 'strong-correlations'), - ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), - ('Systematic reduction', 2, None, 'systematic-reduction'), - ('Prerequisites: Collect and pre-process data', - 2, - None, - 'prerequisites-collect-and-pre-process-data'), - ('Importing Keras and Tensorflow', - 2, - None, - 'importing-keras-and-tensorflow'), - ('Running with Keras', 2, None, 'running-with-keras'), - ('Final part', 2, None, 'final-part'), - ('Final visualization', 2, None, 'final-visualization')]} + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -244,59 +271,74 @@ MathJax.Hub.Config({
  • CNNs in brief
  • A deep CNN model ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • Key Idea
  • -
  • Mathematics of CNNs
  • -
  • Convolution Examples: Polynomial multiplication
  • -
  • Efficient Polynomial Multiplication
  • -
  • Further simplification
  • -
  • A more efficient way of coding the above Convolution
  • -
  • Fourier series and Toeplitz matrices
  • -
  • Generalizing the above one-dimensional case
  • -
  • Two-dimensional Objects
  • -
  • CNNs in more detail
  • -
  • Performing a discrete convolution with padding ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Set of filters
  • -
  • Pooling
  • -
  • No zero padding, unit strides
  • -
  • Zero padding, unit strides
  • -
  • Half (same) padding
  • -
  • Full padding
  • -
  • Pooling arithmetic
  • -
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Building our own CNN code
  • -
  •    List of contents:
  • -
  •    Schedulers
  • -
  •    Usage of schedulers
  • -
  •    Cost functions
  • -
  •    Usage of cost functions
  • -
  •    Activation functions
  • -
  •    Usage of activation functions
  • -
  •    Convolution
  • -
  •    Layers
  • -
  •    Convolution2DLayer: convolution in a hidden layer
  • -
  •    Backpropagation in the convolutional layer
  • -
  •    Demonstration
  • -
  •    Pooling Layer
  • -
  •    Flattening Layer
  • -
  •    Fully Connected Layers
  • -
  •    Optimized Convolution2DLayer
  • -
  •    The Convolutional Neural Network (CNN)
  • -
  •    Usage of CNN code
  • -
  •    Additional Remarks
  • -
  •    Remarks on the speed
  • -
  •    Convolution using separable kernels
  • -
  •    Convolution in the Fourier domain
  • -
  • Building convolutional neural networks in Tensorflow and Keras
  • -
  • Setting it up
  • -
  • The MNIST dataset again
  • -
  • Strong correlations
  • -
  • Layers of a CNN
  • -
  • Systematic reduction
  • -
  • Prerequisites: Collect and pre-process data
  • -
  • Importing Keras and Tensorflow
  • -
  • Running with Keras
  • -
  • Final part
  • -
  • Final visualization
  • +
  • How to do image compression before the era of deep learning
  • +
  • The SVD example
  • +
  • Mathematics of CNNs
  • +
  • Mathematics of CNNs
  • +
  • Convolution Examples: Polynomial multiplication
  • +
  • Efficient Polynomial Multiplication
  • +
  • Further simplification
  • +
  • A more efficient way of coding the above Convolution
  • +
  • Commutative process
  • +
  • Toeplitz matrices
  • +
  • Fourier series and Toeplitz matrices
  • +
  • Generalizing the above one-dimensional case
  • +
  • Memory considerations
  • +
  • Padding
  • +
  • New vector
  • +
  • Rewriting as dot products
  • +
  • Cross correlation
  • +
  • Two-dimensional objects
  • +
  • CNNs in more detail, simple example
  • +
  • The convolution stage
  • +
  • Finding the number of parameters
  • +
  • New image (or volume)
  • +
  • Parameters to train, common settings
  • +
  • Examples of CNN setups
  • +
  • Summarizing: Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Pooling
  • +
  • Pooling arithmetic
  • +
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Building convolutional neural networks in Tensorflow and Keras
  • +
  • Setting it up
  • +
  • The MNIST dataset again
  • +
  • Strong correlations
  • +
  • Layers of a CNN
  • +
  • Systematic reduction
  • +
  • Prerequisites: Collect and pre-process data
  • +
  • Importing Keras and Tensorflow
  • +
  • Running with Keras
  • +
  • Final part
  • +
  • Final visualization
  • +
  • The CIFAR01 data set
  • +
  • Verifying the data set
  • +
  • Set up the model
  • +
  • Add Dense layers on top
  • +
  • Compile and train the model
  • +
  • Finally, evaluate the model
  • +
  • Building our own CNN code
  • +
  •    List of contents:
  • +
  •    Schedulers
  • +
  •    Usage of schedulers
  • +
  •    Cost functions
  • +
  •    Usage of cost functions
  • +
  •    Activation functions
  • +
  •    Usage of activation functions
  • +
  •    Convolution
  • +
  •    Layers
  • +
  •    Convolution2DLayer: convolution in a hidden layer
  • +
  •    Backpropagation in the convolutional layer
  • +
  •    Demonstration
  • +
  •    Pooling Layer
  • +
  •    Flattening Layer
  • +
  •    Fully Connected Layers
  • +
  •    Optimized Convolution2DLayer
  • +
  •    The Convolutional Neural Network (CNN)
  • +
  •    Usage of CNN code
  • +
  •    Additional Remarks
  • +
  •    Remarks on the speed
  • +
  •    Convolution using separable kernels
  • +
  •    Convolution in the Fourier domain
  • @@ -343,7 +385,7 @@ MathJax.Hub.Config({
  • 24
  • 25
  • ...
  • -
  • 47
  • +
  • 62
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs016.html b/doc/pub/week44/html/._week44-bs016.html index 98df55d62..658ac8bb3 100644 --- a/doc/pub/week44/html/._week44-bs016.html +++ b/doc/pub/week44/html/._week44-bs016.html @@ -75,6 +75,12 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d None, 'a-deep-cnn-model-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Key Idea', 2, None, 'key-idea'), + ('How to do image compression before the era of deep learning', + 2, + None, + 'how-to-do-image-compression-before-the-era-of-deep-learning'), + ('The SVD example', 2, None, 'the-svd-example'), + ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Convolution Examples: Polynomial multiplication', 2, @@ -89,6 +95,8 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'a-more-efficient-way-of-coding-the-above-convolution'), + ('Commutative process', 2, None, 'commutative-process'), + ('Toeplitz matrices', 2, None, 'toeplitz-matrices'), ('Fourier series and Toeplitz matrices', 2, None, @@ -97,36 +105,75 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'generalizing-the-above-one-dimensional-case'), - ('Two-dimensional Objects', 2, None, 'two-dimensional-objects'), - ('CNNs in more detail', 2, None, 'cnns-in-more-detail'), - ('Performing a discrete convolution with padding ("From Raschka ' - 'et al":"https://github.com/rasbt/machine-learning-book")', + ('Memory considerations', 2, None, 'memory-considerations'), + ('Padding', 2, None, 'padding'), + ('New vector', 2, None, 'new-vector'), + ('Rewriting as dot products', 2, None, - 'performing-a-discrete-convolution-with-padding-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Performing a general discrete convolution ("From Raschka et ' + 'rewriting-as-dot-products'), + ('Cross correlation', 2, None, 'cross-correlation'), + ('Two-dimensional objects', 2, None, 'two-dimensional-objects'), + ('CNNs in more detail, simple example', + 2, + None, + 'cnns-in-more-detail-simple-example'), + ('The convolution stage', 2, None, 'the-convolution-stage'), + ('Finding the number of parameters', + 2, + None, + 'finding-the-number-of-parameters'), + ('New image (or volume)', 2, None, 'new-image-or-volume'), + ('Parameters to train, common settings', + 2, + None, + 'parameters-to-train-common-settings'), + ('Examples of CNN setups', 2, None, 'examples-of-cnn-setups'), + ('Summarizing: Performing a general discrete convolution ("From ' + 'Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, - 'performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Set of filters', 2, None, 'set-of-filters'), + 'summarizing-performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Pooling', 2, None, 'pooling'), - ('No zero padding, unit strides', - 2, - None, - 'no-zero-padding-unit-strides'), - ('Zero padding, unit strides', - 2, - None, - 'zero-padding-unit-strides'), - ('Half (same) padding', 2, None, 'half-same-padding'), - ('Full padding', 2, None, 'full-padding'), ('Pooling arithmetic', 2, None, 'pooling-arithmetic'), ('Pooling types ("From Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, 'pooling-types-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), + ('Building convolutional neural networks in Tensorflow and Keras', + 2, + None, + 'building-convolutional-neural-networks-in-tensorflow-and-keras'), + ('Setting it up', 2, None, 'setting-it-up'), + ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), + ('Strong correlations', 2, None, 'strong-correlations'), + ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), + ('Systematic reduction', 2, None, 'systematic-reduction'), + ('Prerequisites: Collect and pre-process data', + 2, + None, + 'prerequisites-collect-and-pre-process-data'), + ('Importing Keras and Tensorflow', + 2, + None, + 'importing-keras-and-tensorflow'), + ('Running with Keras', 2, None, 'running-with-keras'), + ('Final part', 2, None, 'final-part'), + ('Final visualization', 2, None, 'final-visualization'), + ('The CIFAR01 data set', 2, None, 'the-cifar01-data-set'), + ('Verifying the data set', 2, None, 'verifying-the-data-set'), + ('Set up the model', 2, None, 'set-up-the-model'), + ('Add Dense layers on top', 2, None, 'add-dense-layers-on-top'), + ('Compile and train the model', + 2, + None, + 'compile-and-train-the-model'), + ('Finally, evaluate the model', + 2, + None, + 'finally-evaluate-the-model'), ('Building our own CNN code', 2, None, @@ -173,27 +220,7 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Convolution in the Fourier domain', 3, None, - 'convolution-in-the-fourier-domain'), - ('Building convolutional neural networks in Tensorflow and Keras', - 2, - None, - 'building-convolutional-neural-networks-in-tensorflow-and-keras'), - ('Setting it up', 2, None, 'setting-it-up'), - ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), - ('Strong correlations', 2, None, 'strong-correlations'), - ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), - ('Systematic reduction', 2, None, 'systematic-reduction'), - ('Prerequisites: Collect and pre-process data', - 2, - None, - 'prerequisites-collect-and-pre-process-data'), - ('Importing Keras and Tensorflow', - 2, - None, - 'importing-keras-and-tensorflow'), - ('Running with Keras', 2, None, 'running-with-keras'), - ('Final part', 2, None, 'final-part'), - ('Final visualization', 2, None, 'final-visualization')]} + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -244,59 +271,74 @@ MathJax.Hub.Config({
  • CNNs in brief
  • A deep CNN model ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • Key Idea
  • -
  • Mathematics of CNNs
  • -
  • Convolution Examples: Polynomial multiplication
  • -
  • Efficient Polynomial Multiplication
  • -
  • Further simplification
  • -
  • A more efficient way of coding the above Convolution
  • -
  • Fourier series and Toeplitz matrices
  • -
  • Generalizing the above one-dimensional case
  • -
  • Two-dimensional Objects
  • -
  • CNNs in more detail
  • -
  • Performing a discrete convolution with padding ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Set of filters
  • -
  • Pooling
  • -
  • No zero padding, unit strides
  • -
  • Zero padding, unit strides
  • -
  • Half (same) padding
  • -
  • Full padding
  • -
  • Pooling arithmetic
  • -
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Building our own CNN code
  • -
  •    List of contents:
  • -
  •    Schedulers
  • -
  •    Usage of schedulers
  • -
  •    Cost functions
  • -
  •    Usage of cost functions
  • -
  •    Activation functions
  • -
  •    Usage of activation functions
  • -
  •    Convolution
  • -
  •    Layers
  • -
  •    Convolution2DLayer: convolution in a hidden layer
  • -
  •    Backpropagation in the convolutional layer
  • -
  •    Demonstration
  • -
  •    Pooling Layer
  • -
  •    Flattening Layer
  • -
  •    Fully Connected Layers
  • -
  •    Optimized Convolution2DLayer
  • -
  •    The Convolutional Neural Network (CNN)
  • -
  •    Usage of CNN code
  • -
  •    Additional Remarks
  • -
  •    Remarks on the speed
  • -
  •    Convolution using separable kernels
  • -
  •    Convolution in the Fourier domain
  • -
  • Building convolutional neural networks in Tensorflow and Keras
  • -
  • Setting it up
  • -
  • The MNIST dataset again
  • -
  • Strong correlations
  • -
  • Layers of a CNN
  • -
  • Systematic reduction
  • -
  • Prerequisites: Collect and pre-process data
  • -
  • Importing Keras and Tensorflow
  • -
  • Running with Keras
  • -
  • Final part
  • -
  • Final visualization
  • +
  • How to do image compression before the era of deep learning
  • +
  • The SVD example
  • +
  • Mathematics of CNNs
  • +
  • Mathematics of CNNs
  • +
  • Convolution Examples: Polynomial multiplication
  • +
  • Efficient Polynomial Multiplication
  • +
  • Further simplification
  • +
  • A more efficient way of coding the above Convolution
  • +
  • Commutative process
  • +
  • Toeplitz matrices
  • +
  • Fourier series and Toeplitz matrices
  • +
  • Generalizing the above one-dimensional case
  • +
  • Memory considerations
  • +
  • Padding
  • +
  • New vector
  • +
  • Rewriting as dot products
  • +
  • Cross correlation
  • +
  • Two-dimensional objects
  • +
  • CNNs in more detail, simple example
  • +
  • The convolution stage
  • +
  • Finding the number of parameters
  • +
  • New image (or volume)
  • +
  • Parameters to train, common settings
  • +
  • Examples of CNN setups
  • +
  • Summarizing: Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Pooling
  • +
  • Pooling arithmetic
  • +
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Building convolutional neural networks in Tensorflow and Keras
  • +
  • Setting it up
  • +
  • The MNIST dataset again
  • +
  • Strong correlations
  • +
  • Layers of a CNN
  • +
  • Systematic reduction
  • +
  • Prerequisites: Collect and pre-process data
  • +
  • Importing Keras and Tensorflow
  • +
  • Running with Keras
  • +
  • Final part
  • +
  • Final visualization
  • +
  • The CIFAR01 data set
  • +
  • Verifying the data set
  • +
  • Set up the model
  • +
  • Add Dense layers on top
  • +
  • Compile and train the model
  • +
  • Finally, evaluate the model
  • +
  • Building our own CNN code
  • +
  •    List of contents:
  • +
  •    Schedulers
  • +
  •    Usage of schedulers
  • +
  •    Cost functions
  • +
  •    Usage of cost functions
  • +
  •    Activation functions
  • +
  •    Usage of activation functions
  • +
  •    Convolution
  • +
  •    Layers
  • +
  •    Convolution2DLayer: convolution in a hidden layer
  • +
  •    Backpropagation in the convolutional layer
  • +
  •    Demonstration
  • +
  •    Pooling Layer
  • +
  •    Flattening Layer
  • +
  •    Fully Connected Layers
  • +
  •    Optimized Convolution2DLayer
  • +
  •    The Convolutional Neural Network (CNN)
  • +
  •    Usage of CNN code
  • +
  •    Additional Remarks
  • +
  •    Remarks on the speed
  • +
  •    Convolution using separable kernels
  • +
  •    Convolution in the Fourier domain
  • @@ -343,7 +385,7 @@ only neighboring neurons in the input instead of connecting all with the first h
  • 25
  • 26
  • ...
  • -
  • 47
  • +
  • 62
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs017.html b/doc/pub/week44/html/._week44-bs017.html index a24fbd0c1..bf405105c 100644 --- a/doc/pub/week44/html/._week44-bs017.html +++ b/doc/pub/week44/html/._week44-bs017.html @@ -75,6 +75,12 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d None, 'a-deep-cnn-model-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Key Idea', 2, None, 'key-idea'), + ('How to do image compression before the era of deep learning', + 2, + None, + 'how-to-do-image-compression-before-the-era-of-deep-learning'), + ('The SVD example', 2, None, 'the-svd-example'), + ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Convolution Examples: Polynomial multiplication', 2, @@ -89,6 +95,8 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'a-more-efficient-way-of-coding-the-above-convolution'), + ('Commutative process', 2, None, 'commutative-process'), + ('Toeplitz matrices', 2, None, 'toeplitz-matrices'), ('Fourier series and Toeplitz matrices', 2, None, @@ -97,36 +105,75 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'generalizing-the-above-one-dimensional-case'), - ('Two-dimensional Objects', 2, None, 'two-dimensional-objects'), - ('CNNs in more detail', 2, None, 'cnns-in-more-detail'), - ('Performing a discrete convolution with padding ("From Raschka ' - 'et al":"https://github.com/rasbt/machine-learning-book")', + ('Memory considerations', 2, None, 'memory-considerations'), + ('Padding', 2, None, 'padding'), + ('New vector', 2, None, 'new-vector'), + ('Rewriting as dot products', 2, None, - 'performing-a-discrete-convolution-with-padding-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Performing a general discrete convolution ("From Raschka et ' + 'rewriting-as-dot-products'), + ('Cross correlation', 2, None, 'cross-correlation'), + ('Two-dimensional objects', 2, None, 'two-dimensional-objects'), + ('CNNs in more detail, simple example', + 2, + None, + 'cnns-in-more-detail-simple-example'), + ('The convolution stage', 2, None, 'the-convolution-stage'), + ('Finding the number of parameters', + 2, + None, + 'finding-the-number-of-parameters'), + ('New image (or volume)', 2, None, 'new-image-or-volume'), + ('Parameters to train, common settings', + 2, + None, + 'parameters-to-train-common-settings'), + ('Examples of CNN setups', 2, None, 'examples-of-cnn-setups'), + ('Summarizing: Performing a general discrete convolution ("From ' + 'Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, - 'performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Set of filters', 2, None, 'set-of-filters'), + 'summarizing-performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Pooling', 2, None, 'pooling'), - ('No zero padding, unit strides', - 2, - None, - 'no-zero-padding-unit-strides'), - ('Zero padding, unit strides', - 2, - None, - 'zero-padding-unit-strides'), - ('Half (same) padding', 2, None, 'half-same-padding'), - ('Full padding', 2, None, 'full-padding'), ('Pooling arithmetic', 2, None, 'pooling-arithmetic'), ('Pooling types ("From Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, 'pooling-types-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), + ('Building convolutional neural networks in Tensorflow and Keras', + 2, + None, + 'building-convolutional-neural-networks-in-tensorflow-and-keras'), + ('Setting it up', 2, None, 'setting-it-up'), + ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), + ('Strong correlations', 2, None, 'strong-correlations'), + ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), + ('Systematic reduction', 2, None, 'systematic-reduction'), + ('Prerequisites: Collect and pre-process data', + 2, + None, + 'prerequisites-collect-and-pre-process-data'), + ('Importing Keras and Tensorflow', + 2, + None, + 'importing-keras-and-tensorflow'), + ('Running with Keras', 2, None, 'running-with-keras'), + ('Final part', 2, None, 'final-part'), + ('Final visualization', 2, None, 'final-visualization'), + ('The CIFAR01 data set', 2, None, 'the-cifar01-data-set'), + ('Verifying the data set', 2, None, 'verifying-the-data-set'), + ('Set up the model', 2, None, 'set-up-the-model'), + ('Add Dense layers on top', 2, None, 'add-dense-layers-on-top'), + ('Compile and train the model', + 2, + None, + 'compile-and-train-the-model'), + ('Finally, evaluate the model', + 2, + None, + 'finally-evaluate-the-model'), ('Building our own CNN code', 2, None, @@ -173,27 +220,7 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Convolution in the Fourier domain', 3, None, - 'convolution-in-the-fourier-domain'), - ('Building convolutional neural networks in Tensorflow and Keras', - 2, - None, - 'building-convolutional-neural-networks-in-tensorflow-and-keras'), - ('Setting it up', 2, None, 'setting-it-up'), - ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), - ('Strong correlations', 2, None, 'strong-correlations'), - ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), - ('Systematic reduction', 2, None, 'systematic-reduction'), - ('Prerequisites: Collect and pre-process data', - 2, - None, - 'prerequisites-collect-and-pre-process-data'), - ('Importing Keras and Tensorflow', - 2, - None, - 'importing-keras-and-tensorflow'), - ('Running with Keras', 2, None, 'running-with-keras'), - ('Final part', 2, None, 'final-part'), - ('Final visualization', 2, None, 'final-visualization')]} + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -244,59 +271,74 @@ MathJax.Hub.Config({
  • CNNs in brief
  • A deep CNN model ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • Key Idea
  • -
  • Mathematics of CNNs
  • -
  • Convolution Examples: Polynomial multiplication
  • -
  • Efficient Polynomial Multiplication
  • -
  • Further simplification
  • -
  • A more efficient way of coding the above Convolution
  • -
  • Fourier series and Toeplitz matrices
  • -
  • Generalizing the above one-dimensional case
  • -
  • Two-dimensional Objects
  • -
  • CNNs in more detail
  • -
  • Performing a discrete convolution with padding ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Set of filters
  • -
  • Pooling
  • -
  • No zero padding, unit strides
  • -
  • Zero padding, unit strides
  • -
  • Half (same) padding
  • -
  • Full padding
  • -
  • Pooling arithmetic
  • -
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Building our own CNN code
  • -
  •    List of contents:
  • -
  •    Schedulers
  • -
  •    Usage of schedulers
  • -
  •    Cost functions
  • -
  •    Usage of cost functions
  • -
  •    Activation functions
  • -
  •    Usage of activation functions
  • -
  •    Convolution
  • -
  •    Layers
  • -
  •    Convolution2DLayer: convolution in a hidden layer
  • -
  •    Backpropagation in the convolutional layer
  • -
  •    Demonstration
  • -
  •    Pooling Layer
  • -
  •    Flattening Layer
  • -
  •    Fully Connected Layers
  • -
  •    Optimized Convolution2DLayer
  • -
  •    The Convolutional Neural Network (CNN)
  • -
  •    Usage of CNN code
  • -
  •    Additional Remarks
  • -
  •    Remarks on the speed
  • -
  •    Convolution using separable kernels
  • -
  •    Convolution in the Fourier domain
  • -
  • Building convolutional neural networks in Tensorflow and Keras
  • -
  • Setting it up
  • -
  • The MNIST dataset again
  • -
  • Strong correlations
  • -
  • Layers of a CNN
  • -
  • Systematic reduction
  • -
  • Prerequisites: Collect and pre-process data
  • -
  • Importing Keras and Tensorflow
  • -
  • Running with Keras
  • -
  • Final part
  • -
  • Final visualization
  • +
  • How to do image compression before the era of deep learning
  • +
  • The SVD example
  • +
  • Mathematics of CNNs
  • +
  • Mathematics of CNNs
  • +
  • Convolution Examples: Polynomial multiplication
  • +
  • Efficient Polynomial Multiplication
  • +
  • Further simplification
  • +
  • A more efficient way of coding the above Convolution
  • +
  • Commutative process
  • +
  • Toeplitz matrices
  • +
  • Fourier series and Toeplitz matrices
  • +
  • Generalizing the above one-dimensional case
  • +
  • Memory considerations
  • +
  • Padding
  • +
  • New vector
  • +
  • Rewriting as dot products
  • +
  • Cross correlation
  • +
  • Two-dimensional objects
  • +
  • CNNs in more detail, simple example
  • +
  • The convolution stage
  • +
  • Finding the number of parameters
  • +
  • New image (or volume)
  • +
  • Parameters to train, common settings
  • +
  • Examples of CNN setups
  • +
  • Summarizing: Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Pooling
  • +
  • Pooling arithmetic
  • +
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Building convolutional neural networks in Tensorflow and Keras
  • +
  • Setting it up
  • +
  • The MNIST dataset again
  • +
  • Strong correlations
  • +
  • Layers of a CNN
  • +
  • Systematic reduction
  • +
  • Prerequisites: Collect and pre-process data
  • +
  • Importing Keras and Tensorflow
  • +
  • Running with Keras
  • +
  • Final part
  • +
  • Final visualization
  • +
  • The CIFAR01 data set
  • +
  • Verifying the data set
  • +
  • Set up the model
  • +
  • Add Dense layers on top
  • +
  • Compile and train the model
  • +
  • Finally, evaluate the model
  • +
  • Building our own CNN code
  • +
  •    List of contents:
  • +
  •    Schedulers
  • +
  •    Usage of schedulers
  • +
  •    Cost functions
  • +
  •    Usage of cost functions
  • +
  •    Activation functions
  • +
  •    Usage of activation functions
  • +
  •    Convolution
  • +
  •    Layers
  • +
  •    Convolution2DLayer: convolution in a hidden layer
  • +
  •    Backpropagation in the convolutional layer
  • +
  •    Demonstration
  • +
  •    Pooling Layer
  • +
  •    Flattening Layer
  • +
  •    Fully Connected Layers
  • +
  •    Optimized Convolution2DLayer
  • +
  •    The Convolutional Neural Network (CNN)
  • +
  •    Usage of CNN code
  • +
  •    Additional Remarks
  • +
  •    Remarks on the speed
  • +
  •    Convolution using separable kernels
  • +
  •    Convolution in the Fourier domain
  • @@ -308,41 +350,24 @@ MathJax.Hub.Config({

     

     

     

    -

    Mathematics of CNNs

    +

    How to do image compression before the era of deep learning

    -

    The mathematics of CNNs is based on the mathematical operation of -convolution. In mathematics (in particular in functional analysis), -convolution is represented by mathematical operations (integration, -summation etc) on two functions in order to produce a third function -that expresses how the shape of one gets modified by the other. -Convolution has a plethora of applications in a variety of -disciplines, spanning from statistics to signal processing, computer -vision, solutions of differential equations,linear algebra, -engineering, and yes, machine learning. +

    The singular-value decomposition (SVD) algorithm has been for decades one of the standard ways of compressing images. +The lectures on the SVD give many of the essential details concerning the SVD.

    -

    Mathematically, convolution is defined as follows (one-dimensional example): -Let us define a continuous function \( y(t) \) given by +

    The orthogonal vectors which are obtained from the SVD, can be used to +project down the dimensionality of a given image. In the example here +we gray-scale an image and downsize it.

    -$$ -y(t) = \int x(a) w(t-a) da, -$$ -

    where \( x(a) \) represents a so-called input and \( w(t-a) \) is normally called the weight function or kernel.

    - -

    The above integral is written in a more compact form as

    -$$ -y(t) = \left(x * w\right)(t). -$$ - -

    The discretized version reads

    -$$ -y(t) = \sum_{a=-\infty}^{a=\infty}x(a)w(t-a). -$$ - -

    Computing the inverse of the above convolution operations is known as deconvolution and the process is commutative.

    - -

    How can we use this? And what does it mean? Let us study some familiar examples first.

    +

    This recipe relies on us being able to actually perform the SVD. For +large images, and in particular with many images to reconstruct, using the SVD +may quickly become an overwhelming task. With the advent of efficient deep +learning methods like CNNs and later generative methods, these methods +have become in the last years the premier way of performing image +analysis. In particular for classification problems with labelled images. +

    @@ -369,7 +394,7 @@ $$

  • 26
  • 27
  • ...
  • -
  • 47
  • +
  • 62
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs018.html b/doc/pub/week44/html/._week44-bs018.html index a65c89667..755dc9894 100644 --- a/doc/pub/week44/html/._week44-bs018.html +++ b/doc/pub/week44/html/._week44-bs018.html @@ -75,6 +75,12 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d None, 'a-deep-cnn-model-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Key Idea', 2, None, 'key-idea'), + ('How to do image compression before the era of deep learning', + 2, + None, + 'how-to-do-image-compression-before-the-era-of-deep-learning'), + ('The SVD example', 2, None, 'the-svd-example'), + ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Convolution Examples: Polynomial multiplication', 2, @@ -89,6 +95,8 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'a-more-efficient-way-of-coding-the-above-convolution'), + ('Commutative process', 2, None, 'commutative-process'), + ('Toeplitz matrices', 2, None, 'toeplitz-matrices'), ('Fourier series and Toeplitz matrices', 2, None, @@ -97,36 +105,75 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'generalizing-the-above-one-dimensional-case'), - ('Two-dimensional Objects', 2, None, 'two-dimensional-objects'), - ('CNNs in more detail', 2, None, 'cnns-in-more-detail'), - ('Performing a discrete convolution with padding ("From Raschka ' - 'et al":"https://github.com/rasbt/machine-learning-book")', + ('Memory considerations', 2, None, 'memory-considerations'), + ('Padding', 2, None, 'padding'), + ('New vector', 2, None, 'new-vector'), + ('Rewriting as dot products', 2, None, - 'performing-a-discrete-convolution-with-padding-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Performing a general discrete convolution ("From Raschka et ' + 'rewriting-as-dot-products'), + ('Cross correlation', 2, None, 'cross-correlation'), + ('Two-dimensional objects', 2, None, 'two-dimensional-objects'), + ('CNNs in more detail, simple example', + 2, + None, + 'cnns-in-more-detail-simple-example'), + ('The convolution stage', 2, None, 'the-convolution-stage'), + ('Finding the number of parameters', + 2, + None, + 'finding-the-number-of-parameters'), + ('New image (or volume)', 2, None, 'new-image-or-volume'), + ('Parameters to train, common settings', + 2, + None, + 'parameters-to-train-common-settings'), + ('Examples of CNN setups', 2, None, 'examples-of-cnn-setups'), + ('Summarizing: Performing a general discrete convolution ("From ' + 'Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, - 'performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Set of filters', 2, None, 'set-of-filters'), + 'summarizing-performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Pooling', 2, None, 'pooling'), - ('No zero padding, unit strides', - 2, - None, - 'no-zero-padding-unit-strides'), - ('Zero padding, unit strides', - 2, - None, - 'zero-padding-unit-strides'), - ('Half (same) padding', 2, None, 'half-same-padding'), - ('Full padding', 2, None, 'full-padding'), ('Pooling arithmetic', 2, None, 'pooling-arithmetic'), ('Pooling types ("From Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, 'pooling-types-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), + ('Building convolutional neural networks in Tensorflow and Keras', + 2, + None, + 'building-convolutional-neural-networks-in-tensorflow-and-keras'), + ('Setting it up', 2, None, 'setting-it-up'), + ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), + ('Strong correlations', 2, None, 'strong-correlations'), + ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), + ('Systematic reduction', 2, None, 'systematic-reduction'), + ('Prerequisites: Collect and pre-process data', + 2, + None, + 'prerequisites-collect-and-pre-process-data'), + ('Importing Keras and Tensorflow', + 2, + None, + 'importing-keras-and-tensorflow'), + ('Running with Keras', 2, None, 'running-with-keras'), + ('Final part', 2, None, 'final-part'), + ('Final visualization', 2, None, 'final-visualization'), + ('The CIFAR01 data set', 2, None, 'the-cifar01-data-set'), + ('Verifying the data set', 2, None, 'verifying-the-data-set'), + ('Set up the model', 2, None, 'set-up-the-model'), + ('Add Dense layers on top', 2, None, 'add-dense-layers-on-top'), + ('Compile and train the model', + 2, + None, + 'compile-and-train-the-model'), + ('Finally, evaluate the model', + 2, + None, + 'finally-evaluate-the-model'), ('Building our own CNN code', 2, None, @@ -173,27 +220,7 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Convolution in the Fourier domain', 3, None, - 'convolution-in-the-fourier-domain'), - ('Building convolutional neural networks in Tensorflow and Keras', - 2, - None, - 'building-convolutional-neural-networks-in-tensorflow-and-keras'), - ('Setting it up', 2, None, 'setting-it-up'), - ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), - ('Strong correlations', 2, None, 'strong-correlations'), - ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), - ('Systematic reduction', 2, None, 'systematic-reduction'), - ('Prerequisites: Collect and pre-process data', - 2, - None, - 'prerequisites-collect-and-pre-process-data'), - ('Importing Keras and Tensorflow', - 2, - None, - 'importing-keras-and-tensorflow'), - ('Running with Keras', 2, None, 'running-with-keras'), - ('Final part', 2, None, 'final-part'), - ('Final visualization', 2, None, 'final-visualization')]} + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -244,59 +271,74 @@ MathJax.Hub.Config({
  • CNNs in brief
  • A deep CNN model ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • Key Idea
  • -
  • Mathematics of CNNs
  • -
  • Convolution Examples: Polynomial multiplication
  • -
  • Efficient Polynomial Multiplication
  • -
  • Further simplification
  • -
  • A more efficient way of coding the above Convolution
  • -
  • Fourier series and Toeplitz matrices
  • -
  • Generalizing the above one-dimensional case
  • -
  • Two-dimensional Objects
  • -
  • CNNs in more detail
  • -
  • Performing a discrete convolution with padding ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Set of filters
  • -
  • Pooling
  • -
  • No zero padding, unit strides
  • -
  • Zero padding, unit strides
  • -
  • Half (same) padding
  • -
  • Full padding
  • -
  • Pooling arithmetic
  • -
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Building our own CNN code
  • -
  •    List of contents:
  • -
  •    Schedulers
  • -
  •    Usage of schedulers
  • -
  •    Cost functions
  • -
  •    Usage of cost functions
  • -
  •    Activation functions
  • -
  •    Usage of activation functions
  • -
  •    Convolution
  • -
  •    Layers
  • -
  •    Convolution2DLayer: convolution in a hidden layer
  • -
  •    Backpropagation in the convolutional layer
  • -
  •    Demonstration
  • -
  •    Pooling Layer
  • -
  •    Flattening Layer
  • -
  •    Fully Connected Layers
  • -
  •    Optimized Convolution2DLayer
  • -
  •    The Convolutional Neural Network (CNN)
  • -
  •    Usage of CNN code
  • -
  •    Additional Remarks
  • -
  •    Remarks on the speed
  • -
  •    Convolution using separable kernels
  • -
  •    Convolution in the Fourier domain
  • -
  • Building convolutional neural networks in Tensorflow and Keras
  • -
  • Setting it up
  • -
  • The MNIST dataset again
  • -
  • Strong correlations
  • -
  • Layers of a CNN
  • -
  • Systematic reduction
  • -
  • Prerequisites: Collect and pre-process data
  • -
  • Importing Keras and Tensorflow
  • -
  • Running with Keras
  • -
  • Final part
  • -
  • Final visualization
  • +
  • How to do image compression before the era of deep learning
  • +
  • The SVD example
  • +
  • Mathematics of CNNs
  • +
  • Mathematics of CNNs
  • +
  • Convolution Examples: Polynomial multiplication
  • +
  • Efficient Polynomial Multiplication
  • +
  • Further simplification
  • +
  • A more efficient way of coding the above Convolution
  • +
  • Commutative process
  • +
  • Toeplitz matrices
  • +
  • Fourier series and Toeplitz matrices
  • +
  • Generalizing the above one-dimensional case
  • +
  • Memory considerations
  • +
  • Padding
  • +
  • New vector
  • +
  • Rewriting as dot products
  • +
  • Cross correlation
  • +
  • Two-dimensional objects
  • +
  • CNNs in more detail, simple example
  • +
  • The convolution stage
  • +
  • Finding the number of parameters
  • +
  • New image (or volume)
  • +
  • Parameters to train, common settings
  • +
  • Examples of CNN setups
  • +
  • Summarizing: Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Pooling
  • +
  • Pooling arithmetic
  • +
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Building convolutional neural networks in Tensorflow and Keras
  • +
  • Setting it up
  • +
  • The MNIST dataset again
  • +
  • Strong correlations
  • +
  • Layers of a CNN
  • +
  • Systematic reduction
  • +
  • Prerequisites: Collect and pre-process data
  • +
  • Importing Keras and Tensorflow
  • +
  • Running with Keras
  • +
  • Final part
  • +
  • Final visualization
  • +
  • The CIFAR01 data set
  • +
  • Verifying the data set
  • +
  • Set up the model
  • +
  • Add Dense layers on top
  • +
  • Compile and train the model
  • +
  • Finally, evaluate the model
  • +
  • Building our own CNN code
  • +
  •    List of contents:
  • +
  •    Schedulers
  • +
  •    Usage of schedulers
  • +
  •    Cost functions
  • +
  •    Usage of cost functions
  • +
  •    Activation functions
  • +
  •    Usage of activation functions
  • +
  •    Convolution
  • +
  •    Layers
  • +
  •    Convolution2DLayer: convolution in a hidden layer
  • +
  •    Backpropagation in the convolutional layer
  • +
  •    Demonstration
  • +
  •    Pooling Layer
  • +
  •    Flattening Layer
  • +
  •    Fully Connected Layers
  • +
  •    Optimized Convolution2DLayer
  • +
  •    The Convolutional Neural Network (CNN)
  • +
  •    Usage of CNN code
  • +
  •    Additional Remarks
  • +
  •    Remarks on the speed
  • +
  •    Convolution using separable kernels
  • +
  •    Convolution in the Fourier domain
  • @@ -308,30 +350,87 @@ MathJax.Hub.Config({

     

     

     

    -

    Convolution Examples: Polynomial multiplication

    +

    The SVD example

    -

    Our first example is that of a multiplication between two polynomials, -which we will rewrite in terms of the mathematics of convolution. In -the final stage, since the problem here is a discrete one, we will -recast the final expression in terms of a matrix-vector -multiplication, where the matrix is a so-called Toeplitz matrix -. -

    -

    Let us look a the following polynomials to second and third order, respectively:

    -$$ -p(t) = \alpha_0+\alpha_1 t+\alpha_2 t^2, -$$ + +
    +
    +
    +
    +
    +
    from matplotlib.image import imread
    +import matplotlib.pyplot as plt
    +import scipy.linalg as ln
    +import numpy as np
    +import os
    +from PIL import Image
    +from math import log10, sqrt 
    +plt.rcParams['figure.figsize'] = [16, 8]
    +# Import image
    +A = imread(os.path.join("figslides/photo1.jpg"))
    +X = A.dot([0.299, 0.5870, 0.114]) # Convert RGB to grayscale
    +img = plt.imshow(X)
    +# convert to gray
    +img.set_cmap('gray')
    +plt.axis('off')
    +plt.show()
    +# Call image size
    +print(': %s'%str(X.shape))
     
    -

    and

    -$$ -s(t) = \beta_0+\beta_1 t+\beta_2 t^2+\beta_3 t^3. -$$ -

    The polynomial multiplication gives us a new polynomial of degree \( 5 \)

    -$$ -z(t) = \delta_0+\delta_1 t+\delta_2 t^2+\delta_3 t^3+\delta_4 t^4+\delta_5 t^5. -$$ +# split the matrix into U, S, VT +U, S, VT = np.linalg.svd(X,full_matrices=False) +S = np.diag(S) +m = 800 # Image's width +n = 1200 # Image's height +j = 0 +# Try compression with different k vectors (these represent projections): +for k in (5,10, 20, 100,200,400,500): + # Original size of the image + originalSize = m * n + # Size after compressed + compressedSize = k * (1 + m + n) + # The projection of the original image + Xapprox = U[:,:k] @ S[0:k,:k] @ VT[:k,:] + plt.figure(j+1) + j += 1 + img = plt.imshow(Xapprox) + img.set_cmap('gray') + + plt.axis('off') + plt.title('k = ' + str(k)) + plt.show() + print('Original size of image:') + print(originalSize) + print('Compression rate as Compressed image / Original size:') + ratio = compressedSize * 1.0 / originalSize + print(ratio) + print('Compression rate is ' + str( round(ratio * 100 ,2)) + '%' ) + # Estimate MQA + x= X.astype("float") + y=Xapprox.astype("float") + err = np.sum((x - y) ** 2) + err /= float(X.shape[0] * Xapprox.shape[1]) + print('The mean-square deviation '+ str(round( err))) + max_pixel = 255.0 + # Estimate Signal Noise Ratio + srv = 20 * (log10(max_pixel / sqrt(err))) + print('Signa to noise ratio '+ str(round(srv)) +'dB') +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    @@ -359,7 +458,7 @@ $$

  • 27
  • 28
  • ...
  • -
  • 47
  • +
  • 62
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs019.html b/doc/pub/week44/html/._week44-bs019.html index 7868d9229..9f4418b19 100644 --- a/doc/pub/week44/html/._week44-bs019.html +++ b/doc/pub/week44/html/._week44-bs019.html @@ -75,6 +75,12 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d None, 'a-deep-cnn-model-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Key Idea', 2, None, 'key-idea'), + ('How to do image compression before the era of deep learning', + 2, + None, + 'how-to-do-image-compression-before-the-era-of-deep-learning'), + ('The SVD example', 2, None, 'the-svd-example'), + ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Convolution Examples: Polynomial multiplication', 2, @@ -89,6 +95,8 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'a-more-efficient-way-of-coding-the-above-convolution'), + ('Commutative process', 2, None, 'commutative-process'), + ('Toeplitz matrices', 2, None, 'toeplitz-matrices'), ('Fourier series and Toeplitz matrices', 2, None, @@ -97,36 +105,75 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'generalizing-the-above-one-dimensional-case'), - ('Two-dimensional Objects', 2, None, 'two-dimensional-objects'), - ('CNNs in more detail', 2, None, 'cnns-in-more-detail'), - ('Performing a discrete convolution with padding ("From Raschka ' - 'et al":"https://github.com/rasbt/machine-learning-book")', + ('Memory considerations', 2, None, 'memory-considerations'), + ('Padding', 2, None, 'padding'), + ('New vector', 2, None, 'new-vector'), + ('Rewriting as dot products', 2, None, - 'performing-a-discrete-convolution-with-padding-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Performing a general discrete convolution ("From Raschka et ' + 'rewriting-as-dot-products'), + ('Cross correlation', 2, None, 'cross-correlation'), + ('Two-dimensional objects', 2, None, 'two-dimensional-objects'), + ('CNNs in more detail, simple example', + 2, + None, + 'cnns-in-more-detail-simple-example'), + ('The convolution stage', 2, None, 'the-convolution-stage'), + ('Finding the number of parameters', + 2, + None, + 'finding-the-number-of-parameters'), + ('New image (or volume)', 2, None, 'new-image-or-volume'), + ('Parameters to train, common settings', + 2, + None, + 'parameters-to-train-common-settings'), + ('Examples of CNN setups', 2, None, 'examples-of-cnn-setups'), + ('Summarizing: Performing a general discrete convolution ("From ' + 'Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, - 'performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Set of filters', 2, None, 'set-of-filters'), + 'summarizing-performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Pooling', 2, None, 'pooling'), - ('No zero padding, unit strides', - 2, - None, - 'no-zero-padding-unit-strides'), - ('Zero padding, unit strides', - 2, - None, - 'zero-padding-unit-strides'), - ('Half (same) padding', 2, None, 'half-same-padding'), - ('Full padding', 2, None, 'full-padding'), ('Pooling arithmetic', 2, None, 'pooling-arithmetic'), ('Pooling types ("From Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, 'pooling-types-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), + ('Building convolutional neural networks in Tensorflow and Keras', + 2, + None, + 'building-convolutional-neural-networks-in-tensorflow-and-keras'), + ('Setting it up', 2, None, 'setting-it-up'), + ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), + ('Strong correlations', 2, None, 'strong-correlations'), + ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), + ('Systematic reduction', 2, None, 'systematic-reduction'), + ('Prerequisites: Collect and pre-process data', + 2, + None, + 'prerequisites-collect-and-pre-process-data'), + ('Importing Keras and Tensorflow', + 2, + None, + 'importing-keras-and-tensorflow'), + ('Running with Keras', 2, None, 'running-with-keras'), + ('Final part', 2, None, 'final-part'), + ('Final visualization', 2, None, 'final-visualization'), + ('The CIFAR01 data set', 2, None, 'the-cifar01-data-set'), + ('Verifying the data set', 2, None, 'verifying-the-data-set'), + ('Set up the model', 2, None, 'set-up-the-model'), + ('Add Dense layers on top', 2, None, 'add-dense-layers-on-top'), + ('Compile and train the model', + 2, + None, + 'compile-and-train-the-model'), + ('Finally, evaluate the model', + 2, + None, + 'finally-evaluate-the-model'), ('Building our own CNN code', 2, None, @@ -173,27 +220,7 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Convolution in the Fourier domain', 3, None, - 'convolution-in-the-fourier-domain'), - ('Building convolutional neural networks in Tensorflow and Keras', - 2, - None, - 'building-convolutional-neural-networks-in-tensorflow-and-keras'), - ('Setting it up', 2, None, 'setting-it-up'), - ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), - ('Strong correlations', 2, None, 'strong-correlations'), - ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), - ('Systematic reduction', 2, None, 'systematic-reduction'), - ('Prerequisites: Collect and pre-process data', - 2, - None, - 'prerequisites-collect-and-pre-process-data'), - ('Importing Keras and Tensorflow', - 2, - None, - 'importing-keras-and-tensorflow'), - ('Running with Keras', 2, None, 'running-with-keras'), - ('Final part', 2, None, 'final-part'), - ('Final visualization', 2, None, 'final-visualization')]} + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -244,59 +271,74 @@ MathJax.Hub.Config({
  • CNNs in brief
  • A deep CNN model ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • Key Idea
  • -
  • Mathematics of CNNs
  • -
  • Convolution Examples: Polynomial multiplication
  • -
  • Efficient Polynomial Multiplication
  • -
  • Further simplification
  • -
  • A more efficient way of coding the above Convolution
  • -
  • Fourier series and Toeplitz matrices
  • -
  • Generalizing the above one-dimensional case
  • -
  • Two-dimensional Objects
  • -
  • CNNs in more detail
  • -
  • Performing a discrete convolution with padding ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Set of filters
  • -
  • Pooling
  • -
  • No zero padding, unit strides
  • -
  • Zero padding, unit strides
  • -
  • Half (same) padding
  • -
  • Full padding
  • -
  • Pooling arithmetic
  • -
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Building our own CNN code
  • -
  •    List of contents:
  • -
  •    Schedulers
  • -
  •    Usage of schedulers
  • -
  •    Cost functions
  • -
  •    Usage of cost functions
  • -
  •    Activation functions
  • -
  •    Usage of activation functions
  • -
  •    Convolution
  • -
  •    Layers
  • -
  •    Convolution2DLayer: convolution in a hidden layer
  • -
  •    Backpropagation in the convolutional layer
  • -
  •    Demonstration
  • -
  •    Pooling Layer
  • -
  •    Flattening Layer
  • -
  •    Fully Connected Layers
  • -
  •    Optimized Convolution2DLayer
  • -
  •    The Convolutional Neural Network (CNN)
  • -
  •    Usage of CNN code
  • -
  •    Additional Remarks
  • -
  •    Remarks on the speed
  • -
  •    Convolution using separable kernels
  • -
  •    Convolution in the Fourier domain
  • -
  • Building convolutional neural networks in Tensorflow and Keras
  • -
  • Setting it up
  • -
  • The MNIST dataset again
  • -
  • Strong correlations
  • -
  • Layers of a CNN
  • -
  • Systematic reduction
  • -
  • Prerequisites: Collect and pre-process data
  • -
  • Importing Keras and Tensorflow
  • -
  • Running with Keras
  • -
  • Final part
  • -
  • Final visualization
  • +
  • How to do image compression before the era of deep learning
  • +
  • The SVD example
  • +
  • Mathematics of CNNs
  • +
  • Mathematics of CNNs
  • +
  • Convolution Examples: Polynomial multiplication
  • +
  • Efficient Polynomial Multiplication
  • +
  • Further simplification
  • +
  • A more efficient way of coding the above Convolution
  • +
  • Commutative process
  • +
  • Toeplitz matrices
  • +
  • Fourier series and Toeplitz matrices
  • +
  • Generalizing the above one-dimensional case
  • +
  • Memory considerations
  • +
  • Padding
  • +
  • New vector
  • +
  • Rewriting as dot products
  • +
  • Cross correlation
  • +
  • Two-dimensional objects
  • +
  • CNNs in more detail, simple example
  • +
  • The convolution stage
  • +
  • Finding the number of parameters
  • +
  • New image (or volume)
  • +
  • Parameters to train, common settings
  • +
  • Examples of CNN setups
  • +
  • Summarizing: Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Pooling
  • +
  • Pooling arithmetic
  • +
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Building convolutional neural networks in Tensorflow and Keras
  • +
  • Setting it up
  • +
  • The MNIST dataset again
  • +
  • Strong correlations
  • +
  • Layers of a CNN
  • +
  • Systematic reduction
  • +
  • Prerequisites: Collect and pre-process data
  • +
  • Importing Keras and Tensorflow
  • +
  • Running with Keras
  • +
  • Final part
  • +
  • Final visualization
  • +
  • The CIFAR01 data set
  • +
  • Verifying the data set
  • +
  • Set up the model
  • +
  • Add Dense layers on top
  • +
  • Compile and train the model
  • +
  • Finally, evaluate the model
  • +
  • Building our own CNN code
  • +
  •    List of contents:
  • +
  •    Schedulers
  • +
  •    Usage of schedulers
  • +
  •    Cost functions
  • +
  •    Usage of cost functions
  • +
  •    Activation functions
  • +
  •    Usage of activation functions
  • +
  •    Convolution
  • +
  •    Layers
  • +
  •    Convolution2DLayer: convolution in a hidden layer
  • +
  •    Backpropagation in the convolutional layer
  • +
  •    Demonstration
  • +
  •    Pooling Layer
  • +
  •    Flattening Layer
  • +
  •    Fully Connected Layers
  • +
  •    Optimized Convolution2DLayer
  • +
  •    The Convolutional Neural Network (CNN)
  • +
  •    Usage of CNN code
  • +
  •    Additional Remarks
  • +
  •    Remarks on the speed
  • +
  •    Convolution using separable kernels
  • +
  •    Convolution in the Fourier domain
  • @@ -308,35 +350,41 @@ MathJax.Hub.Config({

     

     

     

    -

    Efficient Polynomial Multiplication

    +

    Mathematics of CNNs

    -

    Computing polynomial products can be implemented efficiently if we rewrite the more brute force multiplications using convolution. -We note first that the new coefficients are given as +

    The mathematics of CNNs is based on the mathematical operation of +convolution. In mathematics (in particular in functional analysis), +convolution is represented by mathematical operations (integration, +summation etc) on two functions in order to produce a third function +that expresses how the shape of one gets modified by the other. +Convolution has a plethora of applications in a variety of +disciplines, spanning from statistics to signal processing, computer +vision, solutions of differential equations,linear algebra, +engineering, and yes, machine learning.

    +

    Mathematically, convolution is defined as follows (one-dimensional example): +Let us define a continuous function \( y(t) \) given by +

    $$ -\begin{split} -\delta_0=&\alpha_0\beta_0\\ -\delta_1=&\alpha_1\beta_0+\alpha_0\beta_1\\ -\delta_2=&\alpha_0\beta_2+\alpha_1\beta_1+\alpha_2\beta_0\\ -\delta_3=&\alpha_1\beta_2+\alpha_2\beta_1+\alpha_0\beta_3\\ -\delta_4=&\alpha_2\beta_2+\alpha_1\beta_3\\ -\delta_5=&\alpha_2\beta_3.\\ -\end{split} +y(t) = \int x(a) w(t-a) da, $$ -

    We note that \( \alpha_i=0 \) except for \( i\in \left\{0,1,2\right\} \) and \( \beta_i=0 \) except for \( i\in\left\{0,1,2,3\right\} \).

    +

    where \( x(a) \) represents a so-called input and \( w(t-a) \) is normally called the weight function or kernel.

    -

    We can then rewrite the coefficients \( \delta_j \) using a discrete convolution as

    +

    The above integral is written in a more compact form as

    $$ -\delta_j = \sum_{i=-\infty}^{i=\infty}\alpha_i\beta_{j-i}=(\alpha * \beta)_j, +y(t) = \left(x * w\right)(t). $$ -

    or as a double sum with restriction \( l=i+j \)

    +

    The discretized version reads

    $$ -\delta_l = \sum_{ij}\alpha_i\beta_{j}. +y(t) = \sum_{a=-\infty}^{a=\infty}x(a)w(t-a). $$ +

    Computing the inverse of the above convolution operations is known as deconvolution and the process is commutative.

    + +

    How can we use this? And what does it mean? Let us study some familiar examples first.

    @@ -363,7 +411,7 @@ $$

  • 28
  • 29
  • ...
  • -
  • 47
  • +
  • 62
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs020.html b/doc/pub/week44/html/._week44-bs020.html index a9649fb5d..75e91e754 100644 --- a/doc/pub/week44/html/._week44-bs020.html +++ b/doc/pub/week44/html/._week44-bs020.html @@ -75,6 +75,12 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d None, 'a-deep-cnn-model-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Key Idea', 2, None, 'key-idea'), + ('How to do image compression before the era of deep learning', + 2, + None, + 'how-to-do-image-compression-before-the-era-of-deep-learning'), + ('The SVD example', 2, None, 'the-svd-example'), + ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Convolution Examples: Polynomial multiplication', 2, @@ -89,6 +95,8 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'a-more-efficient-way-of-coding-the-above-convolution'), + ('Commutative process', 2, None, 'commutative-process'), + ('Toeplitz matrices', 2, None, 'toeplitz-matrices'), ('Fourier series and Toeplitz matrices', 2, None, @@ -97,36 +105,75 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'generalizing-the-above-one-dimensional-case'), - ('Two-dimensional Objects', 2, None, 'two-dimensional-objects'), - ('CNNs in more detail', 2, None, 'cnns-in-more-detail'), - ('Performing a discrete convolution with padding ("From Raschka ' - 'et al":"https://github.com/rasbt/machine-learning-book")', + ('Memory considerations', 2, None, 'memory-considerations'), + ('Padding', 2, None, 'padding'), + ('New vector', 2, None, 'new-vector'), + ('Rewriting as dot products', 2, None, - 'performing-a-discrete-convolution-with-padding-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Performing a general discrete convolution ("From Raschka et ' + 'rewriting-as-dot-products'), + ('Cross correlation', 2, None, 'cross-correlation'), + ('Two-dimensional objects', 2, None, 'two-dimensional-objects'), + ('CNNs in more detail, simple example', + 2, + None, + 'cnns-in-more-detail-simple-example'), + ('The convolution stage', 2, None, 'the-convolution-stage'), + ('Finding the number of parameters', + 2, + None, + 'finding-the-number-of-parameters'), + ('New image (or volume)', 2, None, 'new-image-or-volume'), + ('Parameters to train, common settings', + 2, + None, + 'parameters-to-train-common-settings'), + ('Examples of CNN setups', 2, None, 'examples-of-cnn-setups'), + ('Summarizing: Performing a general discrete convolution ("From ' + 'Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, - 'performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Set of filters', 2, None, 'set-of-filters'), + 'summarizing-performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Pooling', 2, None, 'pooling'), - ('No zero padding, unit strides', - 2, - None, - 'no-zero-padding-unit-strides'), - ('Zero padding, unit strides', - 2, - None, - 'zero-padding-unit-strides'), - ('Half (same) padding', 2, None, 'half-same-padding'), - ('Full padding', 2, None, 'full-padding'), ('Pooling arithmetic', 2, None, 'pooling-arithmetic'), ('Pooling types ("From Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, 'pooling-types-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), + ('Building convolutional neural networks in Tensorflow and Keras', + 2, + None, + 'building-convolutional-neural-networks-in-tensorflow-and-keras'), + ('Setting it up', 2, None, 'setting-it-up'), + ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), + ('Strong correlations', 2, None, 'strong-correlations'), + ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), + ('Systematic reduction', 2, None, 'systematic-reduction'), + ('Prerequisites: Collect and pre-process data', + 2, + None, + 'prerequisites-collect-and-pre-process-data'), + ('Importing Keras and Tensorflow', + 2, + None, + 'importing-keras-and-tensorflow'), + ('Running with Keras', 2, None, 'running-with-keras'), + ('Final part', 2, None, 'final-part'), + ('Final visualization', 2, None, 'final-visualization'), + ('The CIFAR01 data set', 2, None, 'the-cifar01-data-set'), + ('Verifying the data set', 2, None, 'verifying-the-data-set'), + ('Set up the model', 2, None, 'set-up-the-model'), + ('Add Dense layers on top', 2, None, 'add-dense-layers-on-top'), + ('Compile and train the model', + 2, + None, + 'compile-and-train-the-model'), + ('Finally, evaluate the model', + 2, + None, + 'finally-evaluate-the-model'), ('Building our own CNN code', 2, None, @@ -173,27 +220,7 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Convolution in the Fourier domain', 3, None, - 'convolution-in-the-fourier-domain'), - ('Building convolutional neural networks in Tensorflow and Keras', - 2, - None, - 'building-convolutional-neural-networks-in-tensorflow-and-keras'), - ('Setting it up', 2, None, 'setting-it-up'), - ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), - ('Strong correlations', 2, None, 'strong-correlations'), - ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), - ('Systematic reduction', 2, None, 'systematic-reduction'), - ('Prerequisites: Collect and pre-process data', - 2, - None, - 'prerequisites-collect-and-pre-process-data'), - ('Importing Keras and Tensorflow', - 2, - None, - 'importing-keras-and-tensorflow'), - ('Running with Keras', 2, None, 'running-with-keras'), - ('Final part', 2, None, 'final-part'), - ('Final visualization', 2, None, 'final-visualization')]} + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -244,59 +271,74 @@ MathJax.Hub.Config({
  • CNNs in brief
  • A deep CNN model ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • Key Idea
  • -
  • Mathematics of CNNs
  • -
  • Convolution Examples: Polynomial multiplication
  • -
  • Efficient Polynomial Multiplication
  • -
  • Further simplification
  • -
  • A more efficient way of coding the above Convolution
  • -
  • Fourier series and Toeplitz matrices
  • -
  • Generalizing the above one-dimensional case
  • -
  • Two-dimensional Objects
  • -
  • CNNs in more detail
  • -
  • Performing a discrete convolution with padding ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Set of filters
  • -
  • Pooling
  • -
  • No zero padding, unit strides
  • -
  • Zero padding, unit strides
  • -
  • Half (same) padding
  • -
  • Full padding
  • -
  • Pooling arithmetic
  • -
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Building our own CNN code
  • -
  •    List of contents:
  • -
  •    Schedulers
  • -
  •    Usage of schedulers
  • -
  •    Cost functions
  • -
  •    Usage of cost functions
  • -
  •    Activation functions
  • -
  •    Usage of activation functions
  • -
  •    Convolution
  • -
  •    Layers
  • -
  •    Convolution2DLayer: convolution in a hidden layer
  • -
  •    Backpropagation in the convolutional layer
  • -
  •    Demonstration
  • -
  •    Pooling Layer
  • -
  •    Flattening Layer
  • -
  •    Fully Connected Layers
  • -
  •    Optimized Convolution2DLayer
  • -
  •    The Convolutional Neural Network (CNN)
  • -
  •    Usage of CNN code
  • -
  •    Additional Remarks
  • -
  •    Remarks on the speed
  • -
  •    Convolution using separable kernels
  • -
  •    Convolution in the Fourier domain
  • -
  • Building convolutional neural networks in Tensorflow and Keras
  • -
  • Setting it up
  • -
  • The MNIST dataset again
  • -
  • Strong correlations
  • -
  • Layers of a CNN
  • -
  • Systematic reduction
  • -
  • Prerequisites: Collect and pre-process data
  • -
  • Importing Keras and Tensorflow
  • -
  • Running with Keras
  • -
  • Final part
  • -
  • Final visualization
  • +
  • How to do image compression before the era of deep learning
  • +
  • The SVD example
  • +
  • Mathematics of CNNs
  • +
  • Mathematics of CNNs
  • +
  • Convolution Examples: Polynomial multiplication
  • +
  • Efficient Polynomial Multiplication
  • +
  • Further simplification
  • +
  • A more efficient way of coding the above Convolution
  • +
  • Commutative process
  • +
  • Toeplitz matrices
  • +
  • Fourier series and Toeplitz matrices
  • +
  • Generalizing the above one-dimensional case
  • +
  • Memory considerations
  • +
  • Padding
  • +
  • New vector
  • +
  • Rewriting as dot products
  • +
  • Cross correlation
  • +
  • Two-dimensional objects
  • +
  • CNNs in more detail, simple example
  • +
  • The convolution stage
  • +
  • Finding the number of parameters
  • +
  • New image (or volume)
  • +
  • Parameters to train, common settings
  • +
  • Examples of CNN setups
  • +
  • Summarizing: Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Pooling
  • +
  • Pooling arithmetic
  • +
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Building convolutional neural networks in Tensorflow and Keras
  • +
  • Setting it up
  • +
  • The MNIST dataset again
  • +
  • Strong correlations
  • +
  • Layers of a CNN
  • +
  • Systematic reduction
  • +
  • Prerequisites: Collect and pre-process data
  • +
  • Importing Keras and Tensorflow
  • +
  • Running with Keras
  • +
  • Final part
  • +
  • Final visualization
  • +
  • The CIFAR01 data set
  • +
  • Verifying the data set
  • +
  • Set up the model
  • +
  • Add Dense layers on top
  • +
  • Compile and train the model
  • +
  • Finally, evaluate the model
  • +
  • Building our own CNN code
  • +
  •    List of contents:
  • +
  •    Schedulers
  • +
  •    Usage of schedulers
  • +
  •    Cost functions
  • +
  •    Usage of cost functions
  • +
  •    Activation functions
  • +
  •    Usage of activation functions
  • +
  •    Convolution
  • +
  •    Layers
  • +
  •    Convolution2DLayer: convolution in a hidden layer
  • +
  •    Backpropagation in the convolutional layer
  • +
  •    Demonstration
  • +
  •    Pooling Layer
  • +
  •    Flattening Layer
  • +
  •    Fully Connected Layers
  • +
  •    Optimized Convolution2DLayer
  • +
  •    The Convolutional Neural Network (CNN)
  • +
  •    Usage of CNN code
  • +
  •    Additional Remarks
  • +
  •    Remarks on the speed
  • +
  •    Convolution using separable kernels
  • +
  •    Convolution in the Fourier domain
  • @@ -308,14 +350,41 @@ MathJax.Hub.Config({

     

     

     

    -

    Further simplification

    +

    Mathematics of CNNs

    -

    Although we may have redundant operations with some few zeros for \( \beta_i \), we can rewrite the above sum in a more compact way as

    +

    The mathematics of CNNs is based on the mathematical operation of +convolution. In mathematics (in particular in functional analysis), +convolution is represented by mathematical operations (integration, +summation etc) on two functions in order to produce a third function +that expresses how the shape of one gets modified by the other. +Convolution has a plethora of applications in a variety of +disciplines, spanning from statistics to signal processing, computer +vision, solutions of differential equations,linear algebra, +engineering, and yes, machine learning. +

    + +

    Mathematically, convolution is defined as follows (one-dimensional example): +Let us define a continuous function \( y(t) \) given by +

    $$ -\delta_i = \sum_{k=0}^{k=m-1}\alpha_k\beta_{i-k}, +y(t) = \int x(a) w(t-a) da, $$ -

    where \( m=3 \) in our case, the maximum length of the vector \( \alpha \). Note that the vector \( \boldsymbol{\beta} \) has length \( n=4 \).

    +

    where \( x(a) \) represents a so-called input and \( w(t-a) \) is normally called the weight function or kernel.

    + +

    The above integral is written in a more compact form as

    +$$ +y(t) = \left(x * w\right)(t). +$$ + +

    The discretized version reads

    +$$ +y(t) = \sum_{a=-\infty}^{a=\infty}x(a)w(t-a). +$$ + +

    Computing the inverse of the above convolution operations is known as deconvolution and the process is commutative.

    + +

    How can we use this? And what does it mean? Let us study some familiar examples first.

    @@ -342,7 +411,7 @@ $$

  • 29
  • 30
  • ...
  • -
  • 47
  • +
  • 62
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs021.html b/doc/pub/week44/html/._week44-bs021.html index 40543bfb3..4dcc8e13f 100644 --- a/doc/pub/week44/html/._week44-bs021.html +++ b/doc/pub/week44/html/._week44-bs021.html @@ -75,6 +75,12 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d None, 'a-deep-cnn-model-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Key Idea', 2, None, 'key-idea'), + ('How to do image compression before the era of deep learning', + 2, + None, + 'how-to-do-image-compression-before-the-era-of-deep-learning'), + ('The SVD example', 2, None, 'the-svd-example'), + ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Convolution Examples: Polynomial multiplication', 2, @@ -89,6 +95,8 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'a-more-efficient-way-of-coding-the-above-convolution'), + ('Commutative process', 2, None, 'commutative-process'), + ('Toeplitz matrices', 2, None, 'toeplitz-matrices'), ('Fourier series and Toeplitz matrices', 2, None, @@ -97,36 +105,75 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'generalizing-the-above-one-dimensional-case'), - ('Two-dimensional Objects', 2, None, 'two-dimensional-objects'), - ('CNNs in more detail', 2, None, 'cnns-in-more-detail'), - ('Performing a discrete convolution with padding ("From Raschka ' - 'et al":"https://github.com/rasbt/machine-learning-book")', + ('Memory considerations', 2, None, 'memory-considerations'), + ('Padding', 2, None, 'padding'), + ('New vector', 2, None, 'new-vector'), + ('Rewriting as dot products', 2, None, - 'performing-a-discrete-convolution-with-padding-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Performing a general discrete convolution ("From Raschka et ' + 'rewriting-as-dot-products'), + ('Cross correlation', 2, None, 'cross-correlation'), + ('Two-dimensional objects', 2, None, 'two-dimensional-objects'), + ('CNNs in more detail, simple example', + 2, + None, + 'cnns-in-more-detail-simple-example'), + ('The convolution stage', 2, None, 'the-convolution-stage'), + ('Finding the number of parameters', + 2, + None, + 'finding-the-number-of-parameters'), + ('New image (or volume)', 2, None, 'new-image-or-volume'), + ('Parameters to train, common settings', + 2, + None, + 'parameters-to-train-common-settings'), + ('Examples of CNN setups', 2, None, 'examples-of-cnn-setups'), + ('Summarizing: Performing a general discrete convolution ("From ' + 'Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, - 'performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Set of filters', 2, None, 'set-of-filters'), + 'summarizing-performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Pooling', 2, None, 'pooling'), - ('No zero padding, unit strides', - 2, - None, - 'no-zero-padding-unit-strides'), - ('Zero padding, unit strides', - 2, - None, - 'zero-padding-unit-strides'), - ('Half (same) padding', 2, None, 'half-same-padding'), - ('Full padding', 2, None, 'full-padding'), ('Pooling arithmetic', 2, None, 'pooling-arithmetic'), ('Pooling types ("From Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, 'pooling-types-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), + ('Building convolutional neural networks in Tensorflow and Keras', + 2, + None, + 'building-convolutional-neural-networks-in-tensorflow-and-keras'), + ('Setting it up', 2, None, 'setting-it-up'), + ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), + ('Strong correlations', 2, None, 'strong-correlations'), + ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), + ('Systematic reduction', 2, None, 'systematic-reduction'), + ('Prerequisites: Collect and pre-process data', + 2, + None, + 'prerequisites-collect-and-pre-process-data'), + ('Importing Keras and Tensorflow', + 2, + None, + 'importing-keras-and-tensorflow'), + ('Running with Keras', 2, None, 'running-with-keras'), + ('Final part', 2, None, 'final-part'), + ('Final visualization', 2, None, 'final-visualization'), + ('The CIFAR01 data set', 2, None, 'the-cifar01-data-set'), + ('Verifying the data set', 2, None, 'verifying-the-data-set'), + ('Set up the model', 2, None, 'set-up-the-model'), + ('Add Dense layers on top', 2, None, 'add-dense-layers-on-top'), + ('Compile and train the model', + 2, + None, + 'compile-and-train-the-model'), + ('Finally, evaluate the model', + 2, + None, + 'finally-evaluate-the-model'), ('Building our own CNN code', 2, None, @@ -173,27 +220,7 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Convolution in the Fourier domain', 3, None, - 'convolution-in-the-fourier-domain'), - ('Building convolutional neural networks in Tensorflow and Keras', - 2, - None, - 'building-convolutional-neural-networks-in-tensorflow-and-keras'), - ('Setting it up', 2, None, 'setting-it-up'), - ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), - ('Strong correlations', 2, None, 'strong-correlations'), - ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), - ('Systematic reduction', 2, None, 'systematic-reduction'), - ('Prerequisites: Collect and pre-process data', - 2, - None, - 'prerequisites-collect-and-pre-process-data'), - ('Importing Keras and Tensorflow', - 2, - None, - 'importing-keras-and-tensorflow'), - ('Running with Keras', 2, None, 'running-with-keras'), - ('Final part', 2, None, 'final-part'), - ('Final visualization', 2, None, 'final-visualization')]} + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -244,59 +271,74 @@ MathJax.Hub.Config({
  • CNNs in brief
  • A deep CNN model ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • Key Idea
  • -
  • Mathematics of CNNs
  • -
  • Convolution Examples: Polynomial multiplication
  • -
  • Efficient Polynomial Multiplication
  • -
  • Further simplification
  • -
  • A more efficient way of coding the above Convolution
  • -
  • Fourier series and Toeplitz matrices
  • -
  • Generalizing the above one-dimensional case
  • -
  • Two-dimensional Objects
  • -
  • CNNs in more detail
  • -
  • Performing a discrete convolution with padding ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Set of filters
  • -
  • Pooling
  • -
  • No zero padding, unit strides
  • -
  • Zero padding, unit strides
  • -
  • Half (same) padding
  • -
  • Full padding
  • -
  • Pooling arithmetic
  • -
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Building our own CNN code
  • -
  •    List of contents:
  • -
  •    Schedulers
  • -
  •    Usage of schedulers
  • -
  •    Cost functions
  • -
  •    Usage of cost functions
  • -
  •    Activation functions
  • -
  •    Usage of activation functions
  • -
  •    Convolution
  • -
  •    Layers
  • -
  •    Convolution2DLayer: convolution in a hidden layer
  • -
  •    Backpropagation in the convolutional layer
  • -
  •    Demonstration
  • -
  •    Pooling Layer
  • -
  •    Flattening Layer
  • -
  •    Fully Connected Layers
  • -
  •    Optimized Convolution2DLayer
  • -
  •    The Convolutional Neural Network (CNN)
  • -
  •    Usage of CNN code
  • -
  •    Additional Remarks
  • -
  •    Remarks on the speed
  • -
  •    Convolution using separable kernels
  • -
  •    Convolution in the Fourier domain
  • -
  • Building convolutional neural networks in Tensorflow and Keras
  • -
  • Setting it up
  • -
  • The MNIST dataset again
  • -
  • Strong correlations
  • -
  • Layers of a CNN
  • -
  • Systematic reduction
  • -
  • Prerequisites: Collect and pre-process data
  • -
  • Importing Keras and Tensorflow
  • -
  • Running with Keras
  • -
  • Final part
  • -
  • Final visualization
  • +
  • How to do image compression before the era of deep learning
  • +
  • The SVD example
  • +
  • Mathematics of CNNs
  • +
  • Mathematics of CNNs
  • +
  • Convolution Examples: Polynomial multiplication
  • +
  • Efficient Polynomial Multiplication
  • +
  • Further simplification
  • +
  • A more efficient way of coding the above Convolution
  • +
  • Commutative process
  • +
  • Toeplitz matrices
  • +
  • Fourier series and Toeplitz matrices
  • +
  • Generalizing the above one-dimensional case
  • +
  • Memory considerations
  • +
  • Padding
  • +
  • New vector
  • +
  • Rewriting as dot products
  • +
  • Cross correlation
  • +
  • Two-dimensional objects
  • +
  • CNNs in more detail, simple example
  • +
  • The convolution stage
  • +
  • Finding the number of parameters
  • +
  • New image (or volume)
  • +
  • Parameters to train, common settings
  • +
  • Examples of CNN setups
  • +
  • Summarizing: Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Pooling
  • +
  • Pooling arithmetic
  • +
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Building convolutional neural networks in Tensorflow and Keras
  • +
  • Setting it up
  • +
  • The MNIST dataset again
  • +
  • Strong correlations
  • +
  • Layers of a CNN
  • +
  • Systematic reduction
  • +
  • Prerequisites: Collect and pre-process data
  • +
  • Importing Keras and Tensorflow
  • +
  • Running with Keras
  • +
  • Final part
  • +
  • Final visualization
  • +
  • The CIFAR01 data set
  • +
  • Verifying the data set
  • +
  • Set up the model
  • +
  • Add Dense layers on top
  • +
  • Compile and train the model
  • +
  • Finally, evaluate the model
  • +
  • Building our own CNN code
  • +
  •    List of contents:
  • +
  •    Schedulers
  • +
  •    Usage of schedulers
  • +
  •    Cost functions
  • +
  •    Usage of cost functions
  • +
  •    Activation functions
  • +
  •    Usage of activation functions
  • +
  •    Convolution
  • +
  •    Layers
  • +
  •    Convolution2DLayer: convolution in a hidden layer
  • +
  •    Backpropagation in the convolutional layer
  • +
  •    Demonstration
  • +
  •    Pooling Layer
  • +
  •    Flattening Layer
  • +
  •    Fully Connected Layers
  • +
  •    Optimized Convolution2DLayer
  • +
  •    The Convolutional Neural Network (CNN)
  • +
  •    Usage of CNN code
  • +
  •    Additional Remarks
  • +
  •    Remarks on the speed
  • +
  •    Convolution using separable kernels
  • +
  •    Convolution in the Fourier domain
  • @@ -308,67 +350,31 @@ MathJax.Hub.Config({

     

     

     

    -

    A more efficient way of coding the above Convolution

    +

    Convolution Examples: Polynomial multiplication

    -

    Since we only have a finite number of \( \alpha \) and \( \beta \) values -which are non-zero, we can rewrite the above convolution expressions -as a matrix-vector multiplication +

    Our first example is that of a multiplication between two polynomials, +which we will rewrite in terms of the mathematics of convolution. In +the final stage, since the problem here is a discrete one, we will +recast the final expression in terms of a matrix-vector +multiplication, where the matrix is a so-called Toeplitz matrix +.

    +

    Let us look a the following polynomials to second and third order, respectively:

    $$ -\boldsymbol{\delta}=\begin{bmatrix}\alpha_0 & 0 & 0 & 0 \\ - \alpha_1 & \alpha_0 & 0 & 0 \\ - \alpha_2 & \alpha_1 & \alpha_0 & 0 \\ - 0 & \alpha_2 & \alpha_1 & \alpha_0 \\ - 0 & 0 & \alpha_2 & \alpha_1 \\ - 0 & 0 & 0 & \alpha_2 - \end{bmatrix}\begin{bmatrix} \beta_0 \\ \beta_1 \\ \beta_2 \\ \beta_3\end{bmatrix}. +p(t) = \alpha_0+\alpha_1 t+\alpha_2 t^2, $$ -

    The process is commutative and we can easily see that we can rewrite the multiplication in terms of a matrix holding \( \beta \) and a vector holding \( \alpha \). -In this case we have -

    +

    and

    $$ -\boldsymbol{\delta}=\begin{bmatrix}\beta_0 & 0 & 0 \\ - \beta_1 & \beta_0 & 0 \\ - \beta_2 & \beta_1 & \beta_0 \\ - \beta_3 & \beta_2 & \beta_1 \\ - 0 & \beta_3 & \beta_2 \\ - 0 & 0 & \beta_3 - \end{bmatrix}\begin{bmatrix} \alpha_0 \\ \alpha_1 \\ \alpha_2\end{bmatrix}. +s(t) = \beta_0+\beta_1 t+\beta_2 t^2+\beta_3 t^3. $$ -

    Note that the use of these matrices is for mathematical purposes only -and not implementation purposes. When implementing the above equation -we do not encode (and allocate memory) the matrices explicitely. We -rather code the convolutions in the minimal memory footprint that they -require. -

    - -

    The above matrices are examples of so-called Toeplitz -matrices. A -Toeplitz matrix is a matrix in which each descending diagonal from -left to right is constant. For instance the last matrix, which we -rewrite as -

    +

    The polynomial multiplication gives us a new polynomial of degree \( 5 \)

    $$ -\boldsymbol{A}=\begin{bmatrix}a_0 & 0 & 0 \\ - a_1 & a_0 & 0 \\ - a_2 & a_1 & a_0 \\ - a_3 & a_2 & a_1 \\ - 0 & a_3 & a_2 \\ - 0 & 0 & a_3 - \end{bmatrix}, +z(t) = \delta_0+\delta_1 t+\delta_2 t^2+\delta_3 t^3+\delta_4 t^4+\delta_5 t^5. $$ -

    with elements \( a_{ii}=a_{i+1,j+1}=a_{i-j} \) is an example of a Toeplitz -matrix. Such a matrix does not need to be a square matrix. Toeplitz -matrices are also closely connected with Fourier series, because the multiplication operator by a trigonometric -polynomial, compressed to a finite-dimensional space, can be -represented by such a matrix. The example above shows that we can -represent linear convolution as multiplication of a Toeplitz matrix by -a vector. -

    @@ -395,7 +401,7 @@ a vector.

  • 30
  • 31
  • ...
  • -
  • 47
  • +
  • 62
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs022.html b/doc/pub/week44/html/._week44-bs022.html index 2b1c06f38..9e20c0f4c 100644 --- a/doc/pub/week44/html/._week44-bs022.html +++ b/doc/pub/week44/html/._week44-bs022.html @@ -75,6 +75,12 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d None, 'a-deep-cnn-model-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Key Idea', 2, None, 'key-idea'), + ('How to do image compression before the era of deep learning', + 2, + None, + 'how-to-do-image-compression-before-the-era-of-deep-learning'), + ('The SVD example', 2, None, 'the-svd-example'), + ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Convolution Examples: Polynomial multiplication', 2, @@ -89,6 +95,8 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'a-more-efficient-way-of-coding-the-above-convolution'), + ('Commutative process', 2, None, 'commutative-process'), + ('Toeplitz matrices', 2, None, 'toeplitz-matrices'), ('Fourier series and Toeplitz matrices', 2, None, @@ -97,36 +105,75 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'generalizing-the-above-one-dimensional-case'), - ('Two-dimensional Objects', 2, None, 'two-dimensional-objects'), - ('CNNs in more detail', 2, None, 'cnns-in-more-detail'), - ('Performing a discrete convolution with padding ("From Raschka ' - 'et al":"https://github.com/rasbt/machine-learning-book")', + ('Memory considerations', 2, None, 'memory-considerations'), + ('Padding', 2, None, 'padding'), + ('New vector', 2, None, 'new-vector'), + ('Rewriting as dot products', 2, None, - 'performing-a-discrete-convolution-with-padding-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Performing a general discrete convolution ("From Raschka et ' + 'rewriting-as-dot-products'), + ('Cross correlation', 2, None, 'cross-correlation'), + ('Two-dimensional objects', 2, None, 'two-dimensional-objects'), + ('CNNs in more detail, simple example', + 2, + None, + 'cnns-in-more-detail-simple-example'), + ('The convolution stage', 2, None, 'the-convolution-stage'), + ('Finding the number of parameters', + 2, + None, + 'finding-the-number-of-parameters'), + ('New image (or volume)', 2, None, 'new-image-or-volume'), + ('Parameters to train, common settings', + 2, + None, + 'parameters-to-train-common-settings'), + ('Examples of CNN setups', 2, None, 'examples-of-cnn-setups'), + ('Summarizing: Performing a general discrete convolution ("From ' + 'Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, - 'performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Set of filters', 2, None, 'set-of-filters'), + 'summarizing-performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Pooling', 2, None, 'pooling'), - ('No zero padding, unit strides', - 2, - None, - 'no-zero-padding-unit-strides'), - ('Zero padding, unit strides', - 2, - None, - 'zero-padding-unit-strides'), - ('Half (same) padding', 2, None, 'half-same-padding'), - ('Full padding', 2, None, 'full-padding'), ('Pooling arithmetic', 2, None, 'pooling-arithmetic'), ('Pooling types ("From Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, 'pooling-types-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), + ('Building convolutional neural networks in Tensorflow and Keras', + 2, + None, + 'building-convolutional-neural-networks-in-tensorflow-and-keras'), + ('Setting it up', 2, None, 'setting-it-up'), + ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), + ('Strong correlations', 2, None, 'strong-correlations'), + ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), + ('Systematic reduction', 2, None, 'systematic-reduction'), + ('Prerequisites: Collect and pre-process data', + 2, + None, + 'prerequisites-collect-and-pre-process-data'), + ('Importing Keras and Tensorflow', + 2, + None, + 'importing-keras-and-tensorflow'), + ('Running with Keras', 2, None, 'running-with-keras'), + ('Final part', 2, None, 'final-part'), + ('Final visualization', 2, None, 'final-visualization'), + ('The CIFAR01 data set', 2, None, 'the-cifar01-data-set'), + ('Verifying the data set', 2, None, 'verifying-the-data-set'), + ('Set up the model', 2, None, 'set-up-the-model'), + ('Add Dense layers on top', 2, None, 'add-dense-layers-on-top'), + ('Compile and train the model', + 2, + None, + 'compile-and-train-the-model'), + ('Finally, evaluate the model', + 2, + None, + 'finally-evaluate-the-model'), ('Building our own CNN code', 2, None, @@ -173,27 +220,7 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Convolution in the Fourier domain', 3, None, - 'convolution-in-the-fourier-domain'), - ('Building convolutional neural networks in Tensorflow and Keras', - 2, - None, - 'building-convolutional-neural-networks-in-tensorflow-and-keras'), - ('Setting it up', 2, None, 'setting-it-up'), - ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), - ('Strong correlations', 2, None, 'strong-correlations'), - ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), - ('Systematic reduction', 2, None, 'systematic-reduction'), - ('Prerequisites: Collect and pre-process data', - 2, - None, - 'prerequisites-collect-and-pre-process-data'), - ('Importing Keras and Tensorflow', - 2, - None, - 'importing-keras-and-tensorflow'), - ('Running with Keras', 2, None, 'running-with-keras'), - ('Final part', 2, None, 'final-part'), - ('Final visualization', 2, None, 'final-visualization')]} + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -244,59 +271,74 @@ MathJax.Hub.Config({
  • CNNs in brief
  • A deep CNN model ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • Key Idea
  • -
  • Mathematics of CNNs
  • -
  • Convolution Examples: Polynomial multiplication
  • -
  • Efficient Polynomial Multiplication
  • -
  • Further simplification
  • -
  • A more efficient way of coding the above Convolution
  • -
  • Fourier series and Toeplitz matrices
  • -
  • Generalizing the above one-dimensional case
  • -
  • Two-dimensional Objects
  • -
  • CNNs in more detail
  • -
  • Performing a discrete convolution with padding ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Set of filters
  • -
  • Pooling
  • -
  • No zero padding, unit strides
  • -
  • Zero padding, unit strides
  • -
  • Half (same) padding
  • -
  • Full padding
  • -
  • Pooling arithmetic
  • -
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Building our own CNN code
  • -
  •    List of contents:
  • -
  •    Schedulers
  • -
  •    Usage of schedulers
  • -
  •    Cost functions
  • -
  •    Usage of cost functions
  • -
  •    Activation functions
  • -
  •    Usage of activation functions
  • -
  •    Convolution
  • -
  •    Layers
  • -
  •    Convolution2DLayer: convolution in a hidden layer
  • -
  •    Backpropagation in the convolutional layer
  • -
  •    Demonstration
  • -
  •    Pooling Layer
  • -
  •    Flattening Layer
  • -
  •    Fully Connected Layers
  • -
  •    Optimized Convolution2DLayer
  • -
  •    The Convolutional Neural Network (CNN)
  • -
  •    Usage of CNN code
  • -
  •    Additional Remarks
  • -
  •    Remarks on the speed
  • -
  •    Convolution using separable kernels
  • -
  •    Convolution in the Fourier domain
  • -
  • Building convolutional neural networks in Tensorflow and Keras
  • -
  • Setting it up
  • -
  • The MNIST dataset again
  • -
  • Strong correlations
  • -
  • Layers of a CNN
  • -
  • Systematic reduction
  • -
  • Prerequisites: Collect and pre-process data
  • -
  • Importing Keras and Tensorflow
  • -
  • Running with Keras
  • -
  • Final part
  • -
  • Final visualization
  • +
  • How to do image compression before the era of deep learning
  • +
  • The SVD example
  • +
  • Mathematics of CNNs
  • +
  • Mathematics of CNNs
  • +
  • Convolution Examples: Polynomial multiplication
  • +
  • Efficient Polynomial Multiplication
  • +
  • Further simplification
  • +
  • A more efficient way of coding the above Convolution
  • +
  • Commutative process
  • +
  • Toeplitz matrices
  • +
  • Fourier series and Toeplitz matrices
  • +
  • Generalizing the above one-dimensional case
  • +
  • Memory considerations
  • +
  • Padding
  • +
  • New vector
  • +
  • Rewriting as dot products
  • +
  • Cross correlation
  • +
  • Two-dimensional objects
  • +
  • CNNs in more detail, simple example
  • +
  • The convolution stage
  • +
  • Finding the number of parameters
  • +
  • New image (or volume)
  • +
  • Parameters to train, common settings
  • +
  • Examples of CNN setups
  • +
  • Summarizing: Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Pooling
  • +
  • Pooling arithmetic
  • +
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Building convolutional neural networks in Tensorflow and Keras
  • +
  • Setting it up
  • +
  • The MNIST dataset again
  • +
  • Strong correlations
  • +
  • Layers of a CNN
  • +
  • Systematic reduction
  • +
  • Prerequisites: Collect and pre-process data
  • +
  • Importing Keras and Tensorflow
  • +
  • Running with Keras
  • +
  • Final part
  • +
  • Final visualization
  • +
  • The CIFAR01 data set
  • +
  • Verifying the data set
  • +
  • Set up the model
  • +
  • Add Dense layers on top
  • +
  • Compile and train the model
  • +
  • Finally, evaluate the model
  • +
  • Building our own CNN code
  • +
  •    List of contents:
  • +
  •    Schedulers
  • +
  •    Usage of schedulers
  • +
  •    Cost functions
  • +
  •    Usage of cost functions
  • +
  •    Activation functions
  • +
  •    Usage of activation functions
  • +
  •    Convolution
  • +
  •    Layers
  • +
  •    Convolution2DLayer: convolution in a hidden layer
  • +
  •    Backpropagation in the convolutional layer
  • +
  •    Demonstration
  • +
  •    Pooling Layer
  • +
  •    Flattening Layer
  • +
  •    Fully Connected Layers
  • +
  •    Optimized Convolution2DLayer
  • +
  •    The Convolutional Neural Network (CNN)
  • +
  •    Usage of CNN code
  • +
  •    Additional Remarks
  • +
  •    Remarks on the speed
  • +
  •    Convolution using separable kernels
  • +
  •    Convolution in the Fourier domain
  • @@ -308,13 +350,36 @@ MathJax.Hub.Config({

     

     

     

    -

    Fourier series and Toeplitz matrices

    +

    Efficient Polynomial Multiplication

    + +

    Computing polynomial products can be implemented efficiently if we rewrite the more brute force multiplications using convolution. +We note first that the new coefficients are given as +

    + +$$ +\begin{split} +\delta_0=&\alpha_0\beta_0\\ +\delta_1=&\alpha_1\beta_0+\alpha_0\beta_1\\ +\delta_2=&\alpha_0\beta_2+\alpha_1\beta_1+\alpha_2\beta_0\\ +\delta_3=&\alpha_1\beta_2+\alpha_2\beta_1+\alpha_0\beta_3\\ +\delta_4=&\alpha_2\beta_2+\alpha_1\beta_3\\ +\delta_5=&\alpha_2\beta_3.\\ +\end{split} +$$ + +

    We note that \( \alpha_i=0 \) except for \( i\in \left\{0,1,2\right\} \) and \( \beta_i=0 \) except for \( i\in\left\{0,1,2,3\right\} \).

    + +

    We can then rewrite the coefficients \( \delta_j \) using a discrete convolution as

    +$$ +\delta_j = \sum_{i=-\infty}^{i=\infty}\alpha_i\beta_{j-i}=(\alpha * \beta)_j, +$$ + +

    or as a double sum with restriction \( l=i+j \)

    +$$ +\delta_l = \sum_{ij}\alpha_i\beta_{j}. +$$ + -

    This is an active and ogoing research area concerning CNNs. The following articles may be of interest

    -
      -
    1. Read more about the convolution theorem and Fouriers series
    2. -
    3. Fourier Transform Layer
    4. -

    diff --git a/doc/pub/week44/html/._week44-bs023.html b/doc/pub/week44/html/._week44-bs023.html index a982663d6..7b54e91ce 100644 --- a/doc/pub/week44/html/._week44-bs023.html +++ b/doc/pub/week44/html/._week44-bs023.html @@ -75,6 +75,12 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d None, 'a-deep-cnn-model-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Key Idea', 2, None, 'key-idea'), + ('How to do image compression before the era of deep learning', + 2, + None, + 'how-to-do-image-compression-before-the-era-of-deep-learning'), + ('The SVD example', 2, None, 'the-svd-example'), + ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Convolution Examples: Polynomial multiplication', 2, @@ -89,6 +95,8 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'a-more-efficient-way-of-coding-the-above-convolution'), + ('Commutative process', 2, None, 'commutative-process'), + ('Toeplitz matrices', 2, None, 'toeplitz-matrices'), ('Fourier series and Toeplitz matrices', 2, None, @@ -97,36 +105,75 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'generalizing-the-above-one-dimensional-case'), - ('Two-dimensional Objects', 2, None, 'two-dimensional-objects'), - ('CNNs in more detail', 2, None, 'cnns-in-more-detail'), - ('Performing a discrete convolution with padding ("From Raschka ' - 'et al":"https://github.com/rasbt/machine-learning-book")', + ('Memory considerations', 2, None, 'memory-considerations'), + ('Padding', 2, None, 'padding'), + ('New vector', 2, None, 'new-vector'), + ('Rewriting as dot products', 2, None, - 'performing-a-discrete-convolution-with-padding-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Performing a general discrete convolution ("From Raschka et ' + 'rewriting-as-dot-products'), + ('Cross correlation', 2, None, 'cross-correlation'), + ('Two-dimensional objects', 2, None, 'two-dimensional-objects'), + ('CNNs in more detail, simple example', + 2, + None, + 'cnns-in-more-detail-simple-example'), + ('The convolution stage', 2, None, 'the-convolution-stage'), + ('Finding the number of parameters', + 2, + None, + 'finding-the-number-of-parameters'), + ('New image (or volume)', 2, None, 'new-image-or-volume'), + ('Parameters to train, common settings', + 2, + None, + 'parameters-to-train-common-settings'), + ('Examples of CNN setups', 2, None, 'examples-of-cnn-setups'), + ('Summarizing: Performing a general discrete convolution ("From ' + 'Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, - 'performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Set of filters', 2, None, 'set-of-filters'), + 'summarizing-performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Pooling', 2, None, 'pooling'), - ('No zero padding, unit strides', - 2, - None, - 'no-zero-padding-unit-strides'), - ('Zero padding, unit strides', - 2, - None, - 'zero-padding-unit-strides'), - ('Half (same) padding', 2, None, 'half-same-padding'), - ('Full padding', 2, None, 'full-padding'), ('Pooling arithmetic', 2, None, 'pooling-arithmetic'), ('Pooling types ("From Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, 'pooling-types-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), + ('Building convolutional neural networks in Tensorflow and Keras', + 2, + None, + 'building-convolutional-neural-networks-in-tensorflow-and-keras'), + ('Setting it up', 2, None, 'setting-it-up'), + ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), + ('Strong correlations', 2, None, 'strong-correlations'), + ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), + ('Systematic reduction', 2, None, 'systematic-reduction'), + ('Prerequisites: Collect and pre-process data', + 2, + None, + 'prerequisites-collect-and-pre-process-data'), + ('Importing Keras and Tensorflow', + 2, + None, + 'importing-keras-and-tensorflow'), + ('Running with Keras', 2, None, 'running-with-keras'), + ('Final part', 2, None, 'final-part'), + ('Final visualization', 2, None, 'final-visualization'), + ('The CIFAR01 data set', 2, None, 'the-cifar01-data-set'), + ('Verifying the data set', 2, None, 'verifying-the-data-set'), + ('Set up the model', 2, None, 'set-up-the-model'), + ('Add Dense layers on top', 2, None, 'add-dense-layers-on-top'), + ('Compile and train the model', + 2, + None, + 'compile-and-train-the-model'), + ('Finally, evaluate the model', + 2, + None, + 'finally-evaluate-the-model'), ('Building our own CNN code', 2, None, @@ -173,27 +220,7 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Convolution in the Fourier domain', 3, None, - 'convolution-in-the-fourier-domain'), - ('Building convolutional neural networks in Tensorflow and Keras', - 2, - None, - 'building-convolutional-neural-networks-in-tensorflow-and-keras'), - ('Setting it up', 2, None, 'setting-it-up'), - ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), - ('Strong correlations', 2, None, 'strong-correlations'), - ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), - ('Systematic reduction', 2, None, 'systematic-reduction'), - ('Prerequisites: Collect and pre-process data', - 2, - None, - 'prerequisites-collect-and-pre-process-data'), - ('Importing Keras and Tensorflow', - 2, - None, - 'importing-keras-and-tensorflow'), - ('Running with Keras', 2, None, 'running-with-keras'), - ('Final part', 2, None, 'final-part'), - ('Final visualization', 2, None, 'final-visualization')]} + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -244,59 +271,74 @@ MathJax.Hub.Config({
  • CNNs in brief
  • A deep CNN model ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • Key Idea
  • -
  • Mathematics of CNNs
  • -
  • Convolution Examples: Polynomial multiplication
  • -
  • Efficient Polynomial Multiplication
  • -
  • Further simplification
  • -
  • A more efficient way of coding the above Convolution
  • -
  • Fourier series and Toeplitz matrices
  • -
  • Generalizing the above one-dimensional case
  • -
  • Two-dimensional Objects
  • -
  • CNNs in more detail
  • -
  • Performing a discrete convolution with padding ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Set of filters
  • -
  • Pooling
  • -
  • No zero padding, unit strides
  • -
  • Zero padding, unit strides
  • -
  • Half (same) padding
  • -
  • Full padding
  • -
  • Pooling arithmetic
  • -
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Building our own CNN code
  • -
  •    List of contents:
  • -
  •    Schedulers
  • -
  •    Usage of schedulers
  • -
  •    Cost functions
  • -
  •    Usage of cost functions
  • -
  •    Activation functions
  • -
  •    Usage of activation functions
  • -
  •    Convolution
  • -
  •    Layers
  • -
  •    Convolution2DLayer: convolution in a hidden layer
  • -
  •    Backpropagation in the convolutional layer
  • -
  •    Demonstration
  • -
  •    Pooling Layer
  • -
  •    Flattening Layer
  • -
  •    Fully Connected Layers
  • -
  •    Optimized Convolution2DLayer
  • -
  •    The Convolutional Neural Network (CNN)
  • -
  •    Usage of CNN code
  • -
  •    Additional Remarks
  • -
  •    Remarks on the speed
  • -
  •    Convolution using separable kernels
  • -
  •    Convolution in the Fourier domain
  • -
  • Building convolutional neural networks in Tensorflow and Keras
  • -
  • Setting it up
  • -
  • The MNIST dataset again
  • -
  • Strong correlations
  • -
  • Layers of a CNN
  • -
  • Systematic reduction
  • -
  • Prerequisites: Collect and pre-process data
  • -
  • Importing Keras and Tensorflow
  • -
  • Running with Keras
  • -
  • Final part
  • -
  • Final visualization
  • +
  • How to do image compression before the era of deep learning
  • +
  • The SVD example
  • +
  • Mathematics of CNNs
  • +
  • Mathematics of CNNs
  • +
  • Convolution Examples: Polynomial multiplication
  • +
  • Efficient Polynomial Multiplication
  • +
  • Further simplification
  • +
  • A more efficient way of coding the above Convolution
  • +
  • Commutative process
  • +
  • Toeplitz matrices
  • +
  • Fourier series and Toeplitz matrices
  • +
  • Generalizing the above one-dimensional case
  • +
  • Memory considerations
  • +
  • Padding
  • +
  • New vector
  • +
  • Rewriting as dot products
  • +
  • Cross correlation
  • +
  • Two-dimensional objects
  • +
  • CNNs in more detail, simple example
  • +
  • The convolution stage
  • +
  • Finding the number of parameters
  • +
  • New image (or volume)
  • +
  • Parameters to train, common settings
  • +
  • Examples of CNN setups
  • +
  • Summarizing: Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Pooling
  • +
  • Pooling arithmetic
  • +
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Building convolutional neural networks in Tensorflow and Keras
  • +
  • Setting it up
  • +
  • The MNIST dataset again
  • +
  • Strong correlations
  • +
  • Layers of a CNN
  • +
  • Systematic reduction
  • +
  • Prerequisites: Collect and pre-process data
  • +
  • Importing Keras and Tensorflow
  • +
  • Running with Keras
  • +
  • Final part
  • +
  • Final visualization
  • +
  • The CIFAR01 data set
  • +
  • Verifying the data set
  • +
  • Set up the model
  • +
  • Add Dense layers on top
  • +
  • Compile and train the model
  • +
  • Finally, evaluate the model
  • +
  • Building our own CNN code
  • +
  •    List of contents:
  • +
  •    Schedulers
  • +
  •    Usage of schedulers
  • +
  •    Cost functions
  • +
  •    Usage of cost functions
  • +
  •    Activation functions
  • +
  •    Usage of activation functions
  • +
  •    Convolution
  • +
  •    Layers
  • +
  •    Convolution2DLayer: convolution in a hidden layer
  • +
  •    Backpropagation in the convolutional layer
  • +
  •    Demonstration
  • +
  •    Pooling Layer
  • +
  •    Flattening Layer
  • +
  •    Fully Connected Layers
  • +
  •    Optimized Convolution2DLayer
  • +
  •    The Convolutional Neural Network (CNN)
  • +
  •    Usage of CNN code
  • +
  •    Additional Remarks
  • +
  •    Remarks on the speed
  • +
  •    Convolution using separable kernels
  • +
  •    Convolution in the Fourier domain
  • @@ -308,43 +350,16 @@ MathJax.Hub.Config({

     

     

     

    -

    Generalizing the above one-dimensional case

    +

    Further simplification

    -

    In order to align the above simple case with the more general convolution cases, we rename \( \boldsymbol{\alpha} \), whose length is \( m=3 \), with \( \boldsymbol{w} \). -We will interpret \( \boldsymbol{w} \) as a weight/filter function with which we want to perform the convolution with an input varibale \( \boldsymbol{x} \). -We replace thus \( \boldsymbol{\beta} \) with \( \boldsymbol{x} \) and \( \boldsymbol{\delta} \) with \( \boldsymbol{s} \) and have +

    Although we may have redundant operations with some few zeros for \( \beta_i \), we can rewrite the above sum in a more compact way as

    +$$ +\delta_i = \sum_{k=0}^{k=m-1}\alpha_k\beta_{i-k}, +$$ + +

    where \( m=3 \) in our case, the maximum length of +the vector \( \alpha \). Note that the vector \( \boldsymbol{\beta} \) has length \( n=4 \). Below we will find an even more efficient representation.

    -$$ -s(i) \left(x*w\right)(i)= \sum_{k=0}^{k=m-1}w(k)x(i-k), -$$ - -

    where \( m=3 \) in our case, the maximum length of the vector \( \boldsymbol{w} \). -Here the symbol \( * \) represents the mathematical operation of convolution. -

    -

    Two-dimensional Objects

    - -

    We are now ready to start studying the discrete convolutions relevant for convolutional neural networks. -We often use convolutions over more than one dimension at a time. If -we have a two-dimensional image \( X \) as input, we can have a filter -defined by a two-dimensional kernel/weight/filter \( W \). This leads to an output \( Y \) -

    - -$$ -Y(i,j)=(X * W)(i,j) = \sum_m\sum_n X(m,n)W(i-m,j-n). -$$ - -

    Convolution is a commutative process, which means we can rewrite this equation as

    -$$ -Y(i,j)=(X * W)(i,j) = \sum_m\sum_n X(i-m,j-n)W(m,n). -$$ - -

    Normally the latter is more straightforward to implement in a machine larning library since there is less variation in the range of values of \( m \) and \( n \).

    - -

    Many deep learning libraries implement cross-correlation instead of convolution (although it is referred to s convolution)

    -$$ -Y(i,j)=(X * W)(i,j) = \sum_m\sum_n X(i+m,j+n)W(m,n). -$$ -

    @@ -371,7 +386,7 @@ $$

  • 32
  • 33
  • ...
  • -
  • 47
  • +
  • 62
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs024.html b/doc/pub/week44/html/._week44-bs024.html index 87ec16d92..5c0d35788 100644 --- a/doc/pub/week44/html/._week44-bs024.html +++ b/doc/pub/week44/html/._week44-bs024.html @@ -75,6 +75,12 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d None, 'a-deep-cnn-model-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Key Idea', 2, None, 'key-idea'), + ('How to do image compression before the era of deep learning', + 2, + None, + 'how-to-do-image-compression-before-the-era-of-deep-learning'), + ('The SVD example', 2, None, 'the-svd-example'), + ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Convolution Examples: Polynomial multiplication', 2, @@ -89,6 +95,8 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'a-more-efficient-way-of-coding-the-above-convolution'), + ('Commutative process', 2, None, 'commutative-process'), + ('Toeplitz matrices', 2, None, 'toeplitz-matrices'), ('Fourier series and Toeplitz matrices', 2, None, @@ -97,36 +105,75 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'generalizing-the-above-one-dimensional-case'), - ('Two-dimensional Objects', 2, None, 'two-dimensional-objects'), - ('CNNs in more detail', 2, None, 'cnns-in-more-detail'), - ('Performing a discrete convolution with padding ("From Raschka ' - 'et al":"https://github.com/rasbt/machine-learning-book")', + ('Memory considerations', 2, None, 'memory-considerations'), + ('Padding', 2, None, 'padding'), + ('New vector', 2, None, 'new-vector'), + ('Rewriting as dot products', 2, None, - 'performing-a-discrete-convolution-with-padding-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Performing a general discrete convolution ("From Raschka et ' + 'rewriting-as-dot-products'), + ('Cross correlation', 2, None, 'cross-correlation'), + ('Two-dimensional objects', 2, None, 'two-dimensional-objects'), + ('CNNs in more detail, simple example', + 2, + None, + 'cnns-in-more-detail-simple-example'), + ('The convolution stage', 2, None, 'the-convolution-stage'), + ('Finding the number of parameters', + 2, + None, + 'finding-the-number-of-parameters'), + ('New image (or volume)', 2, None, 'new-image-or-volume'), + ('Parameters to train, common settings', + 2, + None, + 'parameters-to-train-common-settings'), + ('Examples of CNN setups', 2, None, 'examples-of-cnn-setups'), + ('Summarizing: Performing a general discrete convolution ("From ' + 'Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, - 'performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Set of filters', 2, None, 'set-of-filters'), + 'summarizing-performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Pooling', 2, None, 'pooling'), - ('No zero padding, unit strides', - 2, - None, - 'no-zero-padding-unit-strides'), - ('Zero padding, unit strides', - 2, - None, - 'zero-padding-unit-strides'), - ('Half (same) padding', 2, None, 'half-same-padding'), - ('Full padding', 2, None, 'full-padding'), ('Pooling arithmetic', 2, None, 'pooling-arithmetic'), ('Pooling types ("From Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, 'pooling-types-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), + ('Building convolutional neural networks in Tensorflow and Keras', + 2, + None, + 'building-convolutional-neural-networks-in-tensorflow-and-keras'), + ('Setting it up', 2, None, 'setting-it-up'), + ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), + ('Strong correlations', 2, None, 'strong-correlations'), + ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), + ('Systematic reduction', 2, None, 'systematic-reduction'), + ('Prerequisites: Collect and pre-process data', + 2, + None, + 'prerequisites-collect-and-pre-process-data'), + ('Importing Keras and Tensorflow', + 2, + None, + 'importing-keras-and-tensorflow'), + ('Running with Keras', 2, None, 'running-with-keras'), + ('Final part', 2, None, 'final-part'), + ('Final visualization', 2, None, 'final-visualization'), + ('The CIFAR01 data set', 2, None, 'the-cifar01-data-set'), + ('Verifying the data set', 2, None, 'verifying-the-data-set'), + ('Set up the model', 2, None, 'set-up-the-model'), + ('Add Dense layers on top', 2, None, 'add-dense-layers-on-top'), + ('Compile and train the model', + 2, + None, + 'compile-and-train-the-model'), + ('Finally, evaluate the model', + 2, + None, + 'finally-evaluate-the-model'), ('Building our own CNN code', 2, None, @@ -173,27 +220,7 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Convolution in the Fourier domain', 3, None, - 'convolution-in-the-fourier-domain'), - ('Building convolutional neural networks in Tensorflow and Keras', - 2, - None, - 'building-convolutional-neural-networks-in-tensorflow-and-keras'), - ('Setting it up', 2, None, 'setting-it-up'), - ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), - ('Strong correlations', 2, None, 'strong-correlations'), - ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), - ('Systematic reduction', 2, None, 'systematic-reduction'), - ('Prerequisites: Collect and pre-process data', - 2, - None, - 'prerequisites-collect-and-pre-process-data'), - ('Importing Keras and Tensorflow', - 2, - None, - 'importing-keras-and-tensorflow'), - ('Running with Keras', 2, None, 'running-with-keras'), - ('Final part', 2, None, 'final-part'), - ('Final visualization', 2, None, 'final-visualization')]} + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -244,59 +271,74 @@ MathJax.Hub.Config({
  • CNNs in brief
  • A deep CNN model ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • Key Idea
  • -
  • Mathematics of CNNs
  • -
  • Convolution Examples: Polynomial multiplication
  • -
  • Efficient Polynomial Multiplication
  • -
  • Further simplification
  • -
  • A more efficient way of coding the above Convolution
  • -
  • Fourier series and Toeplitz matrices
  • -
  • Generalizing the above one-dimensional case
  • -
  • Two-dimensional Objects
  • -
  • CNNs in more detail
  • -
  • Performing a discrete convolution with padding ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Set of filters
  • -
  • Pooling
  • -
  • No zero padding, unit strides
  • -
  • Zero padding, unit strides
  • -
  • Half (same) padding
  • -
  • Full padding
  • -
  • Pooling arithmetic
  • -
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Building our own CNN code
  • -
  •    List of contents:
  • -
  •    Schedulers
  • -
  •    Usage of schedulers
  • -
  •    Cost functions
  • -
  •    Usage of cost functions
  • -
  •    Activation functions
  • -
  •    Usage of activation functions
  • -
  •    Convolution
  • -
  •    Layers
  • -
  •    Convolution2DLayer: convolution in a hidden layer
  • -
  •    Backpropagation in the convolutional layer
  • -
  •    Demonstration
  • -
  •    Pooling Layer
  • -
  •    Flattening Layer
  • -
  •    Fully Connected Layers
  • -
  •    Optimized Convolution2DLayer
  • -
  •    The Convolutional Neural Network (CNN)
  • -
  •    Usage of CNN code
  • -
  •    Additional Remarks
  • -
  •    Remarks on the speed
  • -
  •    Convolution using separable kernels
  • -
  •    Convolution in the Fourier domain
  • -
  • Building convolutional neural networks in Tensorflow and Keras
  • -
  • Setting it up
  • -
  • The MNIST dataset again
  • -
  • Strong correlations
  • -
  • Layers of a CNN
  • -
  • Systematic reduction
  • -
  • Prerequisites: Collect and pre-process data
  • -
  • Importing Keras and Tensorflow
  • -
  • Running with Keras
  • -
  • Final part
  • -
  • Final visualization
  • +
  • How to do image compression before the era of deep learning
  • +
  • The SVD example
  • +
  • Mathematics of CNNs
  • +
  • Mathematics of CNNs
  • +
  • Convolution Examples: Polynomial multiplication
  • +
  • Efficient Polynomial Multiplication
  • +
  • Further simplification
  • +
  • A more efficient way of coding the above Convolution
  • +
  • Commutative process
  • +
  • Toeplitz matrices
  • +
  • Fourier series and Toeplitz matrices
  • +
  • Generalizing the above one-dimensional case
  • +
  • Memory considerations
  • +
  • Padding
  • +
  • New vector
  • +
  • Rewriting as dot products
  • +
  • Cross correlation
  • +
  • Two-dimensional objects
  • +
  • CNNs in more detail, simple example
  • +
  • The convolution stage
  • +
  • Finding the number of parameters
  • +
  • New image (or volume)
  • +
  • Parameters to train, common settings
  • +
  • Examples of CNN setups
  • +
  • Summarizing: Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Pooling
  • +
  • Pooling arithmetic
  • +
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Building convolutional neural networks in Tensorflow and Keras
  • +
  • Setting it up
  • +
  • The MNIST dataset again
  • +
  • Strong correlations
  • +
  • Layers of a CNN
  • +
  • Systematic reduction
  • +
  • Prerequisites: Collect and pre-process data
  • +
  • Importing Keras and Tensorflow
  • +
  • Running with Keras
  • +
  • Final part
  • +
  • Final visualization
  • +
  • The CIFAR01 data set
  • +
  • Verifying the data set
  • +
  • Set up the model
  • +
  • Add Dense layers on top
  • +
  • Compile and train the model
  • +
  • Finally, evaluate the model
  • +
  • Building our own CNN code
  • +
  •    List of contents:
  • +
  •    Schedulers
  • +
  •    Usage of schedulers
  • +
  •    Cost functions
  • +
  •    Usage of cost functions
  • +
  •    Activation functions
  • +
  •    Usage of activation functions
  • +
  •    Convolution
  • +
  •    Layers
  • +
  •    Convolution2DLayer: convolution in a hidden layer
  • +
  •    Backpropagation in the convolutional layer
  • +
  •    Demonstration
  • +
  •    Pooling Layer
  • +
  •    Flattening Layer
  • +
  •    Fully Connected Layers
  • +
  •    Optimized Convolution2DLayer
  • +
  •    The Convolutional Neural Network (CNN)
  • +
  •    Usage of CNN code
  • +
  •    Additional Remarks
  • +
  •    Remarks on the speed
  • +
  •    Convolution using separable kernels
  • +
  •    Convolution in the Fourier domain
  • @@ -308,64 +350,23 @@ MathJax.Hub.Config({

     

     

     

    -

    CNNs in more detail

    +

    A more efficient way of coding the above Convolution

    -

    Let assume we have an input matrix \( X \) of dimensionality \( 3\times 3 \) -and a \( 2\times 2 \) filter \( W \) given by the following matrices +

    Since we only have a finite number of \( \alpha \) and \( \beta \) values +which are non-zero, we can rewrite the above convolution expressions +as a matrix-vector multiplication

    $$ -\boldsymbol{X}=\begin{bmatrix}x_{00} & x_{01} & x_{02} \\ - x_{10} & x_{11} & x_{12} \\ - x_{20} & x_{21} & x_{22} \end{bmatrix}, +\boldsymbol{\delta}=\begin{bmatrix}\alpha_0 & 0 & 0 & 0 \\ + \alpha_1 & \alpha_0 & 0 & 0 \\ + \alpha_2 & \alpha_1 & \alpha_0 & 0 \\ + 0 & \alpha_2 & \alpha_1 & \alpha_0 \\ + 0 & 0 & \alpha_2 & \alpha_1 \\ + 0 & 0 & 0 & \alpha_2 + \end{bmatrix}\begin{bmatrix} \beta_0 \\ \beta_1 \\ \beta_2 \\ \beta_3\end{bmatrix}. $$ -

    and

    -$$ -\boldsymbol{W}=\begin{bmatrix}w_{00} & w_{01} \\ - w_{10} & w_{11}\end{bmatrix}. -$$ - -

    We introduce now the hyperparameter \( S \) stride. Stride represents how the filter \( W \) moves the convolution process on the matrix \( X \). -We strongly recommend the repository on Arithmetic of deep learning by Dumoulin and Visin -

    - -

    Here we set the stride equal to \( S=1 \), which means that, starting with the element \( x_{00} \), the filter will act on \( 2\times 2 \) submatrices each time, starting with the upper corner and moving according to the stride value column by column.

    - -

    Here we perform the operation

    -$$ -Y_(i,j)=(X * W)(i,j) = \sum_m\sum_n X(i-m,j-n)W(m,n), -$$ - -

    and obtain

    -$$ -\boldsymbol{Y}=\begin{bmatrix}x_{00}w_{00}+x_{01}w_{01}+x_{10}w_{10}+x_{11}w_{11} & x_{01}w_{00}+x_{02}w_{01}+x_{11}w_{10}+x_{12}w_{11} \\ - x_{10}w_{00}+x_{11}w_{01}+x_{20}w_{10}+x_{21}w_{11} & x_{11}w_{00}+x_{12}w_{01}+x_{21}w_{10}+x_{22}w_{11}\end{bmatrix}. -$$ - -

    We can rewrite this operation in terms of a matrix-vector multiplication by defining a new vector where we flatten out the inputs as a vector \( \boldsymbol{X}' \) of length \( 9 \) and -a matrix \( \boldsymbol{W}' \) with dimension \( 4\times 9 \) as -

    - -$$ -\boldsymbol{X}'=\begin{bmatrix}x_{00} \\ x_{01} \\ x_{02} \\ x_{10} \\ x_{11} \\ x_{12} \\ x_{20} \\ x_{21} \\ x_{22} \end{bmatrix}, -$$ - -

    and the new matrix

    -$$ -\boldsymbol{W}'=\begin{bmatrix} w_{00} & w_{01} & 0 & w_{10} & w_{11} & 0 & 0 & 0 & 0 \\ - 0 & w_{00} & w_{01} & 0 & w_{10} & w_{11} & 0 & 0 & 0 \\ - 0 & 0 & 0 & w_{00} & w_{01} & 0 & w_{10} & w_{11} & 0 \\ - 0 & 0 & 0 & 0 & w_{00} & w_{01} & 0 & w_{10} & w_{11}\end{bmatrix}. -$$ - -

    We see easily that performing the matrix-vector multiplication \( \boldsymbol{W}'\boldsymbol{X}' \) is the same as the above convolution with stride \( S=1 \), that is

    - -$$ -Y=(\boldsymbol{W}*\boldsymbol{X}), -$$ - -

    is now given by \( \boldsymbol{W}'\boldsymbol{X}' \) which is a vector of length \( 4 \) instead of the originally resulting \( 2\times 2 \) output matrix.

    @@ -392,7 +393,7 @@ $$

  • 33
  • 34
  • ...
  • -
  • 47
  • +
  • 62
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs025.html b/doc/pub/week44/html/._week44-bs025.html index 15f2c31e1..f73cb55c2 100644 --- a/doc/pub/week44/html/._week44-bs025.html +++ b/doc/pub/week44/html/._week44-bs025.html @@ -75,6 +75,12 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d None, 'a-deep-cnn-model-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Key Idea', 2, None, 'key-idea'), + ('How to do image compression before the era of deep learning', + 2, + None, + 'how-to-do-image-compression-before-the-era-of-deep-learning'), + ('The SVD example', 2, None, 'the-svd-example'), + ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Convolution Examples: Polynomial multiplication', 2, @@ -89,6 +95,8 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'a-more-efficient-way-of-coding-the-above-convolution'), + ('Commutative process', 2, None, 'commutative-process'), + ('Toeplitz matrices', 2, None, 'toeplitz-matrices'), ('Fourier series and Toeplitz matrices', 2, None, @@ -97,36 +105,75 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'generalizing-the-above-one-dimensional-case'), - ('Two-dimensional Objects', 2, None, 'two-dimensional-objects'), - ('CNNs in more detail', 2, None, 'cnns-in-more-detail'), - ('Performing a discrete convolution with padding ("From Raschka ' - 'et al":"https://github.com/rasbt/machine-learning-book")', + ('Memory considerations', 2, None, 'memory-considerations'), + ('Padding', 2, None, 'padding'), + ('New vector', 2, None, 'new-vector'), + ('Rewriting as dot products', 2, None, - 'performing-a-discrete-convolution-with-padding-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Performing a general discrete convolution ("From Raschka et ' + 'rewriting-as-dot-products'), + ('Cross correlation', 2, None, 'cross-correlation'), + ('Two-dimensional objects', 2, None, 'two-dimensional-objects'), + ('CNNs in more detail, simple example', + 2, + None, + 'cnns-in-more-detail-simple-example'), + ('The convolution stage', 2, None, 'the-convolution-stage'), + ('Finding the number of parameters', + 2, + None, + 'finding-the-number-of-parameters'), + ('New image (or volume)', 2, None, 'new-image-or-volume'), + ('Parameters to train, common settings', + 2, + None, + 'parameters-to-train-common-settings'), + ('Examples of CNN setups', 2, None, 'examples-of-cnn-setups'), + ('Summarizing: Performing a general discrete convolution ("From ' + 'Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, - 'performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Set of filters', 2, None, 'set-of-filters'), + 'summarizing-performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Pooling', 2, None, 'pooling'), - ('No zero padding, unit strides', - 2, - None, - 'no-zero-padding-unit-strides'), - ('Zero padding, unit strides', - 2, - None, - 'zero-padding-unit-strides'), - ('Half (same) padding', 2, None, 'half-same-padding'), - ('Full padding', 2, None, 'full-padding'), ('Pooling arithmetic', 2, None, 'pooling-arithmetic'), ('Pooling types ("From Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, 'pooling-types-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), + ('Building convolutional neural networks in Tensorflow and Keras', + 2, + None, + 'building-convolutional-neural-networks-in-tensorflow-and-keras'), + ('Setting it up', 2, None, 'setting-it-up'), + ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), + ('Strong correlations', 2, None, 'strong-correlations'), + ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), + ('Systematic reduction', 2, None, 'systematic-reduction'), + ('Prerequisites: Collect and pre-process data', + 2, + None, + 'prerequisites-collect-and-pre-process-data'), + ('Importing Keras and Tensorflow', + 2, + None, + 'importing-keras-and-tensorflow'), + ('Running with Keras', 2, None, 'running-with-keras'), + ('Final part', 2, None, 'final-part'), + ('Final visualization', 2, None, 'final-visualization'), + ('The CIFAR01 data set', 2, None, 'the-cifar01-data-set'), + ('Verifying the data set', 2, None, 'verifying-the-data-set'), + ('Set up the model', 2, None, 'set-up-the-model'), + ('Add Dense layers on top', 2, None, 'add-dense-layers-on-top'), + ('Compile and train the model', + 2, + None, + 'compile-and-train-the-model'), + ('Finally, evaluate the model', + 2, + None, + 'finally-evaluate-the-model'), ('Building our own CNN code', 2, None, @@ -173,27 +220,7 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Convolution in the Fourier domain', 3, None, - 'convolution-in-the-fourier-domain'), - ('Building convolutional neural networks in Tensorflow and Keras', - 2, - None, - 'building-convolutional-neural-networks-in-tensorflow-and-keras'), - ('Setting it up', 2, None, 'setting-it-up'), - ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), - ('Strong correlations', 2, None, 'strong-correlations'), - ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), - ('Systematic reduction', 2, None, 'systematic-reduction'), - ('Prerequisites: Collect and pre-process data', - 2, - None, - 'prerequisites-collect-and-pre-process-data'), - ('Importing Keras and Tensorflow', - 2, - None, - 'importing-keras-and-tensorflow'), - ('Running with Keras', 2, None, 'running-with-keras'), - ('Final part', 2, None, 'final-part'), - ('Final visualization', 2, None, 'final-visualization')]} + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -244,59 +271,74 @@ MathJax.Hub.Config({
  • CNNs in brief
  • A deep CNN model ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • Key Idea
  • -
  • Mathematics of CNNs
  • -
  • Convolution Examples: Polynomial multiplication
  • -
  • Efficient Polynomial Multiplication
  • -
  • Further simplification
  • -
  • A more efficient way of coding the above Convolution
  • -
  • Fourier series and Toeplitz matrices
  • -
  • Generalizing the above one-dimensional case
  • -
  • Two-dimensional Objects
  • -
  • CNNs in more detail
  • -
  • Performing a discrete convolution with padding ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Set of filters
  • -
  • Pooling
  • -
  • No zero padding, unit strides
  • -
  • Zero padding, unit strides
  • -
  • Half (same) padding
  • -
  • Full padding
  • -
  • Pooling arithmetic
  • -
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Building our own CNN code
  • -
  •    List of contents:
  • -
  •    Schedulers
  • -
  •    Usage of schedulers
  • -
  •    Cost functions
  • -
  •    Usage of cost functions
  • -
  •    Activation functions
  • -
  •    Usage of activation functions
  • -
  •    Convolution
  • -
  •    Layers
  • -
  •    Convolution2DLayer: convolution in a hidden layer
  • -
  •    Backpropagation in the convolutional layer
  • -
  •    Demonstration
  • -
  •    Pooling Layer
  • -
  •    Flattening Layer
  • -
  •    Fully Connected Layers
  • -
  •    Optimized Convolution2DLayer
  • -
  •    The Convolutional Neural Network (CNN)
  • -
  •    Usage of CNN code
  • -
  •    Additional Remarks
  • -
  •    Remarks on the speed
  • -
  •    Convolution using separable kernels
  • -
  •    Convolution in the Fourier domain
  • -
  • Building convolutional neural networks in Tensorflow and Keras
  • -
  • Setting it up
  • -
  • The MNIST dataset again
  • -
  • Strong correlations
  • -
  • Layers of a CNN
  • -
  • Systematic reduction
  • -
  • Prerequisites: Collect and pre-process data
  • -
  • Importing Keras and Tensorflow
  • -
  • Running with Keras
  • -
  • Final part
  • -
  • Final visualization
  • +
  • How to do image compression before the era of deep learning
  • +
  • The SVD example
  • +
  • Mathematics of CNNs
  • +
  • Mathematics of CNNs
  • +
  • Convolution Examples: Polynomial multiplication
  • +
  • Efficient Polynomial Multiplication
  • +
  • Further simplification
  • +
  • A more efficient way of coding the above Convolution
  • +
  • Commutative process
  • +
  • Toeplitz matrices
  • +
  • Fourier series and Toeplitz matrices
  • +
  • Generalizing the above one-dimensional case
  • +
  • Memory considerations
  • +
  • Padding
  • +
  • New vector
  • +
  • Rewriting as dot products
  • +
  • Cross correlation
  • +
  • Two-dimensional objects
  • +
  • CNNs in more detail, simple example
  • +
  • The convolution stage
  • +
  • Finding the number of parameters
  • +
  • New image (or volume)
  • +
  • Parameters to train, common settings
  • +
  • Examples of CNN setups
  • +
  • Summarizing: Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Pooling
  • +
  • Pooling arithmetic
  • +
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Building convolutional neural networks in Tensorflow and Keras
  • +
  • Setting it up
  • +
  • The MNIST dataset again
  • +
  • Strong correlations
  • +
  • Layers of a CNN
  • +
  • Systematic reduction
  • +
  • Prerequisites: Collect and pre-process data
  • +
  • Importing Keras and Tensorflow
  • +
  • Running with Keras
  • +
  • Final part
  • +
  • Final visualization
  • +
  • The CIFAR01 data set
  • +
  • Verifying the data set
  • +
  • Set up the model
  • +
  • Add Dense layers on top
  • +
  • Compile and train the model
  • +
  • Finally, evaluate the model
  • +
  • Building our own CNN code
  • +
  •    List of contents:
  • +
  •    Schedulers
  • +
  •    Usage of schedulers
  • +
  •    Cost functions
  • +
  •    Usage of cost functions
  • +
  •    Activation functions
  • +
  •    Usage of activation functions
  • +
  •    Convolution
  • +
  •    Layers
  • +
  •    Convolution2DLayer: convolution in a hidden layer
  • +
  •    Backpropagation in the convolutional layer
  • +
  •    Demonstration
  • +
  •    Pooling Layer
  • +
  •    Flattening Layer
  • +
  •    Fully Connected Layers
  • +
  •    Optimized Convolution2DLayer
  • +
  •    The Convolutional Neural Network (CNN)
  • +
  •    Usage of CNN code
  • +
  •    Additional Remarks
  • +
  •    Remarks on the speed
  • +
  •    Convolution using separable kernels
  • +
  •    Convolution in the Fourier domain
  • @@ -308,15 +350,27 @@ MathJax.Hub.Config({

     

     

     

    -

    Performing a discrete convolution with padding (From Raschka et al)

    +

    Commutative process

    -
    -
    -
    -

    Figure 4: A deep CNN

    -
    -

    -
    +

    The process is commutative and we can easily see that we can rewrite the multiplication in terms of a matrix holding \( \beta \) and a vector holding \( \alpha \). +In this case we have +

    +$$ +\boldsymbol{\delta}=\begin{bmatrix}\beta_0 & 0 & 0 \\ + \beta_1 & \beta_0 & 0 \\ + \beta_2 & \beta_1 & \beta_0 \\ + \beta_3 & \beta_2 & \beta_1 \\ + 0 & \beta_3 & \beta_2 \\ + 0 & 0 & \beta_3 + \end{bmatrix}\begin{bmatrix} \alpha_0 \\ \alpha_1 \\ \alpha_2\end{bmatrix}. +$$ + +

    Note that the use of these matrices is for mathematical purposes only +and not implementation purposes. When implementing the above equation +we do not encode (and allocate memory) the matrices explicitely. We +rather code the convolutions in the minimal memory footprint that they +require. +

    @@ -343,7 +397,7 @@ MathJax.Hub.Config({

  • 34
  • 35
  • ...
  • -
  • 47
  • +
  • 62
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs026.html b/doc/pub/week44/html/._week44-bs026.html index 3bae34559..e5ac726f9 100644 --- a/doc/pub/week44/html/._week44-bs026.html +++ b/doc/pub/week44/html/._week44-bs026.html @@ -75,6 +75,12 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d None, 'a-deep-cnn-model-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Key Idea', 2, None, 'key-idea'), + ('How to do image compression before the era of deep learning', + 2, + None, + 'how-to-do-image-compression-before-the-era-of-deep-learning'), + ('The SVD example', 2, None, 'the-svd-example'), + ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Convolution Examples: Polynomial multiplication', 2, @@ -89,6 +95,8 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'a-more-efficient-way-of-coding-the-above-convolution'), + ('Commutative process', 2, None, 'commutative-process'), + ('Toeplitz matrices', 2, None, 'toeplitz-matrices'), ('Fourier series and Toeplitz matrices', 2, None, @@ -97,36 +105,75 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'generalizing-the-above-one-dimensional-case'), - ('Two-dimensional Objects', 2, None, 'two-dimensional-objects'), - ('CNNs in more detail', 2, None, 'cnns-in-more-detail'), - ('Performing a discrete convolution with padding ("From Raschka ' - 'et al":"https://github.com/rasbt/machine-learning-book")', + ('Memory considerations', 2, None, 'memory-considerations'), + ('Padding', 2, None, 'padding'), + ('New vector', 2, None, 'new-vector'), + ('Rewriting as dot products', 2, None, - 'performing-a-discrete-convolution-with-padding-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Performing a general discrete convolution ("From Raschka et ' + 'rewriting-as-dot-products'), + ('Cross correlation', 2, None, 'cross-correlation'), + ('Two-dimensional objects', 2, None, 'two-dimensional-objects'), + ('CNNs in more detail, simple example', + 2, + None, + 'cnns-in-more-detail-simple-example'), + ('The convolution stage', 2, None, 'the-convolution-stage'), + ('Finding the number of parameters', + 2, + None, + 'finding-the-number-of-parameters'), + ('New image (or volume)', 2, None, 'new-image-or-volume'), + ('Parameters to train, common settings', + 2, + None, + 'parameters-to-train-common-settings'), + ('Examples of CNN setups', 2, None, 'examples-of-cnn-setups'), + ('Summarizing: Performing a general discrete convolution ("From ' + 'Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, - 'performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Set of filters', 2, None, 'set-of-filters'), + 'summarizing-performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Pooling', 2, None, 'pooling'), - ('No zero padding, unit strides', - 2, - None, - 'no-zero-padding-unit-strides'), - ('Zero padding, unit strides', - 2, - None, - 'zero-padding-unit-strides'), - ('Half (same) padding', 2, None, 'half-same-padding'), - ('Full padding', 2, None, 'full-padding'), ('Pooling arithmetic', 2, None, 'pooling-arithmetic'), ('Pooling types ("From Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, 'pooling-types-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), + ('Building convolutional neural networks in Tensorflow and Keras', + 2, + None, + 'building-convolutional-neural-networks-in-tensorflow-and-keras'), + ('Setting it up', 2, None, 'setting-it-up'), + ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), + ('Strong correlations', 2, None, 'strong-correlations'), + ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), + ('Systematic reduction', 2, None, 'systematic-reduction'), + ('Prerequisites: Collect and pre-process data', + 2, + None, + 'prerequisites-collect-and-pre-process-data'), + ('Importing Keras and Tensorflow', + 2, + None, + 'importing-keras-and-tensorflow'), + ('Running with Keras', 2, None, 'running-with-keras'), + ('Final part', 2, None, 'final-part'), + ('Final visualization', 2, None, 'final-visualization'), + ('The CIFAR01 data set', 2, None, 'the-cifar01-data-set'), + ('Verifying the data set', 2, None, 'verifying-the-data-set'), + ('Set up the model', 2, None, 'set-up-the-model'), + ('Add Dense layers on top', 2, None, 'add-dense-layers-on-top'), + ('Compile and train the model', + 2, + None, + 'compile-and-train-the-model'), + ('Finally, evaluate the model', + 2, + None, + 'finally-evaluate-the-model'), ('Building our own CNN code', 2, None, @@ -173,27 +220,7 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Convolution in the Fourier domain', 3, None, - 'convolution-in-the-fourier-domain'), - ('Building convolutional neural networks in Tensorflow and Keras', - 2, - None, - 'building-convolutional-neural-networks-in-tensorflow-and-keras'), - ('Setting it up', 2, None, 'setting-it-up'), - ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), - ('Strong correlations', 2, None, 'strong-correlations'), - ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), - ('Systematic reduction', 2, None, 'systematic-reduction'), - ('Prerequisites: Collect and pre-process data', - 2, - None, - 'prerequisites-collect-and-pre-process-data'), - ('Importing Keras and Tensorflow', - 2, - None, - 'importing-keras-and-tensorflow'), - ('Running with Keras', 2, None, 'running-with-keras'), - ('Final part', 2, None, 'final-part'), - ('Final visualization', 2, None, 'final-visualization')]} + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -244,59 +271,74 @@ MathJax.Hub.Config({
  • CNNs in brief
  • A deep CNN model ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • Key Idea
  • -
  • Mathematics of CNNs
  • -
  • Convolution Examples: Polynomial multiplication
  • -
  • Efficient Polynomial Multiplication
  • -
  • Further simplification
  • -
  • A more efficient way of coding the above Convolution
  • -
  • Fourier series and Toeplitz matrices
  • -
  • Generalizing the above one-dimensional case
  • -
  • Two-dimensional Objects
  • -
  • CNNs in more detail
  • -
  • Performing a discrete convolution with padding ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Set of filters
  • -
  • Pooling
  • -
  • No zero padding, unit strides
  • -
  • Zero padding, unit strides
  • -
  • Half (same) padding
  • -
  • Full padding
  • -
  • Pooling arithmetic
  • -
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Building our own CNN code
  • -
  •    List of contents:
  • -
  •    Schedulers
  • -
  •    Usage of schedulers
  • -
  •    Cost functions
  • -
  •    Usage of cost functions
  • -
  •    Activation functions
  • -
  •    Usage of activation functions
  • -
  •    Convolution
  • -
  •    Layers
  • -
  •    Convolution2DLayer: convolution in a hidden layer
  • -
  •    Backpropagation in the convolutional layer
  • -
  •    Demonstration
  • -
  •    Pooling Layer
  • -
  •    Flattening Layer
  • -
  •    Fully Connected Layers
  • -
  •    Optimized Convolution2DLayer
  • -
  •    The Convolutional Neural Network (CNN)
  • -
  •    Usage of CNN code
  • -
  •    Additional Remarks
  • -
  •    Remarks on the speed
  • -
  •    Convolution using separable kernels
  • -
  •    Convolution in the Fourier domain
  • -
  • Building convolutional neural networks in Tensorflow and Keras
  • -
  • Setting it up
  • -
  • The MNIST dataset again
  • -
  • Strong correlations
  • -
  • Layers of a CNN
  • -
  • Systematic reduction
  • -
  • Prerequisites: Collect and pre-process data
  • -
  • Importing Keras and Tensorflow
  • -
  • Running with Keras
  • -
  • Final part
  • -
  • Final visualization
  • +
  • How to do image compression before the era of deep learning
  • +
  • The SVD example
  • +
  • Mathematics of CNNs
  • +
  • Mathematics of CNNs
  • +
  • Convolution Examples: Polynomial multiplication
  • +
  • Efficient Polynomial Multiplication
  • +
  • Further simplification
  • +
  • A more efficient way of coding the above Convolution
  • +
  • Commutative process
  • +
  • Toeplitz matrices
  • +
  • Fourier series and Toeplitz matrices
  • +
  • Generalizing the above one-dimensional case
  • +
  • Memory considerations
  • +
  • Padding
  • +
  • New vector
  • +
  • Rewriting as dot products
  • +
  • Cross correlation
  • +
  • Two-dimensional objects
  • +
  • CNNs in more detail, simple example
  • +
  • The convolution stage
  • +
  • Finding the number of parameters
  • +
  • New image (or volume)
  • +
  • Parameters to train, common settings
  • +
  • Examples of CNN setups
  • +
  • Summarizing: Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Pooling
  • +
  • Pooling arithmetic
  • +
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Building convolutional neural networks in Tensorflow and Keras
  • +
  • Setting it up
  • +
  • The MNIST dataset again
  • +
  • Strong correlations
  • +
  • Layers of a CNN
  • +
  • Systematic reduction
  • +
  • Prerequisites: Collect and pre-process data
  • +
  • Importing Keras and Tensorflow
  • +
  • Running with Keras
  • +
  • Final part
  • +
  • Final visualization
  • +
  • The CIFAR01 data set
  • +
  • Verifying the data set
  • +
  • Set up the model
  • +
  • Add Dense layers on top
  • +
  • Compile and train the model
  • +
  • Finally, evaluate the model
  • +
  • Building our own CNN code
  • +
  •    List of contents:
  • +
  •    Schedulers
  • +
  •    Usage of schedulers
  • +
  •    Cost functions
  • +
  •    Usage of cost functions
  • +
  •    Activation functions
  • +
  •    Usage of activation functions
  • +
  •    Convolution
  • +
  •    Layers
  • +
  •    Convolution2DLayer: convolution in a hidden layer
  • +
  •    Backpropagation in the convolutional layer
  • +
  •    Demonstration
  • +
  •    Pooling Layer
  • +
  •    Flattening Layer
  • +
  •    Fully Connected Layers
  • +
  •    Optimized Convolution2DLayer
  • +
  •    The Convolutional Neural Network (CNN)
  • +
  •    Usage of CNN code
  • +
  •    Additional Remarks
  • +
  •    Remarks on the speed
  • +
  •    Convolution using separable kernels
  • +
  •    Convolution in the Fourier domain
  • @@ -308,15 +350,32 @@ MathJax.Hub.Config({

     

     

     

    -

    Performing a general discrete convolution (From Raschka et al)

    +

    Toeplitz matrices

    -
    -
    -
    -

    Figure 5: A deep CNN

    -
    -

    -
    +

    The above matrices are examples of so-called Toeplitz +matrices. A +Toeplitz matrix is a matrix in which each descending diagonal from +left to right is constant. For instance the last matrix, which we +rewrite as +

    +$$ +\boldsymbol{A}=\begin{bmatrix}a_0 & 0 & 0 \\ + a_1 & a_0 & 0 \\ + a_2 & a_1 & a_0 \\ + a_3 & a_2 & a_1 \\ + 0 & a_3 & a_2 \\ + 0 & 0 & a_3 + \end{bmatrix}, +$$ + +

    with elements \( a_{ii}=a_{i+1,j+1}=a_{i-j} \) is an example of a Toeplitz +matrix. Such a matrix does not need to be a square matrix. Toeplitz +matrices are also closely connected with Fourier series, because the multiplication operator by a trigonometric +polynomial, compressed to a finite-dimensional space, can be +represented by such a matrix. The example above shows that we can +represent linear convolution as multiplication of a Toeplitz matrix by +a vector. +

    @@ -343,7 +402,7 @@ MathJax.Hub.Config({

  • 35
  • 36
  • ...
  • -
  • 47
  • +
  • 62
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs027.html b/doc/pub/week44/html/._week44-bs027.html index ae07a062f..75c51ee78 100644 --- a/doc/pub/week44/html/._week44-bs027.html +++ b/doc/pub/week44/html/._week44-bs027.html @@ -75,6 +75,12 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d None, 'a-deep-cnn-model-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Key Idea', 2, None, 'key-idea'), + ('How to do image compression before the era of deep learning', + 2, + None, + 'how-to-do-image-compression-before-the-era-of-deep-learning'), + ('The SVD example', 2, None, 'the-svd-example'), + ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Convolution Examples: Polynomial multiplication', 2, @@ -89,6 +95,8 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'a-more-efficient-way-of-coding-the-above-convolution'), + ('Commutative process', 2, None, 'commutative-process'), + ('Toeplitz matrices', 2, None, 'toeplitz-matrices'), ('Fourier series and Toeplitz matrices', 2, None, @@ -97,36 +105,75 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'generalizing-the-above-one-dimensional-case'), - ('Two-dimensional Objects', 2, None, 'two-dimensional-objects'), - ('CNNs in more detail', 2, None, 'cnns-in-more-detail'), - ('Performing a discrete convolution with padding ("From Raschka ' - 'et al":"https://github.com/rasbt/machine-learning-book")', + ('Memory considerations', 2, None, 'memory-considerations'), + ('Padding', 2, None, 'padding'), + ('New vector', 2, None, 'new-vector'), + ('Rewriting as dot products', 2, None, - 'performing-a-discrete-convolution-with-padding-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Performing a general discrete convolution ("From Raschka et ' + 'rewriting-as-dot-products'), + ('Cross correlation', 2, None, 'cross-correlation'), + ('Two-dimensional objects', 2, None, 'two-dimensional-objects'), + ('CNNs in more detail, simple example', + 2, + None, + 'cnns-in-more-detail-simple-example'), + ('The convolution stage', 2, None, 'the-convolution-stage'), + ('Finding the number of parameters', + 2, + None, + 'finding-the-number-of-parameters'), + ('New image (or volume)', 2, None, 'new-image-or-volume'), + ('Parameters to train, common settings', + 2, + None, + 'parameters-to-train-common-settings'), + ('Examples of CNN setups', 2, None, 'examples-of-cnn-setups'), + ('Summarizing: Performing a general discrete convolution ("From ' + 'Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, - 'performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Set of filters', 2, None, 'set-of-filters'), + 'summarizing-performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Pooling', 2, None, 'pooling'), - ('No zero padding, unit strides', - 2, - None, - 'no-zero-padding-unit-strides'), - ('Zero padding, unit strides', - 2, - None, - 'zero-padding-unit-strides'), - ('Half (same) padding', 2, None, 'half-same-padding'), - ('Full padding', 2, None, 'full-padding'), ('Pooling arithmetic', 2, None, 'pooling-arithmetic'), ('Pooling types ("From Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, 'pooling-types-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), + ('Building convolutional neural networks in Tensorflow and Keras', + 2, + None, + 'building-convolutional-neural-networks-in-tensorflow-and-keras'), + ('Setting it up', 2, None, 'setting-it-up'), + ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), + ('Strong correlations', 2, None, 'strong-correlations'), + ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), + ('Systematic reduction', 2, None, 'systematic-reduction'), + ('Prerequisites: Collect and pre-process data', + 2, + None, + 'prerequisites-collect-and-pre-process-data'), + ('Importing Keras and Tensorflow', + 2, + None, + 'importing-keras-and-tensorflow'), + ('Running with Keras', 2, None, 'running-with-keras'), + ('Final part', 2, None, 'final-part'), + ('Final visualization', 2, None, 'final-visualization'), + ('The CIFAR01 data set', 2, None, 'the-cifar01-data-set'), + ('Verifying the data set', 2, None, 'verifying-the-data-set'), + ('Set up the model', 2, None, 'set-up-the-model'), + ('Add Dense layers on top', 2, None, 'add-dense-layers-on-top'), + ('Compile and train the model', + 2, + None, + 'compile-and-train-the-model'), + ('Finally, evaluate the model', + 2, + None, + 'finally-evaluate-the-model'), ('Building our own CNN code', 2, None, @@ -173,27 +220,7 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Convolution in the Fourier domain', 3, None, - 'convolution-in-the-fourier-domain'), - ('Building convolutional neural networks in Tensorflow and Keras', - 2, - None, - 'building-convolutional-neural-networks-in-tensorflow-and-keras'), - ('Setting it up', 2, None, 'setting-it-up'), - ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), - ('Strong correlations', 2, None, 'strong-correlations'), - ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), - ('Systematic reduction', 2, None, 'systematic-reduction'), - ('Prerequisites: Collect and pre-process data', - 2, - None, - 'prerequisites-collect-and-pre-process-data'), - ('Importing Keras and Tensorflow', - 2, - None, - 'importing-keras-and-tensorflow'), - ('Running with Keras', 2, None, 'running-with-keras'), - ('Final part', 2, None, 'final-part'), - ('Final visualization', 2, None, 'final-visualization')]} + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -244,59 +271,74 @@ MathJax.Hub.Config({
  • CNNs in brief
  • A deep CNN model ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • Key Idea
  • -
  • Mathematics of CNNs
  • -
  • Convolution Examples: Polynomial multiplication
  • -
  • Efficient Polynomial Multiplication
  • -
  • Further simplification
  • -
  • A more efficient way of coding the above Convolution
  • -
  • Fourier series and Toeplitz matrices
  • -
  • Generalizing the above one-dimensional case
  • -
  • Two-dimensional Objects
  • -
  • CNNs in more detail
  • -
  • Performing a discrete convolution with padding ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Set of filters
  • -
  • Pooling
  • -
  • No zero padding, unit strides
  • -
  • Zero padding, unit strides
  • -
  • Half (same) padding
  • -
  • Full padding
  • -
  • Pooling arithmetic
  • -
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Building our own CNN code
  • -
  •    List of contents:
  • -
  •    Schedulers
  • -
  •    Usage of schedulers
  • -
  •    Cost functions
  • -
  •    Usage of cost functions
  • -
  •    Activation functions
  • -
  •    Usage of activation functions
  • -
  •    Convolution
  • -
  •    Layers
  • -
  •    Convolution2DLayer: convolution in a hidden layer
  • -
  •    Backpropagation in the convolutional layer
  • -
  •    Demonstration
  • -
  •    Pooling Layer
  • -
  •    Flattening Layer
  • -
  •    Fully Connected Layers
  • -
  •    Optimized Convolution2DLayer
  • -
  •    The Convolutional Neural Network (CNN)
  • -
  •    Usage of CNN code
  • -
  •    Additional Remarks
  • -
  •    Remarks on the speed
  • -
  •    Convolution using separable kernels
  • -
  •    Convolution in the Fourier domain
  • -
  • Building convolutional neural networks in Tensorflow and Keras
  • -
  • Setting it up
  • -
  • The MNIST dataset again
  • -
  • Strong correlations
  • -
  • Layers of a CNN
  • -
  • Systematic reduction
  • -
  • Prerequisites: Collect and pre-process data
  • -
  • Importing Keras and Tensorflow
  • -
  • Running with Keras
  • -
  • Final part
  • -
  • Final visualization
  • +
  • How to do image compression before the era of deep learning
  • +
  • The SVD example
  • +
  • Mathematics of CNNs
  • +
  • Mathematics of CNNs
  • +
  • Convolution Examples: Polynomial multiplication
  • +
  • Efficient Polynomial Multiplication
  • +
  • Further simplification
  • +
  • A more efficient way of coding the above Convolution
  • +
  • Commutative process
  • +
  • Toeplitz matrices
  • +
  • Fourier series and Toeplitz matrices
  • +
  • Generalizing the above one-dimensional case
  • +
  • Memory considerations
  • +
  • Padding
  • +
  • New vector
  • +
  • Rewriting as dot products
  • +
  • Cross correlation
  • +
  • Two-dimensional objects
  • +
  • CNNs in more detail, simple example
  • +
  • The convolution stage
  • +
  • Finding the number of parameters
  • +
  • New image (or volume)
  • +
  • Parameters to train, common settings
  • +
  • Examples of CNN setups
  • +
  • Summarizing: Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Pooling
  • +
  • Pooling arithmetic
  • +
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Building convolutional neural networks in Tensorflow and Keras
  • +
  • Setting it up
  • +
  • The MNIST dataset again
  • +
  • Strong correlations
  • +
  • Layers of a CNN
  • +
  • Systematic reduction
  • +
  • Prerequisites: Collect and pre-process data
  • +
  • Importing Keras and Tensorflow
  • +
  • Running with Keras
  • +
  • Final part
  • +
  • Final visualization
  • +
  • The CIFAR01 data set
  • +
  • Verifying the data set
  • +
  • Set up the model
  • +
  • Add Dense layers on top
  • +
  • Compile and train the model
  • +
  • Finally, evaluate the model
  • +
  • Building our own CNN code
  • +
  •    List of contents:
  • +
  •    Schedulers
  • +
  •    Usage of schedulers
  • +
  •    Cost functions
  • +
  •    Usage of cost functions
  • +
  •    Activation functions
  • +
  •    Usage of activation functions
  • +
  •    Convolution
  • +
  •    Layers
  • +
  •    Convolution2DLayer: convolution in a hidden layer
  • +
  •    Backpropagation in the convolutional layer
  • +
  •    Demonstration
  • +
  •    Pooling Layer
  • +
  •    Flattening Layer
  • +
  •    Fully Connected Layers
  • +
  •    Optimized Convolution2DLayer
  • +
  •    The Convolutional Neural Network (CNN)
  • +
  •    Usage of CNN code
  • +
  •    Additional Remarks
  • +
  •    Remarks on the speed
  • +
  •    Convolution using separable kernels
  • +
  •    Convolution in the Fourier domain
  • @@ -308,43 +350,13 @@ MathJax.Hub.Config({

     

     

     

    -

    Set of filters

    - -

    The collection of kernels/filters \( W \) defining a discrete convolution has a shape -corresponding to some permutation of \( (n, m, k_1, \ldots, k_N) \), where -

    - -$$ -\begin{equation*} -\begin{split} - n &\equiv \text{number of output feature maps},\\ - m &\equiv \text{number of input feature maps},\\ - k_j &\equiv \text{kernel size along axis $j$}. -\end{split} -\end{equation*} -$$ - -

    The following properties affect the output size \( o_j \) of a convolutional layer -along axis \( j \): -

    +

    Fourier series and Toeplitz matrices

    +

    This is an active and ogoing research area concerning CNNs. The following articles may be of interest

      -
    1. \( i_j \): input size along axis \( j \),
    2. -
    3. \( k_j \): kernel/filter size along axis \( j \),
    4. -
    5. stride (distance between two consecutive positions of the kernel/filter) along axis \( j \),
    6. -
    7. zero padding (number of zeros concatenated at the beginning and at the end of an axis) along axis \( j \).
    8. +
    9. Read more about the convolution theorem and Fouriers series
    10. +
    11. Fourier Transform Layer
    -

    For instance, the above examples shows a \( 2\times 2 \) kernel/filter \( \boldsymbol{W} \) applied to a \( 3 \times 3 \) input padded with a \( 0 \times 0 \) -border of zeros using \( 1 \times 1 \) strides. -

    - -

    Note that strides constitute a form of subsampling. As an alternative to -being interpreted as a measure of how much the kernel/filter is translated, strides -can also be viewed as how much of the output is retained. For instance, moving -the kernel by hops of two is equivalent to moving the kernel by hops of one but -retaining only odd output elements. -

    -

    diff --git a/doc/pub/week44/html/._week44-bs028.html b/doc/pub/week44/html/._week44-bs028.html index a0fdecb22..b097c3f11 100644 --- a/doc/pub/week44/html/._week44-bs028.html +++ b/doc/pub/week44/html/._week44-bs028.html @@ -75,6 +75,12 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d None, 'a-deep-cnn-model-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Key Idea', 2, None, 'key-idea'), + ('How to do image compression before the era of deep learning', + 2, + None, + 'how-to-do-image-compression-before-the-era-of-deep-learning'), + ('The SVD example', 2, None, 'the-svd-example'), + ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Convolution Examples: Polynomial multiplication', 2, @@ -89,6 +95,8 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'a-more-efficient-way-of-coding-the-above-convolution'), + ('Commutative process', 2, None, 'commutative-process'), + ('Toeplitz matrices', 2, None, 'toeplitz-matrices'), ('Fourier series and Toeplitz matrices', 2, None, @@ -97,36 +105,75 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'generalizing-the-above-one-dimensional-case'), - ('Two-dimensional Objects', 2, None, 'two-dimensional-objects'), - ('CNNs in more detail', 2, None, 'cnns-in-more-detail'), - ('Performing a discrete convolution with padding ("From Raschka ' - 'et al":"https://github.com/rasbt/machine-learning-book")', + ('Memory considerations', 2, None, 'memory-considerations'), + ('Padding', 2, None, 'padding'), + ('New vector', 2, None, 'new-vector'), + ('Rewriting as dot products', 2, None, - 'performing-a-discrete-convolution-with-padding-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Performing a general discrete convolution ("From Raschka et ' + 'rewriting-as-dot-products'), + ('Cross correlation', 2, None, 'cross-correlation'), + ('Two-dimensional objects', 2, None, 'two-dimensional-objects'), + ('CNNs in more detail, simple example', + 2, + None, + 'cnns-in-more-detail-simple-example'), + ('The convolution stage', 2, None, 'the-convolution-stage'), + ('Finding the number of parameters', + 2, + None, + 'finding-the-number-of-parameters'), + ('New image (or volume)', 2, None, 'new-image-or-volume'), + ('Parameters to train, common settings', + 2, + None, + 'parameters-to-train-common-settings'), + ('Examples of CNN setups', 2, None, 'examples-of-cnn-setups'), + ('Summarizing: Performing a general discrete convolution ("From ' + 'Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, - 'performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Set of filters', 2, None, 'set-of-filters'), + 'summarizing-performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Pooling', 2, None, 'pooling'), - ('No zero padding, unit strides', - 2, - None, - 'no-zero-padding-unit-strides'), - ('Zero padding, unit strides', - 2, - None, - 'zero-padding-unit-strides'), - ('Half (same) padding', 2, None, 'half-same-padding'), - ('Full padding', 2, None, 'full-padding'), ('Pooling arithmetic', 2, None, 'pooling-arithmetic'), ('Pooling types ("From Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, 'pooling-types-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), + ('Building convolutional neural networks in Tensorflow and Keras', + 2, + None, + 'building-convolutional-neural-networks-in-tensorflow-and-keras'), + ('Setting it up', 2, None, 'setting-it-up'), + ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), + ('Strong correlations', 2, None, 'strong-correlations'), + ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), + ('Systematic reduction', 2, None, 'systematic-reduction'), + ('Prerequisites: Collect and pre-process data', + 2, + None, + 'prerequisites-collect-and-pre-process-data'), + ('Importing Keras and Tensorflow', + 2, + None, + 'importing-keras-and-tensorflow'), + ('Running with Keras', 2, None, 'running-with-keras'), + ('Final part', 2, None, 'final-part'), + ('Final visualization', 2, None, 'final-visualization'), + ('The CIFAR01 data set', 2, None, 'the-cifar01-data-set'), + ('Verifying the data set', 2, None, 'verifying-the-data-set'), + ('Set up the model', 2, None, 'set-up-the-model'), + ('Add Dense layers on top', 2, None, 'add-dense-layers-on-top'), + ('Compile and train the model', + 2, + None, + 'compile-and-train-the-model'), + ('Finally, evaluate the model', + 2, + None, + 'finally-evaluate-the-model'), ('Building our own CNN code', 2, None, @@ -173,27 +220,7 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Convolution in the Fourier domain', 3, None, - 'convolution-in-the-fourier-domain'), - ('Building convolutional neural networks in Tensorflow and Keras', - 2, - None, - 'building-convolutional-neural-networks-in-tensorflow-and-keras'), - ('Setting it up', 2, None, 'setting-it-up'), - ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), - ('Strong correlations', 2, None, 'strong-correlations'), - ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), - ('Systematic reduction', 2, None, 'systematic-reduction'), - ('Prerequisites: Collect and pre-process data', - 2, - None, - 'prerequisites-collect-and-pre-process-data'), - ('Importing Keras and Tensorflow', - 2, - None, - 'importing-keras-and-tensorflow'), - ('Running with Keras', 2, None, 'running-with-keras'), - ('Final part', 2, None, 'final-part'), - ('Final visualization', 2, None, 'final-visualization')]} + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -244,59 +271,74 @@ MathJax.Hub.Config({
  • CNNs in brief
  • A deep CNN model ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • Key Idea
  • -
  • Mathematics of CNNs
  • -
  • Convolution Examples: Polynomial multiplication
  • -
  • Efficient Polynomial Multiplication
  • -
  • Further simplification
  • -
  • A more efficient way of coding the above Convolution
  • -
  • Fourier series and Toeplitz matrices
  • -
  • Generalizing the above one-dimensional case
  • -
  • Two-dimensional Objects
  • -
  • CNNs in more detail
  • -
  • Performing a discrete convolution with padding ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Set of filters
  • -
  • Pooling
  • -
  • No zero padding, unit strides
  • -
  • Zero padding, unit strides
  • -
  • Half (same) padding
  • -
  • Full padding
  • -
  • Pooling arithmetic
  • -
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Building our own CNN code
  • -
  •    List of contents:
  • -
  •    Schedulers
  • -
  •    Usage of schedulers
  • -
  •    Cost functions
  • -
  •    Usage of cost functions
  • -
  •    Activation functions
  • -
  •    Usage of activation functions
  • -
  •    Convolution
  • -
  •    Layers
  • -
  •    Convolution2DLayer: convolution in a hidden layer
  • -
  •    Backpropagation in the convolutional layer
  • -
  •    Demonstration
  • -
  •    Pooling Layer
  • -
  •    Flattening Layer
  • -
  •    Fully Connected Layers
  • -
  •    Optimized Convolution2DLayer
  • -
  •    The Convolutional Neural Network (CNN)
  • -
  •    Usage of CNN code
  • -
  •    Additional Remarks
  • -
  •    Remarks on the speed
  • -
  •    Convolution using separable kernels
  • -
  •    Convolution in the Fourier domain
  • -
  • Building convolutional neural networks in Tensorflow and Keras
  • -
  • Setting it up
  • -
  • The MNIST dataset again
  • -
  • Strong correlations
  • -
  • Layers of a CNN
  • -
  • Systematic reduction
  • -
  • Prerequisites: Collect and pre-process data
  • -
  • Importing Keras and Tensorflow
  • -
  • Running with Keras
  • -
  • Final part
  • -
  • Final visualization
  • +
  • How to do image compression before the era of deep learning
  • +
  • The SVD example
  • +
  • Mathematics of CNNs
  • +
  • Mathematics of CNNs
  • +
  • Convolution Examples: Polynomial multiplication
  • +
  • Efficient Polynomial Multiplication
  • +
  • Further simplification
  • +
  • A more efficient way of coding the above Convolution
  • +
  • Commutative process
  • +
  • Toeplitz matrices
  • +
  • Fourier series and Toeplitz matrices
  • +
  • Generalizing the above one-dimensional case
  • +
  • Memory considerations
  • +
  • Padding
  • +
  • New vector
  • +
  • Rewriting as dot products
  • +
  • Cross correlation
  • +
  • Two-dimensional objects
  • +
  • CNNs in more detail, simple example
  • +
  • The convolution stage
  • +
  • Finding the number of parameters
  • +
  • New image (or volume)
  • +
  • Parameters to train, common settings
  • +
  • Examples of CNN setups
  • +
  • Summarizing: Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Pooling
  • +
  • Pooling arithmetic
  • +
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Building convolutional neural networks in Tensorflow and Keras
  • +
  • Setting it up
  • +
  • The MNIST dataset again
  • +
  • Strong correlations
  • +
  • Layers of a CNN
  • +
  • Systematic reduction
  • +
  • Prerequisites: Collect and pre-process data
  • +
  • Importing Keras and Tensorflow
  • +
  • Running with Keras
  • +
  • Final part
  • +
  • Final visualization
  • +
  • The CIFAR01 data set
  • +
  • Verifying the data set
  • +
  • Set up the model
  • +
  • Add Dense layers on top
  • +
  • Compile and train the model
  • +
  • Finally, evaluate the model
  • +
  • Building our own CNN code
  • +
  •    List of contents:
  • +
  •    Schedulers
  • +
  •    Usage of schedulers
  • +
  •    Cost functions
  • +
  •    Usage of cost functions
  • +
  •    Activation functions
  • +
  •    Usage of activation functions
  • +
  •    Convolution
  • +
  •    Layers
  • +
  •    Convolution2DLayer: convolution in a hidden layer
  • +
  •    Backpropagation in the convolutional layer
  • +
  •    Demonstration
  • +
  •    Pooling Layer
  • +
  •    Flattening Layer
  • +
  •    Fully Connected Layers
  • +
  •    Optimized Convolution2DLayer
  • +
  •    The Convolutional Neural Network (CNN)
  • +
  •    Usage of CNN code
  • +
  •    Additional Remarks
  • +
  •    Remarks on the speed
  • +
  •    Convolution using separable kernels
  • +
  •    Convolution in the Fourier domain
  • @@ -308,47 +350,23 @@ MathJax.Hub.Config({

     

     

     

    -

    Pooling

    +

    Generalizing the above one-dimensional case

    -

    In addition to discrete convolutions themselves, {\em pooling\/} operations -make up another important building block in CNNs. Pooling operations reduce -the size of feature maps by using some function to summarize subregions, such -as taking the average or the maximum value. +

    In order to align the above simple case with the more general +convolution cases, we rename \( \boldsymbol{\alpha} \), whose length is \( m=3 \), +with \( \boldsymbol{w} \). We will interpret \( \boldsymbol{w} \) as a weight/filter function +with which we want to perform the convolution with an input variable +\( \boldsymbol{x} \) of length \( n \). We will assume always that the filter +\( \boldsymbol{w} \) has dimensionality \( m \le n \).

    -

    Pooling works by sliding a window across the input and feeding the content of -the window to a {\em pooling function}. In some sense, pooling works very much -like a discrete convolution, but replaces the linear combination described by -the kernel with some other function. Poolin -provides an example for average pooling, and -does the same for max pooling. -

    +

    We replace thus \( \boldsymbol{\beta} \) with \( \boldsymbol{x} \) and \( \boldsymbol{\delta} \) with \( \boldsymbol{y} \) and have

    +$$ +y(i)= \left(x*w\right)(i)= \sum_{k=0}^{k=m-1}w(k)x(i-k), +$$ -

    The following properties affect the output size \( o_j \) of a pooling layer -along axis \( j \): -

    - -
      -
    1. \( i_j \): input size along axis \( j \),
    2. -
    3. \( k_j \): pooling window size along axis \( j \),
    4. -
    5. \( s_j \): stride (distance between two consecutive positions of the pooling window) along axis \( j \).
    6. -
    -

    The analysis of the relationship between convolutional layer properties is eased -by the fact that they don't interact across axes, i.e., the choice of kernel -size, stride and zero padding along axis \( j \) only affects the output size of -axis \( j \). Because of that, we will focus on the following simplified -setting: -

    - -
      -
    1. 2-D discrete convolutions (\( N = 2 \)),
    2. -
    3. square inputs (\( i_1 = i_2 = i \)),
    4. -
    5. square kernel size (\( k_1 = k_2 = k \)),
    6. -
    7. same strides along both axes (\( s_1 = s_2 = s \)),
    8. -
    9. same zero padding along both axes (\( p_1 = p_2 = p \)).
    10. -
    -

    This facilitates the analysis and the visualization, but keep in mind that the -results outlined here also generalize to the N-D and non-square cases. +

    where \( m=3 \) in our case, the maximum length of the vector \( \boldsymbol{w} \). +Here the symbol \( * \) represents the mathematical operation of convolution.

    @@ -376,7 +394,7 @@ results outlined here also generalize to the N-D and non-square cases.

  • 37
  • 38
  • ...
  • -
  • 47
  • +
  • 62
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs029.html b/doc/pub/week44/html/._week44-bs029.html index 6424f3df5..0cb0751b9 100644 --- a/doc/pub/week44/html/._week44-bs029.html +++ b/doc/pub/week44/html/._week44-bs029.html @@ -75,6 +75,12 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d None, 'a-deep-cnn-model-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Key Idea', 2, None, 'key-idea'), + ('How to do image compression before the era of deep learning', + 2, + None, + 'how-to-do-image-compression-before-the-era-of-deep-learning'), + ('The SVD example', 2, None, 'the-svd-example'), + ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Convolution Examples: Polynomial multiplication', 2, @@ -89,6 +95,8 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'a-more-efficient-way-of-coding-the-above-convolution'), + ('Commutative process', 2, None, 'commutative-process'), + ('Toeplitz matrices', 2, None, 'toeplitz-matrices'), ('Fourier series and Toeplitz matrices', 2, None, @@ -97,36 +105,75 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'generalizing-the-above-one-dimensional-case'), - ('Two-dimensional Objects', 2, None, 'two-dimensional-objects'), - ('CNNs in more detail', 2, None, 'cnns-in-more-detail'), - ('Performing a discrete convolution with padding ("From Raschka ' - 'et al":"https://github.com/rasbt/machine-learning-book")', + ('Memory considerations', 2, None, 'memory-considerations'), + ('Padding', 2, None, 'padding'), + ('New vector', 2, None, 'new-vector'), + ('Rewriting as dot products', 2, None, - 'performing-a-discrete-convolution-with-padding-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Performing a general discrete convolution ("From Raschka et ' + 'rewriting-as-dot-products'), + ('Cross correlation', 2, None, 'cross-correlation'), + ('Two-dimensional objects', 2, None, 'two-dimensional-objects'), + ('CNNs in more detail, simple example', + 2, + None, + 'cnns-in-more-detail-simple-example'), + ('The convolution stage', 2, None, 'the-convolution-stage'), + ('Finding the number of parameters', + 2, + None, + 'finding-the-number-of-parameters'), + ('New image (or volume)', 2, None, 'new-image-or-volume'), + ('Parameters to train, common settings', + 2, + None, + 'parameters-to-train-common-settings'), + ('Examples of CNN setups', 2, None, 'examples-of-cnn-setups'), + ('Summarizing: Performing a general discrete convolution ("From ' + 'Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, - 'performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Set of filters', 2, None, 'set-of-filters'), + 'summarizing-performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Pooling', 2, None, 'pooling'), - ('No zero padding, unit strides', - 2, - None, - 'no-zero-padding-unit-strides'), - ('Zero padding, unit strides', - 2, - None, - 'zero-padding-unit-strides'), - ('Half (same) padding', 2, None, 'half-same-padding'), - ('Full padding', 2, None, 'full-padding'), ('Pooling arithmetic', 2, None, 'pooling-arithmetic'), ('Pooling types ("From Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, 'pooling-types-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), + ('Building convolutional neural networks in Tensorflow and Keras', + 2, + None, + 'building-convolutional-neural-networks-in-tensorflow-and-keras'), + ('Setting it up', 2, None, 'setting-it-up'), + ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), + ('Strong correlations', 2, None, 'strong-correlations'), + ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), + ('Systematic reduction', 2, None, 'systematic-reduction'), + ('Prerequisites: Collect and pre-process data', + 2, + None, + 'prerequisites-collect-and-pre-process-data'), + ('Importing Keras and Tensorflow', + 2, + None, + 'importing-keras-and-tensorflow'), + ('Running with Keras', 2, None, 'running-with-keras'), + ('Final part', 2, None, 'final-part'), + ('Final visualization', 2, None, 'final-visualization'), + ('The CIFAR01 data set', 2, None, 'the-cifar01-data-set'), + ('Verifying the data set', 2, None, 'verifying-the-data-set'), + ('Set up the model', 2, None, 'set-up-the-model'), + ('Add Dense layers on top', 2, None, 'add-dense-layers-on-top'), + ('Compile and train the model', + 2, + None, + 'compile-and-train-the-model'), + ('Finally, evaluate the model', + 2, + None, + 'finally-evaluate-the-model'), ('Building our own CNN code', 2, None, @@ -173,27 +220,7 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Convolution in the Fourier domain', 3, None, - 'convolution-in-the-fourier-domain'), - ('Building convolutional neural networks in Tensorflow and Keras', - 2, - None, - 'building-convolutional-neural-networks-in-tensorflow-and-keras'), - ('Setting it up', 2, None, 'setting-it-up'), - ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), - ('Strong correlations', 2, None, 'strong-correlations'), - ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), - ('Systematic reduction', 2, None, 'systematic-reduction'), - ('Prerequisites: Collect and pre-process data', - 2, - None, - 'prerequisites-collect-and-pre-process-data'), - ('Importing Keras and Tensorflow', - 2, - None, - 'importing-keras-and-tensorflow'), - ('Running with Keras', 2, None, 'running-with-keras'), - ('Final part', 2, None, 'final-part'), - ('Final visualization', 2, None, 'final-visualization')]} + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -244,59 +271,74 @@ MathJax.Hub.Config({
  • CNNs in brief
  • A deep CNN model ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • Key Idea
  • -
  • Mathematics of CNNs
  • -
  • Convolution Examples: Polynomial multiplication
  • -
  • Efficient Polynomial Multiplication
  • -
  • Further simplification
  • -
  • A more efficient way of coding the above Convolution
  • -
  • Fourier series and Toeplitz matrices
  • -
  • Generalizing the above one-dimensional case
  • -
  • Two-dimensional Objects
  • -
  • CNNs in more detail
  • -
  • Performing a discrete convolution with padding ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Set of filters
  • -
  • Pooling
  • -
  • No zero padding, unit strides
  • -
  • Zero padding, unit strides
  • -
  • Half (same) padding
  • -
  • Full padding
  • -
  • Pooling arithmetic
  • -
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Building our own CNN code
  • -
  •    List of contents:
  • -
  •    Schedulers
  • -
  •    Usage of schedulers
  • -
  •    Cost functions
  • -
  •    Usage of cost functions
  • -
  •    Activation functions
  • -
  •    Usage of activation functions
  • -
  •    Convolution
  • -
  •    Layers
  • -
  •    Convolution2DLayer: convolution in a hidden layer
  • -
  •    Backpropagation in the convolutional layer
  • -
  •    Demonstration
  • -
  •    Pooling Layer
  • -
  •    Flattening Layer
  • -
  •    Fully Connected Layers
  • -
  •    Optimized Convolution2DLayer
  • -
  •    The Convolutional Neural Network (CNN)
  • -
  •    Usage of CNN code
  • -
  •    Additional Remarks
  • -
  •    Remarks on the speed
  • -
  •    Convolution using separable kernels
  • -
  •    Convolution in the Fourier domain
  • -
  • Building convolutional neural networks in Tensorflow and Keras
  • -
  • Setting it up
  • -
  • The MNIST dataset again
  • -
  • Strong correlations
  • -
  • Layers of a CNN
  • -
  • Systematic reduction
  • -
  • Prerequisites: Collect and pre-process data
  • -
  • Importing Keras and Tensorflow
  • -
  • Running with Keras
  • -
  • Final part
  • -
  • Final visualization
  • +
  • How to do image compression before the era of deep learning
  • +
  • The SVD example
  • +
  • Mathematics of CNNs
  • +
  • Mathematics of CNNs
  • +
  • Convolution Examples: Polynomial multiplication
  • +
  • Efficient Polynomial Multiplication
  • +
  • Further simplification
  • +
  • A more efficient way of coding the above Convolution
  • +
  • Commutative process
  • +
  • Toeplitz matrices
  • +
  • Fourier series and Toeplitz matrices
  • +
  • Generalizing the above one-dimensional case
  • +
  • Memory considerations
  • +
  • Padding
  • +
  • New vector
  • +
  • Rewriting as dot products
  • +
  • Cross correlation
  • +
  • Two-dimensional objects
  • +
  • CNNs in more detail, simple example
  • +
  • The convolution stage
  • +
  • Finding the number of parameters
  • +
  • New image (or volume)
  • +
  • Parameters to train, common settings
  • +
  • Examples of CNN setups
  • +
  • Summarizing: Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Pooling
  • +
  • Pooling arithmetic
  • +
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Building convolutional neural networks in Tensorflow and Keras
  • +
  • Setting it up
  • +
  • The MNIST dataset again
  • +
  • Strong correlations
  • +
  • Layers of a CNN
  • +
  • Systematic reduction
  • +
  • Prerequisites: Collect and pre-process data
  • +
  • Importing Keras and Tensorflow
  • +
  • Running with Keras
  • +
  • Final part
  • +
  • Final visualization
  • +
  • The CIFAR01 data set
  • +
  • Verifying the data set
  • +
  • Set up the model
  • +
  • Add Dense layers on top
  • +
  • Compile and train the model
  • +
  • Finally, evaluate the model
  • +
  • Building our own CNN code
  • +
  •    List of contents:
  • +
  •    Schedulers
  • +
  •    Usage of schedulers
  • +
  •    Cost functions
  • +
  •    Usage of cost functions
  • +
  •    Activation functions
  • +
  •    Usage of activation functions
  • +
  •    Convolution
  • +
  •    Layers
  • +
  •    Convolution2DLayer: convolution in a hidden layer
  • +
  •    Backpropagation in the convolutional layer
  • +
  •    Demonstration
  • +
  •    Pooling Layer
  • +
  •    Flattening Layer
  • +
  •    Fully Connected Layers
  • +
  •    Optimized Convolution2DLayer
  • +
  •    The Convolutional Neural Network (CNN)
  • +
  •    Usage of CNN code
  • +
  •    Additional Remarks
  • +
  •    Remarks on the speed
  • +
  •    Convolution using separable kernels
  • +
  •    Convolution in the Fourier domain
  • @@ -308,19 +350,21 @@ MathJax.Hub.Config({

     

     

     

    -

    No zero padding, unit strides

    +

    Memory considerations

    -

    The simplest case to analyze is when the kernel just slides across every -position of the input (i.e., \( s = 1 \) and \( p = 0 \)). +

    This expression leaves us however with some terms with negative +indices, for example \( x(-1) \) and \( x(-2) \) which may not be defined. Our +vector \( \boldsymbol{x} \) has components \( x(0) \), \( x(1) \), \( x(2) \) and \( x(3) \).

    -

    For any \( i \) and \( k \), and for \( s = 1 \) and \( p = 0 \),

    -$$ -\begin{equation*} - o = (i - k) + 1. -\end{equation*} -$$ +

    The index \( j \) for \( \boldsymbol{x} \) runs from \( j=0 \) to \( j=3 \) since \( \boldsymbol{x} \) is meant to +represent a third-order polynomial. +

    +

    Furthermore, the index \( i \) runs from \( i=0 \) to \( i=5 \) since \( \boldsymbol{y} \) +contains the coefficients of a fifth-order polynomial. When \( i=5 \) we +may also have values of \( x(4) \) and \( x(5) \) which are not defined. +

    @@ -347,7 +391,7 @@ $$

  • 38
  • 39
  • ...
  • -
  • 47
  • +
  • 62
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs030.html b/doc/pub/week44/html/._week44-bs030.html index cf9c7fa09..7abb72049 100644 --- a/doc/pub/week44/html/._week44-bs030.html +++ b/doc/pub/week44/html/._week44-bs030.html @@ -75,6 +75,12 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d None, 'a-deep-cnn-model-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Key Idea', 2, None, 'key-idea'), + ('How to do image compression before the era of deep learning', + 2, + None, + 'how-to-do-image-compression-before-the-era-of-deep-learning'), + ('The SVD example', 2, None, 'the-svd-example'), + ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Convolution Examples: Polynomial multiplication', 2, @@ -89,6 +95,8 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'a-more-efficient-way-of-coding-the-above-convolution'), + ('Commutative process', 2, None, 'commutative-process'), + ('Toeplitz matrices', 2, None, 'toeplitz-matrices'), ('Fourier series and Toeplitz matrices', 2, None, @@ -97,36 +105,75 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'generalizing-the-above-one-dimensional-case'), - ('Two-dimensional Objects', 2, None, 'two-dimensional-objects'), - ('CNNs in more detail', 2, None, 'cnns-in-more-detail'), - ('Performing a discrete convolution with padding ("From Raschka ' - 'et al":"https://github.com/rasbt/machine-learning-book")', + ('Memory considerations', 2, None, 'memory-considerations'), + ('Padding', 2, None, 'padding'), + ('New vector', 2, None, 'new-vector'), + ('Rewriting as dot products', 2, None, - 'performing-a-discrete-convolution-with-padding-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Performing a general discrete convolution ("From Raschka et ' + 'rewriting-as-dot-products'), + ('Cross correlation', 2, None, 'cross-correlation'), + ('Two-dimensional objects', 2, None, 'two-dimensional-objects'), + ('CNNs in more detail, simple example', + 2, + None, + 'cnns-in-more-detail-simple-example'), + ('The convolution stage', 2, None, 'the-convolution-stage'), + ('Finding the number of parameters', + 2, + None, + 'finding-the-number-of-parameters'), + ('New image (or volume)', 2, None, 'new-image-or-volume'), + ('Parameters to train, common settings', + 2, + None, + 'parameters-to-train-common-settings'), + ('Examples of CNN setups', 2, None, 'examples-of-cnn-setups'), + ('Summarizing: Performing a general discrete convolution ("From ' + 'Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, - 'performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Set of filters', 2, None, 'set-of-filters'), + 'summarizing-performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Pooling', 2, None, 'pooling'), - ('No zero padding, unit strides', - 2, - None, - 'no-zero-padding-unit-strides'), - ('Zero padding, unit strides', - 2, - None, - 'zero-padding-unit-strides'), - ('Half (same) padding', 2, None, 'half-same-padding'), - ('Full padding', 2, None, 'full-padding'), ('Pooling arithmetic', 2, None, 'pooling-arithmetic'), ('Pooling types ("From Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, 'pooling-types-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), + ('Building convolutional neural networks in Tensorflow and Keras', + 2, + None, + 'building-convolutional-neural-networks-in-tensorflow-and-keras'), + ('Setting it up', 2, None, 'setting-it-up'), + ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), + ('Strong correlations', 2, None, 'strong-correlations'), + ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), + ('Systematic reduction', 2, None, 'systematic-reduction'), + ('Prerequisites: Collect and pre-process data', + 2, + None, + 'prerequisites-collect-and-pre-process-data'), + ('Importing Keras and Tensorflow', + 2, + None, + 'importing-keras-and-tensorflow'), + ('Running with Keras', 2, None, 'running-with-keras'), + ('Final part', 2, None, 'final-part'), + ('Final visualization', 2, None, 'final-visualization'), + ('The CIFAR01 data set', 2, None, 'the-cifar01-data-set'), + ('Verifying the data set', 2, None, 'verifying-the-data-set'), + ('Set up the model', 2, None, 'set-up-the-model'), + ('Add Dense layers on top', 2, None, 'add-dense-layers-on-top'), + ('Compile and train the model', + 2, + None, + 'compile-and-train-the-model'), + ('Finally, evaluate the model', + 2, + None, + 'finally-evaluate-the-model'), ('Building our own CNN code', 2, None, @@ -173,27 +220,7 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Convolution in the Fourier domain', 3, None, - 'convolution-in-the-fourier-domain'), - ('Building convolutional neural networks in Tensorflow and Keras', - 2, - None, - 'building-convolutional-neural-networks-in-tensorflow-and-keras'), - ('Setting it up', 2, None, 'setting-it-up'), - ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), - ('Strong correlations', 2, None, 'strong-correlations'), - ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), - ('Systematic reduction', 2, None, 'systematic-reduction'), - ('Prerequisites: Collect and pre-process data', - 2, - None, - 'prerequisites-collect-and-pre-process-data'), - ('Importing Keras and Tensorflow', - 2, - None, - 'importing-keras-and-tensorflow'), - ('Running with Keras', 2, None, 'running-with-keras'), - ('Final part', 2, None, 'final-part'), - ('Final visualization', 2, None, 'final-visualization')]} + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -244,59 +271,74 @@ MathJax.Hub.Config({
  • CNNs in brief
  • A deep CNN model ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • Key Idea
  • -
  • Mathematics of CNNs
  • -
  • Convolution Examples: Polynomial multiplication
  • -
  • Efficient Polynomial Multiplication
  • -
  • Further simplification
  • -
  • A more efficient way of coding the above Convolution
  • -
  • Fourier series and Toeplitz matrices
  • -
  • Generalizing the above one-dimensional case
  • -
  • Two-dimensional Objects
  • -
  • CNNs in more detail
  • -
  • Performing a discrete convolution with padding ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Set of filters
  • -
  • Pooling
  • -
  • No zero padding, unit strides
  • -
  • Zero padding, unit strides
  • -
  • Half (same) padding
  • -
  • Full padding
  • -
  • Pooling arithmetic
  • -
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Building our own CNN code
  • -
  •    List of contents:
  • -
  •    Schedulers
  • -
  •    Usage of schedulers
  • -
  •    Cost functions
  • -
  •    Usage of cost functions
  • -
  •    Activation functions
  • -
  •    Usage of activation functions
  • -
  •    Convolution
  • -
  •    Layers
  • -
  •    Convolution2DLayer: convolution in a hidden layer
  • -
  •    Backpropagation in the convolutional layer
  • -
  •    Demonstration
  • -
  •    Pooling Layer
  • -
  •    Flattening Layer
  • -
  •    Fully Connected Layers
  • -
  •    Optimized Convolution2DLayer
  • -
  •    The Convolutional Neural Network (CNN)
  • -
  •    Usage of CNN code
  • -
  •    Additional Remarks
  • -
  •    Remarks on the speed
  • -
  •    Convolution using separable kernels
  • -
  •    Convolution in the Fourier domain
  • -
  • Building convolutional neural networks in Tensorflow and Keras
  • -
  • Setting it up
  • -
  • The MNIST dataset again
  • -
  • Strong correlations
  • -
  • Layers of a CNN
  • -
  • Systematic reduction
  • -
  • Prerequisites: Collect and pre-process data
  • -
  • Importing Keras and Tensorflow
  • -
  • Running with Keras
  • -
  • Final part
  • -
  • Final visualization
  • +
  • How to do image compression before the era of deep learning
  • +
  • The SVD example
  • +
  • Mathematics of CNNs
  • +
  • Mathematics of CNNs
  • +
  • Convolution Examples: Polynomial multiplication
  • +
  • Efficient Polynomial Multiplication
  • +
  • Further simplification
  • +
  • A more efficient way of coding the above Convolution
  • +
  • Commutative process
  • +
  • Toeplitz matrices
  • +
  • Fourier series and Toeplitz matrices
  • +
  • Generalizing the above one-dimensional case
  • +
  • Memory considerations
  • +
  • Padding
  • +
  • New vector
  • +
  • Rewriting as dot products
  • +
  • Cross correlation
  • +
  • Two-dimensional objects
  • +
  • CNNs in more detail, simple example
  • +
  • The convolution stage
  • +
  • Finding the number of parameters
  • +
  • New image (or volume)
  • +
  • Parameters to train, common settings
  • +
  • Examples of CNN setups
  • +
  • Summarizing: Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Pooling
  • +
  • Pooling arithmetic
  • +
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Building convolutional neural networks in Tensorflow and Keras
  • +
  • Setting it up
  • +
  • The MNIST dataset again
  • +
  • Strong correlations
  • +
  • Layers of a CNN
  • +
  • Systematic reduction
  • +
  • Prerequisites: Collect and pre-process data
  • +
  • Importing Keras and Tensorflow
  • +
  • Running with Keras
  • +
  • Final part
  • +
  • Final visualization
  • +
  • The CIFAR01 data set
  • +
  • Verifying the data set
  • +
  • Set up the model
  • +
  • Add Dense layers on top
  • +
  • Compile and train the model
  • +
  • Finally, evaluate the model
  • +
  • Building our own CNN code
  • +
  •    List of contents:
  • +
  •    Schedulers
  • +
  •    Usage of schedulers
  • +
  •    Cost functions
  • +
  •    Usage of cost functions
  • +
  •    Activation functions
  • +
  •    Usage of activation functions
  • +
  •    Convolution
  • +
  •    Layers
  • +
  •    Convolution2DLayer: convolution in a hidden layer
  • +
  •    Backpropagation in the convolutional layer
  • +
  •    Demonstration
  • +
  •    Pooling Layer
  • +
  •    Flattening Layer
  • +
  •    Fully Connected Layers
  • +
  •    Optimized Convolution2DLayer
  • +
  •    The Convolutional Neural Network (CNN)
  • +
  •    Usage of CNN code
  • +
  •    Additional Remarks
  • +
  •    Remarks on the speed
  • +
  •    Convolution using separable kernels
  • +
  •    Convolution in the Fourier domain
  • @@ -308,22 +350,15 @@ MathJax.Hub.Config({

     

     

     

    -

    Zero padding, unit strides

    +

    Padding

    -

    To factor in zero padding (i.e., only restricting to \( s = 1 \)), let's consider -its effect on the effective input size: padding with \( p \) zeros changes the -effective input size from \( i \) to \( i + 2p \). In the general case, we can infer the following -relationship +

    The solution to this is what is called padding! We simply define a +new vector \( x \) with two added elements set to zero before \( x(0) \) and +two new elements after \( x(3) \) set to zero. That is, we augment the +length of \( \boldsymbol{x} \) from \( n=4 \) to \( n+2P=8 \), where \( P=2 \) is the padding +constant (a new hyperparameter), see discussions below as well.

    -

    For any \( i \), \( k \) and \( p \), and for \( s = 1 \),

    -$$ -\begin{equation*} - o = (i - k) + 2p + 1. -\end{equation*} -$$ - -

    diff --git a/doc/pub/week44/html/._week44-bs031.html b/doc/pub/week44/html/._week44-bs031.html index 523411cb7..f2375e2f8 100644 --- a/doc/pub/week44/html/._week44-bs031.html +++ b/doc/pub/week44/html/._week44-bs031.html @@ -75,6 +75,12 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d None, 'a-deep-cnn-model-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Key Idea', 2, None, 'key-idea'), + ('How to do image compression before the era of deep learning', + 2, + None, + 'how-to-do-image-compression-before-the-era-of-deep-learning'), + ('The SVD example', 2, None, 'the-svd-example'), + ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Convolution Examples: Polynomial multiplication', 2, @@ -89,6 +95,8 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'a-more-efficient-way-of-coding-the-above-convolution'), + ('Commutative process', 2, None, 'commutative-process'), + ('Toeplitz matrices', 2, None, 'toeplitz-matrices'), ('Fourier series and Toeplitz matrices', 2, None, @@ -97,36 +105,75 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'generalizing-the-above-one-dimensional-case'), - ('Two-dimensional Objects', 2, None, 'two-dimensional-objects'), - ('CNNs in more detail', 2, None, 'cnns-in-more-detail'), - ('Performing a discrete convolution with padding ("From Raschka ' - 'et al":"https://github.com/rasbt/machine-learning-book")', + ('Memory considerations', 2, None, 'memory-considerations'), + ('Padding', 2, None, 'padding'), + ('New vector', 2, None, 'new-vector'), + ('Rewriting as dot products', 2, None, - 'performing-a-discrete-convolution-with-padding-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Performing a general discrete convolution ("From Raschka et ' + 'rewriting-as-dot-products'), + ('Cross correlation', 2, None, 'cross-correlation'), + ('Two-dimensional objects', 2, None, 'two-dimensional-objects'), + ('CNNs in more detail, simple example', + 2, + None, + 'cnns-in-more-detail-simple-example'), + ('The convolution stage', 2, None, 'the-convolution-stage'), + ('Finding the number of parameters', + 2, + None, + 'finding-the-number-of-parameters'), + ('New image (or volume)', 2, None, 'new-image-or-volume'), + ('Parameters to train, common settings', + 2, + None, + 'parameters-to-train-common-settings'), + ('Examples of CNN setups', 2, None, 'examples-of-cnn-setups'), + ('Summarizing: Performing a general discrete convolution ("From ' + 'Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, - 'performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Set of filters', 2, None, 'set-of-filters'), + 'summarizing-performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Pooling', 2, None, 'pooling'), - ('No zero padding, unit strides', - 2, - None, - 'no-zero-padding-unit-strides'), - ('Zero padding, unit strides', - 2, - None, - 'zero-padding-unit-strides'), - ('Half (same) padding', 2, None, 'half-same-padding'), - ('Full padding', 2, None, 'full-padding'), ('Pooling arithmetic', 2, None, 'pooling-arithmetic'), ('Pooling types ("From Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, 'pooling-types-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), + ('Building convolutional neural networks in Tensorflow and Keras', + 2, + None, + 'building-convolutional-neural-networks-in-tensorflow-and-keras'), + ('Setting it up', 2, None, 'setting-it-up'), + ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), + ('Strong correlations', 2, None, 'strong-correlations'), + ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), + ('Systematic reduction', 2, None, 'systematic-reduction'), + ('Prerequisites: Collect and pre-process data', + 2, + None, + 'prerequisites-collect-and-pre-process-data'), + ('Importing Keras and Tensorflow', + 2, + None, + 'importing-keras-and-tensorflow'), + ('Running with Keras', 2, None, 'running-with-keras'), + ('Final part', 2, None, 'final-part'), + ('Final visualization', 2, None, 'final-visualization'), + ('The CIFAR01 data set', 2, None, 'the-cifar01-data-set'), + ('Verifying the data set', 2, None, 'verifying-the-data-set'), + ('Set up the model', 2, None, 'set-up-the-model'), + ('Add Dense layers on top', 2, None, 'add-dense-layers-on-top'), + ('Compile and train the model', + 2, + None, + 'compile-and-train-the-model'), + ('Finally, evaluate the model', + 2, + None, + 'finally-evaluate-the-model'), ('Building our own CNN code', 2, None, @@ -173,27 +220,7 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Convolution in the Fourier domain', 3, None, - 'convolution-in-the-fourier-domain'), - ('Building convolutional neural networks in Tensorflow and Keras', - 2, - None, - 'building-convolutional-neural-networks-in-tensorflow-and-keras'), - ('Setting it up', 2, None, 'setting-it-up'), - ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), - ('Strong correlations', 2, None, 'strong-correlations'), - ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), - ('Systematic reduction', 2, None, 'systematic-reduction'), - ('Prerequisites: Collect and pre-process data', - 2, - None, - 'prerequisites-collect-and-pre-process-data'), - ('Importing Keras and Tensorflow', - 2, - None, - 'importing-keras-and-tensorflow'), - ('Running with Keras', 2, None, 'running-with-keras'), - ('Final part', 2, None, 'final-part'), - ('Final visualization', 2, None, 'final-visualization')]} + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -244,59 +271,74 @@ MathJax.Hub.Config({
  • CNNs in brief
  • A deep CNN model ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • Key Idea
  • -
  • Mathematics of CNNs
  • -
  • Convolution Examples: Polynomial multiplication
  • -
  • Efficient Polynomial Multiplication
  • -
  • Further simplification
  • -
  • A more efficient way of coding the above Convolution
  • -
  • Fourier series and Toeplitz matrices
  • -
  • Generalizing the above one-dimensional case
  • -
  • Two-dimensional Objects
  • -
  • CNNs in more detail
  • -
  • Performing a discrete convolution with padding ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Set of filters
  • -
  • Pooling
  • -
  • No zero padding, unit strides
  • -
  • Zero padding, unit strides
  • -
  • Half (same) padding
  • -
  • Full padding
  • -
  • Pooling arithmetic
  • -
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Building our own CNN code
  • -
  •    List of contents:
  • -
  •    Schedulers
  • -
  •    Usage of schedulers
  • -
  •    Cost functions
  • -
  •    Usage of cost functions
  • -
  •    Activation functions
  • -
  •    Usage of activation functions
  • -
  •    Convolution
  • -
  •    Layers
  • -
  •    Convolution2DLayer: convolution in a hidden layer
  • -
  •    Backpropagation in the convolutional layer
  • -
  •    Demonstration
  • -
  •    Pooling Layer
  • -
  •    Flattening Layer
  • -
  •    Fully Connected Layers
  • -
  •    Optimized Convolution2DLayer
  • -
  •    The Convolutional Neural Network (CNN)
  • -
  •    Usage of CNN code
  • -
  •    Additional Remarks
  • -
  •    Remarks on the speed
  • -
  •    Convolution using separable kernels
  • -
  •    Convolution in the Fourier domain
  • -
  • Building convolutional neural networks in Tensorflow and Keras
  • -
  • Setting it up
  • -
  • The MNIST dataset again
  • -
  • Strong correlations
  • -
  • Layers of a CNN
  • -
  • Systematic reduction
  • -
  • Prerequisites: Collect and pre-process data
  • -
  • Importing Keras and Tensorflow
  • -
  • Running with Keras
  • -
  • Final part
  • -
  • Final visualization
  • +
  • How to do image compression before the era of deep learning
  • +
  • The SVD example
  • +
  • Mathematics of CNNs
  • +
  • Mathematics of CNNs
  • +
  • Convolution Examples: Polynomial multiplication
  • +
  • Efficient Polynomial Multiplication
  • +
  • Further simplification
  • +
  • A more efficient way of coding the above Convolution
  • +
  • Commutative process
  • +
  • Toeplitz matrices
  • +
  • Fourier series and Toeplitz matrices
  • +
  • Generalizing the above one-dimensional case
  • +
  • Memory considerations
  • +
  • Padding
  • +
  • New vector
  • +
  • Rewriting as dot products
  • +
  • Cross correlation
  • +
  • Two-dimensional objects
  • +
  • CNNs in more detail, simple example
  • +
  • The convolution stage
  • +
  • Finding the number of parameters
  • +
  • New image (or volume)
  • +
  • Parameters to train, common settings
  • +
  • Examples of CNN setups
  • +
  • Summarizing: Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Pooling
  • +
  • Pooling arithmetic
  • +
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Building convolutional neural networks in Tensorflow and Keras
  • +
  • Setting it up
  • +
  • The MNIST dataset again
  • +
  • Strong correlations
  • +
  • Layers of a CNN
  • +
  • Systematic reduction
  • +
  • Prerequisites: Collect and pre-process data
  • +
  • Importing Keras and Tensorflow
  • +
  • Running with Keras
  • +
  • Final part
  • +
  • Final visualization
  • +
  • The CIFAR01 data set
  • +
  • Verifying the data set
  • +
  • Set up the model
  • +
  • Add Dense layers on top
  • +
  • Compile and train the model
  • +
  • Finally, evaluate the model
  • +
  • Building our own CNN code
  • +
  •    List of contents:
  • +
  •    Schedulers
  • +
  •    Usage of schedulers
  • +
  •    Cost functions
  • +
  •    Usage of cost functions
  • +
  •    Activation functions
  • +
  •    Usage of activation functions
  • +
  •    Convolution
  • +
  •    Layers
  • +
  •    Convolution2DLayer: convolution in a hidden layer
  • +
  •    Backpropagation in the convolutional layer
  • +
  •    Demonstration
  • +
  •    Pooling Layer
  • +
  •    Flattening Layer
  • +
  •    Fully Connected Layers
  • +
  •    Optimized Convolution2DLayer
  • +
  •    The Convolutional Neural Network (CNN)
  • +
  •    Usage of CNN code
  • +
  •    Additional Remarks
  • +
  •    Remarks on the speed
  • +
  •    Convolution using separable kernels
  • +
  •    Convolution in the Fourier domain
  • @@ -308,23 +350,36 @@ MathJax.Hub.Config({

     

     

     

    -

    Half (same) padding

    +

    New vector

    -

    Having the output size be the same as the input size (i.e., \( o = i \)) can be a -desirable property: +

    We have a new vector defined as \( x(0)=0 \), \( x(1)=0 \), +\( x(2)=\beta_0 \), \( x(3)=\beta_1 \), \( x(4)=\beta_2 \), \( x(5)=\beta_3 \), +\( x(6)=0 \), and \( x(7)=0 \).

    -

    For any \( i \) and for \( k \) odd (\( k = 2n + 1, \quad n \in \mathbb{N} \)), \( s = 1 \) and -\( p = \lfloor k / 2 \rfloor = n \), +

    We have added four new elements, which +are all zero. The benefit is that we can rewrite the equation for +\( \boldsymbol{y} \), with \( i=0,1,\dots,5 \),

    $$ -\begin{equation*} -\begin{split} - o &= i + 2 \lfloor k / 2 \rfloor - (k - 1) \\ - &= i + 2n - 2n \\ - &= i. -\end{split} -\end{equation*} +y(i) = \sum_{k=0}^{k=m-1}w(k)x(i+(m-1)-k). +$$ + +

    As an example, we have

    +$$ +y(4)=x(6)w(0)+x(5)w(1)+x(4)w(2)=0\times \alpha_0+\beta_3\alpha_1+\beta_2\alpha_2, +$$ + +

    as before except that we have an additional term \( x(6)w(0) \), which is zero.

    + +

    Similarly, for the fifth-order term we have

    +$$ +y(5)=x(7)w(0)+x(6)w(1)+x(5)w(2)=0\times \alpha_0+0\times\alpha_1+\beta_3\alpha_2. +$$ + +

    The zeroth-order term is

    +$$ +y(0)=x(2)w(0)+x(1)w(1)+x(0)w(2)=\beta_0 \alpha_0+0\times\alpha_1+0\times\alpha_2=\alpha_0\beta_0. $$ @@ -353,7 +408,7 @@ $$
  • 40
  • 41
  • ...
  • -
  • 47
  • +
  • 62
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs032.html b/doc/pub/week44/html/._week44-bs032.html index 66913f320..9f6bcb472 100644 --- a/doc/pub/week44/html/._week44-bs032.html +++ b/doc/pub/week44/html/._week44-bs032.html @@ -75,6 +75,12 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d None, 'a-deep-cnn-model-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Key Idea', 2, None, 'key-idea'), + ('How to do image compression before the era of deep learning', + 2, + None, + 'how-to-do-image-compression-before-the-era-of-deep-learning'), + ('The SVD example', 2, None, 'the-svd-example'), + ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Convolution Examples: Polynomial multiplication', 2, @@ -89,6 +95,8 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'a-more-efficient-way-of-coding-the-above-convolution'), + ('Commutative process', 2, None, 'commutative-process'), + ('Toeplitz matrices', 2, None, 'toeplitz-matrices'), ('Fourier series and Toeplitz matrices', 2, None, @@ -97,36 +105,75 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'generalizing-the-above-one-dimensional-case'), - ('Two-dimensional Objects', 2, None, 'two-dimensional-objects'), - ('CNNs in more detail', 2, None, 'cnns-in-more-detail'), - ('Performing a discrete convolution with padding ("From Raschka ' - 'et al":"https://github.com/rasbt/machine-learning-book")', + ('Memory considerations', 2, None, 'memory-considerations'), + ('Padding', 2, None, 'padding'), + ('New vector', 2, None, 'new-vector'), + ('Rewriting as dot products', 2, None, - 'performing-a-discrete-convolution-with-padding-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Performing a general discrete convolution ("From Raschka et ' + 'rewriting-as-dot-products'), + ('Cross correlation', 2, None, 'cross-correlation'), + ('Two-dimensional objects', 2, None, 'two-dimensional-objects'), + ('CNNs in more detail, simple example', + 2, + None, + 'cnns-in-more-detail-simple-example'), + ('The convolution stage', 2, None, 'the-convolution-stage'), + ('Finding the number of parameters', + 2, + None, + 'finding-the-number-of-parameters'), + ('New image (or volume)', 2, None, 'new-image-or-volume'), + ('Parameters to train, common settings', + 2, + None, + 'parameters-to-train-common-settings'), + ('Examples of CNN setups', 2, None, 'examples-of-cnn-setups'), + ('Summarizing: Performing a general discrete convolution ("From ' + 'Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, - 'performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Set of filters', 2, None, 'set-of-filters'), + 'summarizing-performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Pooling', 2, None, 'pooling'), - ('No zero padding, unit strides', - 2, - None, - 'no-zero-padding-unit-strides'), - ('Zero padding, unit strides', - 2, - None, - 'zero-padding-unit-strides'), - ('Half (same) padding', 2, None, 'half-same-padding'), - ('Full padding', 2, None, 'full-padding'), ('Pooling arithmetic', 2, None, 'pooling-arithmetic'), ('Pooling types ("From Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, 'pooling-types-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), + ('Building convolutional neural networks in Tensorflow and Keras', + 2, + None, + 'building-convolutional-neural-networks-in-tensorflow-and-keras'), + ('Setting it up', 2, None, 'setting-it-up'), + ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), + ('Strong correlations', 2, None, 'strong-correlations'), + ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), + ('Systematic reduction', 2, None, 'systematic-reduction'), + ('Prerequisites: Collect and pre-process data', + 2, + None, + 'prerequisites-collect-and-pre-process-data'), + ('Importing Keras and Tensorflow', + 2, + None, + 'importing-keras-and-tensorflow'), + ('Running with Keras', 2, None, 'running-with-keras'), + ('Final part', 2, None, 'final-part'), + ('Final visualization', 2, None, 'final-visualization'), + ('The CIFAR01 data set', 2, None, 'the-cifar01-data-set'), + ('Verifying the data set', 2, None, 'verifying-the-data-set'), + ('Set up the model', 2, None, 'set-up-the-model'), + ('Add Dense layers on top', 2, None, 'add-dense-layers-on-top'), + ('Compile and train the model', + 2, + None, + 'compile-and-train-the-model'), + ('Finally, evaluate the model', + 2, + None, + 'finally-evaluate-the-model'), ('Building our own CNN code', 2, None, @@ -173,27 +220,7 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Convolution in the Fourier domain', 3, None, - 'convolution-in-the-fourier-domain'), - ('Building convolutional neural networks in Tensorflow and Keras', - 2, - None, - 'building-convolutional-neural-networks-in-tensorflow-and-keras'), - ('Setting it up', 2, None, 'setting-it-up'), - ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), - ('Strong correlations', 2, None, 'strong-correlations'), - ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), - ('Systematic reduction', 2, None, 'systematic-reduction'), - ('Prerequisites: Collect and pre-process data', - 2, - None, - 'prerequisites-collect-and-pre-process-data'), - ('Importing Keras and Tensorflow', - 2, - None, - 'importing-keras-and-tensorflow'), - ('Running with Keras', 2, None, 'running-with-keras'), - ('Final part', 2, None, 'final-part'), - ('Final visualization', 2, None, 'final-visualization')]} + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -244,59 +271,74 @@ MathJax.Hub.Config({
  • CNNs in brief
  • A deep CNN model ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • Key Idea
  • -
  • Mathematics of CNNs
  • -
  • Convolution Examples: Polynomial multiplication
  • -
  • Efficient Polynomial Multiplication
  • -
  • Further simplification
  • -
  • A more efficient way of coding the above Convolution
  • -
  • Fourier series and Toeplitz matrices
  • -
  • Generalizing the above one-dimensional case
  • -
  • Two-dimensional Objects
  • -
  • CNNs in more detail
  • -
  • Performing a discrete convolution with padding ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Set of filters
  • -
  • Pooling
  • -
  • No zero padding, unit strides
  • -
  • Zero padding, unit strides
  • -
  • Half (same) padding
  • -
  • Full padding
  • -
  • Pooling arithmetic
  • -
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Building our own CNN code
  • -
  •    List of contents:
  • -
  •    Schedulers
  • -
  •    Usage of schedulers
  • -
  •    Cost functions
  • -
  •    Usage of cost functions
  • -
  •    Activation functions
  • -
  •    Usage of activation functions
  • -
  •    Convolution
  • -
  •    Layers
  • -
  •    Convolution2DLayer: convolution in a hidden layer
  • -
  •    Backpropagation in the convolutional layer
  • -
  •    Demonstration
  • -
  •    Pooling Layer
  • -
  •    Flattening Layer
  • -
  •    Fully Connected Layers
  • -
  •    Optimized Convolution2DLayer
  • -
  •    The Convolutional Neural Network (CNN)
  • -
  •    Usage of CNN code
  • -
  •    Additional Remarks
  • -
  •    Remarks on the speed
  • -
  •    Convolution using separable kernels
  • -
  •    Convolution in the Fourier domain
  • -
  • Building convolutional neural networks in Tensorflow and Keras
  • -
  • Setting it up
  • -
  • The MNIST dataset again
  • -
  • Strong correlations
  • -
  • Layers of a CNN
  • -
  • Systematic reduction
  • -
  • Prerequisites: Collect and pre-process data
  • -
  • Importing Keras and Tensorflow
  • -
  • Running with Keras
  • -
  • Final part
  • -
  • Final visualization
  • +
  • How to do image compression before the era of deep learning
  • +
  • The SVD example
  • +
  • Mathematics of CNNs
  • +
  • Mathematics of CNNs
  • +
  • Convolution Examples: Polynomial multiplication
  • +
  • Efficient Polynomial Multiplication
  • +
  • Further simplification
  • +
  • A more efficient way of coding the above Convolution
  • +
  • Commutative process
  • +
  • Toeplitz matrices
  • +
  • Fourier series and Toeplitz matrices
  • +
  • Generalizing the above one-dimensional case
  • +
  • Memory considerations
  • +
  • Padding
  • +
  • New vector
  • +
  • Rewriting as dot products
  • +
  • Cross correlation
  • +
  • Two-dimensional objects
  • +
  • CNNs in more detail, simple example
  • +
  • The convolution stage
  • +
  • Finding the number of parameters
  • +
  • New image (or volume)
  • +
  • Parameters to train, common settings
  • +
  • Examples of CNN setups
  • +
  • Summarizing: Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Pooling
  • +
  • Pooling arithmetic
  • +
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Building convolutional neural networks in Tensorflow and Keras
  • +
  • Setting it up
  • +
  • The MNIST dataset again
  • +
  • Strong correlations
  • +
  • Layers of a CNN
  • +
  • Systematic reduction
  • +
  • Prerequisites: Collect and pre-process data
  • +
  • Importing Keras and Tensorflow
  • +
  • Running with Keras
  • +
  • Final part
  • +
  • Final visualization
  • +
  • The CIFAR01 data set
  • +
  • Verifying the data set
  • +
  • Set up the model
  • +
  • Add Dense layers on top
  • +
  • Compile and train the model
  • +
  • Finally, evaluate the model
  • +
  • Building our own CNN code
  • +
  •    List of contents:
  • +
  •    Schedulers
  • +
  •    Usage of schedulers
  • +
  •    Cost functions
  • +
  •    Usage of cost functions
  • +
  •    Activation functions
  • +
  •    Usage of activation functions
  • +
  •    Convolution
  • +
  •    Layers
  • +
  •    Convolution2DLayer: convolution in a hidden layer
  • +
  •    Backpropagation in the convolutional layer
  • +
  •    Demonstration
  • +
  •    Pooling Layer
  • +
  •    Flattening Layer
  • +
  •    Fully Connected Layers
  • +
  •    Optimized Convolution2DLayer
  • +
  •    The Convolutional Neural Network (CNN)
  • +
  •    Usage of CNN code
  • +
  •    Additional Remarks
  • +
  •    Remarks on the speed
  • +
  •    Convolution using separable kernels
  • +
  •    Convolution in the Fourier domain
  • @@ -308,26 +350,21 @@ MathJax.Hub.Config({

     

     

     

    -

    Full padding

    +

    Rewriting as dot products

    -

    While convolving a kernel generally decreases the output size with -respect to the input size, sometimes the opposite is required. This can be -achieved with proper zero padding: +

    If we now flip the filter/weight vector, with the following term as a typical example

    +$$ +y(0)=x(2)w(0)+x(1)w(1)+x(0)w(2)=x(2)\tilde{w}(2)+x(1)\tilde{w}(1)+x(0)\tilde{w}(0), +$$ + +

    with \( \tilde{w}(0)=w(2) \), \( \tilde{w}(1)=w(1) \), and \( \tilde{w}(2)=w(0) \), we can then rewrite the above sum as a dot product of +\( x(i:i+(m-1))\tilde{w} \) for element \( y(i) \), where \( x(i:i+(m-1)) \) is simply a patch of \( \boldsymbol{x} \) of size \( m-1 \).

    -

    For any \( i \) and \( k \), and for \( p = k - 1 \) and \( s = 1 \),

    -$$ -\begin{equation*} -\begin{split} - o &= i + 2(k - 1) - (k - 1) \\ - &= i + (k - 1). -\end{split} -\end{equation*} -$$ - -

    This is sometimes referred to as full padding, because in this -setting every possible partial or complete superimposition of the kernel on the -input feature map is taken into account. +

    The padding \( P \) we have introduced for the convolution stage is just +another hyperparameter which is introduced as part of the +architecture. Similarly, below we will also introduce another +hyperparameter called Stride \( S \).

    @@ -355,7 +392,7 @@ input feature map is taken into account.

  • 41
  • 42
  • ...
  • -
  • 47
  • +
  • 62
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs033.html b/doc/pub/week44/html/._week44-bs033.html index e7d939c78..3adce6b7e 100644 --- a/doc/pub/week44/html/._week44-bs033.html +++ b/doc/pub/week44/html/._week44-bs033.html @@ -75,6 +75,12 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d None, 'a-deep-cnn-model-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Key Idea', 2, None, 'key-idea'), + ('How to do image compression before the era of deep learning', + 2, + None, + 'how-to-do-image-compression-before-the-era-of-deep-learning'), + ('The SVD example', 2, None, 'the-svd-example'), + ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Convolution Examples: Polynomial multiplication', 2, @@ -89,6 +95,8 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'a-more-efficient-way-of-coding-the-above-convolution'), + ('Commutative process', 2, None, 'commutative-process'), + ('Toeplitz matrices', 2, None, 'toeplitz-matrices'), ('Fourier series and Toeplitz matrices', 2, None, @@ -97,36 +105,75 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'generalizing-the-above-one-dimensional-case'), - ('Two-dimensional Objects', 2, None, 'two-dimensional-objects'), - ('CNNs in more detail', 2, None, 'cnns-in-more-detail'), - ('Performing a discrete convolution with padding ("From Raschka ' - 'et al":"https://github.com/rasbt/machine-learning-book")', + ('Memory considerations', 2, None, 'memory-considerations'), + ('Padding', 2, None, 'padding'), + ('New vector', 2, None, 'new-vector'), + ('Rewriting as dot products', 2, None, - 'performing-a-discrete-convolution-with-padding-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Performing a general discrete convolution ("From Raschka et ' + 'rewriting-as-dot-products'), + ('Cross correlation', 2, None, 'cross-correlation'), + ('Two-dimensional objects', 2, None, 'two-dimensional-objects'), + ('CNNs in more detail, simple example', + 2, + None, + 'cnns-in-more-detail-simple-example'), + ('The convolution stage', 2, None, 'the-convolution-stage'), + ('Finding the number of parameters', + 2, + None, + 'finding-the-number-of-parameters'), + ('New image (or volume)', 2, None, 'new-image-or-volume'), + ('Parameters to train, common settings', + 2, + None, + 'parameters-to-train-common-settings'), + ('Examples of CNN setups', 2, None, 'examples-of-cnn-setups'), + ('Summarizing: Performing a general discrete convolution ("From ' + 'Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, - 'performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Set of filters', 2, None, 'set-of-filters'), + 'summarizing-performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Pooling', 2, None, 'pooling'), - ('No zero padding, unit strides', - 2, - None, - 'no-zero-padding-unit-strides'), - ('Zero padding, unit strides', - 2, - None, - 'zero-padding-unit-strides'), - ('Half (same) padding', 2, None, 'half-same-padding'), - ('Full padding', 2, None, 'full-padding'), ('Pooling arithmetic', 2, None, 'pooling-arithmetic'), ('Pooling types ("From Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, 'pooling-types-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), + ('Building convolutional neural networks in Tensorflow and Keras', + 2, + None, + 'building-convolutional-neural-networks-in-tensorflow-and-keras'), + ('Setting it up', 2, None, 'setting-it-up'), + ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), + ('Strong correlations', 2, None, 'strong-correlations'), + ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), + ('Systematic reduction', 2, None, 'systematic-reduction'), + ('Prerequisites: Collect and pre-process data', + 2, + None, + 'prerequisites-collect-and-pre-process-data'), + ('Importing Keras and Tensorflow', + 2, + None, + 'importing-keras-and-tensorflow'), + ('Running with Keras', 2, None, 'running-with-keras'), + ('Final part', 2, None, 'final-part'), + ('Final visualization', 2, None, 'final-visualization'), + ('The CIFAR01 data set', 2, None, 'the-cifar01-data-set'), + ('Verifying the data set', 2, None, 'verifying-the-data-set'), + ('Set up the model', 2, None, 'set-up-the-model'), + ('Add Dense layers on top', 2, None, 'add-dense-layers-on-top'), + ('Compile and train the model', + 2, + None, + 'compile-and-train-the-model'), + ('Finally, evaluate the model', + 2, + None, + 'finally-evaluate-the-model'), ('Building our own CNN code', 2, None, @@ -173,27 +220,7 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Convolution in the Fourier domain', 3, None, - 'convolution-in-the-fourier-domain'), - ('Building convolutional neural networks in Tensorflow and Keras', - 2, - None, - 'building-convolutional-neural-networks-in-tensorflow-and-keras'), - ('Setting it up', 2, None, 'setting-it-up'), - ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), - ('Strong correlations', 2, None, 'strong-correlations'), - ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), - ('Systematic reduction', 2, None, 'systematic-reduction'), - ('Prerequisites: Collect and pre-process data', - 2, - None, - 'prerequisites-collect-and-pre-process-data'), - ('Importing Keras and Tensorflow', - 2, - None, - 'importing-keras-and-tensorflow'), - ('Running with Keras', 2, None, 'running-with-keras'), - ('Final part', 2, None, 'final-part'), - ('Final visualization', 2, None, 'final-visualization')]} + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -244,59 +271,74 @@ MathJax.Hub.Config({
  • CNNs in brief
  • A deep CNN model ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • Key Idea
  • -
  • Mathematics of CNNs
  • -
  • Convolution Examples: Polynomial multiplication
  • -
  • Efficient Polynomial Multiplication
  • -
  • Further simplification
  • -
  • A more efficient way of coding the above Convolution
  • -
  • Fourier series and Toeplitz matrices
  • -
  • Generalizing the above one-dimensional case
  • -
  • Two-dimensional Objects
  • -
  • CNNs in more detail
  • -
  • Performing a discrete convolution with padding ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Set of filters
  • -
  • Pooling
  • -
  • No zero padding, unit strides
  • -
  • Zero padding, unit strides
  • -
  • Half (same) padding
  • -
  • Full padding
  • -
  • Pooling arithmetic
  • -
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Building our own CNN code
  • -
  •    List of contents:
  • -
  •    Schedulers
  • -
  •    Usage of schedulers
  • -
  •    Cost functions
  • -
  •    Usage of cost functions
  • -
  •    Activation functions
  • -
  •    Usage of activation functions
  • -
  •    Convolution
  • -
  •    Layers
  • -
  •    Convolution2DLayer: convolution in a hidden layer
  • -
  •    Backpropagation in the convolutional layer
  • -
  •    Demonstration
  • -
  •    Pooling Layer
  • -
  •    Flattening Layer
  • -
  •    Fully Connected Layers
  • -
  •    Optimized Convolution2DLayer
  • -
  •    The Convolutional Neural Network (CNN)
  • -
  •    Usage of CNN code
  • -
  •    Additional Remarks
  • -
  •    Remarks on the speed
  • -
  •    Convolution using separable kernels
  • -
  •    Convolution in the Fourier domain
  • -
  • Building convolutional neural networks in Tensorflow and Keras
  • -
  • Setting it up
  • -
  • The MNIST dataset again
  • -
  • Strong correlations
  • -
  • Layers of a CNN
  • -
  • Systematic reduction
  • -
  • Prerequisites: Collect and pre-process data
  • -
  • Importing Keras and Tensorflow
  • -
  • Running with Keras
  • -
  • Final part
  • -
  • Final visualization
  • +
  • How to do image compression before the era of deep learning
  • +
  • The SVD example
  • +
  • Mathematics of CNNs
  • +
  • Mathematics of CNNs
  • +
  • Convolution Examples: Polynomial multiplication
  • +
  • Efficient Polynomial Multiplication
  • +
  • Further simplification
  • +
  • A more efficient way of coding the above Convolution
  • +
  • Commutative process
  • +
  • Toeplitz matrices
  • +
  • Fourier series and Toeplitz matrices
  • +
  • Generalizing the above one-dimensional case
  • +
  • Memory considerations
  • +
  • Padding
  • +
  • New vector
  • +
  • Rewriting as dot products
  • +
  • Cross correlation
  • +
  • Two-dimensional objects
  • +
  • CNNs in more detail, simple example
  • +
  • The convolution stage
  • +
  • Finding the number of parameters
  • +
  • New image (or volume)
  • +
  • Parameters to train, common settings
  • +
  • Examples of CNN setups
  • +
  • Summarizing: Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Pooling
  • +
  • Pooling arithmetic
  • +
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Building convolutional neural networks in Tensorflow and Keras
  • +
  • Setting it up
  • +
  • The MNIST dataset again
  • +
  • Strong correlations
  • +
  • Layers of a CNN
  • +
  • Systematic reduction
  • +
  • Prerequisites: Collect and pre-process data
  • +
  • Importing Keras and Tensorflow
  • +
  • Running with Keras
  • +
  • Final part
  • +
  • Final visualization
  • +
  • The CIFAR01 data set
  • +
  • Verifying the data set
  • +
  • Set up the model
  • +
  • Add Dense layers on top
  • +
  • Compile and train the model
  • +
  • Finally, evaluate the model
  • +
  • Building our own CNN code
  • +
  •    List of contents:
  • +
  •    Schedulers
  • +
  •    Usage of schedulers
  • +
  •    Cost functions
  • +
  •    Usage of cost functions
  • +
  •    Activation functions
  • +
  •    Usage of activation functions
  • +
  •    Convolution
  • +
  •    Layers
  • +
  •    Convolution2DLayer: convolution in a hidden layer
  • +
  •    Backpropagation in the convolutional layer
  • +
  •    Demonstration
  • +
  •    Pooling Layer
  • +
  •    Flattening Layer
  • +
  •    Fully Connected Layers
  • +
  •    Optimized Convolution2DLayer
  • +
  •    The Convolutional Neural Network (CNN)
  • +
  •    Usage of CNN code
  • +
  •    Additional Remarks
  • +
  •    Remarks on the speed
  • +
  •    Convolution using separable kernels
  • +
  •    Convolution in the Fourier domain
  • @@ -308,25 +350,55 @@ MathJax.Hub.Config({

     

     

     

    -

    Pooling arithmetic

    +

    Cross correlation

    -

    In a neural network, pooling layers provide invariance to small translations of -the input. The most common kind of pooling is max pooling, which -consists in splitting the input in (usually non-overlapping) patches and -outputting the maximum value of each patch. Other kinds of pooling exist, e.g., -mean or average pooling, which all share the same idea of aggregating the input -locally by applying a non-linearity to the content of some patches. +

    In essentially all applications one uses what is called cross correlation instead of the standard convolution described above. +This means that multiplication is performed in the same direction and instead of the general expression we have discussed above (with infinite sums)

    - -

    Since pooling does not involve -zero padding, the relationship describing the general case is as follows: -

    - -

    For any \( i \), \( k \) and \( s \),

    $$ -\begin{equation*} - o = \left\lfloor \frac{i - k}{s} \right\rfloor + 1. -\end{equation*} +y(i) = \sum_{k=-\infty}^{k=\infty}w(k)x(i-k), +$$ + +

    we have now

    +$$ +y(i) = \sum_{k=-\infty}^{k=\infty}w(k)x(i+k). +$$ + +

    Both TensorFlow and PyTorch (as well as our own code example below), +implement the last equation, although it is normally referred to as +convolution. The same padding rules and stride rules discussed below +apply to this expression as well. +

    + +

    We leave it as an exercise for you to convince yourself that the example we have discussed till now, gives the same final expression using the last expression.

    +

    Two-dimensional objects

    + +

    We are now ready to start studying the discrete convolutions relevant for convolutional neural networks. +We often use convolutions over more than one dimension at a time. If +we have a two-dimensional image \( X \) as input, we can have a filter +defined by a two-dimensional kernel/weight/filter \( W \). This leads to an output \( Y \) +

    + +$$ +Y(i,j)=(X * W)(i,j) = \sum_m\sum_n X(m,n)W(i-m,j-n). +$$ + +

    Convolution is a commutative process, which means we can rewrite this equation as

    +$$ +Y(i,j)=(X * W)(i,j) = \sum_m\sum_n X(i-m,j-n)W(m,n). +$$ + +

    Normally the latter is more straightforward to implement in a machine +larning library since there is less variation in the range of values +of \( m \) and \( n \). +

    + +

    As mentioned above, most deep learning libraries implement +cross-correlation instead of convolution (although it is referred to as +convolution) +

    +$$ +Y(i,j)=(X * W)(i,j) = \sum_m\sum_n X(i+m,j+n)W(m,n). $$ @@ -355,7 +427,7 @@ $$
  • 42
  • 43
  • ...
  • -
  • 47
  • +
  • 62
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs034.html b/doc/pub/week44/html/._week44-bs034.html index d4f55423e..46214b787 100644 --- a/doc/pub/week44/html/._week44-bs034.html +++ b/doc/pub/week44/html/._week44-bs034.html @@ -75,6 +75,12 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d None, 'a-deep-cnn-model-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Key Idea', 2, None, 'key-idea'), + ('How to do image compression before the era of deep learning', + 2, + None, + 'how-to-do-image-compression-before-the-era-of-deep-learning'), + ('The SVD example', 2, None, 'the-svd-example'), + ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Convolution Examples: Polynomial multiplication', 2, @@ -89,6 +95,8 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'a-more-efficient-way-of-coding-the-above-convolution'), + ('Commutative process', 2, None, 'commutative-process'), + ('Toeplitz matrices', 2, None, 'toeplitz-matrices'), ('Fourier series and Toeplitz matrices', 2, None, @@ -97,36 +105,75 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'generalizing-the-above-one-dimensional-case'), - ('Two-dimensional Objects', 2, None, 'two-dimensional-objects'), - ('CNNs in more detail', 2, None, 'cnns-in-more-detail'), - ('Performing a discrete convolution with padding ("From Raschka ' - 'et al":"https://github.com/rasbt/machine-learning-book")', + ('Memory considerations', 2, None, 'memory-considerations'), + ('Padding', 2, None, 'padding'), + ('New vector', 2, None, 'new-vector'), + ('Rewriting as dot products', 2, None, - 'performing-a-discrete-convolution-with-padding-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Performing a general discrete convolution ("From Raschka et ' + 'rewriting-as-dot-products'), + ('Cross correlation', 2, None, 'cross-correlation'), + ('Two-dimensional objects', 2, None, 'two-dimensional-objects'), + ('CNNs in more detail, simple example', + 2, + None, + 'cnns-in-more-detail-simple-example'), + ('The convolution stage', 2, None, 'the-convolution-stage'), + ('Finding the number of parameters', + 2, + None, + 'finding-the-number-of-parameters'), + ('New image (or volume)', 2, None, 'new-image-or-volume'), + ('Parameters to train, common settings', + 2, + None, + 'parameters-to-train-common-settings'), + ('Examples of CNN setups', 2, None, 'examples-of-cnn-setups'), + ('Summarizing: Performing a general discrete convolution ("From ' + 'Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, - 'performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Set of filters', 2, None, 'set-of-filters'), + 'summarizing-performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Pooling', 2, None, 'pooling'), - ('No zero padding, unit strides', - 2, - None, - 'no-zero-padding-unit-strides'), - ('Zero padding, unit strides', - 2, - None, - 'zero-padding-unit-strides'), - ('Half (same) padding', 2, None, 'half-same-padding'), - ('Full padding', 2, None, 'full-padding'), ('Pooling arithmetic', 2, None, 'pooling-arithmetic'), ('Pooling types ("From Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, 'pooling-types-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), + ('Building convolutional neural networks in Tensorflow and Keras', + 2, + None, + 'building-convolutional-neural-networks-in-tensorflow-and-keras'), + ('Setting it up', 2, None, 'setting-it-up'), + ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), + ('Strong correlations', 2, None, 'strong-correlations'), + ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), + ('Systematic reduction', 2, None, 'systematic-reduction'), + ('Prerequisites: Collect and pre-process data', + 2, + None, + 'prerequisites-collect-and-pre-process-data'), + ('Importing Keras and Tensorflow', + 2, + None, + 'importing-keras-and-tensorflow'), + ('Running with Keras', 2, None, 'running-with-keras'), + ('Final part', 2, None, 'final-part'), + ('Final visualization', 2, None, 'final-visualization'), + ('The CIFAR01 data set', 2, None, 'the-cifar01-data-set'), + ('Verifying the data set', 2, None, 'verifying-the-data-set'), + ('Set up the model', 2, None, 'set-up-the-model'), + ('Add Dense layers on top', 2, None, 'add-dense-layers-on-top'), + ('Compile and train the model', + 2, + None, + 'compile-and-train-the-model'), + ('Finally, evaluate the model', + 2, + None, + 'finally-evaluate-the-model'), ('Building our own CNN code', 2, None, @@ -173,27 +220,7 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Convolution in the Fourier domain', 3, None, - 'convolution-in-the-fourier-domain'), - ('Building convolutional neural networks in Tensorflow and Keras', - 2, - None, - 'building-convolutional-neural-networks-in-tensorflow-and-keras'), - ('Setting it up', 2, None, 'setting-it-up'), - ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), - ('Strong correlations', 2, None, 'strong-correlations'), - ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), - ('Systematic reduction', 2, None, 'systematic-reduction'), - ('Prerequisites: Collect and pre-process data', - 2, - None, - 'prerequisites-collect-and-pre-process-data'), - ('Importing Keras and Tensorflow', - 2, - None, - 'importing-keras-and-tensorflow'), - ('Running with Keras', 2, None, 'running-with-keras'), - ('Final part', 2, None, 'final-part'), - ('Final visualization', 2, None, 'final-visualization')]} + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -244,59 +271,74 @@ MathJax.Hub.Config({
  • CNNs in brief
  • A deep CNN model ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • Key Idea
  • -
  • Mathematics of CNNs
  • -
  • Convolution Examples: Polynomial multiplication
  • -
  • Efficient Polynomial Multiplication
  • -
  • Further simplification
  • -
  • A more efficient way of coding the above Convolution
  • -
  • Fourier series and Toeplitz matrices
  • -
  • Generalizing the above one-dimensional case
  • -
  • Two-dimensional Objects
  • -
  • CNNs in more detail
  • -
  • Performing a discrete convolution with padding ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Set of filters
  • -
  • Pooling
  • -
  • No zero padding, unit strides
  • -
  • Zero padding, unit strides
  • -
  • Half (same) padding
  • -
  • Full padding
  • -
  • Pooling arithmetic
  • -
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Building our own CNN code
  • -
  •    List of contents:
  • -
  •    Schedulers
  • -
  •    Usage of schedulers
  • -
  •    Cost functions
  • -
  •    Usage of cost functions
  • -
  •    Activation functions
  • -
  •    Usage of activation functions
  • -
  •    Convolution
  • -
  •    Layers
  • -
  •    Convolution2DLayer: convolution in a hidden layer
  • -
  •    Backpropagation in the convolutional layer
  • -
  •    Demonstration
  • -
  •    Pooling Layer
  • -
  •    Flattening Layer
  • -
  •    Fully Connected Layers
  • -
  •    Optimized Convolution2DLayer
  • -
  •    The Convolutional Neural Network (CNN)
  • -
  •    Usage of CNN code
  • -
  •    Additional Remarks
  • -
  •    Remarks on the speed
  • -
  •    Convolution using separable kernels
  • -
  •    Convolution in the Fourier domain
  • -
  • Building convolutional neural networks in Tensorflow and Keras
  • -
  • Setting it up
  • -
  • The MNIST dataset again
  • -
  • Strong correlations
  • -
  • Layers of a CNN
  • -
  • Systematic reduction
  • -
  • Prerequisites: Collect and pre-process data
  • -
  • Importing Keras and Tensorflow
  • -
  • Running with Keras
  • -
  • Final part
  • -
  • Final visualization
  • +
  • How to do image compression before the era of deep learning
  • +
  • The SVD example
  • +
  • Mathematics of CNNs
  • +
  • Mathematics of CNNs
  • +
  • Convolution Examples: Polynomial multiplication
  • +
  • Efficient Polynomial Multiplication
  • +
  • Further simplification
  • +
  • A more efficient way of coding the above Convolution
  • +
  • Commutative process
  • +
  • Toeplitz matrices
  • +
  • Fourier series and Toeplitz matrices
  • +
  • Generalizing the above one-dimensional case
  • +
  • Memory considerations
  • +
  • Padding
  • +
  • New vector
  • +
  • Rewriting as dot products
  • +
  • Cross correlation
  • +
  • Two-dimensional objects
  • +
  • CNNs in more detail, simple example
  • +
  • The convolution stage
  • +
  • Finding the number of parameters
  • +
  • New image (or volume)
  • +
  • Parameters to train, common settings
  • +
  • Examples of CNN setups
  • +
  • Summarizing: Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Pooling
  • +
  • Pooling arithmetic
  • +
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Building convolutional neural networks in Tensorflow and Keras
  • +
  • Setting it up
  • +
  • The MNIST dataset again
  • +
  • Strong correlations
  • +
  • Layers of a CNN
  • +
  • Systematic reduction
  • +
  • Prerequisites: Collect and pre-process data
  • +
  • Importing Keras and Tensorflow
  • +
  • Running with Keras
  • +
  • Final part
  • +
  • Final visualization
  • +
  • The CIFAR01 data set
  • +
  • Verifying the data set
  • +
  • Set up the model
  • +
  • Add Dense layers on top
  • +
  • Compile and train the model
  • +
  • Finally, evaluate the model
  • +
  • Building our own CNN code
  • +
  •    List of contents:
  • +
  •    Schedulers
  • +
  •    Usage of schedulers
  • +
  •    Cost functions
  • +
  •    Usage of cost functions
  • +
  •    Activation functions
  • +
  •    Usage of activation functions
  • +
  •    Convolution
  • +
  •    Layers
  • +
  •    Convolution2DLayer: convolution in a hidden layer
  • +
  •    Backpropagation in the convolutional layer
  • +
  •    Demonstration
  • +
  •    Pooling Layer
  • +
  •    Flattening Layer
  • +
  •    Fully Connected Layers
  • +
  •    Optimized Convolution2DLayer
  • +
  •    The Convolutional Neural Network (CNN)
  • +
  •    Usage of CNN code
  • +
  •    Additional Remarks
  • +
  •    Remarks on the speed
  • +
  •    Convolution using separable kernels
  • +
  •    Convolution in the Fourier domain
  • @@ -308,15 +350,64 @@ MathJax.Hub.Config({

     

     

     

    -

    Pooling types (From Raschka et al)

    +

    CNNs in more detail, simple example

    -
    -
    -
    -

    Figure 6: A deep CNN

    -
    -

    -
    +

    Let assume we have an input matrix \( X \) of dimensionality \( 3\times 3 \) +and a \( 2\times 2 \) filter \( W \) given by the following matrices +

    + +$$ +\boldsymbol{X}=\begin{bmatrix}x_{00} & x_{01} & x_{02} \\ + x_{10} & x_{11} & x_{12} \\ + x_{20} & x_{21} & x_{22} \end{bmatrix}, +$$ + +

    and

    +$$ +\boldsymbol{W}=\begin{bmatrix}w_{00} & w_{01} \\ + w_{10} & w_{11}\end{bmatrix}. +$$ + +

    We introduce now the hyperparameter \( S \) stride. Stride represents how the filter \( W \) moves the convolution process on the matrix \( X \). +We strongly recommend the repository on Arithmetic of deep learning by Dumoulin and Visin +

    + +

    Here we set the stride equal to \( S=1 \), which means that, starting with the element \( x_{00} \), the filter will act on \( 2\times 2 \) submatrices each time, starting with the upper corner and moving according to the stride value column by column.

    + +

    Here we perform the operation

    +$$ +Y_(i,j)=(X * W)(i,j) = \sum_m\sum_n X(i-m,j-n)W(m,n), +$$ + +

    and obtain

    +$$ +\boldsymbol{Y}=\begin{bmatrix}x_{00}w_{00}+x_{01}w_{01}+x_{10}w_{10}+x_{11}w_{11} & x_{01}w_{00}+x_{02}w_{01}+x_{11}w_{10}+x_{12}w_{11} \\ + x_{10}w_{00}+x_{11}w_{01}+x_{20}w_{10}+x_{21}w_{11} & x_{11}w_{00}+x_{12}w_{01}+x_{21}w_{10}+x_{22}w_{11}\end{bmatrix}. +$$ + +

    We can rewrite this operation in terms of a matrix-vector multiplication by defining a new vector where we flatten out the inputs as a vector \( \boldsymbol{X}' \) of length \( 9 \) and +a matrix \( \boldsymbol{W}' \) with dimension \( 4\times 9 \) as +

    + +$$ +\boldsymbol{X}'=\begin{bmatrix}x_{00} \\ x_{01} \\ x_{02} \\ x_{10} \\ x_{11} \\ x_{12} \\ x_{20} \\ x_{21} \\ x_{22} \end{bmatrix}, +$$ + +

    and the new matrix

    +$$ +\boldsymbol{W}'=\begin{bmatrix} w_{00} & w_{01} & 0 & w_{10} & w_{11} & 0 & 0 & 0 & 0 \\ + 0 & w_{00} & w_{01} & 0 & w_{10} & w_{11} & 0 & 0 & 0 \\ + 0 & 0 & 0 & w_{00} & w_{01} & 0 & w_{10} & w_{11} & 0 \\ + 0 & 0 & 0 & 0 & w_{00} & w_{01} & 0 & w_{10} & w_{11}\end{bmatrix}. +$$ + +

    We see easily that performing the matrix-vector multiplication \( \boldsymbol{W}'\boldsymbol{X}' \) is the same as the above convolution with stride \( S=1 \), that is

    + +$$ +Y=(\boldsymbol{W}*\boldsymbol{X}), +$$ + +

    is now given by \( \boldsymbol{W}'\boldsymbol{X}' \) which is a vector of length \( 4 \) instead of the originally resulting \( 2\times 2 \) output matrix.

    @@ -343,7 +434,7 @@ MathJax.Hub.Config({

  • 43
  • 44
  • ...
  • -
  • 47
  • +
  • 62
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs035.html b/doc/pub/week44/html/._week44-bs035.html index 34af1ccd0..02e0ed674 100644 --- a/doc/pub/week44/html/._week44-bs035.html +++ b/doc/pub/week44/html/._week44-bs035.html @@ -75,6 +75,12 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d None, 'a-deep-cnn-model-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Key Idea', 2, None, 'key-idea'), + ('How to do image compression before the era of deep learning', + 2, + None, + 'how-to-do-image-compression-before-the-era-of-deep-learning'), + ('The SVD example', 2, None, 'the-svd-example'), + ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Convolution Examples: Polynomial multiplication', 2, @@ -89,6 +95,8 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'a-more-efficient-way-of-coding-the-above-convolution'), + ('Commutative process', 2, None, 'commutative-process'), + ('Toeplitz matrices', 2, None, 'toeplitz-matrices'), ('Fourier series and Toeplitz matrices', 2, None, @@ -97,36 +105,75 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'generalizing-the-above-one-dimensional-case'), - ('Two-dimensional Objects', 2, None, 'two-dimensional-objects'), - ('CNNs in more detail', 2, None, 'cnns-in-more-detail'), - ('Performing a discrete convolution with padding ("From Raschka ' - 'et al":"https://github.com/rasbt/machine-learning-book")', + ('Memory considerations', 2, None, 'memory-considerations'), + ('Padding', 2, None, 'padding'), + ('New vector', 2, None, 'new-vector'), + ('Rewriting as dot products', 2, None, - 'performing-a-discrete-convolution-with-padding-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Performing a general discrete convolution ("From Raschka et ' + 'rewriting-as-dot-products'), + ('Cross correlation', 2, None, 'cross-correlation'), + ('Two-dimensional objects', 2, None, 'two-dimensional-objects'), + ('CNNs in more detail, simple example', + 2, + None, + 'cnns-in-more-detail-simple-example'), + ('The convolution stage', 2, None, 'the-convolution-stage'), + ('Finding the number of parameters', + 2, + None, + 'finding-the-number-of-parameters'), + ('New image (or volume)', 2, None, 'new-image-or-volume'), + ('Parameters to train, common settings', + 2, + None, + 'parameters-to-train-common-settings'), + ('Examples of CNN setups', 2, None, 'examples-of-cnn-setups'), + ('Summarizing: Performing a general discrete convolution ("From ' + 'Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, - 'performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Set of filters', 2, None, 'set-of-filters'), + 'summarizing-performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Pooling', 2, None, 'pooling'), - ('No zero padding, unit strides', - 2, - None, - 'no-zero-padding-unit-strides'), - ('Zero padding, unit strides', - 2, - None, - 'zero-padding-unit-strides'), - ('Half (same) padding', 2, None, 'half-same-padding'), - ('Full padding', 2, None, 'full-padding'), ('Pooling arithmetic', 2, None, 'pooling-arithmetic'), ('Pooling types ("From Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, 'pooling-types-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), + ('Building convolutional neural networks in Tensorflow and Keras', + 2, + None, + 'building-convolutional-neural-networks-in-tensorflow-and-keras'), + ('Setting it up', 2, None, 'setting-it-up'), + ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), + ('Strong correlations', 2, None, 'strong-correlations'), + ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), + ('Systematic reduction', 2, None, 'systematic-reduction'), + ('Prerequisites: Collect and pre-process data', + 2, + None, + 'prerequisites-collect-and-pre-process-data'), + ('Importing Keras and Tensorflow', + 2, + None, + 'importing-keras-and-tensorflow'), + ('Running with Keras', 2, None, 'running-with-keras'), + ('Final part', 2, None, 'final-part'), + ('Final visualization', 2, None, 'final-visualization'), + ('The CIFAR01 data set', 2, None, 'the-cifar01-data-set'), + ('Verifying the data set', 2, None, 'verifying-the-data-set'), + ('Set up the model', 2, None, 'set-up-the-model'), + ('Add Dense layers on top', 2, None, 'add-dense-layers-on-top'), + ('Compile and train the model', + 2, + None, + 'compile-and-train-the-model'), + ('Finally, evaluate the model', + 2, + None, + 'finally-evaluate-the-model'), ('Building our own CNN code', 2, None, @@ -173,27 +220,7 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Convolution in the Fourier domain', 3, None, - 'convolution-in-the-fourier-domain'), - ('Building convolutional neural networks in Tensorflow and Keras', - 2, - None, - 'building-convolutional-neural-networks-in-tensorflow-and-keras'), - ('Setting it up', 2, None, 'setting-it-up'), - ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), - ('Strong correlations', 2, None, 'strong-correlations'), - ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), - ('Systematic reduction', 2, None, 'systematic-reduction'), - ('Prerequisites: Collect and pre-process data', - 2, - None, - 'prerequisites-collect-and-pre-process-data'), - ('Importing Keras and Tensorflow', - 2, - None, - 'importing-keras-and-tensorflow'), - ('Running with Keras', 2, None, 'running-with-keras'), - ('Final part', 2, None, 'final-part'), - ('Final visualization', 2, None, 'final-visualization')]} + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -244,59 +271,74 @@ MathJax.Hub.Config({
  • CNNs in brief
  • A deep CNN model ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • Key Idea
  • -
  • Mathematics of CNNs
  • -
  • Convolution Examples: Polynomial multiplication
  • -
  • Efficient Polynomial Multiplication
  • -
  • Further simplification
  • -
  • A more efficient way of coding the above Convolution
  • -
  • Fourier series and Toeplitz matrices
  • -
  • Generalizing the above one-dimensional case
  • -
  • Two-dimensional Objects
  • -
  • CNNs in more detail
  • -
  • Performing a discrete convolution with padding ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Set of filters
  • -
  • Pooling
  • -
  • No zero padding, unit strides
  • -
  • Zero padding, unit strides
  • -
  • Half (same) padding
  • -
  • Full padding
  • -
  • Pooling arithmetic
  • -
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Building our own CNN code
  • -
  •    List of contents:
  • -
  •    Schedulers
  • -
  •    Usage of schedulers
  • -
  •    Cost functions
  • -
  •    Usage of cost functions
  • -
  •    Activation functions
  • -
  •    Usage of activation functions
  • -
  •    Convolution
  • -
  •    Layers
  • -
  •    Convolution2DLayer: convolution in a hidden layer
  • -
  •    Backpropagation in the convolutional layer
  • -
  •    Demonstration
  • -
  •    Pooling Layer
  • -
  •    Flattening Layer
  • -
  •    Fully Connected Layers
  • -
  •    Optimized Convolution2DLayer
  • -
  •    The Convolutional Neural Network (CNN)
  • -
  •    Usage of CNN code
  • -
  •    Additional Remarks
  • -
  •    Remarks on the speed
  • -
  •    Convolution using separable kernels
  • -
  •    Convolution in the Fourier domain
  • -
  • Building convolutional neural networks in Tensorflow and Keras
  • -
  • Setting it up
  • -
  • The MNIST dataset again
  • -
  • Strong correlations
  • -
  • Layers of a CNN
  • -
  • Systematic reduction
  • -
  • Prerequisites: Collect and pre-process data
  • -
  • Importing Keras and Tensorflow
  • -
  • Running with Keras
  • -
  • Final part
  • -
  • Final visualization
  • +
  • How to do image compression before the era of deep learning
  • +
  • The SVD example
  • +
  • Mathematics of CNNs
  • +
  • Mathematics of CNNs
  • +
  • Convolution Examples: Polynomial multiplication
  • +
  • Efficient Polynomial Multiplication
  • +
  • Further simplification
  • +
  • A more efficient way of coding the above Convolution
  • +
  • Commutative process
  • +
  • Toeplitz matrices
  • +
  • Fourier series and Toeplitz matrices
  • +
  • Generalizing the above one-dimensional case
  • +
  • Memory considerations
  • +
  • Padding
  • +
  • New vector
  • +
  • Rewriting as dot products
  • +
  • Cross correlation
  • +
  • Two-dimensional objects
  • +
  • CNNs in more detail, simple example
  • +
  • The convolution stage
  • +
  • Finding the number of parameters
  • +
  • New image (or volume)
  • +
  • Parameters to train, common settings
  • +
  • Examples of CNN setups
  • +
  • Summarizing: Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Pooling
  • +
  • Pooling arithmetic
  • +
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Building convolutional neural networks in Tensorflow and Keras
  • +
  • Setting it up
  • +
  • The MNIST dataset again
  • +
  • Strong correlations
  • +
  • Layers of a CNN
  • +
  • Systematic reduction
  • +
  • Prerequisites: Collect and pre-process data
  • +
  • Importing Keras and Tensorflow
  • +
  • Running with Keras
  • +
  • Final part
  • +
  • Final visualization
  • +
  • The CIFAR01 data set
  • +
  • Verifying the data set
  • +
  • Set up the model
  • +
  • Add Dense layers on top
  • +
  • Compile and train the model
  • +
  • Finally, evaluate the model
  • +
  • Building our own CNN code
  • +
  •    List of contents:
  • +
  •    Schedulers
  • +
  •    Usage of schedulers
  • +
  •    Cost functions
  • +
  •    Usage of cost functions
  • +
  •    Activation functions
  • +
  •    Usage of activation functions
  • +
  •    Convolution
  • +
  •    Layers
  • +
  •    Convolution2DLayer: convolution in a hidden layer
  • +
  •    Backpropagation in the convolutional layer
  • +
  •    Demonstration
  • +
  •    Pooling Layer
  • +
  •    Flattening Layer
  • +
  •    Fully Connected Layers
  • +
  •    Optimized Convolution2DLayer
  • +
  •    The Convolutional Neural Network (CNN)
  • +
  •    Usage of CNN code
  • +
  •    Additional Remarks
  • +
  •    Remarks on the speed
  • +
  •    Convolution using separable kernels
  • +
  •    Convolution in the Fourier domain
  • @@ -308,3259 +350,13 @@ MathJax.Hub.Config({

     

     

     

    -

    Building our own CNN code

    +

    The convolution stage

    -

    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. +

    The convolution stage, where we apply different filters \( \boldsymbol{W} \) in +order to reduce the dimensionality of an image, adds, in addition to +the weights and biases (to be trained by the back propagation +algorithm) that define the filters, two new hyperparameters, the so-called +padding \( P \) and the stride \( S \).

    @@ -3588,7 +384,7 @@ optimization technique.

  • 44
  • 45
  • ...
  • -
  • 47
  • +
  • 62
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs036.html b/doc/pub/week44/html/._week44-bs036.html index 1201e6182..91901cd36 100644 --- a/doc/pub/week44/html/._week44-bs036.html +++ b/doc/pub/week44/html/._week44-bs036.html @@ -75,6 +75,12 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d None, 'a-deep-cnn-model-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Key Idea', 2, None, 'key-idea'), + ('How to do image compression before the era of deep learning', + 2, + None, + 'how-to-do-image-compression-before-the-era-of-deep-learning'), + ('The SVD example', 2, None, 'the-svd-example'), + ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Convolution Examples: Polynomial multiplication', 2, @@ -89,6 +95,8 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'a-more-efficient-way-of-coding-the-above-convolution'), + ('Commutative process', 2, None, 'commutative-process'), + ('Toeplitz matrices', 2, None, 'toeplitz-matrices'), ('Fourier series and Toeplitz matrices', 2, None, @@ -97,36 +105,75 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'generalizing-the-above-one-dimensional-case'), - ('Two-dimensional Objects', 2, None, 'two-dimensional-objects'), - ('CNNs in more detail', 2, None, 'cnns-in-more-detail'), - ('Performing a discrete convolution with padding ("From Raschka ' - 'et al":"https://github.com/rasbt/machine-learning-book")', + ('Memory considerations', 2, None, 'memory-considerations'), + ('Padding', 2, None, 'padding'), + ('New vector', 2, None, 'new-vector'), + ('Rewriting as dot products', 2, None, - 'performing-a-discrete-convolution-with-padding-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Performing a general discrete convolution ("From Raschka et ' + 'rewriting-as-dot-products'), + ('Cross correlation', 2, None, 'cross-correlation'), + ('Two-dimensional objects', 2, None, 'two-dimensional-objects'), + ('CNNs in more detail, simple example', + 2, + None, + 'cnns-in-more-detail-simple-example'), + ('The convolution stage', 2, None, 'the-convolution-stage'), + ('Finding the number of parameters', + 2, + None, + 'finding-the-number-of-parameters'), + ('New image (or volume)', 2, None, 'new-image-or-volume'), + ('Parameters to train, common settings', + 2, + None, + 'parameters-to-train-common-settings'), + ('Examples of CNN setups', 2, None, 'examples-of-cnn-setups'), + ('Summarizing: Performing a general discrete convolution ("From ' + 'Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, - 'performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Set of filters', 2, None, 'set-of-filters'), + 'summarizing-performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Pooling', 2, None, 'pooling'), - ('No zero padding, unit strides', - 2, - None, - 'no-zero-padding-unit-strides'), - ('Zero padding, unit strides', - 2, - None, - 'zero-padding-unit-strides'), - ('Half (same) padding', 2, None, 'half-same-padding'), - ('Full padding', 2, None, 'full-padding'), ('Pooling arithmetic', 2, None, 'pooling-arithmetic'), ('Pooling types ("From Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, 'pooling-types-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), + ('Building convolutional neural networks in Tensorflow and Keras', + 2, + None, + 'building-convolutional-neural-networks-in-tensorflow-and-keras'), + ('Setting it up', 2, None, 'setting-it-up'), + ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), + ('Strong correlations', 2, None, 'strong-correlations'), + ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), + ('Systematic reduction', 2, None, 'systematic-reduction'), + ('Prerequisites: Collect and pre-process data', + 2, + None, + 'prerequisites-collect-and-pre-process-data'), + ('Importing Keras and Tensorflow', + 2, + None, + 'importing-keras-and-tensorflow'), + ('Running with Keras', 2, None, 'running-with-keras'), + ('Final part', 2, None, 'final-part'), + ('Final visualization', 2, None, 'final-visualization'), + ('The CIFAR01 data set', 2, None, 'the-cifar01-data-set'), + ('Verifying the data set', 2, None, 'verifying-the-data-set'), + ('Set up the model', 2, None, 'set-up-the-model'), + ('Add Dense layers on top', 2, None, 'add-dense-layers-on-top'), + ('Compile and train the model', + 2, + None, + 'compile-and-train-the-model'), + ('Finally, evaluate the model', + 2, + None, + 'finally-evaluate-the-model'), ('Building our own CNN code', 2, None, @@ -173,27 +220,7 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Convolution in the Fourier domain', 3, None, - 'convolution-in-the-fourier-domain'), - ('Building convolutional neural networks in Tensorflow and Keras', - 2, - None, - 'building-convolutional-neural-networks-in-tensorflow-and-keras'), - ('Setting it up', 2, None, 'setting-it-up'), - ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), - ('Strong correlations', 2, None, 'strong-correlations'), - ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), - ('Systematic reduction', 2, None, 'systematic-reduction'), - ('Prerequisites: Collect and pre-process data', - 2, - None, - 'prerequisites-collect-and-pre-process-data'), - ('Importing Keras and Tensorflow', - 2, - None, - 'importing-keras-and-tensorflow'), - ('Running with Keras', 2, None, 'running-with-keras'), - ('Final part', 2, None, 'final-part'), - ('Final visualization', 2, None, 'final-visualization')]} + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -244,59 +271,74 @@ MathJax.Hub.Config({
  • CNNs in brief
  • A deep CNN model ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • Key Idea
  • -
  • Mathematics of CNNs
  • -
  • Convolution Examples: Polynomial multiplication
  • -
  • Efficient Polynomial Multiplication
  • -
  • Further simplification
  • -
  • A more efficient way of coding the above Convolution
  • -
  • Fourier series and Toeplitz matrices
  • -
  • Generalizing the above one-dimensional case
  • -
  • Two-dimensional Objects
  • -
  • CNNs in more detail
  • -
  • Performing a discrete convolution with padding ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Set of filters
  • -
  • Pooling
  • -
  • No zero padding, unit strides
  • -
  • Zero padding, unit strides
  • -
  • Half (same) padding
  • -
  • Full padding
  • -
  • Pooling arithmetic
  • -
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Building our own CNN code
  • -
  •    List of contents:
  • -
  •    Schedulers
  • -
  •    Usage of schedulers
  • -
  •    Cost functions
  • -
  •    Usage of cost functions
  • -
  •    Activation functions
  • -
  •    Usage of activation functions
  • -
  •    Convolution
  • -
  •    Layers
  • -
  •    Convolution2DLayer: convolution in a hidden layer
  • -
  •    Backpropagation in the convolutional layer
  • -
  •    Demonstration
  • -
  •    Pooling Layer
  • -
  •    Flattening Layer
  • -
  •    Fully Connected Layers
  • -
  •    Optimized Convolution2DLayer
  • -
  •    The Convolutional Neural Network (CNN)
  • -
  •    Usage of CNN code
  • -
  •    Additional Remarks
  • -
  •    Remarks on the speed
  • -
  •    Convolution using separable kernels
  • -
  •    Convolution in the Fourier domain
  • -
  • Building convolutional neural networks in Tensorflow and Keras
  • -
  • Setting it up
  • -
  • The MNIST dataset again
  • -
  • Strong correlations
  • -
  • Layers of a CNN
  • -
  • Systematic reduction
  • -
  • Prerequisites: Collect and pre-process data
  • -
  • Importing Keras and Tensorflow
  • -
  • Running with Keras
  • -
  • Final part
  • -
  • Final visualization
  • +
  • How to do image compression before the era of deep learning
  • +
  • The SVD example
  • +
  • Mathematics of CNNs
  • +
  • Mathematics of CNNs
  • +
  • Convolution Examples: Polynomial multiplication
  • +
  • Efficient Polynomial Multiplication
  • +
  • Further simplification
  • +
  • A more efficient way of coding the above Convolution
  • +
  • Commutative process
  • +
  • Toeplitz matrices
  • +
  • Fourier series and Toeplitz matrices
  • +
  • Generalizing the above one-dimensional case
  • +
  • Memory considerations
  • +
  • Padding
  • +
  • New vector
  • +
  • Rewriting as dot products
  • +
  • Cross correlation
  • +
  • Two-dimensional objects
  • +
  • CNNs in more detail, simple example
  • +
  • The convolution stage
  • +
  • Finding the number of parameters
  • +
  • New image (or volume)
  • +
  • Parameters to train, common settings
  • +
  • Examples of CNN setups
  • +
  • Summarizing: Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Pooling
  • +
  • Pooling arithmetic
  • +
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Building convolutional neural networks in Tensorflow and Keras
  • +
  • Setting it up
  • +
  • The MNIST dataset again
  • +
  • Strong correlations
  • +
  • Layers of a CNN
  • +
  • Systematic reduction
  • +
  • Prerequisites: Collect and pre-process data
  • +
  • Importing Keras and Tensorflow
  • +
  • Running with Keras
  • +
  • Final part
  • +
  • Final visualization
  • +
  • The CIFAR01 data set
  • +
  • Verifying the data set
  • +
  • Set up the model
  • +
  • Add Dense layers on top
  • +
  • Compile and train the model
  • +
  • Finally, evaluate the model
  • +
  • Building our own CNN code
  • +
  •    List of contents:
  • +
  •    Schedulers
  • +
  •    Usage of schedulers
  • +
  •    Cost functions
  • +
  •    Usage of cost functions
  • +
  •    Activation functions
  • +
  •    Usage of activation functions
  • +
  •    Convolution
  • +
  •    Layers
  • +
  •    Convolution2DLayer: convolution in a hidden layer
  • +
  •    Backpropagation in the convolutional layer
  • +
  •    Demonstration
  • +
  •    Pooling Layer
  • +
  •    Flattening Layer
  • +
  •    Fully Connected Layers
  • +
  •    Optimized Convolution2DLayer
  • +
  •    The Convolutional Neural Network (CNN)
  • +
  •    Usage of CNN code
  • +
  •    Additional Remarks
  • +
  •    Remarks on the speed
  • +
  •    Convolution using separable kernels
  • +
  •    Convolution in the Fourier domain
  • @@ -308,18 +350,24 @@ MathJax.Hub.Config({

     

     

     

    -

    Building convolutional neural networks in Tensorflow and Keras

    +

    Finding the number of parameters

    -

    As discussed above, CNNs are neural networks built from the assumption that the inputs -to the network are 2D images. This is important because the number of features or pixels in images -grows very fast with the image size, and an enormous number of weights and biases are needed in order to build an accurate network. +

    In the above example we have an input matrix of dimension \( 3\times +3 \). In general we call the input for an input volume and it is defined +by its width \( H_1 \), height \( H_1 \) and depth \( D_1 \). If we have the +standard three color channels \( D_1=3 \).

    -

    As before, we still have our input, a hidden layer and an output. What's novel about convolutional networks -are the convolutional and pooling layers stacked in pairs between the input and the hidden layer. -In addition, the data is no longer represented as a 2D feature matrix, instead each input is a number of 2D -matrices, typically 1 for each color dimension (Red, Green, Blue). -

    +

    The above example has \( W_1=H_1=3 \) and \( D_1=1 \).

    + +

    When we introduce the filter we have the following additional hyperparameters

    +
      +
    1. \( K \) the number of filters. It is common to perform the convolution of the input several times since by experience shrinking the input too fast does not work well
    2. +
    3. \( F \) as the filter's spatial extent
    4. +
    5. \( S \) as the stride parameter
    6. +
    7. \( P \) as the padding parameter
    8. +
    +

    These parameters are defined by the architecture of the network and are not included in the training.

    @@ -346,7 +394,7 @@ matrices, typically 1 for each color dimension (Red, Green, Blue).

  • 45
  • 46
  • ...
  • -
  • 47
  • +
  • 62
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs037.html b/doc/pub/week44/html/._week44-bs037.html index 394e728ac..a3a441870 100644 --- a/doc/pub/week44/html/._week44-bs037.html +++ b/doc/pub/week44/html/._week44-bs037.html @@ -75,6 +75,12 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d None, 'a-deep-cnn-model-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Key Idea', 2, None, 'key-idea'), + ('How to do image compression before the era of deep learning', + 2, + None, + 'how-to-do-image-compression-before-the-era-of-deep-learning'), + ('The SVD example', 2, None, 'the-svd-example'), + ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Convolution Examples: Polynomial multiplication', 2, @@ -89,6 +95,8 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'a-more-efficient-way-of-coding-the-above-convolution'), + ('Commutative process', 2, None, 'commutative-process'), + ('Toeplitz matrices', 2, None, 'toeplitz-matrices'), ('Fourier series and Toeplitz matrices', 2, None, @@ -97,36 +105,75 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'generalizing-the-above-one-dimensional-case'), - ('Two-dimensional Objects', 2, None, 'two-dimensional-objects'), - ('CNNs in more detail', 2, None, 'cnns-in-more-detail'), - ('Performing a discrete convolution with padding ("From Raschka ' - 'et al":"https://github.com/rasbt/machine-learning-book")', + ('Memory considerations', 2, None, 'memory-considerations'), + ('Padding', 2, None, 'padding'), + ('New vector', 2, None, 'new-vector'), + ('Rewriting as dot products', 2, None, - 'performing-a-discrete-convolution-with-padding-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Performing a general discrete convolution ("From Raschka et ' + 'rewriting-as-dot-products'), + ('Cross correlation', 2, None, 'cross-correlation'), + ('Two-dimensional objects', 2, None, 'two-dimensional-objects'), + ('CNNs in more detail, simple example', + 2, + None, + 'cnns-in-more-detail-simple-example'), + ('The convolution stage', 2, None, 'the-convolution-stage'), + ('Finding the number of parameters', + 2, + None, + 'finding-the-number-of-parameters'), + ('New image (or volume)', 2, None, 'new-image-or-volume'), + ('Parameters to train, common settings', + 2, + None, + 'parameters-to-train-common-settings'), + ('Examples of CNN setups', 2, None, 'examples-of-cnn-setups'), + ('Summarizing: Performing a general discrete convolution ("From ' + 'Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, - 'performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Set of filters', 2, None, 'set-of-filters'), + 'summarizing-performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Pooling', 2, None, 'pooling'), - ('No zero padding, unit strides', - 2, - None, - 'no-zero-padding-unit-strides'), - ('Zero padding, unit strides', - 2, - None, - 'zero-padding-unit-strides'), - ('Half (same) padding', 2, None, 'half-same-padding'), - ('Full padding', 2, None, 'full-padding'), ('Pooling arithmetic', 2, None, 'pooling-arithmetic'), ('Pooling types ("From Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, 'pooling-types-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), + ('Building convolutional neural networks in Tensorflow and Keras', + 2, + None, + 'building-convolutional-neural-networks-in-tensorflow-and-keras'), + ('Setting it up', 2, None, 'setting-it-up'), + ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), + ('Strong correlations', 2, None, 'strong-correlations'), + ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), + ('Systematic reduction', 2, None, 'systematic-reduction'), + ('Prerequisites: Collect and pre-process data', + 2, + None, + 'prerequisites-collect-and-pre-process-data'), + ('Importing Keras and Tensorflow', + 2, + None, + 'importing-keras-and-tensorflow'), + ('Running with Keras', 2, None, 'running-with-keras'), + ('Final part', 2, None, 'final-part'), + ('Final visualization', 2, None, 'final-visualization'), + ('The CIFAR01 data set', 2, None, 'the-cifar01-data-set'), + ('Verifying the data set', 2, None, 'verifying-the-data-set'), + ('Set up the model', 2, None, 'set-up-the-model'), + ('Add Dense layers on top', 2, None, 'add-dense-layers-on-top'), + ('Compile and train the model', + 2, + None, + 'compile-and-train-the-model'), + ('Finally, evaluate the model', + 2, + None, + 'finally-evaluate-the-model'), ('Building our own CNN code', 2, None, @@ -173,27 +220,7 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Convolution in the Fourier domain', 3, None, - 'convolution-in-the-fourier-domain'), - ('Building convolutional neural networks in Tensorflow and Keras', - 2, - None, - 'building-convolutional-neural-networks-in-tensorflow-and-keras'), - ('Setting it up', 2, None, 'setting-it-up'), - ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), - ('Strong correlations', 2, None, 'strong-correlations'), - ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), - ('Systematic reduction', 2, None, 'systematic-reduction'), - ('Prerequisites: Collect and pre-process data', - 2, - None, - 'prerequisites-collect-and-pre-process-data'), - ('Importing Keras and Tensorflow', - 2, - None, - 'importing-keras-and-tensorflow'), - ('Running with Keras', 2, None, 'running-with-keras'), - ('Final part', 2, None, 'final-part'), - ('Final visualization', 2, None, 'final-visualization')]} + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -244,59 +271,74 @@ MathJax.Hub.Config({
  • CNNs in brief
  • A deep CNN model ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • Key Idea
  • -
  • Mathematics of CNNs
  • -
  • Convolution Examples: Polynomial multiplication
  • -
  • Efficient Polynomial Multiplication
  • -
  • Further simplification
  • -
  • A more efficient way of coding the above Convolution
  • -
  • Fourier series and Toeplitz matrices
  • -
  • Generalizing the above one-dimensional case
  • -
  • Two-dimensional Objects
  • -
  • CNNs in more detail
  • -
  • Performing a discrete convolution with padding ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Set of filters
  • -
  • Pooling
  • -
  • No zero padding, unit strides
  • -
  • Zero padding, unit strides
  • -
  • Half (same) padding
  • -
  • Full padding
  • -
  • Pooling arithmetic
  • -
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Building our own CNN code
  • -
  •    List of contents:
  • -
  •    Schedulers
  • -
  •    Usage of schedulers
  • -
  •    Cost functions
  • -
  •    Usage of cost functions
  • -
  •    Activation functions
  • -
  •    Usage of activation functions
  • -
  •    Convolution
  • -
  •    Layers
  • -
  •    Convolution2DLayer: convolution in a hidden layer
  • -
  •    Backpropagation in the convolutional layer
  • -
  •    Demonstration
  • -
  •    Pooling Layer
  • -
  •    Flattening Layer
  • -
  •    Fully Connected Layers
  • -
  •    Optimized Convolution2DLayer
  • -
  •    The Convolutional Neural Network (CNN)
  • -
  •    Usage of CNN code
  • -
  •    Additional Remarks
  • -
  •    Remarks on the speed
  • -
  •    Convolution using separable kernels
  • -
  •    Convolution in the Fourier domain
  • -
  • Building convolutional neural networks in Tensorflow and Keras
  • -
  • Setting it up
  • -
  • The MNIST dataset again
  • -
  • Strong correlations
  • -
  • Layers of a CNN
  • -
  • Systematic reduction
  • -
  • Prerequisites: Collect and pre-process data
  • -
  • Importing Keras and Tensorflow
  • -
  • Running with Keras
  • -
  • Final part
  • -
  • Final visualization
  • +
  • How to do image compression before the era of deep learning
  • +
  • The SVD example
  • +
  • Mathematics of CNNs
  • +
  • Mathematics of CNNs
  • +
  • Convolution Examples: Polynomial multiplication
  • +
  • Efficient Polynomial Multiplication
  • +
  • Further simplification
  • +
  • A more efficient way of coding the above Convolution
  • +
  • Commutative process
  • +
  • Toeplitz matrices
  • +
  • Fourier series and Toeplitz matrices
  • +
  • Generalizing the above one-dimensional case
  • +
  • Memory considerations
  • +
  • Padding
  • +
  • New vector
  • +
  • Rewriting as dot products
  • +
  • Cross correlation
  • +
  • Two-dimensional objects
  • +
  • CNNs in more detail, simple example
  • +
  • The convolution stage
  • +
  • Finding the number of parameters
  • +
  • New image (or volume)
  • +
  • Parameters to train, common settings
  • +
  • Examples of CNN setups
  • +
  • Summarizing: Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Pooling
  • +
  • Pooling arithmetic
  • +
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Building convolutional neural networks in Tensorflow and Keras
  • +
  • Setting it up
  • +
  • The MNIST dataset again
  • +
  • Strong correlations
  • +
  • Layers of a CNN
  • +
  • Systematic reduction
  • +
  • Prerequisites: Collect and pre-process data
  • +
  • Importing Keras and Tensorflow
  • +
  • Running with Keras
  • +
  • Final part
  • +
  • Final visualization
  • +
  • The CIFAR01 data set
  • +
  • Verifying the data set
  • +
  • Set up the model
  • +
  • Add Dense layers on top
  • +
  • Compile and train the model
  • +
  • Finally, evaluate the model
  • +
  • Building our own CNN code
  • +
  •    List of contents:
  • +
  •    Schedulers
  • +
  •    Usage of schedulers
  • +
  •    Cost functions
  • +
  •    Usage of cost functions
  • +
  •    Activation functions
  • +
  •    Usage of activation functions
  • +
  •    Convolution
  • +
  •    Layers
  • +
  •    Convolution2DLayer: convolution in a hidden layer
  • +
  •    Backpropagation in the convolutional layer
  • +
  •    Demonstration
  • +
  •    Pooling Layer
  • +
  •    Flattening Layer
  • +
  •    Fully Connected Layers
  • +
  •    Optimized Convolution2DLayer
  • +
  •    The Convolutional Neural Network (CNN)
  • +
  •    Usage of CNN code
  • +
  •    Additional Remarks
  • +
  •    Remarks on the speed
  • +
  •    Convolution using separable kernels
  • +
  •    Convolution in the Fourier domain
  • @@ -308,15 +350,23 @@ MathJax.Hub.Config({

     

     

     

    -

    Setting it up

    +

    New image (or volume)

    -

    It means that to represent the entire -dataset of images, we require a 4D matrix or tensor. This tensor has the dimensions: +

    Acting with the filter on the input volume produces an output volume +which is defined by its width \( W_2 \), its height \( H_2 \) and its depth +\( D_2 \).

    -$$ -(n_{inputs},\, n_{pixels, width},\, n_{pixels, height},\, depth) . + +

    These are defined by the following relations

    +$$ +W_2 = \frac{(W_1-F+2P)}{S}+1, $$ +$$ +H_2 = \frac{(H_1-F+2P)}{S}+1, +$$ + +

    and \( D_2=K \).

    @@ -342,6 +392,8 @@ $$

  • 45
  • 46
  • 47
  • +
  • ...
  • +
  • 62
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs038.html b/doc/pub/week44/html/._week44-bs038.html index 503f24246..ce55b0d63 100644 --- a/doc/pub/week44/html/._week44-bs038.html +++ b/doc/pub/week44/html/._week44-bs038.html @@ -75,6 +75,12 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d None, 'a-deep-cnn-model-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Key Idea', 2, None, 'key-idea'), + ('How to do image compression before the era of deep learning', + 2, + None, + 'how-to-do-image-compression-before-the-era-of-deep-learning'), + ('The SVD example', 2, None, 'the-svd-example'), + ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Convolution Examples: Polynomial multiplication', 2, @@ -89,6 +95,8 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'a-more-efficient-way-of-coding-the-above-convolution'), + ('Commutative process', 2, None, 'commutative-process'), + ('Toeplitz matrices', 2, None, 'toeplitz-matrices'), ('Fourier series and Toeplitz matrices', 2, None, @@ -97,36 +105,75 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'generalizing-the-above-one-dimensional-case'), - ('Two-dimensional Objects', 2, None, 'two-dimensional-objects'), - ('CNNs in more detail', 2, None, 'cnns-in-more-detail'), - ('Performing a discrete convolution with padding ("From Raschka ' - 'et al":"https://github.com/rasbt/machine-learning-book")', + ('Memory considerations', 2, None, 'memory-considerations'), + ('Padding', 2, None, 'padding'), + ('New vector', 2, None, 'new-vector'), + ('Rewriting as dot products', 2, None, - 'performing-a-discrete-convolution-with-padding-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Performing a general discrete convolution ("From Raschka et ' + 'rewriting-as-dot-products'), + ('Cross correlation', 2, None, 'cross-correlation'), + ('Two-dimensional objects', 2, None, 'two-dimensional-objects'), + ('CNNs in more detail, simple example', + 2, + None, + 'cnns-in-more-detail-simple-example'), + ('The convolution stage', 2, None, 'the-convolution-stage'), + ('Finding the number of parameters', + 2, + None, + 'finding-the-number-of-parameters'), + ('New image (or volume)', 2, None, 'new-image-or-volume'), + ('Parameters to train, common settings', + 2, + None, + 'parameters-to-train-common-settings'), + ('Examples of CNN setups', 2, None, 'examples-of-cnn-setups'), + ('Summarizing: Performing a general discrete convolution ("From ' + 'Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, - 'performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Set of filters', 2, None, 'set-of-filters'), + 'summarizing-performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Pooling', 2, None, 'pooling'), - ('No zero padding, unit strides', - 2, - None, - 'no-zero-padding-unit-strides'), - ('Zero padding, unit strides', - 2, - None, - 'zero-padding-unit-strides'), - ('Half (same) padding', 2, None, 'half-same-padding'), - ('Full padding', 2, None, 'full-padding'), ('Pooling arithmetic', 2, None, 'pooling-arithmetic'), ('Pooling types ("From Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, 'pooling-types-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), + ('Building convolutional neural networks in Tensorflow and Keras', + 2, + None, + 'building-convolutional-neural-networks-in-tensorflow-and-keras'), + ('Setting it up', 2, None, 'setting-it-up'), + ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), + ('Strong correlations', 2, None, 'strong-correlations'), + ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), + ('Systematic reduction', 2, None, 'systematic-reduction'), + ('Prerequisites: Collect and pre-process data', + 2, + None, + 'prerequisites-collect-and-pre-process-data'), + ('Importing Keras and Tensorflow', + 2, + None, + 'importing-keras-and-tensorflow'), + ('Running with Keras', 2, None, 'running-with-keras'), + ('Final part', 2, None, 'final-part'), + ('Final visualization', 2, None, 'final-visualization'), + ('The CIFAR01 data set', 2, None, 'the-cifar01-data-set'), + ('Verifying the data set', 2, None, 'verifying-the-data-set'), + ('Set up the model', 2, None, 'set-up-the-model'), + ('Add Dense layers on top', 2, None, 'add-dense-layers-on-top'), + ('Compile and train the model', + 2, + None, + 'compile-and-train-the-model'), + ('Finally, evaluate the model', + 2, + None, + 'finally-evaluate-the-model'), ('Building our own CNN code', 2, None, @@ -173,27 +220,7 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Convolution in the Fourier domain', 3, None, - 'convolution-in-the-fourier-domain'), - ('Building convolutional neural networks in Tensorflow and Keras', - 2, - None, - 'building-convolutional-neural-networks-in-tensorflow-and-keras'), - ('Setting it up', 2, None, 'setting-it-up'), - ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), - ('Strong correlations', 2, None, 'strong-correlations'), - ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), - ('Systematic reduction', 2, None, 'systematic-reduction'), - ('Prerequisites: Collect and pre-process data', - 2, - None, - 'prerequisites-collect-and-pre-process-data'), - ('Importing Keras and Tensorflow', - 2, - None, - 'importing-keras-and-tensorflow'), - ('Running with Keras', 2, None, 'running-with-keras'), - ('Final part', 2, None, 'final-part'), - ('Final visualization', 2, None, 'final-visualization')]} + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -244,59 +271,74 @@ MathJax.Hub.Config({
  • CNNs in brief
  • A deep CNN model ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • Key Idea
  • -
  • Mathematics of CNNs
  • -
  • Convolution Examples: Polynomial multiplication
  • -
  • Efficient Polynomial Multiplication
  • -
  • Further simplification
  • -
  • A more efficient way of coding the above Convolution
  • -
  • Fourier series and Toeplitz matrices
  • -
  • Generalizing the above one-dimensional case
  • -
  • Two-dimensional Objects
  • -
  • CNNs in more detail
  • -
  • Performing a discrete convolution with padding ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Set of filters
  • -
  • Pooling
  • -
  • No zero padding, unit strides
  • -
  • Zero padding, unit strides
  • -
  • Half (same) padding
  • -
  • Full padding
  • -
  • Pooling arithmetic
  • -
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Building our own CNN code
  • -
  •    List of contents:
  • -
  •    Schedulers
  • -
  •    Usage of schedulers
  • -
  •    Cost functions
  • -
  •    Usage of cost functions
  • -
  •    Activation functions
  • -
  •    Usage of activation functions
  • -
  •    Convolution
  • -
  •    Layers
  • -
  •    Convolution2DLayer: convolution in a hidden layer
  • -
  •    Backpropagation in the convolutional layer
  • -
  •    Demonstration
  • -
  •    Pooling Layer
  • -
  •    Flattening Layer
  • -
  •    Fully Connected Layers
  • -
  •    Optimized Convolution2DLayer
  • -
  •    The Convolutional Neural Network (CNN)
  • -
  •    Usage of CNN code
  • -
  •    Additional Remarks
  • -
  •    Remarks on the speed
  • -
  •    Convolution using separable kernels
  • -
  •    Convolution in the Fourier domain
  • -
  • Building convolutional neural networks in Tensorflow and Keras
  • -
  • Setting it up
  • -
  • The MNIST dataset again
  • -
  • Strong correlations
  • -
  • Layers of a CNN
  • -
  • Systematic reduction
  • -
  • Prerequisites: Collect and pre-process data
  • -
  • Importing Keras and Tensorflow
  • -
  • Running with Keras
  • -
  • Final part
  • -
  • Final visualization
  • +
  • How to do image compression before the era of deep learning
  • +
  • The SVD example
  • +
  • Mathematics of CNNs
  • +
  • Mathematics of CNNs
  • +
  • Convolution Examples: Polynomial multiplication
  • +
  • Efficient Polynomial Multiplication
  • +
  • Further simplification
  • +
  • A more efficient way of coding the above Convolution
  • +
  • Commutative process
  • +
  • Toeplitz matrices
  • +
  • Fourier series and Toeplitz matrices
  • +
  • Generalizing the above one-dimensional case
  • +
  • Memory considerations
  • +
  • Padding
  • +
  • New vector
  • +
  • Rewriting as dot products
  • +
  • Cross correlation
  • +
  • Two-dimensional objects
  • +
  • CNNs in more detail, simple example
  • +
  • The convolution stage
  • +
  • Finding the number of parameters
  • +
  • New image (or volume)
  • +
  • Parameters to train, common settings
  • +
  • Examples of CNN setups
  • +
  • Summarizing: Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Pooling
  • +
  • Pooling arithmetic
  • +
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Building convolutional neural networks in Tensorflow and Keras
  • +
  • Setting it up
  • +
  • The MNIST dataset again
  • +
  • Strong correlations
  • +
  • Layers of a CNN
  • +
  • Systematic reduction
  • +
  • Prerequisites: Collect and pre-process data
  • +
  • Importing Keras and Tensorflow
  • +
  • Running with Keras
  • +
  • Final part
  • +
  • Final visualization
  • +
  • The CIFAR01 data set
  • +
  • Verifying the data set
  • +
  • Set up the model
  • +
  • Add Dense layers on top
  • +
  • Compile and train the model
  • +
  • Finally, evaluate the model
  • +
  • Building our own CNN code
  • +
  •    List of contents:
  • +
  •    Schedulers
  • +
  •    Usage of schedulers
  • +
  •    Cost functions
  • +
  •    Usage of cost functions
  • +
  •    Activation functions
  • +
  •    Usage of activation functions
  • +
  •    Convolution
  • +
  •    Layers
  • +
  •    Convolution2DLayer: convolution in a hidden layer
  • +
  •    Backpropagation in the convolutional layer
  • +
  •    Demonstration
  • +
  •    Pooling Layer
  • +
  •    Flattening Layer
  • +
  •    Fully Connected Layers
  • +
  •    Optimized Convolution2DLayer
  • +
  •    The Convolutional Neural Network (CNN)
  • +
  •    Usage of CNN code
  • +
  •    Additional Remarks
  • +
  •    Remarks on the speed
  • +
  •    Convolution using separable kernels
  • +
  •    Convolution in the Fourier domain
  • @@ -308,20 +350,30 @@ MathJax.Hub.Config({

     

     

     

    -

    The MNIST dataset again

    +

    Parameters to train, common settings

    -

    The MNIST dataset consists of grayscale images with a pixel size of -\( 28\times 28 \), meaning we require \( 28 \times 28 = 724 \) weights to each -neuron in the first hidden layer. -

    +

    With parameter sharing, the convolution involves thus for each filter \( F\times F\times D_1 \) weights plus one bias parameter.

    -

    If we were to analyze images of size \( 128\times 128 \) we would require -\( 128 \times 128 = 16384 \) weights to each neuron. Even worse if we were -dealing with color images, as most images are, we have an image matrix -of size \( 128\times 128 \) for each color dimension (Red, Green, Blue), -meaning 3 times the number of weights \( = 49152 \) are required for every -single neuron in the first hidden layer. -

    +

    In total we have

    +$$ +\left(F\times F\times D_1)\right) \times K+(K\mathrm{--biases}), +$$ + +

    parameters to train by back propagation.

    + +

    It is common to let \( K \) come in powers of \( 2 \), that is \( 32 \), \( 64 \), \( 128 \) etc.

    + +
    +
    + +
      +
    1. \( \begin{array}{c} F=3 & S=1 & P=1 \end{array} \)
    2. +
    3. \( \begin{array}{c} F=5 & S=1 & P=2 \end{array} \)
    4. +
    5. \( \begin{array}{c} F=5 & S=2 & P=\mathrm{open} \end{array} \)
    6. +
    7. \( \begin{array}{c} F=1 & S=1 & P=0 \end{array} \)
    8. +
    +
    +

    @@ -347,6 +399,9 @@ single neuron in the first hidden layer.

  • 45
  • 46
  • 47
  • +
  • 48
  • +
  • ...
  • +
  • 62
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs039.html b/doc/pub/week44/html/._week44-bs039.html index 0c84d4e92..c97e2a6e9 100644 --- a/doc/pub/week44/html/._week44-bs039.html +++ b/doc/pub/week44/html/._week44-bs039.html @@ -75,6 +75,12 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d None, 'a-deep-cnn-model-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Key Idea', 2, None, 'key-idea'), + ('How to do image compression before the era of deep learning', + 2, + None, + 'how-to-do-image-compression-before-the-era-of-deep-learning'), + ('The SVD example', 2, None, 'the-svd-example'), + ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Convolution Examples: Polynomial multiplication', 2, @@ -89,6 +95,8 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'a-more-efficient-way-of-coding-the-above-convolution'), + ('Commutative process', 2, None, 'commutative-process'), + ('Toeplitz matrices', 2, None, 'toeplitz-matrices'), ('Fourier series and Toeplitz matrices', 2, None, @@ -97,36 +105,75 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'generalizing-the-above-one-dimensional-case'), - ('Two-dimensional Objects', 2, None, 'two-dimensional-objects'), - ('CNNs in more detail', 2, None, 'cnns-in-more-detail'), - ('Performing a discrete convolution with padding ("From Raschka ' - 'et al":"https://github.com/rasbt/machine-learning-book")', + ('Memory considerations', 2, None, 'memory-considerations'), + ('Padding', 2, None, 'padding'), + ('New vector', 2, None, 'new-vector'), + ('Rewriting as dot products', 2, None, - 'performing-a-discrete-convolution-with-padding-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Performing a general discrete convolution ("From Raschka et ' + 'rewriting-as-dot-products'), + ('Cross correlation', 2, None, 'cross-correlation'), + ('Two-dimensional objects', 2, None, 'two-dimensional-objects'), + ('CNNs in more detail, simple example', + 2, + None, + 'cnns-in-more-detail-simple-example'), + ('The convolution stage', 2, None, 'the-convolution-stage'), + ('Finding the number of parameters', + 2, + None, + 'finding-the-number-of-parameters'), + ('New image (or volume)', 2, None, 'new-image-or-volume'), + ('Parameters to train, common settings', + 2, + None, + 'parameters-to-train-common-settings'), + ('Examples of CNN setups', 2, None, 'examples-of-cnn-setups'), + ('Summarizing: Performing a general discrete convolution ("From ' + 'Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, - 'performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Set of filters', 2, None, 'set-of-filters'), + 'summarizing-performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Pooling', 2, None, 'pooling'), - ('No zero padding, unit strides', - 2, - None, - 'no-zero-padding-unit-strides'), - ('Zero padding, unit strides', - 2, - None, - 'zero-padding-unit-strides'), - ('Half (same) padding', 2, None, 'half-same-padding'), - ('Full padding', 2, None, 'full-padding'), ('Pooling arithmetic', 2, None, 'pooling-arithmetic'), ('Pooling types ("From Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, 'pooling-types-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), + ('Building convolutional neural networks in Tensorflow and Keras', + 2, + None, + 'building-convolutional-neural-networks-in-tensorflow-and-keras'), + ('Setting it up', 2, None, 'setting-it-up'), + ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), + ('Strong correlations', 2, None, 'strong-correlations'), + ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), + ('Systematic reduction', 2, None, 'systematic-reduction'), + ('Prerequisites: Collect and pre-process data', + 2, + None, + 'prerequisites-collect-and-pre-process-data'), + ('Importing Keras and Tensorflow', + 2, + None, + 'importing-keras-and-tensorflow'), + ('Running with Keras', 2, None, 'running-with-keras'), + ('Final part', 2, None, 'final-part'), + ('Final visualization', 2, None, 'final-visualization'), + ('The CIFAR01 data set', 2, None, 'the-cifar01-data-set'), + ('Verifying the data set', 2, None, 'verifying-the-data-set'), + ('Set up the model', 2, None, 'set-up-the-model'), + ('Add Dense layers on top', 2, None, 'add-dense-layers-on-top'), + ('Compile and train the model', + 2, + None, + 'compile-and-train-the-model'), + ('Finally, evaluate the model', + 2, + None, + 'finally-evaluate-the-model'), ('Building our own CNN code', 2, None, @@ -173,27 +220,7 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Convolution in the Fourier domain', 3, None, - 'convolution-in-the-fourier-domain'), - ('Building convolutional neural networks in Tensorflow and Keras', - 2, - None, - 'building-convolutional-neural-networks-in-tensorflow-and-keras'), - ('Setting it up', 2, None, 'setting-it-up'), - ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), - ('Strong correlations', 2, None, 'strong-correlations'), - ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), - ('Systematic reduction', 2, None, 'systematic-reduction'), - ('Prerequisites: Collect and pre-process data', - 2, - None, - 'prerequisites-collect-and-pre-process-data'), - ('Importing Keras and Tensorflow', - 2, - None, - 'importing-keras-and-tensorflow'), - ('Running with Keras', 2, None, 'running-with-keras'), - ('Final part', 2, None, 'final-part'), - ('Final visualization', 2, None, 'final-visualization')]} + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -244,59 +271,74 @@ MathJax.Hub.Config({
  • CNNs in brief
  • A deep CNN model ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • Key Idea
  • -
  • Mathematics of CNNs
  • -
  • Convolution Examples: Polynomial multiplication
  • -
  • Efficient Polynomial Multiplication
  • -
  • Further simplification
  • -
  • A more efficient way of coding the above Convolution
  • -
  • Fourier series and Toeplitz matrices
  • -
  • Generalizing the above one-dimensional case
  • -
  • Two-dimensional Objects
  • -
  • CNNs in more detail
  • -
  • Performing a discrete convolution with padding ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Set of filters
  • -
  • Pooling
  • -
  • No zero padding, unit strides
  • -
  • Zero padding, unit strides
  • -
  • Half (same) padding
  • -
  • Full padding
  • -
  • Pooling arithmetic
  • -
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Building our own CNN code
  • -
  •    List of contents:
  • -
  •    Schedulers
  • -
  •    Usage of schedulers
  • -
  •    Cost functions
  • -
  •    Usage of cost functions
  • -
  •    Activation functions
  • -
  •    Usage of activation functions
  • -
  •    Convolution
  • -
  •    Layers
  • -
  •    Convolution2DLayer: convolution in a hidden layer
  • -
  •    Backpropagation in the convolutional layer
  • -
  •    Demonstration
  • -
  •    Pooling Layer
  • -
  •    Flattening Layer
  • -
  •    Fully Connected Layers
  • -
  •    Optimized Convolution2DLayer
  • -
  •    The Convolutional Neural Network (CNN)
  • -
  •    Usage of CNN code
  • -
  •    Additional Remarks
  • -
  •    Remarks on the speed
  • -
  •    Convolution using separable kernels
  • -
  •    Convolution in the Fourier domain
  • -
  • Building convolutional neural networks in Tensorflow and Keras
  • -
  • Setting it up
  • -
  • The MNIST dataset again
  • -
  • Strong correlations
  • -
  • Layers of a CNN
  • -
  • Systematic reduction
  • -
  • Prerequisites: Collect and pre-process data
  • -
  • Importing Keras and Tensorflow
  • -
  • Running with Keras
  • -
  • Final part
  • -
  • Final visualization
  • +
  • How to do image compression before the era of deep learning
  • +
  • The SVD example
  • +
  • Mathematics of CNNs
  • +
  • Mathematics of CNNs
  • +
  • Convolution Examples: Polynomial multiplication
  • +
  • Efficient Polynomial Multiplication
  • +
  • Further simplification
  • +
  • A more efficient way of coding the above Convolution
  • +
  • Commutative process
  • +
  • Toeplitz matrices
  • +
  • Fourier series and Toeplitz matrices
  • +
  • Generalizing the above one-dimensional case
  • +
  • Memory considerations
  • +
  • Padding
  • +
  • New vector
  • +
  • Rewriting as dot products
  • +
  • Cross correlation
  • +
  • Two-dimensional objects
  • +
  • CNNs in more detail, simple example
  • +
  • The convolution stage
  • +
  • Finding the number of parameters
  • +
  • New image (or volume)
  • +
  • Parameters to train, common settings
  • +
  • Examples of CNN setups
  • +
  • Summarizing: Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Pooling
  • +
  • Pooling arithmetic
  • +
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Building convolutional neural networks in Tensorflow and Keras
  • +
  • Setting it up
  • +
  • The MNIST dataset again
  • +
  • Strong correlations
  • +
  • Layers of a CNN
  • +
  • Systematic reduction
  • +
  • Prerequisites: Collect and pre-process data
  • +
  • Importing Keras and Tensorflow
  • +
  • Running with Keras
  • +
  • Final part
  • +
  • Final visualization
  • +
  • The CIFAR01 data set
  • +
  • Verifying the data set
  • +
  • Set up the model
  • +
  • Add Dense layers on top
  • +
  • Compile and train the model
  • +
  • Finally, evaluate the model
  • +
  • Building our own CNN code
  • +
  •    List of contents:
  • +
  •    Schedulers
  • +
  •    Usage of schedulers
  • +
  •    Cost functions
  • +
  •    Usage of cost functions
  • +
  •    Activation functions
  • +
  •    Usage of activation functions
  • +
  •    Convolution
  • +
  •    Layers
  • +
  •    Convolution2DLayer: convolution in a hidden layer
  • +
  •    Backpropagation in the convolutional layer
  • +
  •    Demonstration
  • +
  •    Pooling Layer
  • +
  •    Flattening Layer
  • +
  •    Fully Connected Layers
  • +
  •    Optimized Convolution2DLayer
  • +
  •    The Convolutional Neural Network (CNN)
  • +
  •    Usage of CNN code
  • +
  •    Additional Remarks
  • +
  •    Remarks on the speed
  • +
  •    Convolution using separable kernels
  • +
  •    Convolution in the Fourier domain
  • @@ -308,21 +350,34 @@ MathJax.Hub.Config({

     

     

     

    -

    Strong correlations

    +

    Examples of CNN setups

    -

    Images typically have strong local correlations, meaning that a small -part of the image varies little from its neighboring regions. If for -example we have an image of a blue car, we can roughly assume that a -small blue part of the image is surrounded by other blue regions. +

    Let us assume we have an input volume \( V \) given by an image of dimensionality +\( 32\times 32 \times 3 \), that is three color channels and \( 32\times 32 \) pixels.

    -

    Therefore, instead of connecting every single pixel to a neuron in the -first hidden layer, as we have previously done with deep neural -networks, we can instead connect each neuron to a small part of the -image (in all 3 RGB depth dimensions). The size of each small area is -fixed, and known as a receptive. +

    We apply a filter of dimension \( 5\times 5 \) ten times with stride \( S=1 \) and padding \( P=0 \).

    + +

    The output volume is given by \( (32-5)/1+1=28 \), resulting in ten images +of dimensionality \( 28\times 28\times 3 \).

    +

    The total number of parameters to train for each filter is then +\( 5\times 5\times 3+1 \), where the last parameter is the bias. This +gives us \( 76 \) parameters for each filter, leading to a total of \( 760 \) +parameters for the ten filters. +

    + +

    How many parameters will a filter of dimensionality \( 3\times 3 \) +(adding color channels) result in if we produce \( 32 \) new images? Use \( S=1 \) and \( P=0 \). +

    + +

    Note that strides constitute a form of subsampling. As an alternative to +being interpreted as a measure of how much the kernel/filter is translated, strides +can also be viewed as how much of the output is retained. For instance, moving +the kernel by hops of two is equivalent to moving the kernel by hops of one but +retaining only odd output elements. +

    @@ -346,6 +401,10 @@ fixed, and known as a 45

  • 46
  • 47
  • +
  • 48
  • +
  • 49
  • +
  • ...
  • +
  • 62
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs040.html b/doc/pub/week44/html/._week44-bs040.html index 6adb8bbf6..1a539a527 100644 --- a/doc/pub/week44/html/._week44-bs040.html +++ b/doc/pub/week44/html/._week44-bs040.html @@ -75,6 +75,12 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d None, 'a-deep-cnn-model-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Key Idea', 2, None, 'key-idea'), + ('How to do image compression before the era of deep learning', + 2, + None, + 'how-to-do-image-compression-before-the-era-of-deep-learning'), + ('The SVD example', 2, None, 'the-svd-example'), + ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Convolution Examples: Polynomial multiplication', 2, @@ -89,6 +95,8 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'a-more-efficient-way-of-coding-the-above-convolution'), + ('Commutative process', 2, None, 'commutative-process'), + ('Toeplitz matrices', 2, None, 'toeplitz-matrices'), ('Fourier series and Toeplitz matrices', 2, None, @@ -97,36 +105,75 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'generalizing-the-above-one-dimensional-case'), - ('Two-dimensional Objects', 2, None, 'two-dimensional-objects'), - ('CNNs in more detail', 2, None, 'cnns-in-more-detail'), - ('Performing a discrete convolution with padding ("From Raschka ' - 'et al":"https://github.com/rasbt/machine-learning-book")', + ('Memory considerations', 2, None, 'memory-considerations'), + ('Padding', 2, None, 'padding'), + ('New vector', 2, None, 'new-vector'), + ('Rewriting as dot products', 2, None, - 'performing-a-discrete-convolution-with-padding-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Performing a general discrete convolution ("From Raschka et ' + 'rewriting-as-dot-products'), + ('Cross correlation', 2, None, 'cross-correlation'), + ('Two-dimensional objects', 2, None, 'two-dimensional-objects'), + ('CNNs in more detail, simple example', + 2, + None, + 'cnns-in-more-detail-simple-example'), + ('The convolution stage', 2, None, 'the-convolution-stage'), + ('Finding the number of parameters', + 2, + None, + 'finding-the-number-of-parameters'), + ('New image (or volume)', 2, None, 'new-image-or-volume'), + ('Parameters to train, common settings', + 2, + None, + 'parameters-to-train-common-settings'), + ('Examples of CNN setups', 2, None, 'examples-of-cnn-setups'), + ('Summarizing: Performing a general discrete convolution ("From ' + 'Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, - 'performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Set of filters', 2, None, 'set-of-filters'), + 'summarizing-performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Pooling', 2, None, 'pooling'), - ('No zero padding, unit strides', - 2, - None, - 'no-zero-padding-unit-strides'), - ('Zero padding, unit strides', - 2, - None, - 'zero-padding-unit-strides'), - ('Half (same) padding', 2, None, 'half-same-padding'), - ('Full padding', 2, None, 'full-padding'), ('Pooling arithmetic', 2, None, 'pooling-arithmetic'), ('Pooling types ("From Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, 'pooling-types-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), + ('Building convolutional neural networks in Tensorflow and Keras', + 2, + None, + 'building-convolutional-neural-networks-in-tensorflow-and-keras'), + ('Setting it up', 2, None, 'setting-it-up'), + ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), + ('Strong correlations', 2, None, 'strong-correlations'), + ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), + ('Systematic reduction', 2, None, 'systematic-reduction'), + ('Prerequisites: Collect and pre-process data', + 2, + None, + 'prerequisites-collect-and-pre-process-data'), + ('Importing Keras and Tensorflow', + 2, + None, + 'importing-keras-and-tensorflow'), + ('Running with Keras', 2, None, 'running-with-keras'), + ('Final part', 2, None, 'final-part'), + ('Final visualization', 2, None, 'final-visualization'), + ('The CIFAR01 data set', 2, None, 'the-cifar01-data-set'), + ('Verifying the data set', 2, None, 'verifying-the-data-set'), + ('Set up the model', 2, None, 'set-up-the-model'), + ('Add Dense layers on top', 2, None, 'add-dense-layers-on-top'), + ('Compile and train the model', + 2, + None, + 'compile-and-train-the-model'), + ('Finally, evaluate the model', + 2, + None, + 'finally-evaluate-the-model'), ('Building our own CNN code', 2, None, @@ -173,27 +220,7 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Convolution in the Fourier domain', 3, None, - 'convolution-in-the-fourier-domain'), - ('Building convolutional neural networks in Tensorflow and Keras', - 2, - None, - 'building-convolutional-neural-networks-in-tensorflow-and-keras'), - ('Setting it up', 2, None, 'setting-it-up'), - ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), - ('Strong correlations', 2, None, 'strong-correlations'), - ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), - ('Systematic reduction', 2, None, 'systematic-reduction'), - ('Prerequisites: Collect and pre-process data', - 2, - None, - 'prerequisites-collect-and-pre-process-data'), - ('Importing Keras and Tensorflow', - 2, - None, - 'importing-keras-and-tensorflow'), - ('Running with Keras', 2, None, 'running-with-keras'), - ('Final part', 2, None, 'final-part'), - ('Final visualization', 2, None, 'final-visualization')]} + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -244,59 +271,74 @@ MathJax.Hub.Config({
  • CNNs in brief
  • A deep CNN model ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • Key Idea
  • -
  • Mathematics of CNNs
  • -
  • Convolution Examples: Polynomial multiplication
  • -
  • Efficient Polynomial Multiplication
  • -
  • Further simplification
  • -
  • A more efficient way of coding the above Convolution
  • -
  • Fourier series and Toeplitz matrices
  • -
  • Generalizing the above one-dimensional case
  • -
  • Two-dimensional Objects
  • -
  • CNNs in more detail
  • -
  • Performing a discrete convolution with padding ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Set of filters
  • -
  • Pooling
  • -
  • No zero padding, unit strides
  • -
  • Zero padding, unit strides
  • -
  • Half (same) padding
  • -
  • Full padding
  • -
  • Pooling arithmetic
  • -
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Building our own CNN code
  • -
  •    List of contents:
  • -
  •    Schedulers
  • -
  •    Usage of schedulers
  • -
  •    Cost functions
  • -
  •    Usage of cost functions
  • -
  •    Activation functions
  • -
  •    Usage of activation functions
  • -
  •    Convolution
  • -
  •    Layers
  • -
  •    Convolution2DLayer: convolution in a hidden layer
  • -
  •    Backpropagation in the convolutional layer
  • -
  •    Demonstration
  • -
  •    Pooling Layer
  • -
  •    Flattening Layer
  • -
  •    Fully Connected Layers
  • -
  •    Optimized Convolution2DLayer
  • -
  •    The Convolutional Neural Network (CNN)
  • -
  •    Usage of CNN code
  • -
  •    Additional Remarks
  • -
  •    Remarks on the speed
  • -
  •    Convolution using separable kernels
  • -
  •    Convolution in the Fourier domain
  • -
  • Building convolutional neural networks in Tensorflow and Keras
  • -
  • Setting it up
  • -
  • The MNIST dataset again
  • -
  • Strong correlations
  • -
  • Layers of a CNN
  • -
  • Systematic reduction
  • -
  • Prerequisites: Collect and pre-process data
  • -
  • Importing Keras and Tensorflow
  • -
  • Running with Keras
  • -
  • Final part
  • -
  • Final visualization
  • +
  • How to do image compression before the era of deep learning
  • +
  • The SVD example
  • +
  • Mathematics of CNNs
  • +
  • Mathematics of CNNs
  • +
  • Convolution Examples: Polynomial multiplication
  • +
  • Efficient Polynomial Multiplication
  • +
  • Further simplification
  • +
  • A more efficient way of coding the above Convolution
  • +
  • Commutative process
  • +
  • Toeplitz matrices
  • +
  • Fourier series and Toeplitz matrices
  • +
  • Generalizing the above one-dimensional case
  • +
  • Memory considerations
  • +
  • Padding
  • +
  • New vector
  • +
  • Rewriting as dot products
  • +
  • Cross correlation
  • +
  • Two-dimensional objects
  • +
  • CNNs in more detail, simple example
  • +
  • The convolution stage
  • +
  • Finding the number of parameters
  • +
  • New image (or volume)
  • +
  • Parameters to train, common settings
  • +
  • Examples of CNN setups
  • +
  • Summarizing: Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Pooling
  • +
  • Pooling arithmetic
  • +
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Building convolutional neural networks in Tensorflow and Keras
  • +
  • Setting it up
  • +
  • The MNIST dataset again
  • +
  • Strong correlations
  • +
  • Layers of a CNN
  • +
  • Systematic reduction
  • +
  • Prerequisites: Collect and pre-process data
  • +
  • Importing Keras and Tensorflow
  • +
  • Running with Keras
  • +
  • Final part
  • +
  • Final visualization
  • +
  • The CIFAR01 data set
  • +
  • Verifying the data set
  • +
  • Set up the model
  • +
  • Add Dense layers on top
  • +
  • Compile and train the model
  • +
  • Finally, evaluate the model
  • +
  • Building our own CNN code
  • +
  •    List of contents:
  • +
  •    Schedulers
  • +
  •    Usage of schedulers
  • +
  •    Cost functions
  • +
  •    Usage of cost functions
  • +
  •    Activation functions
  • +
  •    Usage of activation functions
  • +
  •    Convolution
  • +
  •    Layers
  • +
  •    Convolution2DLayer: convolution in a hidden layer
  • +
  •    Backpropagation in the convolutional layer
  • +
  •    Demonstration
  • +
  •    Pooling Layer
  • +
  •    Flattening Layer
  • +
  •    Fully Connected Layers
  • +
  •    Optimized Convolution2DLayer
  • +
  •    The Convolutional Neural Network (CNN)
  • +
  •    Usage of CNN code
  • +
  •    Additional Remarks
  • +
  •    Remarks on the speed
  • +
  •    Convolution using separable kernels
  • +
  •    Convolution in the Fourier domain
  • @@ -307,27 +349,16 @@ MathJax.Hub.Config({

     

     

     

    - -

    Layers of a CNN

    + +

    Summarizing: Performing a general discrete convolution (From Raschka et al)

    -

    The layers of a convolutional neural network arrange neurons in 3D: width, height and depth. -The input image is typically a square matrix of depth 3. -

    - -

    A convolution is performed on the image which outputs -a 3D volume of neurons. The weights to the input are arranged in a number of 2D matrices, known as filters. -

    - -

    Each filter slides along the input image, taking the dot product -between each small part of the image and the filter, in all depth -dimensions. This is then passed through a non-linear function, -typically the Rectified Linear (ReLu) function, which serves as the -activation of the neurons in the first convolutional layer. This is -further passed through a pooling layer, which reduces the size of the -convolutional layer, e.g. by taking the maximum or average across some -small regions, and this serves as input to the next convolutional -layer. -

    +
    +
    +
    +

    Figure 4: A deep CNN

    +
    +

    +

    @@ -350,6 +381,11 @@ layer.

  • 45
  • 46
  • 47
  • +
  • 48
  • +
  • 49
  • +
  • 50
  • +
  • ...
  • +
  • 62
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs041.html b/doc/pub/week44/html/._week44-bs041.html index f3006d333..bfda4cc53 100644 --- a/doc/pub/week44/html/._week44-bs041.html +++ b/doc/pub/week44/html/._week44-bs041.html @@ -75,6 +75,12 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d None, 'a-deep-cnn-model-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Key Idea', 2, None, 'key-idea'), + ('How to do image compression before the era of deep learning', + 2, + None, + 'how-to-do-image-compression-before-the-era-of-deep-learning'), + ('The SVD example', 2, None, 'the-svd-example'), + ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Convolution Examples: Polynomial multiplication', 2, @@ -89,6 +95,8 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'a-more-efficient-way-of-coding-the-above-convolution'), + ('Commutative process', 2, None, 'commutative-process'), + ('Toeplitz matrices', 2, None, 'toeplitz-matrices'), ('Fourier series and Toeplitz matrices', 2, None, @@ -97,36 +105,75 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'generalizing-the-above-one-dimensional-case'), - ('Two-dimensional Objects', 2, None, 'two-dimensional-objects'), - ('CNNs in more detail', 2, None, 'cnns-in-more-detail'), - ('Performing a discrete convolution with padding ("From Raschka ' - 'et al":"https://github.com/rasbt/machine-learning-book")', + ('Memory considerations', 2, None, 'memory-considerations'), + ('Padding', 2, None, 'padding'), + ('New vector', 2, None, 'new-vector'), + ('Rewriting as dot products', 2, None, - 'performing-a-discrete-convolution-with-padding-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Performing a general discrete convolution ("From Raschka et ' + 'rewriting-as-dot-products'), + ('Cross correlation', 2, None, 'cross-correlation'), + ('Two-dimensional objects', 2, None, 'two-dimensional-objects'), + ('CNNs in more detail, simple example', + 2, + None, + 'cnns-in-more-detail-simple-example'), + ('The convolution stage', 2, None, 'the-convolution-stage'), + ('Finding the number of parameters', + 2, + None, + 'finding-the-number-of-parameters'), + ('New image (or volume)', 2, None, 'new-image-or-volume'), + ('Parameters to train, common settings', + 2, + None, + 'parameters-to-train-common-settings'), + ('Examples of CNN setups', 2, None, 'examples-of-cnn-setups'), + ('Summarizing: Performing a general discrete convolution ("From ' + 'Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, - 'performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Set of filters', 2, None, 'set-of-filters'), + 'summarizing-performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Pooling', 2, None, 'pooling'), - ('No zero padding, unit strides', - 2, - None, - 'no-zero-padding-unit-strides'), - ('Zero padding, unit strides', - 2, - None, - 'zero-padding-unit-strides'), - ('Half (same) padding', 2, None, 'half-same-padding'), - ('Full padding', 2, None, 'full-padding'), ('Pooling arithmetic', 2, None, 'pooling-arithmetic'), ('Pooling types ("From Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, 'pooling-types-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), + ('Building convolutional neural networks in Tensorflow and Keras', + 2, + None, + 'building-convolutional-neural-networks-in-tensorflow-and-keras'), + ('Setting it up', 2, None, 'setting-it-up'), + ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), + ('Strong correlations', 2, None, 'strong-correlations'), + ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), + ('Systematic reduction', 2, None, 'systematic-reduction'), + ('Prerequisites: Collect and pre-process data', + 2, + None, + 'prerequisites-collect-and-pre-process-data'), + ('Importing Keras and Tensorflow', + 2, + None, + 'importing-keras-and-tensorflow'), + ('Running with Keras', 2, None, 'running-with-keras'), + ('Final part', 2, None, 'final-part'), + ('Final visualization', 2, None, 'final-visualization'), + ('The CIFAR01 data set', 2, None, 'the-cifar01-data-set'), + ('Verifying the data set', 2, None, 'verifying-the-data-set'), + ('Set up the model', 2, None, 'set-up-the-model'), + ('Add Dense layers on top', 2, None, 'add-dense-layers-on-top'), + ('Compile and train the model', + 2, + None, + 'compile-and-train-the-model'), + ('Finally, evaluate the model', + 2, + None, + 'finally-evaluate-the-model'), ('Building our own CNN code', 2, None, @@ -173,27 +220,7 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Convolution in the Fourier domain', 3, None, - 'convolution-in-the-fourier-domain'), - ('Building convolutional neural networks in Tensorflow and Keras', - 2, - None, - 'building-convolutional-neural-networks-in-tensorflow-and-keras'), - ('Setting it up', 2, None, 'setting-it-up'), - ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), - ('Strong correlations', 2, None, 'strong-correlations'), - ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), - ('Systematic reduction', 2, None, 'systematic-reduction'), - ('Prerequisites: Collect and pre-process data', - 2, - None, - 'prerequisites-collect-and-pre-process-data'), - ('Importing Keras and Tensorflow', - 2, - None, - 'importing-keras-and-tensorflow'), - ('Running with Keras', 2, None, 'running-with-keras'), - ('Final part', 2, None, 'final-part'), - ('Final visualization', 2, None, 'final-visualization')]} + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -244,59 +271,74 @@ MathJax.Hub.Config({
  • CNNs in brief
  • A deep CNN model ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • Key Idea
  • -
  • Mathematics of CNNs
  • -
  • Convolution Examples: Polynomial multiplication
  • -
  • Efficient Polynomial Multiplication
  • -
  • Further simplification
  • -
  • A more efficient way of coding the above Convolution
  • -
  • Fourier series and Toeplitz matrices
  • -
  • Generalizing the above one-dimensional case
  • -
  • Two-dimensional Objects
  • -
  • CNNs in more detail
  • -
  • Performing a discrete convolution with padding ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Set of filters
  • -
  • Pooling
  • -
  • No zero padding, unit strides
  • -
  • Zero padding, unit strides
  • -
  • Half (same) padding
  • -
  • Full padding
  • -
  • Pooling arithmetic
  • -
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Building our own CNN code
  • -
  •    List of contents:
  • -
  •    Schedulers
  • -
  •    Usage of schedulers
  • -
  •    Cost functions
  • -
  •    Usage of cost functions
  • -
  •    Activation functions
  • -
  •    Usage of activation functions
  • -
  •    Convolution
  • -
  •    Layers
  • -
  •    Convolution2DLayer: convolution in a hidden layer
  • -
  •    Backpropagation in the convolutional layer
  • -
  •    Demonstration
  • -
  •    Pooling Layer
  • -
  •    Flattening Layer
  • -
  •    Fully Connected Layers
  • -
  •    Optimized Convolution2DLayer
  • -
  •    The Convolutional Neural Network (CNN)
  • -
  •    Usage of CNN code
  • -
  •    Additional Remarks
  • -
  •    Remarks on the speed
  • -
  •    Convolution using separable kernels
  • -
  •    Convolution in the Fourier domain
  • -
  • Building convolutional neural networks in Tensorflow and Keras
  • -
  • Setting it up
  • -
  • The MNIST dataset again
  • -
  • Strong correlations
  • -
  • Layers of a CNN
  • -
  • Systematic reduction
  • -
  • Prerequisites: Collect and pre-process data
  • -
  • Importing Keras and Tensorflow
  • -
  • Running with Keras
  • -
  • Final part
  • -
  • Final visualization
  • +
  • How to do image compression before the era of deep learning
  • +
  • The SVD example
  • +
  • Mathematics of CNNs
  • +
  • Mathematics of CNNs
  • +
  • Convolution Examples: Polynomial multiplication
  • +
  • Efficient Polynomial Multiplication
  • +
  • Further simplification
  • +
  • A more efficient way of coding the above Convolution
  • +
  • Commutative process
  • +
  • Toeplitz matrices
  • +
  • Fourier series and Toeplitz matrices
  • +
  • Generalizing the above one-dimensional case
  • +
  • Memory considerations
  • +
  • Padding
  • +
  • New vector
  • +
  • Rewriting as dot products
  • +
  • Cross correlation
  • +
  • Two-dimensional objects
  • +
  • CNNs in more detail, simple example
  • +
  • The convolution stage
  • +
  • Finding the number of parameters
  • +
  • New image (or volume)
  • +
  • Parameters to train, common settings
  • +
  • Examples of CNN setups
  • +
  • Summarizing: Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Pooling
  • +
  • Pooling arithmetic
  • +
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Building convolutional neural networks in Tensorflow and Keras
  • +
  • Setting it up
  • +
  • The MNIST dataset again
  • +
  • Strong correlations
  • +
  • Layers of a CNN
  • +
  • Systematic reduction
  • +
  • Prerequisites: Collect and pre-process data
  • +
  • Importing Keras and Tensorflow
  • +
  • Running with Keras
  • +
  • Final part
  • +
  • Final visualization
  • +
  • The CIFAR01 data set
  • +
  • Verifying the data set
  • +
  • Set up the model
  • +
  • Add Dense layers on top
  • +
  • Compile and train the model
  • +
  • Finally, evaluate the model
  • +
  • Building our own CNN code
  • +
  •    List of contents:
  • +
  •    Schedulers
  • +
  •    Usage of schedulers
  • +
  •    Cost functions
  • +
  •    Usage of cost functions
  • +
  •    Activation functions
  • +
  •    Usage of activation functions
  • +
  •    Convolution
  • +
  •    Layers
  • +
  •    Convolution2DLayer: convolution in a hidden layer
  • +
  •    Backpropagation in the convolutional layer
  • +
  •    Demonstration
  • +
  •    Pooling Layer
  • +
  •    Flattening Layer
  • +
  •    Fully Connected Layers
  • +
  •    Optimized Convolution2DLayer
  • +
  •    The Convolutional Neural Network (CNN)
  • +
  •    Usage of CNN code
  • +
  •    Additional Remarks
  • +
  •    Remarks on the speed
  • +
  •    Convolution using separable kernels
  • +
  •    Convolution in the Fourier domain
  • @@ -308,18 +350,19 @@ MathJax.Hub.Config({

     

     

     

    -

    Systematic reduction

    +

    Pooling

    -

    By systematically reducing the size of the input volume, through -convolution and pooling, the network should create representations of -small parts of the input, and then from them assemble representations -of larger areas. The final pooling layer is flattened to serve as -input to a hidden layer, such that each neuron in the final pooling -layer is connected to every single neuron in the hidden layer. This -then serves as input to the output layer, e.g. a softmax output for -classification. +

    In addition to discrete convolutions themselves, pooling operations +make up another important building block in CNNs. Pooling operations reduce +the size of feature maps by using some function to summarize subregions, such +as taking the average or the maximum value.

    +

    Pooling works by sliding a window across the input and feeding the content of +the window to a pooling function. In some sense, pooling works very much +like a discrete convolution, but replaces the linear combination described by +the kernel with some other function. +

    @@ -341,6 +384,12 @@ classification.

  • 45
  • 46
  • 47
  • +
  • 48
  • +
  • 49
  • +
  • 50
  • +
  • 51
  • +
  • ...
  • +
  • 62
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs042.html b/doc/pub/week44/html/._week44-bs042.html index 728dab2b0..19e47880a 100644 --- a/doc/pub/week44/html/._week44-bs042.html +++ b/doc/pub/week44/html/._week44-bs042.html @@ -75,6 +75,12 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d None, 'a-deep-cnn-model-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Key Idea', 2, None, 'key-idea'), + ('How to do image compression before the era of deep learning', + 2, + None, + 'how-to-do-image-compression-before-the-era-of-deep-learning'), + ('The SVD example', 2, None, 'the-svd-example'), + ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Convolution Examples: Polynomial multiplication', 2, @@ -89,6 +95,8 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'a-more-efficient-way-of-coding-the-above-convolution'), + ('Commutative process', 2, None, 'commutative-process'), + ('Toeplitz matrices', 2, None, 'toeplitz-matrices'), ('Fourier series and Toeplitz matrices', 2, None, @@ -97,36 +105,75 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'generalizing-the-above-one-dimensional-case'), - ('Two-dimensional Objects', 2, None, 'two-dimensional-objects'), - ('CNNs in more detail', 2, None, 'cnns-in-more-detail'), - ('Performing a discrete convolution with padding ("From Raschka ' - 'et al":"https://github.com/rasbt/machine-learning-book")', + ('Memory considerations', 2, None, 'memory-considerations'), + ('Padding', 2, None, 'padding'), + ('New vector', 2, None, 'new-vector'), + ('Rewriting as dot products', 2, None, - 'performing-a-discrete-convolution-with-padding-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Performing a general discrete convolution ("From Raschka et ' + 'rewriting-as-dot-products'), + ('Cross correlation', 2, None, 'cross-correlation'), + ('Two-dimensional objects', 2, None, 'two-dimensional-objects'), + ('CNNs in more detail, simple example', + 2, + None, + 'cnns-in-more-detail-simple-example'), + ('The convolution stage', 2, None, 'the-convolution-stage'), + ('Finding the number of parameters', + 2, + None, + 'finding-the-number-of-parameters'), + ('New image (or volume)', 2, None, 'new-image-or-volume'), + ('Parameters to train, common settings', + 2, + None, + 'parameters-to-train-common-settings'), + ('Examples of CNN setups', 2, None, 'examples-of-cnn-setups'), + ('Summarizing: Performing a general discrete convolution ("From ' + 'Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, - 'performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Set of filters', 2, None, 'set-of-filters'), + 'summarizing-performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Pooling', 2, None, 'pooling'), - ('No zero padding, unit strides', - 2, - None, - 'no-zero-padding-unit-strides'), - ('Zero padding, unit strides', - 2, - None, - 'zero-padding-unit-strides'), - ('Half (same) padding', 2, None, 'half-same-padding'), - ('Full padding', 2, None, 'full-padding'), ('Pooling arithmetic', 2, None, 'pooling-arithmetic'), ('Pooling types ("From Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, 'pooling-types-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), + ('Building convolutional neural networks in Tensorflow and Keras', + 2, + None, + 'building-convolutional-neural-networks-in-tensorflow-and-keras'), + ('Setting it up', 2, None, 'setting-it-up'), + ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), + ('Strong correlations', 2, None, 'strong-correlations'), + ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), + ('Systematic reduction', 2, None, 'systematic-reduction'), + ('Prerequisites: Collect and pre-process data', + 2, + None, + 'prerequisites-collect-and-pre-process-data'), + ('Importing Keras and Tensorflow', + 2, + None, + 'importing-keras-and-tensorflow'), + ('Running with Keras', 2, None, 'running-with-keras'), + ('Final part', 2, None, 'final-part'), + ('Final visualization', 2, None, 'final-visualization'), + ('The CIFAR01 data set', 2, None, 'the-cifar01-data-set'), + ('Verifying the data set', 2, None, 'verifying-the-data-set'), + ('Set up the model', 2, None, 'set-up-the-model'), + ('Add Dense layers on top', 2, None, 'add-dense-layers-on-top'), + ('Compile and train the model', + 2, + None, + 'compile-and-train-the-model'), + ('Finally, evaluate the model', + 2, + None, + 'finally-evaluate-the-model'), ('Building our own CNN code', 2, None, @@ -173,27 +220,7 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Convolution in the Fourier domain', 3, None, - 'convolution-in-the-fourier-domain'), - ('Building convolutional neural networks in Tensorflow and Keras', - 2, - None, - 'building-convolutional-neural-networks-in-tensorflow-and-keras'), - ('Setting it up', 2, None, 'setting-it-up'), - ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), - ('Strong correlations', 2, None, 'strong-correlations'), - ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), - ('Systematic reduction', 2, None, 'systematic-reduction'), - ('Prerequisites: Collect and pre-process data', - 2, - None, - 'prerequisites-collect-and-pre-process-data'), - ('Importing Keras and Tensorflow', - 2, - None, - 'importing-keras-and-tensorflow'), - ('Running with Keras', 2, None, 'running-with-keras'), - ('Final part', 2, None, 'final-part'), - ('Final visualization', 2, None, 'final-visualization')]} + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -244,59 +271,74 @@ MathJax.Hub.Config({
  • CNNs in brief
  • A deep CNN model ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • Key Idea
  • -
  • Mathematics of CNNs
  • -
  • Convolution Examples: Polynomial multiplication
  • -
  • Efficient Polynomial Multiplication
  • -
  • Further simplification
  • -
  • A more efficient way of coding the above Convolution
  • -
  • Fourier series and Toeplitz matrices
  • -
  • Generalizing the above one-dimensional case
  • -
  • Two-dimensional Objects
  • -
  • CNNs in more detail
  • -
  • Performing a discrete convolution with padding ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Set of filters
  • -
  • Pooling
  • -
  • No zero padding, unit strides
  • -
  • Zero padding, unit strides
  • -
  • Half (same) padding
  • -
  • Full padding
  • -
  • Pooling arithmetic
  • -
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Building our own CNN code
  • -
  •    List of contents:
  • -
  •    Schedulers
  • -
  •    Usage of schedulers
  • -
  •    Cost functions
  • -
  •    Usage of cost functions
  • -
  •    Activation functions
  • -
  •    Usage of activation functions
  • -
  •    Convolution
  • -
  •    Layers
  • -
  •    Convolution2DLayer: convolution in a hidden layer
  • -
  •    Backpropagation in the convolutional layer
  • -
  •    Demonstration
  • -
  •    Pooling Layer
  • -
  •    Flattening Layer
  • -
  •    Fully Connected Layers
  • -
  •    Optimized Convolution2DLayer
  • -
  •    The Convolutional Neural Network (CNN)
  • -
  •    Usage of CNN code
  • -
  •    Additional Remarks
  • -
  •    Remarks on the speed
  • -
  •    Convolution using separable kernels
  • -
  •    Convolution in the Fourier domain
  • -
  • Building convolutional neural networks in Tensorflow and Keras
  • -
  • Setting it up
  • -
  • The MNIST dataset again
  • -
  • Strong correlations
  • -
  • Layers of a CNN
  • -
  • Systematic reduction
  • -
  • Prerequisites: Collect and pre-process data
  • -
  • Importing Keras and Tensorflow
  • -
  • Running with Keras
  • -
  • Final part
  • -
  • Final visualization
  • +
  • How to do image compression before the era of deep learning
  • +
  • The SVD example
  • +
  • Mathematics of CNNs
  • +
  • Mathematics of CNNs
  • +
  • Convolution Examples: Polynomial multiplication
  • +
  • Efficient Polynomial Multiplication
  • +
  • Further simplification
  • +
  • A more efficient way of coding the above Convolution
  • +
  • Commutative process
  • +
  • Toeplitz matrices
  • +
  • Fourier series and Toeplitz matrices
  • +
  • Generalizing the above one-dimensional case
  • +
  • Memory considerations
  • +
  • Padding
  • +
  • New vector
  • +
  • Rewriting as dot products
  • +
  • Cross correlation
  • +
  • Two-dimensional objects
  • +
  • CNNs in more detail, simple example
  • +
  • The convolution stage
  • +
  • Finding the number of parameters
  • +
  • New image (or volume)
  • +
  • Parameters to train, common settings
  • +
  • Examples of CNN setups
  • +
  • Summarizing: Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Pooling
  • +
  • Pooling arithmetic
  • +
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Building convolutional neural networks in Tensorflow and Keras
  • +
  • Setting it up
  • +
  • The MNIST dataset again
  • +
  • Strong correlations
  • +
  • Layers of a CNN
  • +
  • Systematic reduction
  • +
  • Prerequisites: Collect and pre-process data
  • +
  • Importing Keras and Tensorflow
  • +
  • Running with Keras
  • +
  • Final part
  • +
  • Final visualization
  • +
  • The CIFAR01 data set
  • +
  • Verifying the data set
  • +
  • Set up the model
  • +
  • Add Dense layers on top
  • +
  • Compile and train the model
  • +
  • Finally, evaluate the model
  • +
  • Building our own CNN code
  • +
  •    List of contents:
  • +
  •    Schedulers
  • +
  •    Usage of schedulers
  • +
  •    Cost functions
  • +
  •    Usage of cost functions
  • +
  •    Activation functions
  • +
  •    Usage of activation functions
  • +
  •    Convolution
  • +
  •    Layers
  • +
  •    Convolution2DLayer: convolution in a hidden layer
  • +
  •    Backpropagation in the convolutional layer
  • +
  •    Demonstration
  • +
  •    Pooling Layer
  • +
  •    Flattening Layer
  • +
  •    Fully Connected Layers
  • +
  •    Optimized Convolution2DLayer
  • +
  •    The Convolutional Neural Network (CNN)
  • +
  •    Usage of CNN code
  • +
  •    Additional Remarks
  • +
  •    Remarks on the speed
  • +
  •    Convolution using separable kernels
  • +
  •    Convolution in the Fourier domain
  • @@ -308,69 +350,15 @@ MathJax.Hub.Config({

     

     

     

    -

    Prerequisites: Collect and pre-process data

    - - -
    -
    -
    -
    -
    -
    # import necessary packages
    -import numpy as np
    -import matplotlib.pyplot as plt
    -from sklearn import datasets
    -
    -
    -# ensure the same random numbers appear every time
    -np.random.seed(0)
    -
    -# display images in notebook
    -%matplotlib inline
    -plt.rcParams['figure.figsize'] = (12,12)
    -
    -
    -# download MNIST dataset
    -digits = datasets.load_digits()
    -
    -# define inputs and labels
    -inputs = digits.images
    -labels = digits.target
    -
    -# RGB images have a depth of 3
    -# our images are grayscale so they should have a depth of 1
    -inputs = inputs[:,:,:,np.newaxis]
    -
    -print("inputs = (n_inputs, pixel_width, pixel_height, depth) = " + str(inputs.shape))
    -print("labels = (n_inputs) = " + str(labels.shape))
    -
    -
    -# choose some random images to display
    -n_inputs = len(inputs)
    -indices = np.arange(n_inputs)
    -random_indices = np.random.choice(indices, size=5)
    -
    -for i, image in enumerate(digits.images[random_indices]):
    -    plt.subplot(1, 5, i+1)
    -    plt.axis('off')
    -    plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
    -    plt.title("Label: %d" % digits.target[random_indices[i]])
    -plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    +

    Pooling arithmetic

    +

    In a neural network, pooling layers provide invariance to small translations of +the input. The most common kind of pooling is max pooling, which +consists in splitting the input in (usually non-overlapping) patches and +outputting the maximum value of each patch. Other kinds of pooling exist, e.g., +mean or average pooling, which all share the same idea of aggregating the input +locally by applying a non-linearity to the content of some patches. +

    @@ -391,6 +379,13 @@ plt.show()

  • 45
  • 46
  • 47
  • +
  • 48
  • +
  • 49
  • +
  • 50
  • +
  • 51
  • +
  • 52
  • +
  • ...
  • +
  • 62
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs043.html b/doc/pub/week44/html/._week44-bs043.html index 57914b217..eeff4c046 100644 --- a/doc/pub/week44/html/._week44-bs043.html +++ b/doc/pub/week44/html/._week44-bs043.html @@ -75,6 +75,12 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d None, 'a-deep-cnn-model-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Key Idea', 2, None, 'key-idea'), + ('How to do image compression before the era of deep learning', + 2, + None, + 'how-to-do-image-compression-before-the-era-of-deep-learning'), + ('The SVD example', 2, None, 'the-svd-example'), + ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Convolution Examples: Polynomial multiplication', 2, @@ -89,6 +95,8 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'a-more-efficient-way-of-coding-the-above-convolution'), + ('Commutative process', 2, None, 'commutative-process'), + ('Toeplitz matrices', 2, None, 'toeplitz-matrices'), ('Fourier series and Toeplitz matrices', 2, None, @@ -97,36 +105,75 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'generalizing-the-above-one-dimensional-case'), - ('Two-dimensional Objects', 2, None, 'two-dimensional-objects'), - ('CNNs in more detail', 2, None, 'cnns-in-more-detail'), - ('Performing a discrete convolution with padding ("From Raschka ' - 'et al":"https://github.com/rasbt/machine-learning-book")', + ('Memory considerations', 2, None, 'memory-considerations'), + ('Padding', 2, None, 'padding'), + ('New vector', 2, None, 'new-vector'), + ('Rewriting as dot products', 2, None, - 'performing-a-discrete-convolution-with-padding-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Performing a general discrete convolution ("From Raschka et ' + 'rewriting-as-dot-products'), + ('Cross correlation', 2, None, 'cross-correlation'), + ('Two-dimensional objects', 2, None, 'two-dimensional-objects'), + ('CNNs in more detail, simple example', + 2, + None, + 'cnns-in-more-detail-simple-example'), + ('The convolution stage', 2, None, 'the-convolution-stage'), + ('Finding the number of parameters', + 2, + None, + 'finding-the-number-of-parameters'), + ('New image (or volume)', 2, None, 'new-image-or-volume'), + ('Parameters to train, common settings', + 2, + None, + 'parameters-to-train-common-settings'), + ('Examples of CNN setups', 2, None, 'examples-of-cnn-setups'), + ('Summarizing: Performing a general discrete convolution ("From ' + 'Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, - 'performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Set of filters', 2, None, 'set-of-filters'), + 'summarizing-performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Pooling', 2, None, 'pooling'), - ('No zero padding, unit strides', - 2, - None, - 'no-zero-padding-unit-strides'), - ('Zero padding, unit strides', - 2, - None, - 'zero-padding-unit-strides'), - ('Half (same) padding', 2, None, 'half-same-padding'), - ('Full padding', 2, None, 'full-padding'), ('Pooling arithmetic', 2, None, 'pooling-arithmetic'), ('Pooling types ("From Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, 'pooling-types-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), + ('Building convolutional neural networks in Tensorflow and Keras', + 2, + None, + 'building-convolutional-neural-networks-in-tensorflow-and-keras'), + ('Setting it up', 2, None, 'setting-it-up'), + ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), + ('Strong correlations', 2, None, 'strong-correlations'), + ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), + ('Systematic reduction', 2, None, 'systematic-reduction'), + ('Prerequisites: Collect and pre-process data', + 2, + None, + 'prerequisites-collect-and-pre-process-data'), + ('Importing Keras and Tensorflow', + 2, + None, + 'importing-keras-and-tensorflow'), + ('Running with Keras', 2, None, 'running-with-keras'), + ('Final part', 2, None, 'final-part'), + ('Final visualization', 2, None, 'final-visualization'), + ('The CIFAR01 data set', 2, None, 'the-cifar01-data-set'), + ('Verifying the data set', 2, None, 'verifying-the-data-set'), + ('Set up the model', 2, None, 'set-up-the-model'), + ('Add Dense layers on top', 2, None, 'add-dense-layers-on-top'), + ('Compile and train the model', + 2, + None, + 'compile-and-train-the-model'), + ('Finally, evaluate the model', + 2, + None, + 'finally-evaluate-the-model'), ('Building our own CNN code', 2, None, @@ -173,27 +220,7 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Convolution in the Fourier domain', 3, None, - 'convolution-in-the-fourier-domain'), - ('Building convolutional neural networks in Tensorflow and Keras', - 2, - None, - 'building-convolutional-neural-networks-in-tensorflow-and-keras'), - ('Setting it up', 2, None, 'setting-it-up'), - ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), - ('Strong correlations', 2, None, 'strong-correlations'), - ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), - ('Systematic reduction', 2, None, 'systematic-reduction'), - ('Prerequisites: Collect and pre-process data', - 2, - None, - 'prerequisites-collect-and-pre-process-data'), - ('Importing Keras and Tensorflow', - 2, - None, - 'importing-keras-and-tensorflow'), - ('Running with Keras', 2, None, 'running-with-keras'), - ('Final part', 2, None, 'final-part'), - ('Final visualization', 2, None, 'final-visualization')]} + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -244,59 +271,74 @@ MathJax.Hub.Config({
  • CNNs in brief
  • A deep CNN model ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • Key Idea
  • -
  • Mathematics of CNNs
  • -
  • Convolution Examples: Polynomial multiplication
  • -
  • Efficient Polynomial Multiplication
  • -
  • Further simplification
  • -
  • A more efficient way of coding the above Convolution
  • -
  • Fourier series and Toeplitz matrices
  • -
  • Generalizing the above one-dimensional case
  • -
  • Two-dimensional Objects
  • -
  • CNNs in more detail
  • -
  • Performing a discrete convolution with padding ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Set of filters
  • -
  • Pooling
  • -
  • No zero padding, unit strides
  • -
  • Zero padding, unit strides
  • -
  • Half (same) padding
  • -
  • Full padding
  • -
  • Pooling arithmetic
  • -
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Building our own CNN code
  • -
  •    List of contents:
  • -
  •    Schedulers
  • -
  •    Usage of schedulers
  • -
  •    Cost functions
  • -
  •    Usage of cost functions
  • -
  •    Activation functions
  • -
  •    Usage of activation functions
  • -
  •    Convolution
  • -
  •    Layers
  • -
  •    Convolution2DLayer: convolution in a hidden layer
  • -
  •    Backpropagation in the convolutional layer
  • -
  •    Demonstration
  • -
  •    Pooling Layer
  • -
  •    Flattening Layer
  • -
  •    Fully Connected Layers
  • -
  •    Optimized Convolution2DLayer
  • -
  •    The Convolutional Neural Network (CNN)
  • -
  •    Usage of CNN code
  • -
  •    Additional Remarks
  • -
  •    Remarks on the speed
  • -
  •    Convolution using separable kernels
  • -
  •    Convolution in the Fourier domain
  • -
  • Building convolutional neural networks in Tensorflow and Keras
  • -
  • Setting it up
  • -
  • The MNIST dataset again
  • -
  • Strong correlations
  • -
  • Layers of a CNN
  • -
  • Systematic reduction
  • -
  • Prerequisites: Collect and pre-process data
  • -
  • Importing Keras and Tensorflow
  • -
  • Running with Keras
  • -
  • Final part
  • -
  • Final visualization
  • +
  • How to do image compression before the era of deep learning
  • +
  • The SVD example
  • +
  • Mathematics of CNNs
  • +
  • Mathematics of CNNs
  • +
  • Convolution Examples: Polynomial multiplication
  • +
  • Efficient Polynomial Multiplication
  • +
  • Further simplification
  • +
  • A more efficient way of coding the above Convolution
  • +
  • Commutative process
  • +
  • Toeplitz matrices
  • +
  • Fourier series and Toeplitz matrices
  • +
  • Generalizing the above one-dimensional case
  • +
  • Memory considerations
  • +
  • Padding
  • +
  • New vector
  • +
  • Rewriting as dot products
  • +
  • Cross correlation
  • +
  • Two-dimensional objects
  • +
  • CNNs in more detail, simple example
  • +
  • The convolution stage
  • +
  • Finding the number of parameters
  • +
  • New image (or volume)
  • +
  • Parameters to train, common settings
  • +
  • Examples of CNN setups
  • +
  • Summarizing: Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Pooling
  • +
  • Pooling arithmetic
  • +
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Building convolutional neural networks in Tensorflow and Keras
  • +
  • Setting it up
  • +
  • The MNIST dataset again
  • +
  • Strong correlations
  • +
  • Layers of a CNN
  • +
  • Systematic reduction
  • +
  • Prerequisites: Collect and pre-process data
  • +
  • Importing Keras and Tensorflow
  • +
  • Running with Keras
  • +
  • Final part
  • +
  • Final visualization
  • +
  • The CIFAR01 data set
  • +
  • Verifying the data set
  • +
  • Set up the model
  • +
  • Add Dense layers on top
  • +
  • Compile and train the model
  • +
  • Finally, evaluate the model
  • +
  • Building our own CNN code
  • +
  •    List of contents:
  • +
  •    Schedulers
  • +
  •    Usage of schedulers
  • +
  •    Cost functions
  • +
  •    Usage of cost functions
  • +
  •    Activation functions
  • +
  •    Usage of activation functions
  • +
  •    Convolution
  • +
  •    Layers
  • +
  •    Convolution2DLayer: convolution in a hidden layer
  • +
  •    Backpropagation in the convolutional layer
  • +
  •    Demonstration
  • +
  •    Pooling Layer
  • +
  •    Flattening Layer
  • +
  •    Fully Connected Layers
  • +
  •    Optimized Convolution2DLayer
  • +
  •    The Convolutional Neural Network (CNN)
  • +
  •    Usage of CNN code
  • +
  •    Additional Remarks
  • +
  •    Remarks on the speed
  • +
  •    Convolution using separable kernels
  • +
  •    Convolution in the Fourier domain
  • @@ -308,51 +350,15 @@ MathJax.Hub.Config({

     

     

     

    -

    Importing Keras and Tensorflow

    - - -
    -
    -
    -
    -
    -
    from tensorflow.keras import datasets, layers, models
    -from tensorflow.keras.layers import Input
    -from tensorflow.keras.models import Sequential      #This allows appending layers to existing models
    -from tensorflow.keras.layers import Dense           #This allows defining the characteristics of a particular layer
    -from tensorflow.keras import optimizers             #This allows using whichever optimiser we want (sgd,adam,RMSprop)
    -from tensorflow.keras import regularizers           #This allows using whichever regularizer we want (l1,l2,l1_l2)
    -from tensorflow.keras.utils import to_categorical   #This allows using categorical cross entropy as the cost function
    -#from tensorflow.keras import Conv2D
    -#from tensorflow.keras import MaxPooling2D
    -#from tensorflow.keras import Flatten
    -
    -from sklearn.model_selection import train_test_split
    -
    -# representation of labels
    -labels = to_categorical(labels)
    -
    -# split into train and test data
    -# one-liner from scikit-learn library
    -train_size = 0.8
    -test_size = 1 - train_size
    -X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,
    -                                                    test_size=test_size)
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    +

    Pooling types (From Raschka et al)

    +
    +
    +
    +

    Figure 5: A deep CNN

    +
    +

    +

    @@ -372,6 +378,14 @@ X_train, X_test, Y_train, Y_test = train_tes

  • 45
  • 46
  • 47
  • +
  • 48
  • +
  • 49
  • +
  • 50
  • +
  • 51
  • +
  • 52
  • +
  • 53
  • +
  • ...
  • +
  • 62
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs044.html b/doc/pub/week44/html/._week44-bs044.html index 823e99d4b..8aea60144 100644 --- a/doc/pub/week44/html/._week44-bs044.html +++ b/doc/pub/week44/html/._week44-bs044.html @@ -75,6 +75,12 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d None, 'a-deep-cnn-model-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Key Idea', 2, None, 'key-idea'), + ('How to do image compression before the era of deep learning', + 2, + None, + 'how-to-do-image-compression-before-the-era-of-deep-learning'), + ('The SVD example', 2, None, 'the-svd-example'), + ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Convolution Examples: Polynomial multiplication', 2, @@ -89,6 +95,8 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'a-more-efficient-way-of-coding-the-above-convolution'), + ('Commutative process', 2, None, 'commutative-process'), + ('Toeplitz matrices', 2, None, 'toeplitz-matrices'), ('Fourier series and Toeplitz matrices', 2, None, @@ -97,36 +105,75 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'generalizing-the-above-one-dimensional-case'), - ('Two-dimensional Objects', 2, None, 'two-dimensional-objects'), - ('CNNs in more detail', 2, None, 'cnns-in-more-detail'), - ('Performing a discrete convolution with padding ("From Raschka ' - 'et al":"https://github.com/rasbt/machine-learning-book")', + ('Memory considerations', 2, None, 'memory-considerations'), + ('Padding', 2, None, 'padding'), + ('New vector', 2, None, 'new-vector'), + ('Rewriting as dot products', 2, None, - 'performing-a-discrete-convolution-with-padding-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Performing a general discrete convolution ("From Raschka et ' + 'rewriting-as-dot-products'), + ('Cross correlation', 2, None, 'cross-correlation'), + ('Two-dimensional objects', 2, None, 'two-dimensional-objects'), + ('CNNs in more detail, simple example', + 2, + None, + 'cnns-in-more-detail-simple-example'), + ('The convolution stage', 2, None, 'the-convolution-stage'), + ('Finding the number of parameters', + 2, + None, + 'finding-the-number-of-parameters'), + ('New image (or volume)', 2, None, 'new-image-or-volume'), + ('Parameters to train, common settings', + 2, + None, + 'parameters-to-train-common-settings'), + ('Examples of CNN setups', 2, None, 'examples-of-cnn-setups'), + ('Summarizing: Performing a general discrete convolution ("From ' + 'Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, - 'performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Set of filters', 2, None, 'set-of-filters'), + 'summarizing-performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Pooling', 2, None, 'pooling'), - ('No zero padding, unit strides', - 2, - None, - 'no-zero-padding-unit-strides'), - ('Zero padding, unit strides', - 2, - None, - 'zero-padding-unit-strides'), - ('Half (same) padding', 2, None, 'half-same-padding'), - ('Full padding', 2, None, 'full-padding'), ('Pooling arithmetic', 2, None, 'pooling-arithmetic'), ('Pooling types ("From Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, 'pooling-types-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), + ('Building convolutional neural networks in Tensorflow and Keras', + 2, + None, + 'building-convolutional-neural-networks-in-tensorflow-and-keras'), + ('Setting it up', 2, None, 'setting-it-up'), + ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), + ('Strong correlations', 2, None, 'strong-correlations'), + ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), + ('Systematic reduction', 2, None, 'systematic-reduction'), + ('Prerequisites: Collect and pre-process data', + 2, + None, + 'prerequisites-collect-and-pre-process-data'), + ('Importing Keras and Tensorflow', + 2, + None, + 'importing-keras-and-tensorflow'), + ('Running with Keras', 2, None, 'running-with-keras'), + ('Final part', 2, None, 'final-part'), + ('Final visualization', 2, None, 'final-visualization'), + ('The CIFAR01 data set', 2, None, 'the-cifar01-data-set'), + ('Verifying the data set', 2, None, 'verifying-the-data-set'), + ('Set up the model', 2, None, 'set-up-the-model'), + ('Add Dense layers on top', 2, None, 'add-dense-layers-on-top'), + ('Compile and train the model', + 2, + None, + 'compile-and-train-the-model'), + ('Finally, evaluate the model', + 2, + None, + 'finally-evaluate-the-model'), ('Building our own CNN code', 2, None, @@ -173,27 +220,7 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Convolution in the Fourier domain', 3, None, - 'convolution-in-the-fourier-domain'), - ('Building convolutional neural networks in Tensorflow and Keras', - 2, - None, - 'building-convolutional-neural-networks-in-tensorflow-and-keras'), - ('Setting it up', 2, None, 'setting-it-up'), - ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), - ('Strong correlations', 2, None, 'strong-correlations'), - ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), - ('Systematic reduction', 2, None, 'systematic-reduction'), - ('Prerequisites: Collect and pre-process data', - 2, - None, - 'prerequisites-collect-and-pre-process-data'), - ('Importing Keras and Tensorflow', - 2, - None, - 'importing-keras-and-tensorflow'), - ('Running with Keras', 2, None, 'running-with-keras'), - ('Final part', 2, None, 'final-part'), - ('Final visualization', 2, None, 'final-visualization')]} + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -244,59 +271,74 @@ MathJax.Hub.Config({
  • CNNs in brief
  • A deep CNN model ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • Key Idea
  • -
  • Mathematics of CNNs
  • -
  • Convolution Examples: Polynomial multiplication
  • -
  • Efficient Polynomial Multiplication
  • -
  • Further simplification
  • -
  • A more efficient way of coding the above Convolution
  • -
  • Fourier series and Toeplitz matrices
  • -
  • Generalizing the above one-dimensional case
  • -
  • Two-dimensional Objects
  • -
  • CNNs in more detail
  • -
  • Performing a discrete convolution with padding ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Set of filters
  • -
  • Pooling
  • -
  • No zero padding, unit strides
  • -
  • Zero padding, unit strides
  • -
  • Half (same) padding
  • -
  • Full padding
  • -
  • Pooling arithmetic
  • -
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Building our own CNN code
  • -
  •    List of contents:
  • -
  •    Schedulers
  • -
  •    Usage of schedulers
  • -
  •    Cost functions
  • -
  •    Usage of cost functions
  • -
  •    Activation functions
  • -
  •    Usage of activation functions
  • -
  •    Convolution
  • -
  •    Layers
  • -
  •    Convolution2DLayer: convolution in a hidden layer
  • -
  •    Backpropagation in the convolutional layer
  • -
  •    Demonstration
  • -
  •    Pooling Layer
  • -
  •    Flattening Layer
  • -
  •    Fully Connected Layers
  • -
  •    Optimized Convolution2DLayer
  • -
  •    The Convolutional Neural Network (CNN)
  • -
  •    Usage of CNN code
  • -
  •    Additional Remarks
  • -
  •    Remarks on the speed
  • -
  •    Convolution using separable kernels
  • -
  •    Convolution in the Fourier domain
  • -
  • Building convolutional neural networks in Tensorflow and Keras
  • -
  • Setting it up
  • -
  • The MNIST dataset again
  • -
  • Strong correlations
  • -
  • Layers of a CNN
  • -
  • Systematic reduction
  • -
  • Prerequisites: Collect and pre-process data
  • -
  • Importing Keras and Tensorflow
  • -
  • Running with Keras
  • -
  • Final part
  • -
  • Final visualization
  • +
  • How to do image compression before the era of deep learning
  • +
  • The SVD example
  • +
  • Mathematics of CNNs
  • +
  • Mathematics of CNNs
  • +
  • Convolution Examples: Polynomial multiplication
  • +
  • Efficient Polynomial Multiplication
  • +
  • Further simplification
  • +
  • A more efficient way of coding the above Convolution
  • +
  • Commutative process
  • +
  • Toeplitz matrices
  • +
  • Fourier series and Toeplitz matrices
  • +
  • Generalizing the above one-dimensional case
  • +
  • Memory considerations
  • +
  • Padding
  • +
  • New vector
  • +
  • Rewriting as dot products
  • +
  • Cross correlation
  • +
  • Two-dimensional objects
  • +
  • CNNs in more detail, simple example
  • +
  • The convolution stage
  • +
  • Finding the number of parameters
  • +
  • New image (or volume)
  • +
  • Parameters to train, common settings
  • +
  • Examples of CNN setups
  • +
  • Summarizing: Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Pooling
  • +
  • Pooling arithmetic
  • +
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Building convolutional neural networks in Tensorflow and Keras
  • +
  • Setting it up
  • +
  • The MNIST dataset again
  • +
  • Strong correlations
  • +
  • Layers of a CNN
  • +
  • Systematic reduction
  • +
  • Prerequisites: Collect and pre-process data
  • +
  • Importing Keras and Tensorflow
  • +
  • Running with Keras
  • +
  • Final part
  • +
  • Final visualization
  • +
  • The CIFAR01 data set
  • +
  • Verifying the data set
  • +
  • Set up the model
  • +
  • Add Dense layers on top
  • +
  • Compile and train the model
  • +
  • Finally, evaluate the model
  • +
  • Building our own CNN code
  • +
  •    List of contents:
  • +
  •    Schedulers
  • +
  •    Usage of schedulers
  • +
  •    Cost functions
  • +
  •    Usage of cost functions
  • +
  •    Activation functions
  • +
  •    Usage of activation functions
  • +
  •    Convolution
  • +
  •    Layers
  • +
  •    Convolution2DLayer: convolution in a hidden layer
  • +
  •    Backpropagation in the convolutional layer
  • +
  •    Demonstration
  • +
  •    Pooling Layer
  • +
  •    Flattening Layer
  • +
  •    Fully Connected Layers
  • +
  •    Optimized Convolution2DLayer
  • +
  •    The Convolutional Neural Network (CNN)
  • +
  •    Usage of CNN code
  • +
  •    Additional Remarks
  • +
  •    Remarks on the speed
  • +
  •    Convolution using separable kernels
  • +
  •    Convolution in the Fourier domain
  • @@ -307,57 +349,19 @@ MathJax.Hub.Config({

     

     

     

    - -

    Running with Keras

    + +

    Building convolutional neural networks in Tensorflow and Keras

    +

    As discussed above, CNNs are neural networks built from the assumption that the inputs +to the network are 2D images. This is important because the number of features or pixels in images +grows very fast with the image size, and an enormous number of weights and biases are needed in order to build an accurate network. +

    - -
    -
    -
    -
    -
    -
    def create_convolutional_neural_network_keras(input_shape, receptive_field,
    -                                              n_filters, n_neurons_connected, n_categories,
    -                                              eta, lmbd):
    -    model = Sequential()
    -    model.add(layers.Conv2D(n_filters, (receptive_field, receptive_field), input_shape=input_shape, padding='same',
    -              activation='relu', kernel_regularizer=regularizers.l2(lmbd)))
    -    model.add(layers.MaxPooling2D(pool_size=(2, 2)))
    -    model.add(layers.Flatten())
    -    model.add(layers.Dense(n_neurons_connected, activation='relu', kernel_regularizer=regularizers.l2(lmbd)))
    -    model.add(layers.Dense(n_categories, activation='softmax', kernel_regularizer=regularizers.l2(lmbd)))
    -    
    -    sgd = optimizers.SGD(learning_rate=eta)
    -    model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])
    -    
    -    return model
    -
    -epochs = 100
    -batch_size = 100
    -input_shape = X_train.shape[1:4]
    -receptive_field = 3
    -n_filters = 10
    -n_neurons_connected = 50
    -n_categories = 10
    -
    -eta_vals = np.logspace(-5, 1, 7)
    -lmbd_vals = np.logspace(-5, 1, 7)
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - +

    As before, we still have our input, a hidden layer and an output. What's novel about convolutional networks +are the convolutional and pooling layers stacked in pairs between the input and the hidden layer. +In addition, the data is no longer represented as a 2D feature matrix, instead each input is a number of 2D +matrices, typically 1 for each color dimension (Red, Green, Blue). +

    @@ -376,6 +380,15 @@ lmbd_vals = np.

  • 45
  • 46
  • 47
  • +
  • 48
  • +
  • 49
  • +
  • 50
  • +
  • 51
  • +
  • 52
  • +
  • 53
  • +
  • 54
  • +
  • ...
  • +
  • 62
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs045.html b/doc/pub/week44/html/._week44-bs045.html index 29c333ad4..7b05ade0e 100644 --- a/doc/pub/week44/html/._week44-bs045.html +++ b/doc/pub/week44/html/._week44-bs045.html @@ -75,6 +75,12 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d None, 'a-deep-cnn-model-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Key Idea', 2, None, 'key-idea'), + ('How to do image compression before the era of deep learning', + 2, + None, + 'how-to-do-image-compression-before-the-era-of-deep-learning'), + ('The SVD example', 2, None, 'the-svd-example'), + ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Convolution Examples: Polynomial multiplication', 2, @@ -89,6 +95,8 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'a-more-efficient-way-of-coding-the-above-convolution'), + ('Commutative process', 2, None, 'commutative-process'), + ('Toeplitz matrices', 2, None, 'toeplitz-matrices'), ('Fourier series and Toeplitz matrices', 2, None, @@ -97,36 +105,75 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'generalizing-the-above-one-dimensional-case'), - ('Two-dimensional Objects', 2, None, 'two-dimensional-objects'), - ('CNNs in more detail', 2, None, 'cnns-in-more-detail'), - ('Performing a discrete convolution with padding ("From Raschka ' - 'et al":"https://github.com/rasbt/machine-learning-book")', + ('Memory considerations', 2, None, 'memory-considerations'), + ('Padding', 2, None, 'padding'), + ('New vector', 2, None, 'new-vector'), + ('Rewriting as dot products', 2, None, - 'performing-a-discrete-convolution-with-padding-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Performing a general discrete convolution ("From Raschka et ' + 'rewriting-as-dot-products'), + ('Cross correlation', 2, None, 'cross-correlation'), + ('Two-dimensional objects', 2, None, 'two-dimensional-objects'), + ('CNNs in more detail, simple example', + 2, + None, + 'cnns-in-more-detail-simple-example'), + ('The convolution stage', 2, None, 'the-convolution-stage'), + ('Finding the number of parameters', + 2, + None, + 'finding-the-number-of-parameters'), + ('New image (or volume)', 2, None, 'new-image-or-volume'), + ('Parameters to train, common settings', + 2, + None, + 'parameters-to-train-common-settings'), + ('Examples of CNN setups', 2, None, 'examples-of-cnn-setups'), + ('Summarizing: Performing a general discrete convolution ("From ' + 'Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, - 'performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Set of filters', 2, None, 'set-of-filters'), + 'summarizing-performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Pooling', 2, None, 'pooling'), - ('No zero padding, unit strides', - 2, - None, - 'no-zero-padding-unit-strides'), - ('Zero padding, unit strides', - 2, - None, - 'zero-padding-unit-strides'), - ('Half (same) padding', 2, None, 'half-same-padding'), - ('Full padding', 2, None, 'full-padding'), ('Pooling arithmetic', 2, None, 'pooling-arithmetic'), ('Pooling types ("From Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, 'pooling-types-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), + ('Building convolutional neural networks in Tensorflow and Keras', + 2, + None, + 'building-convolutional-neural-networks-in-tensorflow-and-keras'), + ('Setting it up', 2, None, 'setting-it-up'), + ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), + ('Strong correlations', 2, None, 'strong-correlations'), + ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), + ('Systematic reduction', 2, None, 'systematic-reduction'), + ('Prerequisites: Collect and pre-process data', + 2, + None, + 'prerequisites-collect-and-pre-process-data'), + ('Importing Keras and Tensorflow', + 2, + None, + 'importing-keras-and-tensorflow'), + ('Running with Keras', 2, None, 'running-with-keras'), + ('Final part', 2, None, 'final-part'), + ('Final visualization', 2, None, 'final-visualization'), + ('The CIFAR01 data set', 2, None, 'the-cifar01-data-set'), + ('Verifying the data set', 2, None, 'verifying-the-data-set'), + ('Set up the model', 2, None, 'set-up-the-model'), + ('Add Dense layers on top', 2, None, 'add-dense-layers-on-top'), + ('Compile and train the model', + 2, + None, + 'compile-and-train-the-model'), + ('Finally, evaluate the model', + 2, + None, + 'finally-evaluate-the-model'), ('Building our own CNN code', 2, None, @@ -173,27 +220,7 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Convolution in the Fourier domain', 3, None, - 'convolution-in-the-fourier-domain'), - ('Building convolutional neural networks in Tensorflow and Keras', - 2, - None, - 'building-convolutional-neural-networks-in-tensorflow-and-keras'), - ('Setting it up', 2, None, 'setting-it-up'), - ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), - ('Strong correlations', 2, None, 'strong-correlations'), - ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), - ('Systematic reduction', 2, None, 'systematic-reduction'), - ('Prerequisites: Collect and pre-process data', - 2, - None, - 'prerequisites-collect-and-pre-process-data'), - ('Importing Keras and Tensorflow', - 2, - None, - 'importing-keras-and-tensorflow'), - ('Running with Keras', 2, None, 'running-with-keras'), - ('Final part', 2, None, 'final-part'), - ('Final visualization', 2, None, 'final-visualization')]} + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -244,59 +271,74 @@ MathJax.Hub.Config({
  • CNNs in brief
  • A deep CNN model ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • Key Idea
  • -
  • Mathematics of CNNs
  • -
  • Convolution Examples: Polynomial multiplication
  • -
  • Efficient Polynomial Multiplication
  • -
  • Further simplification
  • -
  • A more efficient way of coding the above Convolution
  • -
  • Fourier series and Toeplitz matrices
  • -
  • Generalizing the above one-dimensional case
  • -
  • Two-dimensional Objects
  • -
  • CNNs in more detail
  • -
  • Performing a discrete convolution with padding ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Set of filters
  • -
  • Pooling
  • -
  • No zero padding, unit strides
  • -
  • Zero padding, unit strides
  • -
  • Half (same) padding
  • -
  • Full padding
  • -
  • Pooling arithmetic
  • -
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Building our own CNN code
  • -
  •    List of contents:
  • -
  •    Schedulers
  • -
  •    Usage of schedulers
  • -
  •    Cost functions
  • -
  •    Usage of cost functions
  • -
  •    Activation functions
  • -
  •    Usage of activation functions
  • -
  •    Convolution
  • -
  •    Layers
  • -
  •    Convolution2DLayer: convolution in a hidden layer
  • -
  •    Backpropagation in the convolutional layer
  • -
  •    Demonstration
  • -
  •    Pooling Layer
  • -
  •    Flattening Layer
  • -
  •    Fully Connected Layers
  • -
  •    Optimized Convolution2DLayer
  • -
  •    The Convolutional Neural Network (CNN)
  • -
  •    Usage of CNN code
  • -
  •    Additional Remarks
  • -
  •    Remarks on the speed
  • -
  •    Convolution using separable kernels
  • -
  •    Convolution in the Fourier domain
  • -
  • Building convolutional neural networks in Tensorflow and Keras
  • -
  • Setting it up
  • -
  • The MNIST dataset again
  • -
  • Strong correlations
  • -
  • Layers of a CNN
  • -
  • Systematic reduction
  • -
  • Prerequisites: Collect and pre-process data
  • -
  • Importing Keras and Tensorflow
  • -
  • Running with Keras
  • -
  • Final part
  • -
  • Final visualization
  • +
  • How to do image compression before the era of deep learning
  • +
  • The SVD example
  • +
  • Mathematics of CNNs
  • +
  • Mathematics of CNNs
  • +
  • Convolution Examples: Polynomial multiplication
  • +
  • Efficient Polynomial Multiplication
  • +
  • Further simplification
  • +
  • A more efficient way of coding the above Convolution
  • +
  • Commutative process
  • +
  • Toeplitz matrices
  • +
  • Fourier series and Toeplitz matrices
  • +
  • Generalizing the above one-dimensional case
  • +
  • Memory considerations
  • +
  • Padding
  • +
  • New vector
  • +
  • Rewriting as dot products
  • +
  • Cross correlation
  • +
  • Two-dimensional objects
  • +
  • CNNs in more detail, simple example
  • +
  • The convolution stage
  • +
  • Finding the number of parameters
  • +
  • New image (or volume)
  • +
  • Parameters to train, common settings
  • +
  • Examples of CNN setups
  • +
  • Summarizing: Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Pooling
  • +
  • Pooling arithmetic
  • +
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Building convolutional neural networks in Tensorflow and Keras
  • +
  • Setting it up
  • +
  • The MNIST dataset again
  • +
  • Strong correlations
  • +
  • Layers of a CNN
  • +
  • Systematic reduction
  • +
  • Prerequisites: Collect and pre-process data
  • +
  • Importing Keras and Tensorflow
  • +
  • Running with Keras
  • +
  • Final part
  • +
  • Final visualization
  • +
  • The CIFAR01 data set
  • +
  • Verifying the data set
  • +
  • Set up the model
  • +
  • Add Dense layers on top
  • +
  • Compile and train the model
  • +
  • Finally, evaluate the model
  • +
  • Building our own CNN code
  • +
  •    List of contents:
  • +
  •    Schedulers
  • +
  •    Usage of schedulers
  • +
  •    Cost functions
  • +
  •    Usage of cost functions
  • +
  •    Activation functions
  • +
  •    Usage of activation functions
  • +
  •    Convolution
  • +
  •    Layers
  • +
  •    Convolution2DLayer: convolution in a hidden layer
  • +
  •    Backpropagation in the convolutional layer
  • +
  •    Demonstration
  • +
  •    Pooling Layer
  • +
  •    Flattening Layer
  • +
  •    Fully Connected Layers
  • +
  •    Optimized Convolution2DLayer
  • +
  •    The Convolutional Neural Network (CNN)
  • +
  •    Usage of CNN code
  • +
  •    Additional Remarks
  • +
  •    Remarks on the speed
  • +
  •    Convolution using separable kernels
  • +
  •    Convolution in the Fourier domain
  • @@ -308,45 +350,14 @@ MathJax.Hub.Config({

     

     

     

    -

    Final part

    +

    Setting it up

    - - -
    -
    -
    -
    -
    -
    CNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
    -        
    -for i, eta in enumerate(eta_vals):
    -    for j, lmbd in enumerate(lmbd_vals):
    -        CNN = create_convolutional_neural_network_keras(input_shape, receptive_field,
    -                                              n_filters, n_neurons_connected, n_categories,
    -                                              eta, lmbd)
    -        CNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0)
    -        scores = CNN.evaluate(X_test, Y_test)
    -        
    -        CNN_keras[i][j] = CNN
    -        
    -        print("Learning rate = ", eta)
    -        print("Lambda = ", lmbd)
    -        print("Test accuracy: %.3f" % scores[1])
    -        print()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    +

    It means that to represent the entire +dataset of images, we require a 4D matrix or tensor. This tensor has the dimensions: +

    +$$ +(n_{inputs},\, n_{pixels, width},\, n_{pixels, height},\, depth) . +$$

    @@ -365,6 +376,16 @@ MathJax.Hub.Config({

  • 45
  • 46
  • 47
  • +
  • 48
  • +
  • 49
  • +
  • 50
  • +
  • 51
  • +
  • 52
  • +
  • 53
  • +
  • 54
  • +
  • 55
  • +
  • ...
  • +
  • 62
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs046.html b/doc/pub/week44/html/._week44-bs046.html index 1b6c525cd..1efc4cf20 100644 --- a/doc/pub/week44/html/._week44-bs046.html +++ b/doc/pub/week44/html/._week44-bs046.html @@ -75,6 +75,12 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d None, 'a-deep-cnn-model-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Key Idea', 2, None, 'key-idea'), + ('How to do image compression before the era of deep learning', + 2, + None, + 'how-to-do-image-compression-before-the-era-of-deep-learning'), + ('The SVD example', 2, None, 'the-svd-example'), + ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Convolution Examples: Polynomial multiplication', 2, @@ -89,6 +95,8 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'a-more-efficient-way-of-coding-the-above-convolution'), + ('Commutative process', 2, None, 'commutative-process'), + ('Toeplitz matrices', 2, None, 'toeplitz-matrices'), ('Fourier series and Toeplitz matrices', 2, None, @@ -97,36 +105,75 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'generalizing-the-above-one-dimensional-case'), - ('Two-dimensional Objects', 2, None, 'two-dimensional-objects'), - ('CNNs in more detail', 2, None, 'cnns-in-more-detail'), - ('Performing a discrete convolution with padding ("From Raschka ' - 'et al":"https://github.com/rasbt/machine-learning-book")', + ('Memory considerations', 2, None, 'memory-considerations'), + ('Padding', 2, None, 'padding'), + ('New vector', 2, None, 'new-vector'), + ('Rewriting as dot products', 2, None, - 'performing-a-discrete-convolution-with-padding-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Performing a general discrete convolution ("From Raschka et ' + 'rewriting-as-dot-products'), + ('Cross correlation', 2, None, 'cross-correlation'), + ('Two-dimensional objects', 2, None, 'two-dimensional-objects'), + ('CNNs in more detail, simple example', + 2, + None, + 'cnns-in-more-detail-simple-example'), + ('The convolution stage', 2, None, 'the-convolution-stage'), + ('Finding the number of parameters', + 2, + None, + 'finding-the-number-of-parameters'), + ('New image (or volume)', 2, None, 'new-image-or-volume'), + ('Parameters to train, common settings', + 2, + None, + 'parameters-to-train-common-settings'), + ('Examples of CNN setups', 2, None, 'examples-of-cnn-setups'), + ('Summarizing: Performing a general discrete convolution ("From ' + 'Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, - 'performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Set of filters', 2, None, 'set-of-filters'), + 'summarizing-performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Pooling', 2, None, 'pooling'), - ('No zero padding, unit strides', - 2, - None, - 'no-zero-padding-unit-strides'), - ('Zero padding, unit strides', - 2, - None, - 'zero-padding-unit-strides'), - ('Half (same) padding', 2, None, 'half-same-padding'), - ('Full padding', 2, None, 'full-padding'), ('Pooling arithmetic', 2, None, 'pooling-arithmetic'), ('Pooling types ("From Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, 'pooling-types-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), + ('Building convolutional neural networks in Tensorflow and Keras', + 2, + None, + 'building-convolutional-neural-networks-in-tensorflow-and-keras'), + ('Setting it up', 2, None, 'setting-it-up'), + ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), + ('Strong correlations', 2, None, 'strong-correlations'), + ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), + ('Systematic reduction', 2, None, 'systematic-reduction'), + ('Prerequisites: Collect and pre-process data', + 2, + None, + 'prerequisites-collect-and-pre-process-data'), + ('Importing Keras and Tensorflow', + 2, + None, + 'importing-keras-and-tensorflow'), + ('Running with Keras', 2, None, 'running-with-keras'), + ('Final part', 2, None, 'final-part'), + ('Final visualization', 2, None, 'final-visualization'), + ('The CIFAR01 data set', 2, None, 'the-cifar01-data-set'), + ('Verifying the data set', 2, None, 'verifying-the-data-set'), + ('Set up the model', 2, None, 'set-up-the-model'), + ('Add Dense layers on top', 2, None, 'add-dense-layers-on-top'), + ('Compile and train the model', + 2, + None, + 'compile-and-train-the-model'), + ('Finally, evaluate the model', + 2, + None, + 'finally-evaluate-the-model'), ('Building our own CNN code', 2, None, @@ -173,27 +220,7 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Convolution in the Fourier domain', 3, None, - 'convolution-in-the-fourier-domain'), - ('Building convolutional neural networks in Tensorflow and Keras', - 2, - None, - 'building-convolutional-neural-networks-in-tensorflow-and-keras'), - ('Setting it up', 2, None, 'setting-it-up'), - ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), - ('Strong correlations', 2, None, 'strong-correlations'), - ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), - ('Systematic reduction', 2, None, 'systematic-reduction'), - ('Prerequisites: Collect and pre-process data', - 2, - None, - 'prerequisites-collect-and-pre-process-data'), - ('Importing Keras and Tensorflow', - 2, - None, - 'importing-keras-and-tensorflow'), - ('Running with Keras', 2, None, 'running-with-keras'), - ('Final part', 2, None, 'final-part'), - ('Final visualization', 2, None, 'final-visualization')]} + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -244,59 +271,74 @@ MathJax.Hub.Config({
  • CNNs in brief
  • A deep CNN model ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • Key Idea
  • -
  • Mathematics of CNNs
  • -
  • Convolution Examples: Polynomial multiplication
  • -
  • Efficient Polynomial Multiplication
  • -
  • Further simplification
  • -
  • A more efficient way of coding the above Convolution
  • -
  • Fourier series and Toeplitz matrices
  • -
  • Generalizing the above one-dimensional case
  • -
  • Two-dimensional Objects
  • -
  • CNNs in more detail
  • -
  • Performing a discrete convolution with padding ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Set of filters
  • -
  • Pooling
  • -
  • No zero padding, unit strides
  • -
  • Zero padding, unit strides
  • -
  • Half (same) padding
  • -
  • Full padding
  • -
  • Pooling arithmetic
  • -
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Building our own CNN code
  • -
  •    List of contents:
  • -
  •    Schedulers
  • -
  •    Usage of schedulers
  • -
  •    Cost functions
  • -
  •    Usage of cost functions
  • -
  •    Activation functions
  • -
  •    Usage of activation functions
  • -
  •    Convolution
  • -
  •    Layers
  • -
  •    Convolution2DLayer: convolution in a hidden layer
  • -
  •    Backpropagation in the convolutional layer
  • -
  •    Demonstration
  • -
  •    Pooling Layer
  • -
  •    Flattening Layer
  • -
  •    Fully Connected Layers
  • -
  •    Optimized Convolution2DLayer
  • -
  •    The Convolutional Neural Network (CNN)
  • -
  •    Usage of CNN code
  • -
  •    Additional Remarks
  • -
  •    Remarks on the speed
  • -
  •    Convolution using separable kernels
  • -
  •    Convolution in the Fourier domain
  • -
  • Building convolutional neural networks in Tensorflow and Keras
  • -
  • Setting it up
  • -
  • The MNIST dataset again
  • -
  • Strong correlations
  • -
  • Layers of a CNN
  • -
  • Systematic reduction
  • -
  • Prerequisites: Collect and pre-process data
  • -
  • Importing Keras and Tensorflow
  • -
  • Running with Keras
  • -
  • Final part
  • -
  • Final visualization
  • +
  • How to do image compression before the era of deep learning
  • +
  • The SVD example
  • +
  • Mathematics of CNNs
  • +
  • Mathematics of CNNs
  • +
  • Convolution Examples: Polynomial multiplication
  • +
  • Efficient Polynomial Multiplication
  • +
  • Further simplification
  • +
  • A more efficient way of coding the above Convolution
  • +
  • Commutative process
  • +
  • Toeplitz matrices
  • +
  • Fourier series and Toeplitz matrices
  • +
  • Generalizing the above one-dimensional case
  • +
  • Memory considerations
  • +
  • Padding
  • +
  • New vector
  • +
  • Rewriting as dot products
  • +
  • Cross correlation
  • +
  • Two-dimensional objects
  • +
  • CNNs in more detail, simple example
  • +
  • The convolution stage
  • +
  • Finding the number of parameters
  • +
  • New image (or volume)
  • +
  • Parameters to train, common settings
  • +
  • Examples of CNN setups
  • +
  • Summarizing: Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Pooling
  • +
  • Pooling arithmetic
  • +
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Building convolutional neural networks in Tensorflow and Keras
  • +
  • Setting it up
  • +
  • The MNIST dataset again
  • +
  • Strong correlations
  • +
  • Layers of a CNN
  • +
  • Systematic reduction
  • +
  • Prerequisites: Collect and pre-process data
  • +
  • Importing Keras and Tensorflow
  • +
  • Running with Keras
  • +
  • Final part
  • +
  • Final visualization
  • +
  • The CIFAR01 data set
  • +
  • Verifying the data set
  • +
  • Set up the model
  • +
  • Add Dense layers on top
  • +
  • Compile and train the model
  • +
  • Finally, evaluate the model
  • +
  • Building our own CNN code
  • +
  •    List of contents:
  • +
  •    Schedulers
  • +
  •    Usage of schedulers
  • +
  •    Cost functions
  • +
  •    Usage of cost functions
  • +
  •    Activation functions
  • +
  •    Usage of activation functions
  • +
  •    Convolution
  • +
  •    Layers
  • +
  •    Convolution2DLayer: convolution in a hidden layer
  • +
  •    Backpropagation in the convolutional layer
  • +
  •    Demonstration
  • +
  •    Pooling Layer
  • +
  •    Flattening Layer
  • +
  •    Fully Connected Layers
  • +
  •    Optimized Convolution2DLayer
  • +
  •    The Convolutional Neural Network (CNN)
  • +
  •    Usage of CNN code
  • +
  •    Additional Remarks
  • +
  •    Remarks on the speed
  • +
  •    Convolution using separable kernels
  • +
  •    Convolution in the Fourier domain
  • @@ -308,59 +350,20 @@ MathJax.Hub.Config({

     

     

     

    -

    Final visualization

    +

    The MNIST dataset again

    +

    The MNIST dataset consists of grayscale images with a pixel size of +\( 28\times 28 \), meaning we require \( 28 \times 28 = 724 \) weights to each +neuron in the first hidden layer. +

    - -
    -
    -
    -
    -
    -
    # visual representation of grid search
    -# uses seaborn heatmap, could probably do this in matplotlib
    -import seaborn as sns
    -
    -sns.set()
    -
    -train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
    -test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
    -
    -for i in range(len(eta_vals)):
    -    for j in range(len(lmbd_vals)):
    -        CNN = CNN_keras[i][j]
    -
    -        train_accuracy[i][j] = CNN.evaluate(X_train, Y_train)[1]
    -        test_accuracy[i][j] = CNN.evaluate(X_test, Y_test)[1]
    -
    -        
    -fig, ax = plt.subplots(figsize = (10, 10))
    -sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
    -ax.set_title("Training Accuracy")
    -ax.set_ylabel("$\eta$")
    -ax.set_xlabel("$\lambda$")
    -plt.show()
    -
    -fig, ax = plt.subplots(figsize = (10, 10))
    -sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
    -ax.set_title("Test Accuracy")
    -ax.set_ylabel("$\eta$")
    -ax.set_xlabel("$\lambda$")
    -plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    +

    If we were to analyze images of size \( 128\times 128 \) we would require +\( 128 \times 128 = 16384 \) weights to each neuron. Even worse if we were +dealing with color images, as most images are, we have an image matrix +of size \( 128\times 128 \) for each color dimension (Red, Green, Blue), +meaning 3 times the number of weights \( = 49152 \) are required for every +single neuron in the first hidden layer. +

    @@ -378,6 +381,18 @@ plt.show()

  • 45
  • 46
  • 47
  • +
  • 48
  • +
  • 49
  • +
  • 50
  • +
  • 51
  • +
  • 52
  • +
  • 53
  • +
  • 54
  • +
  • 55
  • +
  • 56
  • +
  • ...
  • +
  • 62
  • +
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs047.html b/doc/pub/week44/html/._week44-bs047.html index 0f3fceb51..4efe23450 100644 --- a/doc/pub/week44/html/._week44-bs047.html +++ b/doc/pub/week44/html/._week44-bs047.html @@ -37,10 +37,14 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d
  • Plan for week 44
  • -
  • Material for Lecture Thursday November 2
  • -
  • Convolutional Neural Networks (recognizing images)
  • -
  • What is the Difference
  • -
  • Neural Networks vs CNNs
  • -
  • Why CNNS for images, sound files, medical images from CT scans etc?
  • -
  • Regular NNs don’t scale well to full images
  • -
  • 3D volumes of neurons
  • -
  • Layers used to build CNNs
  • -
  • Transforming images
  • -
  • CNNs in brief
  • -
  • Key Idea
  • -
  • Mathematics of CNNs
  • -
  • Convolution Examples: Polynomial multiplication
  • -
  • Efficient Polynomial Multiplication
  • -
  • A more efficient way of coding the above Convolution
  • -
  • Convolution Examples: Principle of Superposition and Periodic Forces (Fourier Transforms)
  • -
  • Simple Code Example
  • -
  • Wrapping up Fourier transforms
  • -
  • Finding the Coefficients
  • -
  • Final words on Fourier Transforms
  • -
  •    Fourier transforms and convolution
  • -
  • Two-dimensional Objects
  • -
  • More on Dimensionalities
  • -
  • Further Dimensionality Remarks
  • -
  • CNNs in more detail
  • -
  • Pooling
  • -
  • No zero padding, unit strides
  • -
  • Zero padding, unit strides
  • -
  • Half (same) padding
  • -
  • Full padding
  • -
  • Pooling arithmetic
  • -
  • CNNs in more detail, building convolutional neural networks in Tensorflow and Keras
  • -
  • Setting it up
  • -
  • The MNIST dataset again
  • -
  • Strong correlations
  • -
  • Layers of a CNN
  • -
  • Systematic reduction
  • -
  • Prerequisites: Collect and pre-process data
  • -
  • Importing Keras and Tensorflow
  • -
  • Running with Keras
  • -
  • Final part
  • -
  • Final visualization
  • -
  • The CIFAR01 data set
  • -
  • Verifying the data set
  • -
  • Set up the model
  • -
  • Add Dense layers on top
  • -
  • Compile and train the model
  • -
  • Finally, evaluate the model
  • -
  • Building our own CNN code
  • -
  •    List of contents:
  • -
  •    Schedulers
  • -
  •    Usage of schedulers
  • -
  •    Cost functions
  • -
  •    Usage of cost functions
  • -
  •    Activation functions
  • -
  •    Usage of activation functions
  • -
  •    Convolution
  • -
  •    Layers
  • -
  •    Convolution2DLayer: convolution in a hidden layer
  • -
  •    Backpropagation in the convolutional layer
  • -
  •    Demonstration
  • -
  •    Pooling Layer
  • -
  •    Flattening Layer
  • -
  •    Fully Connected Layers
  • -
  •    Optimized Convolution2DLayer
  • -
  •    The Convolutional Neural Network (CNN)
  • -
  •    Usage of CNN code
  • -
  •    Additional Remarks
  • -
  •    Remarks on the speed
  • -
  •    Convolution using separable kernels
  • -
  •    Convolution in the Fourier domain
  • +
  • Lab sessions on Tuesday and Wednesday
  • +
  • Material for Lecture Monday October 28
  • +
  • Convolutional Neural Networks (recognizing images)
  • +
  • What is the Difference
  • +
  • Neural Networks vs CNNs
  • +
  • Why CNNS for images, sound files, medical images from CT scans etc?
  • +
  • Regular NNs don’t scale well to full images
  • +
  • 3D volumes of neurons
  • +
  • More on Dimensionalities
  • +
  • Further remarks
  • +
  • Layers used to build CNNs
  • +
  • Transforming images
  • +
  • CNNs in brief
  • +
  • A deep CNN model ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Key Idea
  • +
  • How to do image compression before the era of deep learning
  • +
  • The SVD example
  • +
  • Mathematics of CNNs
  • +
  • Mathematics of CNNs
  • +
  • Convolution Examples: Polynomial multiplication
  • +
  • Efficient Polynomial Multiplication
  • +
  • Further simplification
  • +
  • A more efficient way of coding the above Convolution
  • +
  • Commutative process
  • +
  • Toeplitz matrices
  • +
  • Fourier series and Toeplitz matrices
  • +
  • Generalizing the above one-dimensional case
  • +
  • Memory considerations
  • +
  • Padding
  • +
  • New vector
  • +
  • Rewriting as dot products
  • +
  • Cross correlation
  • +
  • Two-dimensional objects
  • +
  • CNNs in more detail, simple example
  • +
  • The convolution stage
  • +
  • Finding the number of parameters
  • +
  • New image (or volume)
  • +
  • Parameters to train, common settings
  • +
  • Examples of CNN setups
  • +
  • Summarizing: Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Pooling
  • +
  • Pooling arithmetic
  • +
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Building convolutional neural networks in Tensorflow and Keras
  • +
  • Setting it up
  • +
  • The MNIST dataset again
  • +
  • Strong correlations
  • +
  • Layers of a CNN
  • +
  • Systematic reduction
  • +
  • Prerequisites: Collect and pre-process data
  • +
  • Importing Keras and Tensorflow
  • +
  • Running with Keras
  • +
  • Final part
  • +
  • Final visualization
  • +
  • The CIFAR01 data set
  • +
  • Verifying the data set
  • +
  • Set up the model
  • +
  • Add Dense layers on top
  • +
  • Compile and train the model
  • +
  • Finally, evaluate the model
  • +
  • Building our own CNN code
  • +
  •    List of contents:
  • +
  •    Schedulers
  • +
  •    Usage of schedulers
  • +
  •    Cost functions
  • +
  •    Usage of cost functions
  • +
  •    Activation functions
  • +
  •    Usage of activation functions
  • +
  •    Convolution
  • +
  •    Layers
  • +
  •    Convolution2DLayer: convolution in a hidden layer
  • +
  •    Backpropagation in the convolutional layer
  • +
  •    Demonstration
  • +
  •    Pooling Layer
  • +
  •    Flattening Layer
  • +
  •    Fully Connected Layers
  • +
  •    Optimized Convolution2DLayer
  • +
  •    The Convolutional Neural Network (CNN)
  • +
  •    Usage of CNN code
  • +
  •    Additional Remarks
  • +
  •    Remarks on the speed
  • +
  •    Convolution using separable kernels
  • +
  •    Convolution in the Fourier domain
  • @@ -312,39 +350,20 @@ MathJax.Hub.Config({

     

     

     

    -

    Finally, evaluate the model

    +

    Strong correlations

    +

    Images typically have strong local correlations, meaning that a small +part of the image varies little from its neighboring regions. If for +example we have an image of a blue car, we can roughly assume that a +small blue part of the image is surrounded by other blue regions. +

    - -
    -
    -
    -
    -
    -
    plt.plot(history.history['accuracy'], label='accuracy')
    -plt.plot(history.history['val_accuracy'], label = 'val_accuracy')
    -plt.xlabel('Epoch')
    -plt.ylabel('Accuracy')
    -plt.ylim([0.5, 1])
    -plt.legend(loc='lower right')
    -
    -test_loss, test_acc = model.evaluate(test_images,  test_labels, verbose=2)
    -
    -print(test_acc)
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    +

    Therefore, instead of connecting every single pixel to a neuron in the +first hidden layer, as we have previously done with deep neural +networks, we can instead connect each neuron to a small part of the +image (in all 3 RGB depth dimensions). The size of each small area is +fixed, and known as a receptive. +

    @@ -363,6 +382,16 @@ test_loss, test_acc = model47

  • 48
  • 49
  • +
  • 50
  • +
  • 51
  • +
  • 52
  • +
  • 53
  • +
  • 54
  • +
  • 55
  • +
  • 56
  • +
  • 57
  • +
  • ...
  • +
  • 62
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs048.html b/doc/pub/week44/html/._week44-bs048.html index db4de1f2c..17bc78175 100644 --- a/doc/pub/week44/html/._week44-bs048.html +++ b/doc/pub/week44/html/._week44-bs048.html @@ -37,10 +37,14 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d
  • Plan for week 44
  • -
  • Material for Lecture Thursday November 2
  • -
  • Convolutional Neural Networks (recognizing images)
  • -
  • What is the Difference
  • -
  • Neural Networks vs CNNs
  • -
  • Why CNNS for images, sound files, medical images from CT scans etc?
  • -
  • Regular NNs don’t scale well to full images
  • -
  • 3D volumes of neurons
  • -
  • Layers used to build CNNs
  • -
  • Transforming images
  • -
  • CNNs in brief
  • -
  • Key Idea
  • -
  • Mathematics of CNNs
  • -
  • Convolution Examples: Polynomial multiplication
  • -
  • Efficient Polynomial Multiplication
  • -
  • A more efficient way of coding the above Convolution
  • -
  • Convolution Examples: Principle of Superposition and Periodic Forces (Fourier Transforms)
  • -
  • Simple Code Example
  • -
  • Wrapping up Fourier transforms
  • -
  • Finding the Coefficients
  • -
  • Final words on Fourier Transforms
  • -
  •    Fourier transforms and convolution
  • -
  • Two-dimensional Objects
  • -
  • More on Dimensionalities
  • -
  • Further Dimensionality Remarks
  • -
  • CNNs in more detail
  • -
  • Pooling
  • -
  • No zero padding, unit strides
  • -
  • Zero padding, unit strides
  • -
  • Half (same) padding
  • -
  • Full padding
  • -
  • Pooling arithmetic
  • -
  • CNNs in more detail, building convolutional neural networks in Tensorflow and Keras
  • -
  • Setting it up
  • -
  • The MNIST dataset again
  • -
  • Strong correlations
  • -
  • Layers of a CNN
  • -
  • Systematic reduction
  • -
  • Prerequisites: Collect and pre-process data
  • -
  • Importing Keras and Tensorflow
  • -
  • Running with Keras
  • -
  • Final part
  • -
  • Final visualization
  • -
  • The CIFAR01 data set
  • -
  • Verifying the data set
  • -
  • Set up the model
  • -
  • Add Dense layers on top
  • -
  • Compile and train the model
  • -
  • Finally, evaluate the model
  • -
  • Building our own CNN code
  • -
  •    List of contents:
  • -
  •    Schedulers
  • -
  •    Usage of schedulers
  • -
  •    Cost functions
  • -
  •    Usage of cost functions
  • -
  •    Activation functions
  • -
  •    Usage of activation functions
  • -
  •    Convolution
  • -
  •    Layers
  • -
  •    Convolution2DLayer: convolution in a hidden layer
  • -
  •    Backpropagation in the convolutional layer
  • -
  •    Demonstration
  • -
  •    Pooling Layer
  • -
  •    Flattening Layer
  • -
  •    Fully Connected Layers
  • -
  •    Optimized Convolution2DLayer
  • -
  •    The Convolutional Neural Network (CNN)
  • -
  •    Usage of CNN code
  • -
  •    Additional Remarks
  • -
  •    Remarks on the speed
  • -
  •    Convolution using separable kernels
  • -
  •    Convolution in the Fourier domain
  • +
  • Lab sessions on Tuesday and Wednesday
  • +
  • Material for Lecture Monday October 28
  • +
  • Convolutional Neural Networks (recognizing images)
  • +
  • What is the Difference
  • +
  • Neural Networks vs CNNs
  • +
  • Why CNNS for images, sound files, medical images from CT scans etc?
  • +
  • Regular NNs don’t scale well to full images
  • +
  • 3D volumes of neurons
  • +
  • More on Dimensionalities
  • +
  • Further remarks
  • +
  • Layers used to build CNNs
  • +
  • Transforming images
  • +
  • CNNs in brief
  • +
  • A deep CNN model ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Key Idea
  • +
  • How to do image compression before the era of deep learning
  • +
  • The SVD example
  • +
  • Mathematics of CNNs
  • +
  • Mathematics of CNNs
  • +
  • Convolution Examples: Polynomial multiplication
  • +
  • Efficient Polynomial Multiplication
  • +
  • Further simplification
  • +
  • A more efficient way of coding the above Convolution
  • +
  • Commutative process
  • +
  • Toeplitz matrices
  • +
  • Fourier series and Toeplitz matrices
  • +
  • Generalizing the above one-dimensional case
  • +
  • Memory considerations
  • +
  • Padding
  • +
  • New vector
  • +
  • Rewriting as dot products
  • +
  • Cross correlation
  • +
  • Two-dimensional objects
  • +
  • CNNs in more detail, simple example
  • +
  • The convolution stage
  • +
  • Finding the number of parameters
  • +
  • New image (or volume)
  • +
  • Parameters to train, common settings
  • +
  • Examples of CNN setups
  • +
  • Summarizing: Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Pooling
  • +
  • Pooling arithmetic
  • +
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Building convolutional neural networks in Tensorflow and Keras
  • +
  • Setting it up
  • +
  • The MNIST dataset again
  • +
  • Strong correlations
  • +
  • Layers of a CNN
  • +
  • Systematic reduction
  • +
  • Prerequisites: Collect and pre-process data
  • +
  • Importing Keras and Tensorflow
  • +
  • Running with Keras
  • +
  • Final part
  • +
  • Final visualization
  • +
  • The CIFAR01 data set
  • +
  • Verifying the data set
  • +
  • Set up the model
  • +
  • Add Dense layers on top
  • +
  • Compile and train the model
  • +
  • Finally, evaluate the model
  • +
  • Building our own CNN code
  • +
  •    List of contents:
  • +
  •    Schedulers
  • +
  •    Usage of schedulers
  • +
  •    Cost functions
  • +
  •    Usage of cost functions
  • +
  •    Activation functions
  • +
  •    Usage of activation functions
  • +
  •    Convolution
  • +
  •    Layers
  • +
  •    Convolution2DLayer: convolution in a hidden layer
  • +
  •    Backpropagation in the convolutional layer
  • +
  •    Demonstration
  • +
  •    Pooling Layer
  • +
  •    Flattening Layer
  • +
  •    Fully Connected Layers
  • +
  •    Optimized Convolution2DLayer
  • +
  •    The Convolutional Neural Network (CNN)
  • +
  •    Usage of CNN code
  • +
  •    Additional Remarks
  • +
  •    Remarks on the speed
  • +
  •    Convolution using separable kernels
  • +
  •    Convolution in the Fourier domain
  • @@ -311,3260 +349,26 @@ MathJax.Hub.Config({

     

     

     

    - -

    Building our own CNN code

    + +

    Layers of a CNN

    -

    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 layers of a convolutional neural network arrange neurons in 3D: width, height and depth. +The input image is typically a square matrix of depth 3.

    -

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

    A convolution is performed on the image which outputs +a 3D volume of neurons. The weights to the input are arranged in a number of 2D matrices, known as filters.

    -

    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. +

    Each filter slides along the input image, taking the dot product +between each small part of the image and the filter, in all depth +dimensions. This is then passed through a non-linear function, +typically the Rectified Linear (ReLu) function, which serves as the +activation of the neurons in the first convolutional layer. This is +further passed through a pooling layer, which reduces the size of the +convolutional layer, e.g. by taking the maximum or average across some +small regions, and this serves as input to the next convolutional +layer.

    @@ -3582,6 +386,18 @@ optimization technique.

  • 47
  • 48
  • 49
  • +
  • 50
  • +
  • 51
  • +
  • 52
  • +
  • 53
  • +
  • 54
  • +
  • 55
  • +
  • 56
  • +
  • 57
  • +
  • 58
  • +
  • ...
  • +
  • 62
  • +
  • »
  • diff --git a/doc/pub/week44/html/._week44-bs049.html b/doc/pub/week44/html/._week44-bs049.html index 243d34579..c667b312d 100644 --- a/doc/pub/week44/html/._week44-bs049.html +++ b/doc/pub/week44/html/._week44-bs049.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,191 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d @@ -248,78 +248,97 @@ MathJax.Hub.Config({ - Week 44: Decision Trees, Ensemble methods and Random Forests + Week 44, Convolutional Neural Networks (CNN)
    diff --git a/doc/pub/week44/html/week44-bs.html b/doc/pub/week44/html/week44-bs.html index c696978c2..e73a75127 100644 --- a/doc/pub/week44/html/week44-bs.html +++ b/doc/pub/week44/html/week44-bs.html @@ -75,6 +75,12 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d None, 'a-deep-cnn-model-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Key Idea', 2, None, 'key-idea'), + ('How to do image compression before the era of deep learning', + 2, + None, + 'how-to-do-image-compression-before-the-era-of-deep-learning'), + ('The SVD example', 2, None, 'the-svd-example'), + ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Convolution Examples: Polynomial multiplication', 2, @@ -89,6 +95,8 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'a-more-efficient-way-of-coding-the-above-convolution'), + ('Commutative process', 2, None, 'commutative-process'), + ('Toeplitz matrices', 2, None, 'toeplitz-matrices'), ('Fourier series and Toeplitz matrices', 2, None, @@ -97,36 +105,75 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d 2, None, 'generalizing-the-above-one-dimensional-case'), - ('Two-dimensional Objects', 2, None, 'two-dimensional-objects'), - ('CNNs in more detail', 2, None, 'cnns-in-more-detail'), - ('Performing a discrete convolution with padding ("From Raschka ' - 'et al":"https://github.com/rasbt/machine-learning-book")', + ('Memory considerations', 2, None, 'memory-considerations'), + ('Padding', 2, None, 'padding'), + ('New vector', 2, None, 'new-vector'), + ('Rewriting as dot products', 2, None, - 'performing-a-discrete-convolution-with-padding-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Performing a general discrete convolution ("From Raschka et ' + 'rewriting-as-dot-products'), + ('Cross correlation', 2, None, 'cross-correlation'), + ('Two-dimensional objects', 2, None, 'two-dimensional-objects'), + ('CNNs in more detail, simple example', + 2, + None, + 'cnns-in-more-detail-simple-example'), + ('The convolution stage', 2, None, 'the-convolution-stage'), + ('Finding the number of parameters', + 2, + None, + 'finding-the-number-of-parameters'), + ('New image (or volume)', 2, None, 'new-image-or-volume'), + ('Parameters to train, common settings', + 2, + None, + 'parameters-to-train-common-settings'), + ('Examples of CNN setups', 2, None, 'examples-of-cnn-setups'), + ('Summarizing: Performing a general discrete convolution ("From ' + 'Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, - 'performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Set of filters', 2, None, 'set-of-filters'), + 'summarizing-performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Pooling', 2, None, 'pooling'), - ('No zero padding, unit strides', - 2, - None, - 'no-zero-padding-unit-strides'), - ('Zero padding, unit strides', - 2, - None, - 'zero-padding-unit-strides'), - ('Half (same) padding', 2, None, 'half-same-padding'), - ('Full padding', 2, None, 'full-padding'), ('Pooling arithmetic', 2, None, 'pooling-arithmetic'), ('Pooling types ("From Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, 'pooling-types-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), + ('Building convolutional neural networks in Tensorflow and Keras', + 2, + None, + 'building-convolutional-neural-networks-in-tensorflow-and-keras'), + ('Setting it up', 2, None, 'setting-it-up'), + ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), + ('Strong correlations', 2, None, 'strong-correlations'), + ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), + ('Systematic reduction', 2, None, 'systematic-reduction'), + ('Prerequisites: Collect and pre-process data', + 2, + None, + 'prerequisites-collect-and-pre-process-data'), + ('Importing Keras and Tensorflow', + 2, + None, + 'importing-keras-and-tensorflow'), + ('Running with Keras', 2, None, 'running-with-keras'), + ('Final part', 2, None, 'final-part'), + ('Final visualization', 2, None, 'final-visualization'), + ('The CIFAR01 data set', 2, None, 'the-cifar01-data-set'), + ('Verifying the data set', 2, None, 'verifying-the-data-set'), + ('Set up the model', 2, None, 'set-up-the-model'), + ('Add Dense layers on top', 2, None, 'add-dense-layers-on-top'), + ('Compile and train the model', + 2, + None, + 'compile-and-train-the-model'), + ('Finally, evaluate the model', + 2, + None, + 'finally-evaluate-the-model'), ('Building our own CNN code', 2, None, @@ -173,27 +220,7 @@ doconce format html week44.do.txt --html_style=bootstrap --pygments_html_style=d ('Convolution in the Fourier domain', 3, None, - 'convolution-in-the-fourier-domain'), - ('Building convolutional neural networks in Tensorflow and Keras', - 2, - None, - 'building-convolutional-neural-networks-in-tensorflow-and-keras'), - ('Setting it up', 2, None, 'setting-it-up'), - ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), - ('Strong correlations', 2, None, 'strong-correlations'), - ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), - ('Systematic reduction', 2, None, 'systematic-reduction'), - ('Prerequisites: Collect and pre-process data', - 2, - None, - 'prerequisites-collect-and-pre-process-data'), - ('Importing Keras and Tensorflow', - 2, - None, - 'importing-keras-and-tensorflow'), - ('Running with Keras', 2, None, 'running-with-keras'), - ('Final part', 2, None, 'final-part'), - ('Final visualization', 2, None, 'final-visualization')]} + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -244,59 +271,74 @@ MathJax.Hub.Config({
  • CNNs in brief
  • A deep CNN model ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • Key Idea
  • -
  • Mathematics of CNNs
  • -
  • Convolution Examples: Polynomial multiplication
  • -
  • Efficient Polynomial Multiplication
  • -
  • Further simplification
  • -
  • A more efficient way of coding the above Convolution
  • -
  • Fourier series and Toeplitz matrices
  • -
  • Generalizing the above one-dimensional case
  • -
  • Two-dimensional Objects
  • -
  • CNNs in more detail
  • -
  • Performing a discrete convolution with padding ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Set of filters
  • -
  • Pooling
  • -
  • No zero padding, unit strides
  • -
  • Zero padding, unit strides
  • -
  • Half (same) padding
  • -
  • Full padding
  • -
  • Pooling arithmetic
  • -
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • -
  • Building our own CNN code
  • -
  •    List of contents:
  • -
  •    Schedulers
  • -
  •    Usage of schedulers
  • -
  •    Cost functions
  • -
  •    Usage of cost functions
  • -
  •    Activation functions
  • -
  •    Usage of activation functions
  • -
  •    Convolution
  • -
  •    Layers
  • -
  •    Convolution2DLayer: convolution in a hidden layer
  • -
  •    Backpropagation in the convolutional layer
  • -
  •    Demonstration
  • -
  •    Pooling Layer
  • -
  •    Flattening Layer
  • -
  •    Fully Connected Layers
  • -
  •    Optimized Convolution2DLayer
  • -
  •    The Convolutional Neural Network (CNN)
  • -
  •    Usage of CNN code
  • -
  •    Additional Remarks
  • -
  •    Remarks on the speed
  • -
  •    Convolution using separable kernels
  • -
  •    Convolution in the Fourier domain
  • -
  • Building convolutional neural networks in Tensorflow and Keras
  • -
  • Setting it up
  • -
  • The MNIST dataset again
  • -
  • Strong correlations
  • -
  • Layers of a CNN
  • -
  • Systematic reduction
  • -
  • Prerequisites: Collect and pre-process data
  • -
  • Importing Keras and Tensorflow
  • -
  • Running with Keras
  • -
  • Final part
  • -
  • Final visualization
  • +
  • How to do image compression before the era of deep learning
  • +
  • The SVD example
  • +
  • Mathematics of CNNs
  • +
  • Mathematics of CNNs
  • +
  • Convolution Examples: Polynomial multiplication
  • +
  • Efficient Polynomial Multiplication
  • +
  • Further simplification
  • +
  • A more efficient way of coding the above Convolution
  • +
  • Commutative process
  • +
  • Toeplitz matrices
  • +
  • Fourier series and Toeplitz matrices
  • +
  • Generalizing the above one-dimensional case
  • +
  • Memory considerations
  • +
  • Padding
  • +
  • New vector
  • +
  • Rewriting as dot products
  • +
  • Cross correlation
  • +
  • Two-dimensional objects
  • +
  • CNNs in more detail, simple example
  • +
  • The convolution stage
  • +
  • Finding the number of parameters
  • +
  • New image (or volume)
  • +
  • Parameters to train, common settings
  • +
  • Examples of CNN setups
  • +
  • Summarizing: Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Pooling
  • +
  • Pooling arithmetic
  • +
  • Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book")
  • +
  • Building convolutional neural networks in Tensorflow and Keras
  • +
  • Setting it up
  • +
  • The MNIST dataset again
  • +
  • Strong correlations
  • +
  • Layers of a CNN
  • +
  • Systematic reduction
  • +
  • Prerequisites: Collect and pre-process data
  • +
  • Importing Keras and Tensorflow
  • +
  • Running with Keras
  • +
  • Final part
  • +
  • Final visualization
  • +
  • The CIFAR01 data set
  • +
  • Verifying the data set
  • +
  • Set up the model
  • +
  • Add Dense layers on top
  • +
  • Compile and train the model
  • +
  • Finally, evaluate the model
  • +
  • Building our own CNN code
  • +
  •    List of contents:
  • +
  •    Schedulers
  • +
  •    Usage of schedulers
  • +
  •    Cost functions
  • +
  •    Usage of cost functions
  • +
  •    Activation functions
  • +
  •    Usage of activation functions
  • +
  •    Convolution
  • +
  •    Layers
  • +
  •    Convolution2DLayer: convolution in a hidden layer
  • +
  •    Backpropagation in the convolutional layer
  • +
  •    Demonstration
  • +
  •    Pooling Layer
  • +
  •    Flattening Layer
  • +
  •    Fully Connected Layers
  • +
  •    Optimized Convolution2DLayer
  • +
  •    The Convolutional Neural Network (CNN)
  • +
  •    Usage of CNN code
  • +
  •    Additional Remarks
  • +
  •    Remarks on the speed
  • +
  •    Convolution using separable kernels
  • +
  •    Convolution in the Fourier domain
  • @@ -351,7 +393,7 @@ MathJax.Hub.Config({
  • 9
  • 10
  • ...
  • -
  • 47
  • +
  • 62
  • »
  • diff --git a/doc/pub/week44/html/week44-reveal.html b/doc/pub/week44/html/week44-reveal.html index 8f9fadb28..6f2942bdf 100644 --- a/doc/pub/week44/html/week44-reveal.html +++ b/doc/pub/week44/html/week44-reveal.html @@ -506,6 +506,155 @@ only neighboring neurons in the input instead of connecting all with the first h

    We say we perform a filtering (convolution is the mathematical operation).

    +
    +

    How to do image compression before the era of deep learning

    + +

    The singular-value decomposition (SVD) algorithm has been for decades one of the standard ways of compressing images. +The lectures on the SVD give many of the essential details concerning the SVD. +

    + +

    The orthogonal vectors which are obtained from the SVD, can be used to +project down the dimensionality of a given image. In the example here +we gray-scale an image and downsize it. +

    + +

    This recipe relies on us being able to actually perform the SVD. For +large images, and in particular with many images to reconstruct, using the SVD +may quickly become an overwhelming task. With the advent of efficient deep +learning methods like CNNs and later generative methods, these methods +have become in the last years the premier way of performing image +analysis. In particular for classification problems with labelled images. +

    +
    + +
    +

    The SVD example

    + + + +
    +
    +
    +
    +
    +
    from matplotlib.image import imread
    +import matplotlib.pyplot as plt
    +import scipy.linalg as ln
    +import numpy as np
    +import os
    +from PIL import Image
    +from math import log10, sqrt 
    +plt.rcParams['figure.figsize'] = [16, 8]
    +# Import image
    +A = imread(os.path.join("figslides/photo1.jpg"))
    +X = A.dot([0.299, 0.5870, 0.114]) # Convert RGB to grayscale
    +img = plt.imshow(X)
    +# convert to gray
    +img.set_cmap('gray')
    +plt.axis('off')
    +plt.show()
    +# Call image size
    +print(': %s'%str(X.shape))
    +
    +
    +# split the matrix into U, S, VT
    +U, S, VT = np.linalg.svd(X,full_matrices=False)
    +S = np.diag(S)
    +m = 800 # Image's width
    +n = 1200 # Image's height
    +j = 0
    +# Try compression with different k vectors (these represent projections):
    +for k in (5,10, 20, 100,200,400,500):
    +    # Original size of the image
    +    originalSize = m * n 
    +    # Size after compressed
    +    compressedSize = k * (1 + m + n) 
    +    # The projection of the original image
    +    Xapprox = U[:,:k] @ S[0:k,:k] @ VT[:k,:]
    +    plt.figure(j+1)
    +    j += 1
    +    img = plt.imshow(Xapprox)
    +    img.set_cmap('gray')
    +    
    +    plt.axis('off')
    +    plt.title('k = ' + str(k))
    +    plt.show() 
    +    print('Original size of image:')
    +    print(originalSize)
    +    print('Compression rate as Compressed image / Original size:')
    +    ratio = compressedSize * 1.0 / originalSize
    +    print(ratio)
    +    print('Compression rate is ' + str( round(ratio * 100 ,2)) + '%' )  
    +    # Estimate MQA
    +    x= X.astype("float")
    +    y=Xapprox.astype("float")
    +    err = np.sum((x - y) ** 2)
    +    err /= float(X.shape[0] * Xapprox.shape[1])
    +    print('The mean-square deviation '+ str(round( err)))
    +    max_pixel = 255.0
    +    # Estimate Signal Noise Ratio
    +    srv = 20 * (log10(max_pixel / sqrt(err)))
    +    print('Signa to noise ratio '+ str(round(srv)) +'dB')
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +

    Mathematics of CNNs

    + +

    The mathematics of CNNs is based on the mathematical operation of +convolution. In mathematics (in particular in functional analysis), +convolution is represented by mathematical operations (integration, +summation etc) on two functions in order to produce a third function +that expresses how the shape of one gets modified by the other. +Convolution has a plethora of applications in a variety of +disciplines, spanning from statistics to signal processing, computer +vision, solutions of differential equations,linear algebra, +engineering, and yes, machine learning. +

    + +

    Mathematically, convolution is defined as follows (one-dimensional example): +Let us define a continuous function \( y(t) \) given by +

    +

     
    +$$ +y(t) = \int x(a) w(t-a) da, +$$ +

     
    + +

    where \( x(a) \) represents a so-called input and \( w(t-a) \) is normally called the weight function or kernel.

    + +

    The above integral is written in a more compact form as

    +

     
    +$$ +y(t) = \left(x * w\right)(t). +$$ +

     
    + +

    The discretized version reads

    +

     
    +$$ +y(t) = \sum_{a=-\infty}^{a=\infty}x(a)w(t-a). +$$ +

     
    + +

    Computing the inverse of the above convolution operations is known as deconvolution and the process is commutative.

    + +

    How can we use this? And what does it mean? Let us study some familiar examples first.

    +
    +

    Mathematics of CNNs

    @@ -630,7 +779,9 @@ $$ $$

     
    -

    where \( m=3 \) in our case, the maximum length of the vector \( \alpha \). Note that the vector \( \boldsymbol{\beta} \) has length \( n=4 \).

    +

    where \( m=3 \) in our case, the maximum length of +the vector \( \alpha \). Note that the vector \( \boldsymbol{\beta} \) has length \( n=4 \). Below we will find an even more efficient representation. +

    @@ -652,6 +803,10 @@ $$ \end{bmatrix}\begin{bmatrix} \beta_0 \\ \beta_1 \\ \beta_2 \\ \beta_3\end{bmatrix}. $$

     
    +

    + +
    +

    Commutative process

    The process is commutative and we can easily see that we can rewrite the multiplication in terms of a matrix holding \( \beta \) and a vector holding \( \alpha \). In this case we have @@ -674,6 +829,10 @@ we do not encode (and allocate memory) the matrices explicitely. We rather code the convolutions in the minimal memory footprint that they require.

    +
    + +
    +

    Toeplitz matrices

    The above matrices are examples of so-called Toeplitz matrices. A @@ -716,20 +875,145 @@ a vector.

    Generalizing the above one-dimensional case

    -

    In order to align the above simple case with the more general convolution cases, we rename \( \boldsymbol{\alpha} \), whose length is \( m=3 \), with \( \boldsymbol{w} \). -We will interpret \( \boldsymbol{w} \) as a weight/filter function with which we want to perform the convolution with an input varibale \( \boldsymbol{x} \). -We replace thus \( \boldsymbol{\beta} \) with \( \boldsymbol{x} \) and \( \boldsymbol{\delta} \) with \( \boldsymbol{s} \) and have +

    In order to align the above simple case with the more general +convolution cases, we rename \( \boldsymbol{\alpha} \), whose length is \( m=3 \), +with \( \boldsymbol{w} \). We will interpret \( \boldsymbol{w} \) as a weight/filter function +with which we want to perform the convolution with an input variable +\( \boldsymbol{x} \) of length \( n \). We will assume always that the filter +\( \boldsymbol{w} \) has dimensionality \( m \le n \).

    + +

    We replace thus \( \boldsymbol{\beta} \) with \( \boldsymbol{x} \) and \( \boldsymbol{\delta} \) with \( \boldsymbol{y} \) and have

     
    $$ -s(i) \left(x*w\right)(i)= \sum_{k=0}^{k=m-1}w(k)x(i-k), +y(i)= \left(x*w\right)(i)= \sum_{k=0}^{k=m-1}w(k)x(i-k), $$

     

    where \( m=3 \) in our case, the maximum length of the vector \( \boldsymbol{w} \). Here the symbol \( * \) represents the mathematical operation of convolution.

    -

    Two-dimensional Objects

    +
    + +
    +

    Memory considerations

    + +

    This expression leaves us however with some terms with negative +indices, for example \( x(-1) \) and \( x(-2) \) which may not be defined. Our +vector \( \boldsymbol{x} \) has components \( x(0) \), \( x(1) \), \( x(2) \) and \( x(3) \). +

    + +

    The index \( j \) for \( \boldsymbol{x} \) runs from \( j=0 \) to \( j=3 \) since \( \boldsymbol{x} \) is meant to +represent a third-order polynomial. +

    + +

    Furthermore, the index \( i \) runs from \( i=0 \) to \( i=5 \) since \( \boldsymbol{y} \) +contains the coefficients of a fifth-order polynomial. When \( i=5 \) we +may also have values of \( x(4) \) and \( x(5) \) which are not defined. +

    +
    + +
    +

    Padding

    + +

    The solution to this is what is called padding! We simply define a +new vector \( x \) with two added elements set to zero before \( x(0) \) and +two new elements after \( x(3) \) set to zero. That is, we augment the +length of \( \boldsymbol{x} \) from \( n=4 \) to \( n+2P=8 \), where \( P=2 \) is the padding +constant (a new hyperparameter), see discussions below as well. +

    +
    + +
    +

    New vector

    + +

    We have a new vector defined as \( x(0)=0 \), \( x(1)=0 \), +\( x(2)=\beta_0 \), \( x(3)=\beta_1 \), \( x(4)=\beta_2 \), \( x(5)=\beta_3 \), +\( x(6)=0 \), and \( x(7)=0 \). +

    + +

    We have added four new elements, which +are all zero. The benefit is that we can rewrite the equation for +\( \boldsymbol{y} \), with \( i=0,1,\dots,5 \), +

    +

     
    +$$ +y(i) = \sum_{k=0}^{k=m-1}w(k)x(i+(m-1)-k). +$$ +

     
    + +

    As an example, we have

    +

     
    +$$ +y(4)=x(6)w(0)+x(5)w(1)+x(4)w(2)=0\times \alpha_0+\beta_3\alpha_1+\beta_2\alpha_2, +$$ +

     
    + +

    as before except that we have an additional term \( x(6)w(0) \), which is zero.

    + +

    Similarly, for the fifth-order term we have

    +

     
    +$$ +y(5)=x(7)w(0)+x(6)w(1)+x(5)w(2)=0\times \alpha_0+0\times\alpha_1+\beta_3\alpha_2. +$$ +

     
    + +

    The zeroth-order term is

    +

     
    +$$ +y(0)=x(2)w(0)+x(1)w(1)+x(0)w(2)=\beta_0 \alpha_0+0\times\alpha_1+0\times\alpha_2=\alpha_0\beta_0. +$$ +

     
    +

    + +
    +

    Rewriting as dot products

    + +

    If we now flip the filter/weight vector, with the following term as a typical example

    +

     
    +$$ +y(0)=x(2)w(0)+x(1)w(1)+x(0)w(2)=x(2)\tilde{w}(2)+x(1)\tilde{w}(1)+x(0)\tilde{w}(0), +$$ +

     
    + +

    with \( \tilde{w}(0)=w(2) \), \( \tilde{w}(1)=w(1) \), and \( \tilde{w}(2)=w(0) \), we can then rewrite the above sum as a dot product of +\( x(i:i+(m-1))\tilde{w} \) for element \( y(i) \), where \( x(i:i+(m-1)) \) is simply a patch of \( \boldsymbol{x} \) of size \( m-1 \). +

    + +

    The padding \( P \) we have introduced for the convolution stage is just +another hyperparameter which is introduced as part of the +architecture. Similarly, below we will also introduce another +hyperparameter called Stride \( S \). +

    +
    + +
    +

    Cross correlation

    + +

    In essentially all applications one uses what is called cross correlation instead of the standard convolution described above. +This means that multiplication is performed in the same direction and instead of the general expression we have discussed above (with infinite sums) +

    +

     
    +$$ +y(i) = \sum_{k=-\infty}^{k=\infty}w(k)x(i-k), +$$ +

     
    + +

    we have now

    +

     
    +$$ +y(i) = \sum_{k=-\infty}^{k=\infty}w(k)x(i+k). +$$ +

     
    + +

    Both TensorFlow and PyTorch (as well as our own code example below), +implement the last equation, although it is normally referred to as +convolution. The same padding rules and stride rules discussed below +apply to this expression as well. +

    + +

    We leave it as an exercise for you to convince yourself that the example we have discussed till now, gives the same final expression using the last expression.

    +

    Two-dimensional objects

    We are now ready to start studying the discrete convolutions relevant for convolutional neural networks. We often use convolutions over more than one dimension at a time. If @@ -750,9 +1034,15 @@ Y(i,j)=(X * W)(i,j) = \sum_m\sum_n X(i-m,j-n)W(m,n). $$

     
    -

    Normally the latter is more straightforward to implement in a machine larning library since there is less variation in the range of values of \( m \) and \( n \).

    +

    Normally the latter is more straightforward to implement in a machine +larning library since there is less variation in the range of values +of \( m \) and \( n \). +

    -

    Many deep learning libraries implement cross-correlation instead of convolution (although it is referred to s convolution)

    +

    As mentioned above, most deep learning libraries implement +cross-correlation instead of convolution (although it is referred to as +convolution) +

     
    $$ Y(i,j)=(X * W)(i,j) = \sum_m\sum_n X(i+m,j+n)W(m,n). @@ -761,7 +1051,7 @@ $$

    -

    CNNs in more detail

    +

    CNNs in more detail, simple example

    Let assume we have an input matrix \( X \) of dimensionality \( 3\times 3 \) and a \( 2\times 2 \) filter \( W \) given by the following matrices @@ -836,59 +1126,111 @@ $$

    -

    Performing a discrete convolution with padding (From Raschka et al)

    +

    The convolution stage

    -
    -
    -
    -

    Figure 4: A deep CNN

    -
    -

    -
    +

    The convolution stage, where we apply different filters \( \boldsymbol{W} \) in +order to reduce the dimensionality of an image, adds, in addition to +the weights and biases (to be trained by the back propagation +algorithm) that define the filters, two new hyperparameters, the so-called +padding \( P \) and the stride \( S \). +

    -

    Performing a general discrete convolution (From Raschka et al)

    +

    Finding the number of parameters

    -
    -
    -
    -

    Figure 5: A deep CNN

    -
    -

    -
    -
    - -
    -

    Set of filters

    - -

    The collection of kernels/filters \( W \) defining a discrete convolution has a shape -corresponding to some permutation of \( (n, m, k_1, \ldots, k_N) \), where +

    In the above example we have an input matrix of dimension \( 3\times +3 \). In general we call the input for an input volume and it is defined +by its width \( H_1 \), height \( H_1 \) and depth \( D_1 \). If we have the +standard three color channels \( D_1=3 \).

    -$$ -\begin{equation*} -\begin{split} - n &\equiv \text{number of output feature maps},\\ - m &\equiv \text{number of input feature maps},\\ - k_j &\equiv \text{kernel size along axis $j$}. -\end{split} -\end{equation*} -$$ - -

    The following properties affect the output size \( o_j \) of a convolutional layer -along axis \( j \): -

    +

    The above example has \( W_1=H_1=3 \) and \( D_1=1 \).

    +

    When we introduce the filter we have the following additional hyperparameters

      -

    1. \( i_j \): input size along axis \( j \),
    2. -

    3. \( k_j \): kernel/filter size along axis \( j \),
    4. -

    5. stride (distance between two consecutive positions of the kernel/filter) along axis \( j \),
    6. -

    7. zero padding (number of zeros concatenated at the beginning and at the end of an axis) along axis \( j \).
    8. +

    9. \( K \) the number of filters. It is common to perform the convolution of the input several times since by experience shrinking the input too fast does not work well
    10. +

    11. \( F \) as the filter's spatial extent
    12. +

    13. \( S \) as the stride parameter
    14. +

    15. \( P \) as the padding parameter

    -

    For instance, the above examples shows a \( 2\times 2 \) kernel/filter \( \boldsymbol{W} \) applied to a \( 3 \times 3 \) input padded with a \( 0 \times 0 \) -border of zeros using \( 1 \times 1 \) strides. +

    These parameters are defined by the architecture of the network and are not included in the training.

    +
    + +
    +

    New image (or volume)

    + +

    Acting with the filter on the input volume produces an output volume +which is defined by its width \( W_2 \), its height \( H_2 \) and its depth +\( D_2 \). +

    + +

    These are defined by the following relations

    +

     
    +$$ +W_2 = \frac{(W_1-F+2P)}{S}+1, +$$ +

     
    + +

     
    +$$ +H_2 = \frac{(H_1-F+2P)}{S}+1, +$$ +

     
    + +

    and \( D_2=K \).

    +
    + +
    +

    Parameters to train, common settings

    + +

    With parameter sharing, the convolution involves thus for each filter \( F\times F\times D_1 \) weights plus one bias parameter.

    + +

    In total we have

    +

     
    +$$ +\left(F\times F\times D_1)\right) \times K+(K\mathrm{--biases}), +$$ +

     
    + +

    parameters to train by back propagation.

    + +

    It is common to let \( K \) come in powers of \( 2 \), that is \( 32 \), \( 64 \), \( 128 \) etc.

    + +
    +Common settings +

    +

      +

    1. \( \begin{array}{c} F=3 & S=1 & P=1 \end{array} \)
    2. +

    3. \( \begin{array}{c} F=5 & S=1 & P=2 \end{array} \)
    4. +

    5. \( \begin{array}{c} F=5 & S=2 & P=\mathrm{open} \end{array} \)
    6. +

    7. \( \begin{array}{c} F=1 & S=1 & P=0 \end{array} \)
    8. +
    +
    +
    + +
    +

    Examples of CNN setups

    + +

    Let us assume we have an input volume \( V \) given by an image of dimensionality +\( 32\times 32 \times 3 \), that is three color channels and \( 32\times 32 \) pixels. +

    + +

    We apply a filter of dimension \( 5\times 5 \) ten times with stride \( S=1 \) and padding \( P=0 \).

    + +

    The output volume is given by \( (32-5)/1+1=28 \), resulting in ten images +of dimensionality \( 28\times 28\times 3 \). +

    + +

    The total number of parameters to train for each filter is then +\( 5\times 5\times 3+1 \), where the last parameter is the bias. This +gives us \( 76 \) parameters for each filter, leading to a total of \( 760 \) +parameters for the ten filters. +

    + +

    How many parameters will a filter of dimensionality \( 3\times 3 \) +(adding color channels) result in if we produce \( 32 \) new images? Use \( S=1 \) and \( P=0 \).

    Note that strides constitute a form of subsampling. As an alternative to @@ -899,135 +1241,31 @@ retaining only odd output elements.

    +
    +

    Summarizing: Performing a general discrete convolution (From Raschka et al)

    + +
    +
    +
    +

    Figure 4: A deep CNN

    +
    +

    +
    +
    +

    Pooling

    -

    In addition to discrete convolutions themselves, {\em pooling\/} operations +

    In addition to discrete convolutions themselves, pooling operations make up another important building block in CNNs. Pooling operations reduce the size of feature maps by using some function to summarize subregions, such as taking the average or the maximum value.

    Pooling works by sliding a window across the input and feeding the content of -the window to a {\em pooling function}. In some sense, pooling works very much +the window to a pooling function. In some sense, pooling works very much like a discrete convolution, but replaces the linear combination described by -the kernel with some other function. Poolin -provides an example for average pooling, and -does the same for max pooling. -

    - -

    The following properties affect the output size \( o_j \) of a pooling layer -along axis \( j \): -

    - -
      -

    1. \( i_j \): input size along axis \( j \),
    2. -

    3. \( k_j \): pooling window size along axis \( j \),
    4. -

    5. \( s_j \): stride (distance between two consecutive positions of the pooling window) along axis \( j \).
    6. -
    -

    -

    The analysis of the relationship between convolutional layer properties is eased -by the fact that they don't interact across axes, i.e., the choice of kernel -size, stride and zero padding along axis \( j \) only affects the output size of -axis \( j \). Because of that, we will focus on the following simplified -setting: -

    - -
      -

    1. 2-D discrete convolutions (\( N = 2 \)),
    2. -

    3. square inputs (\( i_1 = i_2 = i \)),
    4. -

    5. square kernel size (\( k_1 = k_2 = k \)),
    6. -

    7. same strides along both axes (\( s_1 = s_2 = s \)),
    8. -

    9. same zero padding along both axes (\( p_1 = p_2 = p \)).
    10. -
    -

    -

    This facilitates the analysis and the visualization, but keep in mind that the -results outlined here also generalize to the N-D and non-square cases. -

    -
    - -
    -

    No zero padding, unit strides

    - -

    The simplest case to analyze is when the kernel just slides across every -position of the input (i.e., \( s = 1 \) and \( p = 0 \)). -

    - -

    For any \( i \) and \( k \), and for \( s = 1 \) and \( p = 0 \),

    -

     
    -$$ -\begin{equation*} - o = (i - k) + 1. -\end{equation*} -$$ -

     
    -

    - -
    -

    Zero padding, unit strides

    - -

    To factor in zero padding (i.e., only restricting to \( s = 1 \)), let's consider -its effect on the effective input size: padding with \( p \) zeros changes the -effective input size from \( i \) to \( i + 2p \). In the general case, we can infer the following -relationship -

    - -

    For any \( i \), \( k \) and \( p \), and for \( s = 1 \),

    -

     
    -$$ -\begin{equation*} - o = (i - k) + 2p + 1. -\end{equation*} -$$ -

     
    -

    - -
    -

    Half (same) padding

    - -

    Having the output size be the same as the input size (i.e., \( o = i \)) can be a -desirable property: -

    - -

    For any \( i \) and for \( k \) odd (\( k = 2n + 1, \quad n \in \mathbb{N} \)), \( s = 1 \) and -\( p = \lfloor k / 2 \rfloor = n \), -

    -

     
    -$$ -\begin{equation*} -\begin{split} - o &= i + 2 \lfloor k / 2 \rfloor - (k - 1) \\ - &= i + 2n - 2n \\ - &= i. -\end{split} -\end{equation*} -$$ -

     
    -

    - -
    -

    Full padding

    - -

    While convolving a kernel generally decreases the output size with -respect to the input size, sometimes the opposite is required. This can be -achieved with proper zero padding: -

    - -

    For any \( i \) and \( k \), and for \( p = k - 1 \) and \( s = 1 \),

    -

     
    -$$ -\begin{equation*} -\begin{split} - o &= i + 2(k - 1) - (k - 1) \\ - &= i + (k - 1). -\end{split} -\end{equation*} -$$ -

     
    - -

    This is sometimes referred to as full padding, because in this -setting every possible partial or complete superimposition of the kernel on the -input feature map is taken into account. +the kernel with some other function.

    @@ -1041,19 +1279,6 @@ outputting the maximum value of each patch. Other kinds of pooling exist, e.g., mean or average pooling, which all share the same idea of aggregating the input locally by applying a non-linearity to the content of some patches.

    - -

    Since pooling does not involve -zero padding, the relationship describing the general case is as follows: -

    - -

    For any \( i \), \( k \) and \( s \),

    -

     
    -$$ -\begin{equation*} - o = \left\lfloor \frac{i - k}{s} \right\rfloor + 1. -\end{equation*} -$$ -

     

    @@ -1062,12 +1287,609 @@ $$

    -

    Figure 6: A deep CNN

    +

    Figure 5: A deep CNN

    +
    +

    Building convolutional neural networks in Tensorflow and Keras

    + +

    As discussed above, CNNs are neural networks built from the assumption that the inputs +to the network are 2D images. This is important because the number of features or pixels in images +grows very fast with the image size, and an enormous number of weights and biases are needed in order to build an accurate network. +

    + +

    As before, we still have our input, a hidden layer and an output. What's novel about convolutional networks +are the convolutional and pooling layers stacked in pairs between the input and the hidden layer. +In addition, the data is no longer represented as a 2D feature matrix, instead each input is a number of 2D +matrices, typically 1 for each color dimension (Red, Green, Blue). +

    +
    + +
    +

    Setting it up

    + +

    It means that to represent the entire +dataset of images, we require a 4D matrix or tensor. This tensor has the dimensions: +

    +

     
    +$$ +(n_{inputs},\, n_{pixels, width},\, n_{pixels, height},\, depth) . +$$ +

     
    +

    + +
    +

    The MNIST dataset again

    + +

    The MNIST dataset consists of grayscale images with a pixel size of +\( 28\times 28 \), meaning we require \( 28 \times 28 = 724 \) weights to each +neuron in the first hidden layer. +

    + +

    If we were to analyze images of size \( 128\times 128 \) we would require +\( 128 \times 128 = 16384 \) weights to each neuron. Even worse if we were +dealing with color images, as most images are, we have an image matrix +of size \( 128\times 128 \) for each color dimension (Red, Green, Blue), +meaning 3 times the number of weights \( = 49152 \) are required for every +single neuron in the first hidden layer. +

    +
    + +
    +

    Strong correlations

    + +

    Images typically have strong local correlations, meaning that a small +part of the image varies little from its neighboring regions. If for +example we have an image of a blue car, we can roughly assume that a +small blue part of the image is surrounded by other blue regions. +

    + +

    Therefore, instead of connecting every single pixel to a neuron in the +first hidden layer, as we have previously done with deep neural +networks, we can instead connect each neuron to a small part of the +image (in all 3 RGB depth dimensions). The size of each small area is +fixed, and known as a receptive. +

    +
    + +
    +

    Layers of a CNN

    + +

    The layers of a convolutional neural network arrange neurons in 3D: width, height and depth. +The input image is typically a square matrix of depth 3. +

    + +

    A convolution is performed on the image which outputs +a 3D volume of neurons. The weights to the input are arranged in a number of 2D matrices, known as filters. +

    + +

    Each filter slides along the input image, taking the dot product +between each small part of the image and the filter, in all depth +dimensions. This is then passed through a non-linear function, +typically the Rectified Linear (ReLu) function, which serves as the +activation of the neurons in the first convolutional layer. This is +further passed through a pooling layer, which reduces the size of the +convolutional layer, e.g. by taking the maximum or average across some +small regions, and this serves as input to the next convolutional +layer. +

    +
    + +
    +

    Systematic reduction

    + +

    By systematically reducing the size of the input volume, through +convolution and pooling, the network should create representations of +small parts of the input, and then from them assemble representations +of larger areas. The final pooling layer is flattened to serve as +input to a hidden layer, such that each neuron in the final pooling +layer is connected to every single neuron in the hidden layer. This +then serves as input to the output layer, e.g. a softmax output for +classification. +

    +
    + +
    +

    Prerequisites: Collect and pre-process data

    + + +
    +
    +
    +
    +
    +
    # import necessary packages
    +import numpy as np
    +import matplotlib.pyplot as plt
    +from sklearn import datasets
    +
    +
    +# ensure the same random numbers appear every time
    +np.random.seed(0)
    +
    +# display images in notebook
    +%matplotlib inline
    +plt.rcParams['figure.figsize'] = (12,12)
    +
    +
    +# download MNIST dataset
    +digits = datasets.load_digits()
    +
    +# define inputs and labels
    +inputs = digits.images
    +labels = digits.target
    +
    +# RGB images have a depth of 3
    +# our images are grayscale so they should have a depth of 1
    +inputs = inputs[:,:,:,np.newaxis]
    +
    +print("inputs = (n_inputs, pixel_width, pixel_height, depth) = " + str(inputs.shape))
    +print("labels = (n_inputs) = " + str(labels.shape))
    +
    +
    +# choose some random images to display
    +n_inputs = len(inputs)
    +indices = np.arange(n_inputs)
    +random_indices = np.random.choice(indices, size=5)
    +
    +for i, image in enumerate(digits.images[random_indices]):
    +    plt.subplot(1, 5, i+1)
    +    plt.axis('off')
    +    plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
    +    plt.title("Label: %d" % digits.target[random_indices[i]])
    +plt.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +

    Importing Keras and Tensorflow

    + + +
    +
    +
    +
    +
    +
    from tensorflow.keras import datasets, layers, models
    +from tensorflow.keras.layers import Input
    +from tensorflow.keras.models import Sequential      #This allows appending layers to existing models
    +from tensorflow.keras.layers import Dense           #This allows defining the characteristics of a particular layer
    +from tensorflow.keras import optimizers             #This allows using whichever optimiser we want (sgd,adam,RMSprop)
    +from tensorflow.keras import regularizers           #This allows using whichever regularizer we want (l1,l2,l1_l2)
    +from tensorflow.keras.utils import to_categorical   #This allows using categorical cross entropy as the cost function
    +#from tensorflow.keras import Conv2D
    +#from tensorflow.keras import MaxPooling2D
    +#from tensorflow.keras import Flatten
    +
    +from sklearn.model_selection import train_test_split
    +
    +# representation of labels
    +labels = to_categorical(labels)
    +
    +# split into train and test data
    +# one-liner from scikit-learn library
    +train_size = 0.8
    +test_size = 1 - train_size
    +X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,
    +                                                    test_size=test_size)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +

    Running with Keras

    + + + +
    +
    +
    +
    +
    +
    def create_convolutional_neural_network_keras(input_shape, receptive_field,
    +                                              n_filters, n_neurons_connected, n_categories,
    +                                              eta, lmbd):
    +    model = Sequential()
    +    model.add(layers.Conv2D(n_filters, (receptive_field, receptive_field), input_shape=input_shape, padding='same',
    +              activation='relu', kernel_regularizer=regularizers.l2(lmbd)))
    +    model.add(layers.MaxPooling2D(pool_size=(2, 2)))
    +    model.add(layers.Flatten())
    +    model.add(layers.Dense(n_neurons_connected, activation='relu', kernel_regularizer=regularizers.l2(lmbd)))
    +    model.add(layers.Dense(n_categories, activation='softmax', kernel_regularizer=regularizers.l2(lmbd)))
    +    
    +    sgd = optimizers.SGD(lr=eta)
    +    model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])
    +    
    +    return model
    +
    +epochs = 100
    +batch_size = 100
    +input_shape = X_train.shape[1:4]
    +receptive_field = 3
    +n_filters = 10
    +n_neurons_connected = 50
    +n_categories = 10
    +
    +eta_vals = np.logspace(-5, 1, 7)
    +lmbd_vals = np.logspace(-5, 1, 7)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +

    Final part

    + + + +
    +
    +
    +
    +
    +
    CNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
    +        
    +for i, eta in enumerate(eta_vals):
    +    for j, lmbd in enumerate(lmbd_vals):
    +        CNN = create_convolutional_neural_network_keras(input_shape, receptive_field,
    +                                              n_filters, n_neurons_connected, n_categories,
    +                                              eta, lmbd)
    +        CNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0)
    +        scores = CNN.evaluate(X_test, Y_test)
    +        
    +        CNN_keras[i][j] = CNN
    +        
    +        print("Learning rate = ", eta)
    +        print("Lambda = ", lmbd)
    +        print("Test accuracy: %.3f" % scores[1])
    +        print()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +

    Final visualization

    + + + +
    +
    +
    +
    +
    +
    # visual representation of grid search
    +# uses seaborn heatmap, could probably do this in matplotlib
    +import seaborn as sns
    +
    +sns.set()
    +
    +train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
    +test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
    +
    +for i in range(len(eta_vals)):
    +    for j in range(len(lmbd_vals)):
    +        CNN = CNN_keras[i][j]
    +
    +        train_accuracy[i][j] = CNN.evaluate(X_train, Y_train)[1]
    +        test_accuracy[i][j] = CNN.evaluate(X_test, Y_test)[1]
    +
    +        
    +fig, ax = plt.subplots(figsize = (10, 10))
    +sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
    +ax.set_title("Training Accuracy")
    +ax.set_ylabel("$\eta$")
    +ax.set_xlabel("$\lambda$")
    +plt.show()
    +
    +fig, ax = plt.subplots(figsize = (10, 10))
    +sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
    +ax.set_title("Test Accuracy")
    +ax.set_ylabel("$\eta$")
    +ax.set_xlabel("$\lambda$")
    +plt.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +

    The CIFAR01 data set

    + +

    The CIFAR10 dataset contains 60,000 color images in 10 classes, with +6,000 images in each class. The dataset is divided into 50,000 +training images and 10,000 testing images. The classes are mutually +exclusive and there is no overlap between them. +

    + + + +
    +
    +
    +
    +
    +
    import tensorflow as tf
    +
    +from tensorflow.keras import datasets, layers, models
    +import matplotlib.pyplot as plt
    +
    +# We import the data set
    +(train_images, train_labels), (test_images, test_labels) = datasets.cifar10.load_data()
    +
    +# Normalize pixel values to be between 0 and 1 by dividing by 255. 
    +train_images, test_images = train_images / 255.0, test_images / 255.0
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +

    Verifying the data set

    + +

    To verify that the dataset looks correct, let's plot the first 25 images from the training set and display the class name below each image.

    + + + +
    +
    +
    +
    +
    +
    class_names = ['airplane', 'automobile', 'bird', 'cat', 'deer',
    +               'dog', 'frog', 'horse', 'ship', 'truck']
    +plt.figure(figsize=(10,10))
    +for i in range(25):
    +    plt.subplot(5,5,i+1)
    +    plt.xticks([])
    +    plt.yticks([])
    +    plt.grid(False)
    +    plt.imshow(train_images[i], cmap=plt.cm.binary)
    +    # The CIFAR labels happen to be arrays, 
    +    # which is why you need the extra index
    +    plt.xlabel(class_names[train_labels[i][0]])
    +plt.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +

    Set up the model

    + +

    The 6 lines of code below define the convolutional base using a common pattern: a stack of Conv2D and MaxPooling2D layers.

    + +

    As input, a CNN takes tensors of shape (image_height, image_width, color_channels), ignoring the batch size. If you are new to these dimensions, color_channels refers to (R,G,B). In this example, you will configure our CNN to process inputs of shape (32, 32, 3), which is the format of CIFAR images. You can do this by passing the argument input_shape to our first layer.

    + + + +
    +
    +
    +
    +
    +
    model = models.Sequential()
    +model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)))
    +model.add(layers.MaxPooling2D((2, 2)))
    +model.add(layers.Conv2D(64, (3, 3), activation='relu'))
    +model.add(layers.MaxPooling2D((2, 2)))
    +model.add(layers.Conv2D(64, (3, 3), activation='relu'))
    +
    +# Let's display the architecture of our model so far.
    +
    +model.summary()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    You can see that the output of every Conv2D and MaxPooling2D layer is a 3D tensor of shape (height, width, channels). The width and height dimensions tend to shrink as you go deeper in the network. The number of output channels for each Conv2D layer is controlled by the first argument (e.g., 32 or 64). Typically, as the width and height shrink, you can afford (computationally) to add more output channels in each Conv2D layer.

    +
    + +
    +

    Add Dense layers on top

    + +

    To complete our model, you will feed the last output tensor from the +convolutional base (of shape (4, 4, 64)) into one or more Dense layers +to perform classification. Dense layers take vectors as input (which +are 1D), while the current output is a 3D tensor. First, you will +flatten (or unroll) the 3D output to 1D, then add one or more Dense +layers on top. CIFAR has 10 output classes, so you use a final Dense +layer with 10 outputs and a softmax activation. +

    + + + +
    +
    +
    +
    +
    +
    model.add(layers.Flatten())
    +model.add(layers.Dense(64, activation='relu'))
    +model.add(layers.Dense(10))
    +Here's the complete architecture of our model.
    +
    +model.summary()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    As you can see, our (4, 4, 64) outputs were flattened into vectors of shape (1024) before going through two Dense layers.

    +
    + +
    +

    Compile and train the model

    + + + +
    +
    +
    +
    +
    +
    model.compile(optimizer='adam',
    +              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
    +              metrics=['accuracy'])
    +
    +history = model.fit(train_images, train_labels, epochs=10, 
    +                    validation_data=(test_images, test_labels))
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +

    Finally, evaluate the model

    + + + +
    +
    +
    +
    +
    +
    plt.plot(history.history['accuracy'], label='accuracy')
    +plt.plot(history.history['val_accuracy'], label = 'val_accuracy')
    +plt.xlabel('Epoch')
    +plt.ylabel('Accuracy')
    +plt.ylim([0.5, 1])
    +plt.legend(loc='lower right')
    +
    +test_loss, test_acc = model.evaluate(test_images,  test_labels, verbose=2)
    +
    +print(test_acc)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    Building our own CNN code

    @@ -1077,6 +1899,8 @@ the codebase and fit a CNN that yields a 99% accuracy on the 28x28 MNIST dataset within reasonable time.

    +The codes here were developed by Eric Reber and Gregor Kajda during spring 2023. +

    The CNN is compatible with all schedulers, cost functions and activation functions discussed in constructing our neural network codes. @@ -1570,23 +2394,23 @@ $$ $$

     
    -

    Here, f and g are the two functions on which we want to perform an +

    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 +\( (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: +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]. +(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 +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: @@ -1594,7 +2418,7 @@ 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]. +(f \ast g)(i, j)\sum_{m=0}^{M-1}\sum_{n=0}^{N-1} f(m,n) g(i-m, j-n). $$

     
    @@ -1607,7 +2431,7 @@ 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 \) +suppose we have an image \( f \) of dimension \( 6 \times 6 \)

     
    @@ -1623,7 +2447,7 @@ f = \begin{bmatrix} $$

     
    -

    and a \( 3 \times 3 \) kernel g called a low-pass filter. Note that the +

    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.

    @@ -1640,9 +2464,9 @@ $$

     

    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 +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: +kernel \( g \):

     
    @@ -1664,24 +2488,24 @@ $$ \frac{9}{9} & \frac{5}{9} & \frac{9}{9} \\ \frac{1}{9} & \frac{5}{9} & \frac{9}{9} \\ \end {bmatrix} -= \textbf{A} += \boldsymbol{A} $$

     
    -

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

    +

    Then, following the multiplication, we summarize all the elements of the resulting matrix \( \boldsymbol{A} \):

     
    $$ -(f \ast g)[0, 0]= \sum_{i=0}^{2} \sum_{j=0}^{2} a_{i,j} = 5 +(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) \).

    +

    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 +

    Here we use a stride of \( S=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 +\( 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 @@ -1702,20 +2526,25 @@ $$ $$

     
    -

    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. +

    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 +r =\lfloor \frac{\mathrm{kernel height}}{2} \rfloor \cdot 2 \\ +c =\lfloor \frac{\mathrm{kernel width}}{2} \rfloor \cdot 2 $$

     
    -

    Note the notation \( \lfloor \frac{kernel width}{2} \rfloor \) means that +

    Note the notation \( \lfloor \frac{\mathrm{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 in case \( \frac{\mathrm{kernel width}}{2} \) results in a floating point number.

    @@ -1742,12 +2571,14 @@ $$ 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} +\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. 

    +

    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.~ +

    @@ -1842,9 +2673,10 @@ $$ -

    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 that is not +rotated by 180 degrees is called cross-correlation, which is normally implemented in most libraries.

    @@ -1904,7 +2736,7 @@ feed forward neural network.
    -
    # Now an example using a real image and first a gaussian low-pass filter and then a sobel filter
    +  
    # 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
    @@ -3932,7 +4764,7 @@ cnn.add_OutputLayer(10, softmax)
     
     

    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 \). +will use the MNIST dataset and use 10000 \( 28 \times 28 \) images.

    @@ -4347,367 +5179,6 @@ optimization technique.

    -
    -

    Building convolutional neural networks in Tensorflow and Keras

    - -

    As discussed above, CNNs are neural networks built from the assumption that the inputs -to the network are 2D images. This is important because the number of features or pixels in images -grows very fast with the image size, and an enormous number of weights and biases are needed in order to build an accurate network. -

    - -

    As before, we still have our input, a hidden layer and an output. What's novel about convolutional networks -are the convolutional and pooling layers stacked in pairs between the input and the hidden layer. -In addition, the data is no longer represented as a 2D feature matrix, instead each input is a number of 2D -matrices, typically 1 for each color dimension (Red, Green, Blue). -

    -
    - -
    -

    Setting it up

    - -

    It means that to represent the entire -dataset of images, we require a 4D matrix or tensor. This tensor has the dimensions: -

    -

     
    -$$ -(n_{inputs},\, n_{pixels, width},\, n_{pixels, height},\, depth) . -$$ -

     
    -

    - -
    -

    The MNIST dataset again

    - -

    The MNIST dataset consists of grayscale images with a pixel size of -\( 28\times 28 \), meaning we require \( 28 \times 28 = 724 \) weights to each -neuron in the first hidden layer. -

    - -

    If we were to analyze images of size \( 128\times 128 \) we would require -\( 128 \times 128 = 16384 \) weights to each neuron. Even worse if we were -dealing with color images, as most images are, we have an image matrix -of size \( 128\times 128 \) for each color dimension (Red, Green, Blue), -meaning 3 times the number of weights \( = 49152 \) are required for every -single neuron in the first hidden layer. -

    -
    - -
    -

    Strong correlations

    - -

    Images typically have strong local correlations, meaning that a small -part of the image varies little from its neighboring regions. If for -example we have an image of a blue car, we can roughly assume that a -small blue part of the image is surrounded by other blue regions. -

    - -

    Therefore, instead of connecting every single pixel to a neuron in the -first hidden layer, as we have previously done with deep neural -networks, we can instead connect each neuron to a small part of the -image (in all 3 RGB depth dimensions). The size of each small area is -fixed, and known as a receptive. -

    -
    - -
    -

    Layers of a CNN

    - -

    The layers of a convolutional neural network arrange neurons in 3D: width, height and depth. -The input image is typically a square matrix of depth 3. -

    - -

    A convolution is performed on the image which outputs -a 3D volume of neurons. The weights to the input are arranged in a number of 2D matrices, known as filters. -

    - -

    Each filter slides along the input image, taking the dot product -between each small part of the image and the filter, in all depth -dimensions. This is then passed through a non-linear function, -typically the Rectified Linear (ReLu) function, which serves as the -activation of the neurons in the first convolutional layer. This is -further passed through a pooling layer, which reduces the size of the -convolutional layer, e.g. by taking the maximum or average across some -small regions, and this serves as input to the next convolutional -layer. -

    -
    - -
    -

    Systematic reduction

    - -

    By systematically reducing the size of the input volume, through -convolution and pooling, the network should create representations of -small parts of the input, and then from them assemble representations -of larger areas. The final pooling layer is flattened to serve as -input to a hidden layer, such that each neuron in the final pooling -layer is connected to every single neuron in the hidden layer. This -then serves as input to the output layer, e.g. a softmax output for -classification. -

    -
    - -
    -

    Prerequisites: Collect and pre-process data

    - - -
    -
    -
    -
    -
    -
    # import necessary packages
    -import numpy as np
    -import matplotlib.pyplot as plt
    -from sklearn import datasets
    -
    -
    -# ensure the same random numbers appear every time
    -np.random.seed(0)
    -
    -# display images in notebook
    -%matplotlib inline
    -plt.rcParams['figure.figsize'] = (12,12)
    -
    -
    -# download MNIST dataset
    -digits = datasets.load_digits()
    -
    -# define inputs and labels
    -inputs = digits.images
    -labels = digits.target
    -
    -# RGB images have a depth of 3
    -# our images are grayscale so they should have a depth of 1
    -inputs = inputs[:,:,:,np.newaxis]
    -
    -print("inputs = (n_inputs, pixel_width, pixel_height, depth) = " + str(inputs.shape))
    -print("labels = (n_inputs) = " + str(labels.shape))
    -
    -
    -# choose some random images to display
    -n_inputs = len(inputs)
    -indices = np.arange(n_inputs)
    -random_indices = np.random.choice(indices, size=5)
    -
    -for i, image in enumerate(digits.images[random_indices]):
    -    plt.subplot(1, 5, i+1)
    -    plt.axis('off')
    -    plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
    -    plt.title("Label: %d" % digits.target[random_indices[i]])
    -plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -

    Importing Keras and Tensorflow

    - - -
    -
    -
    -
    -
    -
    from tensorflow.keras import datasets, layers, models
    -from tensorflow.keras.layers import Input
    -from tensorflow.keras.models import Sequential      #This allows appending layers to existing models
    -from tensorflow.keras.layers import Dense           #This allows defining the characteristics of a particular layer
    -from tensorflow.keras import optimizers             #This allows using whichever optimiser we want (sgd,adam,RMSprop)
    -from tensorflow.keras import regularizers           #This allows using whichever regularizer we want (l1,l2,l1_l2)
    -from tensorflow.keras.utils import to_categorical   #This allows using categorical cross entropy as the cost function
    -#from tensorflow.keras import Conv2D
    -#from tensorflow.keras import MaxPooling2D
    -#from tensorflow.keras import Flatten
    -
    -from sklearn.model_selection import train_test_split
    -
    -# representation of labels
    -labels = to_categorical(labels)
    -
    -# split into train and test data
    -# one-liner from scikit-learn library
    -train_size = 0.8
    -test_size = 1 - train_size
    -X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,
    -                                                    test_size=test_size)
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -

    Running with Keras

    - - - -
    -
    -
    -
    -
    -
    def create_convolutional_neural_network_keras(input_shape, receptive_field,
    -                                              n_filters, n_neurons_connected, n_categories,
    -                                              eta, lmbd):
    -    model = Sequential()
    -    model.add(layers.Conv2D(n_filters, (receptive_field, receptive_field), input_shape=input_shape, padding='same',
    -              activation='relu', kernel_regularizer=regularizers.l2(lmbd)))
    -    model.add(layers.MaxPooling2D(pool_size=(2, 2)))
    -    model.add(layers.Flatten())
    -    model.add(layers.Dense(n_neurons_connected, activation='relu', kernel_regularizer=regularizers.l2(lmbd)))
    -    model.add(layers.Dense(n_categories, activation='softmax', kernel_regularizer=regularizers.l2(lmbd)))
    -    
    -    sgd = optimizers.SGD(learning_rate=eta)
    -    model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])
    -    
    -    return model
    -
    -epochs = 100
    -batch_size = 100
    -input_shape = X_train.shape[1:4]
    -receptive_field = 3
    -n_filters = 10
    -n_neurons_connected = 50
    -n_categories = 10
    -
    -eta_vals = np.logspace(-5, 1, 7)
    -lmbd_vals = np.logspace(-5, 1, 7)
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -

    Final part

    - - - -
    -
    -
    -
    -
    -
    CNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
    -        
    -for i, eta in enumerate(eta_vals):
    -    for j, lmbd in enumerate(lmbd_vals):
    -        CNN = create_convolutional_neural_network_keras(input_shape, receptive_field,
    -                                              n_filters, n_neurons_connected, n_categories,
    -                                              eta, lmbd)
    -        CNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0)
    -        scores = CNN.evaluate(X_test, Y_test)
    -        
    -        CNN_keras[i][j] = CNN
    -        
    -        print("Learning rate = ", eta)
    -        print("Lambda = ", lmbd)
    -        print("Test accuracy: %.3f" % scores[1])
    -        print()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    -

    Final visualization

    - - - -
    -
    -
    -
    -
    -
    # visual representation of grid search
    -# uses seaborn heatmap, could probably do this in matplotlib
    -import seaborn as sns
    -
    -sns.set()
    -
    -train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
    -test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
    -
    -for i in range(len(eta_vals)):
    -    for j in range(len(lmbd_vals)):
    -        CNN = CNN_keras[i][j]
    -
    -        train_accuracy[i][j] = CNN.evaluate(X_train, Y_train)[1]
    -        test_accuracy[i][j] = CNN.evaluate(X_test, Y_test)[1]
    -
    -        
    -fig, ax = plt.subplots(figsize = (10, 10))
    -sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
    -ax.set_title("Training Accuracy")
    -ax.set_ylabel("$\eta$")
    -ax.set_xlabel("$\lambda$")
    -plt.show()
    -
    -fig, ax = plt.subplots(figsize = (10, 10))
    -sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
    -ax.set_title("Test Accuracy")
    -ax.set_ylabel("$\eta$")
    -ax.set_xlabel("$\lambda$")
    -plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - diff --git a/doc/pub/week44/html/week44-solarized.html b/doc/pub/week44/html/week44-solarized.html index 0cf7b26c0..ee5abe447 100644 --- a/doc/pub/week44/html/week44-solarized.html +++ b/doc/pub/week44/html/week44-solarized.html @@ -102,6 +102,12 @@ div.toc p,a { None, 'a-deep-cnn-model-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Key Idea', 2, None, 'key-idea'), + ('How to do image compression before the era of deep learning', + 2, + None, + 'how-to-do-image-compression-before-the-era-of-deep-learning'), + ('The SVD example', 2, None, 'the-svd-example'), + ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Convolution Examples: Polynomial multiplication', 2, @@ -116,6 +122,8 @@ div.toc p,a { 2, None, 'a-more-efficient-way-of-coding-the-above-convolution'), + ('Commutative process', 2, None, 'commutative-process'), + ('Toeplitz matrices', 2, None, 'toeplitz-matrices'), ('Fourier series and Toeplitz matrices', 2, None, @@ -124,36 +132,75 @@ div.toc p,a { 2, None, 'generalizing-the-above-one-dimensional-case'), - ('Two-dimensional Objects', 2, None, 'two-dimensional-objects'), - ('CNNs in more detail', 2, None, 'cnns-in-more-detail'), - ('Performing a discrete convolution with padding ("From Raschka ' - 'et al":"https://github.com/rasbt/machine-learning-book")', + ('Memory considerations', 2, None, 'memory-considerations'), + ('Padding', 2, None, 'padding'), + ('New vector', 2, None, 'new-vector'), + ('Rewriting as dot products', 2, None, - 'performing-a-discrete-convolution-with-padding-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Performing a general discrete convolution ("From Raschka et ' + 'rewriting-as-dot-products'), + ('Cross correlation', 2, None, 'cross-correlation'), + ('Two-dimensional objects', 2, None, 'two-dimensional-objects'), + ('CNNs in more detail, simple example', + 2, + None, + 'cnns-in-more-detail-simple-example'), + ('The convolution stage', 2, None, 'the-convolution-stage'), + ('Finding the number of parameters', + 2, + None, + 'finding-the-number-of-parameters'), + ('New image (or volume)', 2, None, 'new-image-or-volume'), + ('Parameters to train, common settings', + 2, + None, + 'parameters-to-train-common-settings'), + ('Examples of CNN setups', 2, None, 'examples-of-cnn-setups'), + ('Summarizing: Performing a general discrete convolution ("From ' + 'Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, - 'performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Set of filters', 2, None, 'set-of-filters'), + 'summarizing-performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Pooling', 2, None, 'pooling'), - ('No zero padding, unit strides', - 2, - None, - 'no-zero-padding-unit-strides'), - ('Zero padding, unit strides', - 2, - None, - 'zero-padding-unit-strides'), - ('Half (same) padding', 2, None, 'half-same-padding'), - ('Full padding', 2, None, 'full-padding'), ('Pooling arithmetic', 2, None, 'pooling-arithmetic'), ('Pooling types ("From Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, 'pooling-types-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), + ('Building convolutional neural networks in Tensorflow and Keras', + 2, + None, + 'building-convolutional-neural-networks-in-tensorflow-and-keras'), + ('Setting it up', 2, None, 'setting-it-up'), + ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), + ('Strong correlations', 2, None, 'strong-correlations'), + ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), + ('Systematic reduction', 2, None, 'systematic-reduction'), + ('Prerequisites: Collect and pre-process data', + 2, + None, + 'prerequisites-collect-and-pre-process-data'), + ('Importing Keras and Tensorflow', + 2, + None, + 'importing-keras-and-tensorflow'), + ('Running with Keras', 2, None, 'running-with-keras'), + ('Final part', 2, None, 'final-part'), + ('Final visualization', 2, None, 'final-visualization'), + ('The CIFAR01 data set', 2, None, 'the-cifar01-data-set'), + ('Verifying the data set', 2, None, 'verifying-the-data-set'), + ('Set up the model', 2, None, 'set-up-the-model'), + ('Add Dense layers on top', 2, None, 'add-dense-layers-on-top'), + ('Compile and train the model', + 2, + None, + 'compile-and-train-the-model'), + ('Finally, evaluate the model', + 2, + None, + 'finally-evaluate-the-model'), ('Building our own CNN code', 2, None, @@ -200,27 +247,7 @@ div.toc p,a { ('Convolution in the Fourier domain', 3, None, - 'convolution-in-the-fourier-domain'), - ('Building convolutional neural networks in Tensorflow and Keras', - 2, - None, - 'building-convolutional-neural-networks-in-tensorflow-and-keras'), - ('Setting it up', 2, None, 'setting-it-up'), - ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), - ('Strong correlations', 2, None, 'strong-correlations'), - ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), - ('Systematic reduction', 2, None, 'systematic-reduction'), - ('Prerequisites: Collect and pre-process data', - 2, - None, - 'prerequisites-collect-and-pre-process-data'), - ('Importing Keras and Tensorflow', - 2, - None, - 'importing-keras-and-tensorflow'), - ('Running with Keras', 2, None, 'running-with-keras'), - ('Final part', 2, None, 'final-part'), - ('Final visualization', 2, None, 'final-visualization')]} + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -548,6 +575,147 @@ only neighboring neurons in the input instead of connecting all with the first h

    We say we perform a filtering (convolution is the mathematical operation).

    +









    +

    How to do image compression before the era of deep learning

    + +

    The singular-value decomposition (SVD) algorithm has been for decades one of the standard ways of compressing images. +The lectures on the SVD give many of the essential details concerning the SVD. +

    + +

    The orthogonal vectors which are obtained from the SVD, can be used to +project down the dimensionality of a given image. In the example here +we gray-scale an image and downsize it. +

    + +

    This recipe relies on us being able to actually perform the SVD. For +large images, and in particular with many images to reconstruct, using the SVD +may quickly become an overwhelming task. With the advent of efficient deep +learning methods like CNNs and later generative methods, these methods +have become in the last years the premier way of performing image +analysis. In particular for classification problems with labelled images. +

    + +









    +

    The SVD example

    + + + +
    +
    +
    +
    +
    +
    from matplotlib.image import imread
    +import matplotlib.pyplot as plt
    +import scipy.linalg as ln
    +import numpy as np
    +import os
    +from PIL import Image
    +from math import log10, sqrt 
    +plt.rcParams['figure.figsize'] = [16, 8]
    +# Import image
    +A = imread(os.path.join("figslides/photo1.jpg"))
    +X = A.dot([0.299, 0.5870, 0.114]) # Convert RGB to grayscale
    +img = plt.imshow(X)
    +# convert to gray
    +img.set_cmap('gray')
    +plt.axis('off')
    +plt.show()
    +# Call image size
    +print(': %s'%str(X.shape))
    +
    +
    +# split the matrix into U, S, VT
    +U, S, VT = np.linalg.svd(X,full_matrices=False)
    +S = np.diag(S)
    +m = 800 # Image's width
    +n = 1200 # Image's height
    +j = 0
    +# Try compression with different k vectors (these represent projections):
    +for k in (5,10, 20, 100,200,400,500):
    +    # Original size of the image
    +    originalSize = m * n 
    +    # Size after compressed
    +    compressedSize = k * (1 + m + n) 
    +    # The projection of the original image
    +    Xapprox = U[:,:k] @ S[0:k,:k] @ VT[:k,:]
    +    plt.figure(j+1)
    +    j += 1
    +    img = plt.imshow(Xapprox)
    +    img.set_cmap('gray')
    +    
    +    plt.axis('off')
    +    plt.title('k = ' + str(k))
    +    plt.show() 
    +    print('Original size of image:')
    +    print(originalSize)
    +    print('Compression rate as Compressed image / Original size:')
    +    ratio = compressedSize * 1.0 / originalSize
    +    print(ratio)
    +    print('Compression rate is ' + str( round(ratio * 100 ,2)) + '%' )  
    +    # Estimate MQA
    +    x= X.astype("float")
    +    y=Xapprox.astype("float")
    +    err = np.sum((x - y) ** 2)
    +    err /= float(X.shape[0] * Xapprox.shape[1])
    +    print('The mean-square deviation '+ str(round( err)))
    +    max_pixel = 255.0
    +    # Estimate Signal Noise Ratio
    +    srv = 20 * (log10(max_pixel / sqrt(err)))
    +    print('Signa to noise ratio '+ str(round(srv)) +'dB')
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    Mathematics of CNNs

    + +

    The mathematics of CNNs is based on the mathematical operation of +convolution. In mathematics (in particular in functional analysis), +convolution is represented by mathematical operations (integration, +summation etc) on two functions in order to produce a third function +that expresses how the shape of one gets modified by the other. +Convolution has a plethora of applications in a variety of +disciplines, spanning from statistics to signal processing, computer +vision, solutions of differential equations,linear algebra, +engineering, and yes, machine learning. +

    + +

    Mathematically, convolution is defined as follows (one-dimensional example): +Let us define a continuous function \( y(t) \) given by +

    +$$ +y(t) = \int x(a) w(t-a) da, +$$ + +

    where \( x(a) \) represents a so-called input and \( w(t-a) \) is normally called the weight function or kernel.

    + +

    The above integral is written in a more compact form as

    +$$ +y(t) = \left(x * w\right)(t). +$$ + +

    The discretized version reads

    +$$ +y(t) = \sum_{a=-\infty}^{a=\infty}x(a)w(t-a). +$$ + +

    Computing the inverse of the above convolution operations is known as deconvolution and the process is commutative.

    + +

    How can we use this? And what does it mean? Let us study some familiar examples first.

    +









    Mathematics of CNNs

    @@ -651,7 +819,9 @@ $$ \delta_i = \sum_{k=0}^{k=m-1}\alpha_k\beta_{i-k}, $$ -

    where \( m=3 \) in our case, the maximum length of the vector \( \alpha \). Note that the vector \( \boldsymbol{\beta} \) has length \( n=4 \).

    +

    where \( m=3 \) in our case, the maximum length of +the vector \( \alpha \). Note that the vector \( \boldsymbol{\beta} \) has length \( n=4 \). Below we will find an even more efficient representation. +











    A more efficient way of coding the above Convolution

    @@ -671,6 +841,10 @@ $$ \end{bmatrix}\begin{bmatrix} \beta_0 \\ \beta_1 \\ \beta_2 \\ \beta_3\end{bmatrix}. $$ + +









    +

    Commutative process

    +

    The process is commutative and we can easily see that we can rewrite the multiplication in terms of a matrix holding \( \beta \) and a vector holding \( \alpha \). In this case we have

    @@ -691,6 +865,9 @@ rather code the convolutions in the minimal memory footprint that they require.

    +









    +

    Toeplitz matrices

    +

    The above matrices are examples of so-called Toeplitz matrices. A Toeplitz matrix is a matrix in which each descending diagonal from @@ -727,18 +904,125 @@ a vector.









    Generalizing the above one-dimensional case

    -

    In order to align the above simple case with the more general convolution cases, we rename \( \boldsymbol{\alpha} \), whose length is \( m=3 \), with \( \boldsymbol{w} \). -We will interpret \( \boldsymbol{w} \) as a weight/filter function with which we want to perform the convolution with an input varibale \( \boldsymbol{x} \). -We replace thus \( \boldsymbol{\beta} \) with \( \boldsymbol{x} \) and \( \boldsymbol{\delta} \) with \( \boldsymbol{s} \) and have +

    In order to align the above simple case with the more general +convolution cases, we rename \( \boldsymbol{\alpha} \), whose length is \( m=3 \), +with \( \boldsymbol{w} \). We will interpret \( \boldsymbol{w} \) as a weight/filter function +with which we want to perform the convolution with an input variable +\( \boldsymbol{x} \) of length \( n \). We will assume always that the filter +\( \boldsymbol{w} \) has dimensionality \( m \le n \).

    + +

    We replace thus \( \boldsymbol{\beta} \) with \( \boldsymbol{x} \) and \( \boldsymbol{\delta} \) with \( \boldsymbol{y} \) and have

    $$ -s(i) \left(x*w\right)(i)= \sum_{k=0}^{k=m-1}w(k)x(i-k), +y(i)= \left(x*w\right)(i)= \sum_{k=0}^{k=m-1}w(k)x(i-k), $$

    where \( m=3 \) in our case, the maximum length of the vector \( \boldsymbol{w} \). Here the symbol \( * \) represents the mathematical operation of convolution.

    -

    Two-dimensional Objects

    + +









    +

    Memory considerations

    + +

    This expression leaves us however with some terms with negative +indices, for example \( x(-1) \) and \( x(-2) \) which may not be defined. Our +vector \( \boldsymbol{x} \) has components \( x(0) \), \( x(1) \), \( x(2) \) and \( x(3) \). +

    + +

    The index \( j \) for \( \boldsymbol{x} \) runs from \( j=0 \) to \( j=3 \) since \( \boldsymbol{x} \) is meant to +represent a third-order polynomial. +

    + +

    Furthermore, the index \( i \) runs from \( i=0 \) to \( i=5 \) since \( \boldsymbol{y} \) +contains the coefficients of a fifth-order polynomial. When \( i=5 \) we +may also have values of \( x(4) \) and \( x(5) \) which are not defined. +

    + +









    +

    Padding

    + +

    The solution to this is what is called padding! We simply define a +new vector \( x \) with two added elements set to zero before \( x(0) \) and +two new elements after \( x(3) \) set to zero. That is, we augment the +length of \( \boldsymbol{x} \) from \( n=4 \) to \( n+2P=8 \), where \( P=2 \) is the padding +constant (a new hyperparameter), see discussions below as well. +

    + +









    +

    New vector

    + +

    We have a new vector defined as \( x(0)=0 \), \( x(1)=0 \), +\( x(2)=\beta_0 \), \( x(3)=\beta_1 \), \( x(4)=\beta_2 \), \( x(5)=\beta_3 \), +\( x(6)=0 \), and \( x(7)=0 \). +

    + +

    We have added four new elements, which +are all zero. The benefit is that we can rewrite the equation for +\( \boldsymbol{y} \), with \( i=0,1,\dots,5 \), +

    +$$ +y(i) = \sum_{k=0}^{k=m-1}w(k)x(i+(m-1)-k). +$$ + +

    As an example, we have

    +$$ +y(4)=x(6)w(0)+x(5)w(1)+x(4)w(2)=0\times \alpha_0+\beta_3\alpha_1+\beta_2\alpha_2, +$$ + +

    as before except that we have an additional term \( x(6)w(0) \), which is zero.

    + +

    Similarly, for the fifth-order term we have

    +$$ +y(5)=x(7)w(0)+x(6)w(1)+x(5)w(2)=0\times \alpha_0+0\times\alpha_1+\beta_3\alpha_2. +$$ + +

    The zeroth-order term is

    +$$ +y(0)=x(2)w(0)+x(1)w(1)+x(0)w(2)=\beta_0 \alpha_0+0\times\alpha_1+0\times\alpha_2=\alpha_0\beta_0. +$$ + + +









    +

    Rewriting as dot products

    + +

    If we now flip the filter/weight vector, with the following term as a typical example

    +$$ +y(0)=x(2)w(0)+x(1)w(1)+x(0)w(2)=x(2)\tilde{w}(2)+x(1)\tilde{w}(1)+x(0)\tilde{w}(0), +$$ + +

    with \( \tilde{w}(0)=w(2) \), \( \tilde{w}(1)=w(1) \), and \( \tilde{w}(2)=w(0) \), we can then rewrite the above sum as a dot product of +\( x(i:i+(m-1))\tilde{w} \) for element \( y(i) \), where \( x(i:i+(m-1)) \) is simply a patch of \( \boldsymbol{x} \) of size \( m-1 \). +

    + +

    The padding \( P \) we have introduced for the convolution stage is just +another hyperparameter which is introduced as part of the +architecture. Similarly, below we will also introduce another +hyperparameter called Stride \( S \). +

    + +









    +

    Cross correlation

    + +

    In essentially all applications one uses what is called cross correlation instead of the standard convolution described above. +This means that multiplication is performed in the same direction and instead of the general expression we have discussed above (with infinite sums) +

    +$$ +y(i) = \sum_{k=-\infty}^{k=\infty}w(k)x(i-k), +$$ + +

    we have now

    +$$ +y(i) = \sum_{k=-\infty}^{k=\infty}w(k)x(i+k). +$$ + +

    Both TensorFlow and PyTorch (as well as our own code example below), +implement the last equation, although it is normally referred to as +convolution. The same padding rules and stride rules discussed below +apply to this expression as well. +

    + +

    We leave it as an exercise for you to convince yourself that the example we have discussed till now, gives the same final expression using the last expression.

    +

    Two-dimensional objects

    We are now ready to start studying the discrete convolutions relevant for convolutional neural networks. We often use convolutions over more than one dimension at a time. If @@ -755,16 +1039,22 @@ $$ Y(i,j)=(X * W)(i,j) = \sum_m\sum_n X(i-m,j-n)W(m,n). $$ -

    Normally the latter is more straightforward to implement in a machine larning library since there is less variation in the range of values of \( m \) and \( n \).

    +

    Normally the latter is more straightforward to implement in a machine +larning library since there is less variation in the range of values +of \( m \) and \( n \). +

    -

    Many deep learning libraries implement cross-correlation instead of convolution (although it is referred to s convolution)

    +

    As mentioned above, most deep learning libraries implement +cross-correlation instead of convolution (although it is referred to as +convolution) +

    $$ Y(i,j)=(X * W)(i,j) = \sum_m\sum_n X(i+m,j+n)W(m,n). $$









    -

    CNNs in more detail

    +

    CNNs in more detail, simple example

    Let assume we have an input matrix \( X \) of dimensionality \( 3\times 3 \) and a \( 2\times 2 \) filter \( W \) given by the following matrices @@ -824,56 +1114,101 @@ $$

    is now given by \( \boldsymbol{W}'\boldsymbol{X}' \) which is a vector of length \( 4 \) instead of the originally resulting \( 2\times 2 \) output matrix.











    -

    Performing a discrete convolution with padding (From Raschka et al)

    +

    The convolution stage

    -
    -
    -
    -

    Figure 4: A deep CNN

    -
    -

    -
    - -









    -

    Performing a general discrete convolution (From Raschka et al)

    - -
    -
    -
    -

    Figure 5: A deep CNN

    -
    -

    -
    - -









    -

    Set of filters

    - -

    The collection of kernels/filters \( W \) defining a discrete convolution has a shape -corresponding to some permutation of \( (n, m, k_1, \ldots, k_N) \), where +

    The convolution stage, where we apply different filters \( \boldsymbol{W} \) in +order to reduce the dimensionality of an image, adds, in addition to +the weights and biases (to be trained by the back propagation +algorithm) that define the filters, two new hyperparameters, the so-called +padding \( P \) and the stride \( S \).

    -$$ -\begin{equation*} -\begin{split} - n &\equiv \text{number of output feature maps},\\ - m &\equiv \text{number of input feature maps},\\ - k_j &\equiv \text{kernel size along axis $j$}. -\end{split} -\end{equation*} -$$ +









    +

    Finding the number of parameters

    -

    The following properties affect the output size \( o_j \) of a convolutional layer -along axis \( j \): +

    In the above example we have an input matrix of dimension \( 3\times +3 \). In general we call the input for an input volume and it is defined +by its width \( H_1 \), height \( H_1 \) and depth \( D_1 \). If we have the +standard three color channels \( D_1=3 \).

    +

    The above example has \( W_1=H_1=3 \) and \( D_1=1 \).

    + +

    When we introduce the filter we have the following additional hyperparameters

      -
    1. \( i_j \): input size along axis \( j \),
    2. -
    3. \( k_j \): kernel/filter size along axis \( j \),
    4. -
    5. stride (distance between two consecutive positions of the kernel/filter) along axis \( j \),
    6. -
    7. zero padding (number of zeros concatenated at the beginning and at the end of an axis) along axis \( j \).
    8. +
    9. \( K \) the number of filters. It is common to perform the convolution of the input several times since by experience shrinking the input too fast does not work well
    10. +
    11. \( F \) as the filter's spatial extent
    12. +
    13. \( S \) as the stride parameter
    14. +
    15. \( P \) as the padding parameter
    -

    For instance, the above examples shows a \( 2\times 2 \) kernel/filter \( \boldsymbol{W} \) applied to a \( 3 \times 3 \) input padded with a \( 0 \times 0 \) -border of zeros using \( 1 \times 1 \) strides. +

    These parameters are defined by the architecture of the network and are not included in the training.

    + +









    +

    New image (or volume)

    + +

    Acting with the filter on the input volume produces an output volume +which is defined by its width \( W_2 \), its height \( H_2 \) and its depth +\( D_2 \). +

    + +

    These are defined by the following relations

    +$$ +W_2 = \frac{(W_1-F+2P)}{S}+1, +$$ + +$$ +H_2 = \frac{(H_1-F+2P)}{S}+1, +$$ + +

    and \( D_2=K \).

    + +









    +

    Parameters to train, common settings

    + +

    With parameter sharing, the convolution involves thus for each filter \( F\times F\times D_1 \) weights plus one bias parameter.

    + +

    In total we have

    +$$ +\left(F\times F\times D_1)\right) \times K+(K\mathrm{--biases}), +$$ + +

    parameters to train by back propagation.

    + +

    It is common to let \( K \) come in powers of \( 2 \), that is \( 32 \), \( 64 \), \( 128 \) etc.

    + +
    +Common settings +

    +

      +
    1. \( \begin{array}{c} F=3 & S=1 & P=1 \end{array} \)
    2. +
    3. \( \begin{array}{c} F=5 & S=1 & P=2 \end{array} \)
    4. +
    5. \( \begin{array}{c} F=5 & S=2 & P=\mathrm{open} \end{array} \)
    6. +
    7. \( \begin{array}{c} F=1 & S=1 & P=0 \end{array} \)
    8. +
    +
    + + +









    +

    Examples of CNN setups

    + +

    Let us assume we have an input volume \( V \) given by an image of dimensionality +\( 32\times 32 \times 3 \), that is three color channels and \( 32\times 32 \) pixels. +

    + +

    We apply a filter of dimension \( 5\times 5 \) ten times with stride \( S=1 \) and padding \( P=0 \).

    + +

    The output volume is given by \( (32-5)/1+1=28 \), resulting in ten images +of dimensionality \( 28\times 28\times 3 \). +

    + +

    The total number of parameters to train for each filter is then +\( 5\times 5\times 3+1 \), where the last parameter is the bias. This +gives us \( 76 \) parameters for each filter, leading to a total of \( 760 \) +parameters for the ten filters. +

    + +

    How many parameters will a filter of dimensionality \( 3\times 3 \) +(adding color channels) result in if we produce \( 32 \) new images? Use \( S=1 \) and \( P=0 \).

    Note that strides constitute a form of subsampling. As an alternative to @@ -883,124 +1218,30 @@ the kernel by hops of two is equivalent to moving the kernel by hops of one but retaining only odd output elements.

    +









    +

    Summarizing: Performing a general discrete convolution (From Raschka et al)

    + +
    +
    +
    +

    Figure 4: A deep CNN

    +
    +

    +
    +









    Pooling

    -

    In addition to discrete convolutions themselves, {\em pooling\/} operations +

    In addition to discrete convolutions themselves, pooling operations make up another important building block in CNNs. Pooling operations reduce the size of feature maps by using some function to summarize subregions, such as taking the average or the maximum value.

    Pooling works by sliding a window across the input and feeding the content of -the window to a {\em pooling function}. In some sense, pooling works very much +the window to a pooling function. In some sense, pooling works very much like a discrete convolution, but replaces the linear combination described by -the kernel with some other function. Poolin -provides an example for average pooling, and -does the same for max pooling. -

    - -

    The following properties affect the output size \( o_j \) of a pooling layer -along axis \( j \): -

    - -
      -
    1. \( i_j \): input size along axis \( j \),
    2. -
    3. \( k_j \): pooling window size along axis \( j \),
    4. -
    5. \( s_j \): stride (distance between two consecutive positions of the pooling window) along axis \( j \).
    6. -
    -

    The analysis of the relationship between convolutional layer properties is eased -by the fact that they don't interact across axes, i.e., the choice of kernel -size, stride and zero padding along axis \( j \) only affects the output size of -axis \( j \). Because of that, we will focus on the following simplified -setting: -

    - -
      -
    1. 2-D discrete convolutions (\( N = 2 \)),
    2. -
    3. square inputs (\( i_1 = i_2 = i \)),
    4. -
    5. square kernel size (\( k_1 = k_2 = k \)),
    6. -
    7. same strides along both axes (\( s_1 = s_2 = s \)),
    8. -
    9. same zero padding along both axes (\( p_1 = p_2 = p \)).
    10. -
    -

    This facilitates the analysis and the visualization, but keep in mind that the -results outlined here also generalize to the N-D and non-square cases. -

    - -









    -

    No zero padding, unit strides

    - -

    The simplest case to analyze is when the kernel just slides across every -position of the input (i.e., \( s = 1 \) and \( p = 0 \)). -

    - -

    For any \( i \) and \( k \), and for \( s = 1 \) and \( p = 0 \),

    -$$ -\begin{equation*} - o = (i - k) + 1. -\end{equation*} -$$ - - -









    -

    Zero padding, unit strides

    - -

    To factor in zero padding (i.e., only restricting to \( s = 1 \)), let's consider -its effect on the effective input size: padding with \( p \) zeros changes the -effective input size from \( i \) to \( i + 2p \). In the general case, we can infer the following -relationship -

    - -

    For any \( i \), \( k \) and \( p \), and for \( s = 1 \),

    -$$ -\begin{equation*} - o = (i - k) + 2p + 1. -\end{equation*} -$$ - - -









    -

    Half (same) padding

    - -

    Having the output size be the same as the input size (i.e., \( o = i \)) can be a -desirable property: -

    - -

    For any \( i \) and for \( k \) odd (\( k = 2n + 1, \quad n \in \mathbb{N} \)), \( s = 1 \) and -\( p = \lfloor k / 2 \rfloor = n \), -

    -$$ -\begin{equation*} -\begin{split} - o &= i + 2 \lfloor k / 2 \rfloor - (k - 1) \\ - &= i + 2n - 2n \\ - &= i. -\end{split} -\end{equation*} -$$ - - -









    -

    Full padding

    - -

    While convolving a kernel generally decreases the output size with -respect to the input size, sometimes the opposite is required. This can be -achieved with proper zero padding: -

    - -

    For any \( i \) and \( k \), and for \( p = k - 1 \) and \( s = 1 \),

    -$$ -\begin{equation*} -\begin{split} - o &= i + 2(k - 1) - (k - 1) \\ - &= i + (k - 1). -\end{split} -\end{equation*} -$$ - -

    This is sometimes referred to as full padding, because in this -setting every possible partial or complete superimposition of the kernel on the -input feature map is taken into account. +the kernel with some other function.











    @@ -1014,29 +1255,608 @@ mean or average pooling, which all share the same idea of aggregating the input locally by applying a non-linearity to the content of some patches.

    -

    Since pooling does not involve -zero padding, the relationship describing the general case is as follows: -

    - -

    For any \( i \), \( k \) and \( s \),

    -$$ -\begin{equation*} - o = \left\lfloor \frac{i - k}{s} \right\rfloor + 1. -\end{equation*} -$$ - -









    Pooling types (From Raschka et al)


    -

    Figure 6: A deep CNN

    +

    Figure 5: A deep CNN

    +









    +

    Building convolutional neural networks in Tensorflow and Keras

    + +

    As discussed above, CNNs are neural networks built from the assumption that the inputs +to the network are 2D images. This is important because the number of features or pixels in images +grows very fast with the image size, and an enormous number of weights and biases are needed in order to build an accurate network. +

    + +

    As before, we still have our input, a hidden layer and an output. What's novel about convolutional networks +are the convolutional and pooling layers stacked in pairs between the input and the hidden layer. +In addition, the data is no longer represented as a 2D feature matrix, instead each input is a number of 2D +matrices, typically 1 for each color dimension (Red, Green, Blue). +

    + +









    +

    Setting it up

    + +

    It means that to represent the entire +dataset of images, we require a 4D matrix or tensor. This tensor has the dimensions: +

    +$$ +(n_{inputs},\, n_{pixels, width},\, n_{pixels, height},\, depth) . +$$ + + +









    +

    The MNIST dataset again

    + +

    The MNIST dataset consists of grayscale images with a pixel size of +\( 28\times 28 \), meaning we require \( 28 \times 28 = 724 \) weights to each +neuron in the first hidden layer. +

    + +

    If we were to analyze images of size \( 128\times 128 \) we would require +\( 128 \times 128 = 16384 \) weights to each neuron. Even worse if we were +dealing with color images, as most images are, we have an image matrix +of size \( 128\times 128 \) for each color dimension (Red, Green, Blue), +meaning 3 times the number of weights \( = 49152 \) are required for every +single neuron in the first hidden layer. +

    + + +









    +

    Strong correlations

    + +

    Images typically have strong local correlations, meaning that a small +part of the image varies little from its neighboring regions. If for +example we have an image of a blue car, we can roughly assume that a +small blue part of the image is surrounded by other blue regions. +

    + +

    Therefore, instead of connecting every single pixel to a neuron in the +first hidden layer, as we have previously done with deep neural +networks, we can instead connect each neuron to a small part of the +image (in all 3 RGB depth dimensions). The size of each small area is +fixed, and known as a receptive. +

    + + + +

    Layers of a CNN

    + +

    The layers of a convolutional neural network arrange neurons in 3D: width, height and depth. +The input image is typically a square matrix of depth 3. +

    + +

    A convolution is performed on the image which outputs +a 3D volume of neurons. The weights to the input are arranged in a number of 2D matrices, known as filters. +

    + +

    Each filter slides along the input image, taking the dot product +between each small part of the image and the filter, in all depth +dimensions. This is then passed through a non-linear function, +typically the Rectified Linear (ReLu) function, which serves as the +activation of the neurons in the first convolutional layer. This is +further passed through a pooling layer, which reduces the size of the +convolutional layer, e.g. by taking the maximum or average across some +small regions, and this serves as input to the next convolutional +layer. +

    + +









    +

    Systematic reduction

    + +

    By systematically reducing the size of the input volume, through +convolution and pooling, the network should create representations of +small parts of the input, and then from them assemble representations +of larger areas. The final pooling layer is flattened to serve as +input to a hidden layer, such that each neuron in the final pooling +layer is connected to every single neuron in the hidden layer. This +then serves as input to the output layer, e.g. a softmax output for +classification. +

    + + +









    +

    Prerequisites: Collect and pre-process data

    + + +
    +
    +
    +
    +
    +
    # import necessary packages
    +import numpy as np
    +import matplotlib.pyplot as plt
    +from sklearn import datasets
    +
    +
    +# ensure the same random numbers appear every time
    +np.random.seed(0)
    +
    +# display images in notebook
    +%matplotlib inline
    +plt.rcParams['figure.figsize'] = (12,12)
    +
    +
    +# download MNIST dataset
    +digits = datasets.load_digits()
    +
    +# define inputs and labels
    +inputs = digits.images
    +labels = digits.target
    +
    +# RGB images have a depth of 3
    +# our images are grayscale so they should have a depth of 1
    +inputs = inputs[:,:,:,np.newaxis]
    +
    +print("inputs = (n_inputs, pixel_width, pixel_height, depth) = " + str(inputs.shape))
    +print("labels = (n_inputs) = " + str(labels.shape))
    +
    +
    +# choose some random images to display
    +n_inputs = len(inputs)
    +indices = np.arange(n_inputs)
    +random_indices = np.random.choice(indices, size=5)
    +
    +for i, image in enumerate(digits.images[random_indices]):
    +    plt.subplot(1, 5, i+1)
    +    plt.axis('off')
    +    plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
    +    plt.title("Label: %d" % digits.target[random_indices[i]])
    +plt.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    Importing Keras and Tensorflow

    + + +
    +
    +
    +
    +
    +
    from tensorflow.keras import datasets, layers, models
    +from tensorflow.keras.layers import Input
    +from tensorflow.keras.models import Sequential      #This allows appending layers to existing models
    +from tensorflow.keras.layers import Dense           #This allows defining the characteristics of a particular layer
    +from tensorflow.keras import optimizers             #This allows using whichever optimiser we want (sgd,adam,RMSprop)
    +from tensorflow.keras import regularizers           #This allows using whichever regularizer we want (l1,l2,l1_l2)
    +from tensorflow.keras.utils import to_categorical   #This allows using categorical cross entropy as the cost function
    +#from tensorflow.keras import Conv2D
    +#from tensorflow.keras import MaxPooling2D
    +#from tensorflow.keras import Flatten
    +
    +from sklearn.model_selection import train_test_split
    +
    +# representation of labels
    +labels = to_categorical(labels)
    +
    +# split into train and test data
    +# one-liner from scikit-learn library
    +train_size = 0.8
    +test_size = 1 - train_size
    +X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,
    +                                                    test_size=test_size)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + + +

    Running with Keras

    + + + +
    +
    +
    +
    +
    +
    def create_convolutional_neural_network_keras(input_shape, receptive_field,
    +                                              n_filters, n_neurons_connected, n_categories,
    +                                              eta, lmbd):
    +    model = Sequential()
    +    model.add(layers.Conv2D(n_filters, (receptive_field, receptive_field), input_shape=input_shape, padding='same',
    +              activation='relu', kernel_regularizer=regularizers.l2(lmbd)))
    +    model.add(layers.MaxPooling2D(pool_size=(2, 2)))
    +    model.add(layers.Flatten())
    +    model.add(layers.Dense(n_neurons_connected, activation='relu', kernel_regularizer=regularizers.l2(lmbd)))
    +    model.add(layers.Dense(n_categories, activation='softmax', kernel_regularizer=regularizers.l2(lmbd)))
    +    
    +    sgd = optimizers.SGD(lr=eta)
    +    model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])
    +    
    +    return model
    +
    +epochs = 100
    +batch_size = 100
    +input_shape = X_train.shape[1:4]
    +receptive_field = 3
    +n_filters = 10
    +n_neurons_connected = 50
    +n_categories = 10
    +
    +eta_vals = np.logspace(-5, 1, 7)
    +lmbd_vals = np.logspace(-5, 1, 7)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    Final part

    + + + +
    +
    +
    +
    +
    +
    CNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
    +        
    +for i, eta in enumerate(eta_vals):
    +    for j, lmbd in enumerate(lmbd_vals):
    +        CNN = create_convolutional_neural_network_keras(input_shape, receptive_field,
    +                                              n_filters, n_neurons_connected, n_categories,
    +                                              eta, lmbd)
    +        CNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0)
    +        scores = CNN.evaluate(X_test, Y_test)
    +        
    +        CNN_keras[i][j] = CNN
    +        
    +        print("Learning rate = ", eta)
    +        print("Lambda = ", lmbd)
    +        print("Test accuracy: %.3f" % scores[1])
    +        print()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    Final visualization

    + + + +
    +
    +
    +
    +
    +
    # visual representation of grid search
    +# uses seaborn heatmap, could probably do this in matplotlib
    +import seaborn as sns
    +
    +sns.set()
    +
    +train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
    +test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
    +
    +for i in range(len(eta_vals)):
    +    for j in range(len(lmbd_vals)):
    +        CNN = CNN_keras[i][j]
    +
    +        train_accuracy[i][j] = CNN.evaluate(X_train, Y_train)[1]
    +        test_accuracy[i][j] = CNN.evaluate(X_test, Y_test)[1]
    +
    +        
    +fig, ax = plt.subplots(figsize = (10, 10))
    +sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
    +ax.set_title("Training Accuracy")
    +ax.set_ylabel("$\eta$")
    +ax.set_xlabel("$\lambda$")
    +plt.show()
    +
    +fig, ax = plt.subplots(figsize = (10, 10))
    +sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
    +ax.set_title("Test Accuracy")
    +ax.set_ylabel("$\eta$")
    +ax.set_xlabel("$\lambda$")
    +plt.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    The CIFAR01 data set

    + +

    The CIFAR10 dataset contains 60,000 color images in 10 classes, with +6,000 images in each class. The dataset is divided into 50,000 +training images and 10,000 testing images. The classes are mutually +exclusive and there is no overlap between them. +

    + + + +
    +
    +
    +
    +
    +
    import tensorflow as tf
    +
    +from tensorflow.keras import datasets, layers, models
    +import matplotlib.pyplot as plt
    +
    +# We import the data set
    +(train_images, train_labels), (test_images, test_labels) = datasets.cifar10.load_data()
    +
    +# Normalize pixel values to be between 0 and 1 by dividing by 255. 
    +train_images, test_images = train_images / 255.0, test_images / 255.0
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    Verifying the data set

    + +

    To verify that the dataset looks correct, let's plot the first 25 images from the training set and display the class name below each image.

    + + + +
    +
    +
    +
    +
    +
    class_names = ['airplane', 'automobile', 'bird', 'cat', 'deer',
    +               'dog', 'frog', 'horse', 'ship', 'truck']
    +plt.figure(figsize=(10,10))
    +for i in range(25):
    +    plt.subplot(5,5,i+1)
    +    plt.xticks([])
    +    plt.yticks([])
    +    plt.grid(False)
    +    plt.imshow(train_images[i], cmap=plt.cm.binary)
    +    # The CIFAR labels happen to be arrays, 
    +    # which is why you need the extra index
    +    plt.xlabel(class_names[train_labels[i][0]])
    +plt.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    Set up the model

    + +

    The 6 lines of code below define the convolutional base using a common pattern: a stack of Conv2D and MaxPooling2D layers.

    + +

    As input, a CNN takes tensors of shape (image_height, image_width, color_channels), ignoring the batch size. If you are new to these dimensions, color_channels refers to (R,G,B). In this example, you will configure our CNN to process inputs of shape (32, 32, 3), which is the format of CIFAR images. You can do this by passing the argument input_shape to our first layer.

    + + + +
    +
    +
    +
    +
    +
    model = models.Sequential()
    +model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)))
    +model.add(layers.MaxPooling2D((2, 2)))
    +model.add(layers.Conv2D(64, (3, 3), activation='relu'))
    +model.add(layers.MaxPooling2D((2, 2)))
    +model.add(layers.Conv2D(64, (3, 3), activation='relu'))
    +
    +# Let's display the architecture of our model so far.
    +
    +model.summary()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    You can see that the output of every Conv2D and MaxPooling2D layer is a 3D tensor of shape (height, width, channels). The width and height dimensions tend to shrink as you go deeper in the network. The number of output channels for each Conv2D layer is controlled by the first argument (e.g., 32 or 64). Typically, as the width and height shrink, you can afford (computationally) to add more output channels in each Conv2D layer.

    + +









    +

    Add Dense layers on top

    + +

    To complete our model, you will feed the last output tensor from the +convolutional base (of shape (4, 4, 64)) into one or more Dense layers +to perform classification. Dense layers take vectors as input (which +are 1D), while the current output is a 3D tensor. First, you will +flatten (or unroll) the 3D output to 1D, then add one or more Dense +layers on top. CIFAR has 10 output classes, so you use a final Dense +layer with 10 outputs and a softmax activation. +

    + + + +
    +
    +
    +
    +
    +
    model.add(layers.Flatten())
    +model.add(layers.Dense(64, activation='relu'))
    +model.add(layers.Dense(10))
    +Here's the complete architecture of our model.
    +
    +model.summary()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    As you can see, our (4, 4, 64) outputs were flattened into vectors of shape (1024) before going through two Dense layers.

    + +









    +

    Compile and train the model

    + + + +
    +
    +
    +
    +
    +
    model.compile(optimizer='adam',
    +              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
    +              metrics=['accuracy'])
    +
    +history = model.fit(train_images, train_labels, epochs=10, 
    +                    validation_data=(test_images, test_labels))
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    Finally, evaluate the model

    + + + +
    +
    +
    +
    +
    +
    plt.plot(history.history['accuracy'], label='accuracy')
    +plt.plot(history.history['val_accuracy'], label = 'val_accuracy')
    +plt.xlabel('Epoch')
    +plt.ylabel('Accuracy')
    +plt.ylim([0.5, 1])
    +plt.legend(loc='lower right')
    +
    +test_loss, test_acc = model.evaluate(test_images,  test_labels, verbose=2)
    +
    +print(test_acc)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +









    Building our own CNN code

    @@ -1046,6 +1866,8 @@ the codebase and fit a CNN that yields a 99% accuracy on the 28x28 MNIST dataset within reasonable time.

    +The codes here were developed by Eric Reber and Gregor Kajda during spring 2023. +

    The CNN is compatible with all schedulers, cost functions and activation functions discussed in constructing our neural network codes. @@ -1536,28 +2358,28 @@ $$ (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 +

    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 +\( (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: +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]. +(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 +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]. +(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 @@ -1569,7 +2391,7 @@ 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 \) +suppose we have an image \( f \) of dimension \( 6 \times 6 \)

    $$ @@ -1583,7 +2405,7 @@ f = \begin{bmatrix} \end{bmatrix} $$ -

    and a \( 3 \times 3 \) kernel g called a low-pass filter. Note that the +

    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.

    @@ -1598,9 +2420,9 @@ g = \frac{1}{9} $$

    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 +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: +kernel \( g \):

    $$ @@ -1621,21 +2443,21 @@ $$ \frac{9}{9} & \frac{5}{9} & \frac{9}{9} \\ \frac{1}{9} & \frac{5}{9} & \frac{9}{9} \\ \end {bmatrix} -= \textbf{A} += \boldsymbol{A} $$ -

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

    +

    Then, following the multiplication, we summarize all the elements of the resulting matrix \( \boldsymbol{A} \):

    $$ -(f \ast g)[0, 0]= \sum_{i=0}^{2} \sum_{j=0}^{2} a_{i,j} = 5 +(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) \).

    +

    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 +

    Here we use a stride of \( S=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 +\( 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 @@ -1654,18 +2476,23 @@ $$ \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. +

    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 +r =\lfloor \frac{\mathrm{kernel height}}{2} \rfloor \cdot 2 \\ +c =\lfloor \frac{\mathrm{kernel width}}{2} \rfloor \cdot 2 $$ -

    Note the notation \( \lfloor \frac{kernel width}{2} \rfloor \) means that +

    Note the notation \( \lfloor \frac{\mathrm{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 in case \( \frac{\mathrm{kernel width}}{2} \) results in a floating point number.

    @@ -1691,11 +2518,13 @@ $$ 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} +\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. 

    +

    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.~ +

    @@ -1790,9 +2619,10 @@ $$ -

    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 that is not +rotated by 180 degrees is called cross-correlation, which is normally implemented in most libraries.

    @@ -1852,7 +2682,7 @@ feed forward neural network.
    -
    # Now an example using a real image and first a gaussian low-pass filter and then a sobel filter
    +  
    # 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
    @@ -3879,7 +4709,7 @@ cnn.add_OutputLayer(10, softmax)
     
  • 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 \). +will use the MNIST dataset and use 10000 \( 28 \times 28 \) images.

    @@ -4293,363 +5123,6 @@ to remain cognizant of this fact when utilizing FFT as the primary optimization technique.

    -









    -

    Building convolutional neural networks in Tensorflow and Keras

    - -

    As discussed above, CNNs are neural networks built from the assumption that the inputs -to the network are 2D images. This is important because the number of features or pixels in images -grows very fast with the image size, and an enormous number of weights and biases are needed in order to build an accurate network. -

    - -

    As before, we still have our input, a hidden layer and an output. What's novel about convolutional networks -are the convolutional and pooling layers stacked in pairs between the input and the hidden layer. -In addition, the data is no longer represented as a 2D feature matrix, instead each input is a number of 2D -matrices, typically 1 for each color dimension (Red, Green, Blue). -

    - -









    -

    Setting it up

    - -

    It means that to represent the entire -dataset of images, we require a 4D matrix or tensor. This tensor has the dimensions: -

    -$$ -(n_{inputs},\, n_{pixels, width},\, n_{pixels, height},\, depth) . -$$ - - -









    -

    The MNIST dataset again

    - -

    The MNIST dataset consists of grayscale images with a pixel size of -\( 28\times 28 \), meaning we require \( 28 \times 28 = 724 \) weights to each -neuron in the first hidden layer. -

    - -

    If we were to analyze images of size \( 128\times 128 \) we would require -\( 128 \times 128 = 16384 \) weights to each neuron. Even worse if we were -dealing with color images, as most images are, we have an image matrix -of size \( 128\times 128 \) for each color dimension (Red, Green, Blue), -meaning 3 times the number of weights \( = 49152 \) are required for every -single neuron in the first hidden layer. -

    - - -









    -

    Strong correlations

    - -

    Images typically have strong local correlations, meaning that a small -part of the image varies little from its neighboring regions. If for -example we have an image of a blue car, we can roughly assume that a -small blue part of the image is surrounded by other blue regions. -

    - -

    Therefore, instead of connecting every single pixel to a neuron in the -first hidden layer, as we have previously done with deep neural -networks, we can instead connect each neuron to a small part of the -image (in all 3 RGB depth dimensions). The size of each small area is -fixed, and known as a receptive. -

    - - - -

    Layers of a CNN

    - -

    The layers of a convolutional neural network arrange neurons in 3D: width, height and depth. -The input image is typically a square matrix of depth 3. -

    - -

    A convolution is performed on the image which outputs -a 3D volume of neurons. The weights to the input are arranged in a number of 2D matrices, known as filters. -

    - -

    Each filter slides along the input image, taking the dot product -between each small part of the image and the filter, in all depth -dimensions. This is then passed through a non-linear function, -typically the Rectified Linear (ReLu) function, which serves as the -activation of the neurons in the first convolutional layer. This is -further passed through a pooling layer, which reduces the size of the -convolutional layer, e.g. by taking the maximum or average across some -small regions, and this serves as input to the next convolutional -layer. -

    - -









    -

    Systematic reduction

    - -

    By systematically reducing the size of the input volume, through -convolution and pooling, the network should create representations of -small parts of the input, and then from them assemble representations -of larger areas. The final pooling layer is flattened to serve as -input to a hidden layer, such that each neuron in the final pooling -layer is connected to every single neuron in the hidden layer. This -then serves as input to the output layer, e.g. a softmax output for -classification. -

    - - -









    -

    Prerequisites: Collect and pre-process data

    - - -
    -
    -
    -
    -
    -
    # import necessary packages
    -import numpy as np
    -import matplotlib.pyplot as plt
    -from sklearn import datasets
    -
    -
    -# ensure the same random numbers appear every time
    -np.random.seed(0)
    -
    -# display images in notebook
    -%matplotlib inline
    -plt.rcParams['figure.figsize'] = (12,12)
    -
    -
    -# download MNIST dataset
    -digits = datasets.load_digits()
    -
    -# define inputs and labels
    -inputs = digits.images
    -labels = digits.target
    -
    -# RGB images have a depth of 3
    -# our images are grayscale so they should have a depth of 1
    -inputs = inputs[:,:,:,np.newaxis]
    -
    -print("inputs = (n_inputs, pixel_width, pixel_height, depth) = " + str(inputs.shape))
    -print("labels = (n_inputs) = " + str(labels.shape))
    -
    -
    -# choose some random images to display
    -n_inputs = len(inputs)
    -indices = np.arange(n_inputs)
    -random_indices = np.random.choice(indices, size=5)
    -
    -for i, image in enumerate(digits.images[random_indices]):
    -    plt.subplot(1, 5, i+1)
    -    plt.axis('off')
    -    plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
    -    plt.title("Label: %d" % digits.target[random_indices[i]])
    -plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    Importing Keras and Tensorflow

    - - -
    -
    -
    -
    -
    -
    from tensorflow.keras import datasets, layers, models
    -from tensorflow.keras.layers import Input
    -from tensorflow.keras.models import Sequential      #This allows appending layers to existing models
    -from tensorflow.keras.layers import Dense           #This allows defining the characteristics of a particular layer
    -from tensorflow.keras import optimizers             #This allows using whichever optimiser we want (sgd,adam,RMSprop)
    -from tensorflow.keras import regularizers           #This allows using whichever regularizer we want (l1,l2,l1_l2)
    -from tensorflow.keras.utils import to_categorical   #This allows using categorical cross entropy as the cost function
    -#from tensorflow.keras import Conv2D
    -#from tensorflow.keras import MaxPooling2D
    -#from tensorflow.keras import Flatten
    -
    -from sklearn.model_selection import train_test_split
    -
    -# representation of labels
    -labels = to_categorical(labels)
    -
    -# split into train and test data
    -# one-liner from scikit-learn library
    -train_size = 0.8
    -test_size = 1 - train_size
    -X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,
    -                                                    test_size=test_size)
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - - -

    Running with Keras

    - - - -
    -
    -
    -
    -
    -
    def create_convolutional_neural_network_keras(input_shape, receptive_field,
    -                                              n_filters, n_neurons_connected, n_categories,
    -                                              eta, lmbd):
    -    model = Sequential()
    -    model.add(layers.Conv2D(n_filters, (receptive_field, receptive_field), input_shape=input_shape, padding='same',
    -              activation='relu', kernel_regularizer=regularizers.l2(lmbd)))
    -    model.add(layers.MaxPooling2D(pool_size=(2, 2)))
    -    model.add(layers.Flatten())
    -    model.add(layers.Dense(n_neurons_connected, activation='relu', kernel_regularizer=regularizers.l2(lmbd)))
    -    model.add(layers.Dense(n_categories, activation='softmax', kernel_regularizer=regularizers.l2(lmbd)))
    -    
    -    sgd = optimizers.SGD(learning_rate=eta)
    -    model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])
    -    
    -    return model
    -
    -epochs = 100
    -batch_size = 100
    -input_shape = X_train.shape[1:4]
    -receptive_field = 3
    -n_filters = 10
    -n_neurons_connected = 50
    -n_categories = 10
    -
    -eta_vals = np.logspace(-5, 1, 7)
    -lmbd_vals = np.logspace(-5, 1, 7)
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    Final part

    - - - -
    -
    -
    -
    -
    -
    CNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
    -        
    -for i, eta in enumerate(eta_vals):
    -    for j, lmbd in enumerate(lmbd_vals):
    -        CNN = create_convolutional_neural_network_keras(input_shape, receptive_field,
    -                                              n_filters, n_neurons_connected, n_categories,
    -                                              eta, lmbd)
    -        CNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0)
    -        scores = CNN.evaluate(X_test, Y_test)
    -        
    -        CNN_keras[i][j] = CNN
    -        
    -        print("Learning rate = ", eta)
    -        print("Lambda = ", lmbd)
    -        print("Test accuracy: %.3f" % scores[1])
    -        print()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    Final visualization

    - - - -
    -
    -
    -
    -
    -
    # visual representation of grid search
    -# uses seaborn heatmap, could probably do this in matplotlib
    -import seaborn as sns
    -
    -sns.set()
    -
    -train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
    -test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
    -
    -for i in range(len(eta_vals)):
    -    for j in range(len(lmbd_vals)):
    -        CNN = CNN_keras[i][j]
    -
    -        train_accuracy[i][j] = CNN.evaluate(X_train, Y_train)[1]
    -        test_accuracy[i][j] = CNN.evaluate(X_test, Y_test)[1]
    -
    -        
    -fig, ax = plt.subplots(figsize = (10, 10))
    -sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
    -ax.set_title("Training Accuracy")
    -ax.set_ylabel("$\eta$")
    -ax.set_xlabel("$\lambda$")
    -plt.show()
    -
    -fig, ax = plt.subplots(figsize = (10, 10))
    -sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
    -ax.set_title("Test Accuracy")
    -ax.set_ylabel("$\eta$")
    -ax.set_xlabel("$\lambda$")
    -plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    © 1999-2024, 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 47f4477f0..088207579 100644 --- a/doc/pub/week44/html/week44.html +++ b/doc/pub/week44/html/week44.html @@ -179,6 +179,12 @@ div.toc p,a { None, 'a-deep-cnn-model-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Key Idea', 2, None, 'key-idea'), + ('How to do image compression before the era of deep learning', + 2, + None, + 'how-to-do-image-compression-before-the-era-of-deep-learning'), + ('The SVD example', 2, None, 'the-svd-example'), + ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Mathematics of CNNs', 2, None, 'mathematics-of-cnns'), ('Convolution Examples: Polynomial multiplication', 2, @@ -193,6 +199,8 @@ div.toc p,a { 2, None, 'a-more-efficient-way-of-coding-the-above-convolution'), + ('Commutative process', 2, None, 'commutative-process'), + ('Toeplitz matrices', 2, None, 'toeplitz-matrices'), ('Fourier series and Toeplitz matrices', 2, None, @@ -201,36 +209,75 @@ div.toc p,a { 2, None, 'generalizing-the-above-one-dimensional-case'), - ('Two-dimensional Objects', 2, None, 'two-dimensional-objects'), - ('CNNs in more detail', 2, None, 'cnns-in-more-detail'), - ('Performing a discrete convolution with padding ("From Raschka ' - 'et al":"https://github.com/rasbt/machine-learning-book")', + ('Memory considerations', 2, None, 'memory-considerations'), + ('Padding', 2, None, 'padding'), + ('New vector', 2, None, 'new-vector'), + ('Rewriting as dot products', 2, None, - 'performing-a-discrete-convolution-with-padding-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Performing a general discrete convolution ("From Raschka et ' + 'rewriting-as-dot-products'), + ('Cross correlation', 2, None, 'cross-correlation'), + ('Two-dimensional objects', 2, None, 'two-dimensional-objects'), + ('CNNs in more detail, simple example', + 2, + None, + 'cnns-in-more-detail-simple-example'), + ('The convolution stage', 2, None, 'the-convolution-stage'), + ('Finding the number of parameters', + 2, + None, + 'finding-the-number-of-parameters'), + ('New image (or volume)', 2, None, 'new-image-or-volume'), + ('Parameters to train, common settings', + 2, + None, + 'parameters-to-train-common-settings'), + ('Examples of CNN setups', 2, None, 'examples-of-cnn-setups'), + ('Summarizing: Performing a general discrete convolution ("From ' + 'Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, - 'performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), - ('Set of filters', 2, None, 'set-of-filters'), + 'summarizing-performing-a-general-discrete-convolution-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), ('Pooling', 2, None, 'pooling'), - ('No zero padding, unit strides', - 2, - None, - 'no-zero-padding-unit-strides'), - ('Zero padding, unit strides', - 2, - None, - 'zero-padding-unit-strides'), - ('Half (same) padding', 2, None, 'half-same-padding'), - ('Full padding', 2, None, 'full-padding'), ('Pooling arithmetic', 2, None, 'pooling-arithmetic'), ('Pooling types ("From Raschka et ' 'al":"https://github.com/rasbt/machine-learning-book")', 2, None, 'pooling-types-from-raschka-et-al-https-github-com-rasbt-machine-learning-book'), + ('Building convolutional neural networks in Tensorflow and Keras', + 2, + None, + 'building-convolutional-neural-networks-in-tensorflow-and-keras'), + ('Setting it up', 2, None, 'setting-it-up'), + ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), + ('Strong correlations', 2, None, 'strong-correlations'), + ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), + ('Systematic reduction', 2, None, 'systematic-reduction'), + ('Prerequisites: Collect and pre-process data', + 2, + None, + 'prerequisites-collect-and-pre-process-data'), + ('Importing Keras and Tensorflow', + 2, + None, + 'importing-keras-and-tensorflow'), + ('Running with Keras', 2, None, 'running-with-keras'), + ('Final part', 2, None, 'final-part'), + ('Final visualization', 2, None, 'final-visualization'), + ('The CIFAR01 data set', 2, None, 'the-cifar01-data-set'), + ('Verifying the data set', 2, None, 'verifying-the-data-set'), + ('Set up the model', 2, None, 'set-up-the-model'), + ('Add Dense layers on top', 2, None, 'add-dense-layers-on-top'), + ('Compile and train the model', + 2, + None, + 'compile-and-train-the-model'), + ('Finally, evaluate the model', + 2, + None, + 'finally-evaluate-the-model'), ('Building our own CNN code', 2, None, @@ -277,27 +324,7 @@ div.toc p,a { ('Convolution in the Fourier domain', 3, None, - 'convolution-in-the-fourier-domain'), - ('Building convolutional neural networks in Tensorflow and Keras', - 2, - None, - 'building-convolutional-neural-networks-in-tensorflow-and-keras'), - ('Setting it up', 2, None, 'setting-it-up'), - ('The MNIST dataset again', 2, None, 'the-mnist-dataset-again'), - ('Strong correlations', 2, None, 'strong-correlations'), - ('Layers of a CNN', 2, None, 'layers-of-a-cnn'), - ('Systematic reduction', 2, None, 'systematic-reduction'), - ('Prerequisites: Collect and pre-process data', - 2, - None, - 'prerequisites-collect-and-pre-process-data'), - ('Importing Keras and Tensorflow', - 2, - None, - 'importing-keras-and-tensorflow'), - ('Running with Keras', 2, None, 'running-with-keras'), - ('Final part', 2, None, 'final-part'), - ('Final visualization', 2, None, 'final-visualization')]} + 'convolution-in-the-fourier-domain')]} end of tocinfo --> @@ -625,6 +652,147 @@ only neighboring neurons in the input instead of connecting all with the first h

    We say we perform a filtering (convolution is the mathematical operation).

    +









    +

    How to do image compression before the era of deep learning

    + +

    The singular-value decomposition (SVD) algorithm has been for decades one of the standard ways of compressing images. +The lectures on the SVD give many of the essential details concerning the SVD. +

    + +

    The orthogonal vectors which are obtained from the SVD, can be used to +project down the dimensionality of a given image. In the example here +we gray-scale an image and downsize it. +

    + +

    This recipe relies on us being able to actually perform the SVD. For +large images, and in particular with many images to reconstruct, using the SVD +may quickly become an overwhelming task. With the advent of efficient deep +learning methods like CNNs and later generative methods, these methods +have become in the last years the premier way of performing image +analysis. In particular for classification problems with labelled images. +

    + +









    +

    The SVD example

    + + + +
    +
    +
    +
    +
    +
    from matplotlib.image import imread
    +import matplotlib.pyplot as plt
    +import scipy.linalg as ln
    +import numpy as np
    +import os
    +from PIL import Image
    +from math import log10, sqrt 
    +plt.rcParams['figure.figsize'] = [16, 8]
    +# Import image
    +A = imread(os.path.join("figslides/photo1.jpg"))
    +X = A.dot([0.299, 0.5870, 0.114]) # Convert RGB to grayscale
    +img = plt.imshow(X)
    +# convert to gray
    +img.set_cmap('gray')
    +plt.axis('off')
    +plt.show()
    +# Call image size
    +print(': %s'%str(X.shape))
    +
    +
    +# split the matrix into U, S, VT
    +U, S, VT = np.linalg.svd(X,full_matrices=False)
    +S = np.diag(S)
    +m = 800 # Image's width
    +n = 1200 # Image's height
    +j = 0
    +# Try compression with different k vectors (these represent projections):
    +for k in (5,10, 20, 100,200,400,500):
    +    # Original size of the image
    +    originalSize = m * n 
    +    # Size after compressed
    +    compressedSize = k * (1 + m + n) 
    +    # The projection of the original image
    +    Xapprox = U[:,:k] @ S[0:k,:k] @ VT[:k,:]
    +    plt.figure(j+1)
    +    j += 1
    +    img = plt.imshow(Xapprox)
    +    img.set_cmap('gray')
    +    
    +    plt.axis('off')
    +    plt.title('k = ' + str(k))
    +    plt.show() 
    +    print('Original size of image:')
    +    print(originalSize)
    +    print('Compression rate as Compressed image / Original size:')
    +    ratio = compressedSize * 1.0 / originalSize
    +    print(ratio)
    +    print('Compression rate is ' + str( round(ratio * 100 ,2)) + '%' )  
    +    # Estimate MQA
    +    x= X.astype("float")
    +    y=Xapprox.astype("float")
    +    err = np.sum((x - y) ** 2)
    +    err /= float(X.shape[0] * Xapprox.shape[1])
    +    print('The mean-square deviation '+ str(round( err)))
    +    max_pixel = 255.0
    +    # Estimate Signal Noise Ratio
    +    srv = 20 * (log10(max_pixel / sqrt(err)))
    +    print('Signa to noise ratio '+ str(round(srv)) +'dB')
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    Mathematics of CNNs

    + +

    The mathematics of CNNs is based on the mathematical operation of +convolution. In mathematics (in particular in functional analysis), +convolution is represented by mathematical operations (integration, +summation etc) on two functions in order to produce a third function +that expresses how the shape of one gets modified by the other. +Convolution has a plethora of applications in a variety of +disciplines, spanning from statistics to signal processing, computer +vision, solutions of differential equations,linear algebra, +engineering, and yes, machine learning. +

    + +

    Mathematically, convolution is defined as follows (one-dimensional example): +Let us define a continuous function \( y(t) \) given by +

    +$$ +y(t) = \int x(a) w(t-a) da, +$$ + +

    where \( x(a) \) represents a so-called input and \( w(t-a) \) is normally called the weight function or kernel.

    + +

    The above integral is written in a more compact form as

    +$$ +y(t) = \left(x * w\right)(t). +$$ + +

    The discretized version reads

    +$$ +y(t) = \sum_{a=-\infty}^{a=\infty}x(a)w(t-a). +$$ + +

    Computing the inverse of the above convolution operations is known as deconvolution and the process is commutative.

    + +

    How can we use this? And what does it mean? Let us study some familiar examples first.

    +









    Mathematics of CNNs

    @@ -728,7 +896,9 @@ $$ \delta_i = \sum_{k=0}^{k=m-1}\alpha_k\beta_{i-k}, $$ -

    where \( m=3 \) in our case, the maximum length of the vector \( \alpha \). Note that the vector \( \boldsymbol{\beta} \) has length \( n=4 \).

    +

    where \( m=3 \) in our case, the maximum length of +the vector \( \alpha \). Note that the vector \( \boldsymbol{\beta} \) has length \( n=4 \). Below we will find an even more efficient representation. +











    A more efficient way of coding the above Convolution

    @@ -748,6 +918,10 @@ $$ \end{bmatrix}\begin{bmatrix} \beta_0 \\ \beta_1 \\ \beta_2 \\ \beta_3\end{bmatrix}. $$ + +









    +

    Commutative process

    +

    The process is commutative and we can easily see that we can rewrite the multiplication in terms of a matrix holding \( \beta \) and a vector holding \( \alpha \). In this case we have

    @@ -768,6 +942,9 @@ rather code the convolutions in the minimal memory footprint that they require.

    +









    +

    Toeplitz matrices

    +

    The above matrices are examples of so-called Toeplitz matrices. A Toeplitz matrix is a matrix in which each descending diagonal from @@ -804,18 +981,125 @@ a vector.









    Generalizing the above one-dimensional case

    -

    In order to align the above simple case with the more general convolution cases, we rename \( \boldsymbol{\alpha} \), whose length is \( m=3 \), with \( \boldsymbol{w} \). -We will interpret \( \boldsymbol{w} \) as a weight/filter function with which we want to perform the convolution with an input varibale \( \boldsymbol{x} \). -We replace thus \( \boldsymbol{\beta} \) with \( \boldsymbol{x} \) and \( \boldsymbol{\delta} \) with \( \boldsymbol{s} \) and have +

    In order to align the above simple case with the more general +convolution cases, we rename \( \boldsymbol{\alpha} \), whose length is \( m=3 \), +with \( \boldsymbol{w} \). We will interpret \( \boldsymbol{w} \) as a weight/filter function +with which we want to perform the convolution with an input variable +\( \boldsymbol{x} \) of length \( n \). We will assume always that the filter +\( \boldsymbol{w} \) has dimensionality \( m \le n \).

    + +

    We replace thus \( \boldsymbol{\beta} \) with \( \boldsymbol{x} \) and \( \boldsymbol{\delta} \) with \( \boldsymbol{y} \) and have

    $$ -s(i) \left(x*w\right)(i)= \sum_{k=0}^{k=m-1}w(k)x(i-k), +y(i)= \left(x*w\right)(i)= \sum_{k=0}^{k=m-1}w(k)x(i-k), $$

    where \( m=3 \) in our case, the maximum length of the vector \( \boldsymbol{w} \). Here the symbol \( * \) represents the mathematical operation of convolution.

    -

    Two-dimensional Objects

    + +









    +

    Memory considerations

    + +

    This expression leaves us however with some terms with negative +indices, for example \( x(-1) \) and \( x(-2) \) which may not be defined. Our +vector \( \boldsymbol{x} \) has components \( x(0) \), \( x(1) \), \( x(2) \) and \( x(3) \). +

    + +

    The index \( j \) for \( \boldsymbol{x} \) runs from \( j=0 \) to \( j=3 \) since \( \boldsymbol{x} \) is meant to +represent a third-order polynomial. +

    + +

    Furthermore, the index \( i \) runs from \( i=0 \) to \( i=5 \) since \( \boldsymbol{y} \) +contains the coefficients of a fifth-order polynomial. When \( i=5 \) we +may also have values of \( x(4) \) and \( x(5) \) which are not defined. +

    + +









    +

    Padding

    + +

    The solution to this is what is called padding! We simply define a +new vector \( x \) with two added elements set to zero before \( x(0) \) and +two new elements after \( x(3) \) set to zero. That is, we augment the +length of \( \boldsymbol{x} \) from \( n=4 \) to \( n+2P=8 \), where \( P=2 \) is the padding +constant (a new hyperparameter), see discussions below as well. +

    + +









    +

    New vector

    + +

    We have a new vector defined as \( x(0)=0 \), \( x(1)=0 \), +\( x(2)=\beta_0 \), \( x(3)=\beta_1 \), \( x(4)=\beta_2 \), \( x(5)=\beta_3 \), +\( x(6)=0 \), and \( x(7)=0 \). +

    + +

    We have added four new elements, which +are all zero. The benefit is that we can rewrite the equation for +\( \boldsymbol{y} \), with \( i=0,1,\dots,5 \), +

    +$$ +y(i) = \sum_{k=0}^{k=m-1}w(k)x(i+(m-1)-k). +$$ + +

    As an example, we have

    +$$ +y(4)=x(6)w(0)+x(5)w(1)+x(4)w(2)=0\times \alpha_0+\beta_3\alpha_1+\beta_2\alpha_2, +$$ + +

    as before except that we have an additional term \( x(6)w(0) \), which is zero.

    + +

    Similarly, for the fifth-order term we have

    +$$ +y(5)=x(7)w(0)+x(6)w(1)+x(5)w(2)=0\times \alpha_0+0\times\alpha_1+\beta_3\alpha_2. +$$ + +

    The zeroth-order term is

    +$$ +y(0)=x(2)w(0)+x(1)w(1)+x(0)w(2)=\beta_0 \alpha_0+0\times\alpha_1+0\times\alpha_2=\alpha_0\beta_0. +$$ + + +









    +

    Rewriting as dot products

    + +

    If we now flip the filter/weight vector, with the following term as a typical example

    +$$ +y(0)=x(2)w(0)+x(1)w(1)+x(0)w(2)=x(2)\tilde{w}(2)+x(1)\tilde{w}(1)+x(0)\tilde{w}(0), +$$ + +

    with \( \tilde{w}(0)=w(2) \), \( \tilde{w}(1)=w(1) \), and \( \tilde{w}(2)=w(0) \), we can then rewrite the above sum as a dot product of +\( x(i:i+(m-1))\tilde{w} \) for element \( y(i) \), where \( x(i:i+(m-1)) \) is simply a patch of \( \boldsymbol{x} \) of size \( m-1 \). +

    + +

    The padding \( P \) we have introduced for the convolution stage is just +another hyperparameter which is introduced as part of the +architecture. Similarly, below we will also introduce another +hyperparameter called Stride \( S \). +

    + +









    +

    Cross correlation

    + +

    In essentially all applications one uses what is called cross correlation instead of the standard convolution described above. +This means that multiplication is performed in the same direction and instead of the general expression we have discussed above (with infinite sums) +

    +$$ +y(i) = \sum_{k=-\infty}^{k=\infty}w(k)x(i-k), +$$ + +

    we have now

    +$$ +y(i) = \sum_{k=-\infty}^{k=\infty}w(k)x(i+k). +$$ + +

    Both TensorFlow and PyTorch (as well as our own code example below), +implement the last equation, although it is normally referred to as +convolution. The same padding rules and stride rules discussed below +apply to this expression as well. +

    + +

    We leave it as an exercise for you to convince yourself that the example we have discussed till now, gives the same final expression using the last expression.

    +

    Two-dimensional objects

    We are now ready to start studying the discrete convolutions relevant for convolutional neural networks. We often use convolutions over more than one dimension at a time. If @@ -832,16 +1116,22 @@ $$ Y(i,j)=(X * W)(i,j) = \sum_m\sum_n X(i-m,j-n)W(m,n). $$ -

    Normally the latter is more straightforward to implement in a machine larning library since there is less variation in the range of values of \( m \) and \( n \).

    +

    Normally the latter is more straightforward to implement in a machine +larning library since there is less variation in the range of values +of \( m \) and \( n \). +

    -

    Many deep learning libraries implement cross-correlation instead of convolution (although it is referred to s convolution)

    +

    As mentioned above, most deep learning libraries implement +cross-correlation instead of convolution (although it is referred to as +convolution) +

    $$ Y(i,j)=(X * W)(i,j) = \sum_m\sum_n X(i+m,j+n)W(m,n). $$









    -

    CNNs in more detail

    +

    CNNs in more detail, simple example

    Let assume we have an input matrix \( X \) of dimensionality \( 3\times 3 \) and a \( 2\times 2 \) filter \( W \) given by the following matrices @@ -901,56 +1191,101 @@ $$

    is now given by \( \boldsymbol{W}'\boldsymbol{X}' \) which is a vector of length \( 4 \) instead of the originally resulting \( 2\times 2 \) output matrix.











    -

    Performing a discrete convolution with padding (From Raschka et al)

    +

    The convolution stage

    -
    -
    -
    -

    Figure 4: A deep CNN

    -
    -

    -
    - -









    -

    Performing a general discrete convolution (From Raschka et al)

    - -
    -
    -
    -

    Figure 5: A deep CNN

    -
    -

    -
    - -









    -

    Set of filters

    - -

    The collection of kernels/filters \( W \) defining a discrete convolution has a shape -corresponding to some permutation of \( (n, m, k_1, \ldots, k_N) \), where +

    The convolution stage, where we apply different filters \( \boldsymbol{W} \) in +order to reduce the dimensionality of an image, adds, in addition to +the weights and biases (to be trained by the back propagation +algorithm) that define the filters, two new hyperparameters, the so-called +padding \( P \) and the stride \( S \).

    -$$ -\begin{equation*} -\begin{split} - n &\equiv \text{number of output feature maps},\\ - m &\equiv \text{number of input feature maps},\\ - k_j &\equiv \text{kernel size along axis $j$}. -\end{split} -\end{equation*} -$$ +









    +

    Finding the number of parameters

    -

    The following properties affect the output size \( o_j \) of a convolutional layer -along axis \( j \): +

    In the above example we have an input matrix of dimension \( 3\times +3 \). In general we call the input for an input volume and it is defined +by its width \( H_1 \), height \( H_1 \) and depth \( D_1 \). If we have the +standard three color channels \( D_1=3 \).

    +

    The above example has \( W_1=H_1=3 \) and \( D_1=1 \).

    + +

    When we introduce the filter we have the following additional hyperparameters

      -
    1. \( i_j \): input size along axis \( j \),
    2. -
    3. \( k_j \): kernel/filter size along axis \( j \),
    4. -
    5. stride (distance between two consecutive positions of the kernel/filter) along axis \( j \),
    6. -
    7. zero padding (number of zeros concatenated at the beginning and at the end of an axis) along axis \( j \).
    8. +
    9. \( K \) the number of filters. It is common to perform the convolution of the input several times since by experience shrinking the input too fast does not work well
    10. +
    11. \( F \) as the filter's spatial extent
    12. +
    13. \( S \) as the stride parameter
    14. +
    15. \( P \) as the padding parameter
    -

    For instance, the above examples shows a \( 2\times 2 \) kernel/filter \( \boldsymbol{W} \) applied to a \( 3 \times 3 \) input padded with a \( 0 \times 0 \) -border of zeros using \( 1 \times 1 \) strides. +

    These parameters are defined by the architecture of the network and are not included in the training.

    + +









    +

    New image (or volume)

    + +

    Acting with the filter on the input volume produces an output volume +which is defined by its width \( W_2 \), its height \( H_2 \) and its depth +\( D_2 \). +

    + +

    These are defined by the following relations

    +$$ +W_2 = \frac{(W_1-F+2P)}{S}+1, +$$ + +$$ +H_2 = \frac{(H_1-F+2P)}{S}+1, +$$ + +

    and \( D_2=K \).

    + +









    +

    Parameters to train, common settings

    + +

    With parameter sharing, the convolution involves thus for each filter \( F\times F\times D_1 \) weights plus one bias parameter.

    + +

    In total we have

    +$$ +\left(F\times F\times D_1)\right) \times K+(K\mathrm{--biases}), +$$ + +

    parameters to train by back propagation.

    + +

    It is common to let \( K \) come in powers of \( 2 \), that is \( 32 \), \( 64 \), \( 128 \) etc.

    + +
    +Common settings +

    +

      +
    1. \( \begin{array}{c} F=3 & S=1 & P=1 \end{array} \)
    2. +
    3. \( \begin{array}{c} F=5 & S=1 & P=2 \end{array} \)
    4. +
    5. \( \begin{array}{c} F=5 & S=2 & P=\mathrm{open} \end{array} \)
    6. +
    7. \( \begin{array}{c} F=1 & S=1 & P=0 \end{array} \)
    8. +
    +
    + + +









    +

    Examples of CNN setups

    + +

    Let us assume we have an input volume \( V \) given by an image of dimensionality +\( 32\times 32 \times 3 \), that is three color channels and \( 32\times 32 \) pixels. +

    + +

    We apply a filter of dimension \( 5\times 5 \) ten times with stride \( S=1 \) and padding \( P=0 \).

    + +

    The output volume is given by \( (32-5)/1+1=28 \), resulting in ten images +of dimensionality \( 28\times 28\times 3 \). +

    + +

    The total number of parameters to train for each filter is then +\( 5\times 5\times 3+1 \), where the last parameter is the bias. This +gives us \( 76 \) parameters for each filter, leading to a total of \( 760 \) +parameters for the ten filters. +

    + +

    How many parameters will a filter of dimensionality \( 3\times 3 \) +(adding color channels) result in if we produce \( 32 \) new images? Use \( S=1 \) and \( P=0 \).

    Note that strides constitute a form of subsampling. As an alternative to @@ -960,124 +1295,30 @@ the kernel by hops of two is equivalent to moving the kernel by hops of one but retaining only odd output elements.

    +









    +

    Summarizing: Performing a general discrete convolution (From Raschka et al)

    + +
    +
    +
    +

    Figure 4: A deep CNN

    +
    +

    +
    +









    Pooling

    -

    In addition to discrete convolutions themselves, {\em pooling\/} operations +

    In addition to discrete convolutions themselves, pooling operations make up another important building block in CNNs. Pooling operations reduce the size of feature maps by using some function to summarize subregions, such as taking the average or the maximum value.

    Pooling works by sliding a window across the input and feeding the content of -the window to a {\em pooling function}. In some sense, pooling works very much +the window to a pooling function. In some sense, pooling works very much like a discrete convolution, but replaces the linear combination described by -the kernel with some other function. Poolin -provides an example for average pooling, and -does the same for max pooling. -

    - -

    The following properties affect the output size \( o_j \) of a pooling layer -along axis \( j \): -

    - -
      -
    1. \( i_j \): input size along axis \( j \),
    2. -
    3. \( k_j \): pooling window size along axis \( j \),
    4. -
    5. \( s_j \): stride (distance between two consecutive positions of the pooling window) along axis \( j \).
    6. -
    -

    The analysis of the relationship between convolutional layer properties is eased -by the fact that they don't interact across axes, i.e., the choice of kernel -size, stride and zero padding along axis \( j \) only affects the output size of -axis \( j \). Because of that, we will focus on the following simplified -setting: -

    - -
      -
    1. 2-D discrete convolutions (\( N = 2 \)),
    2. -
    3. square inputs (\( i_1 = i_2 = i \)),
    4. -
    5. square kernel size (\( k_1 = k_2 = k \)),
    6. -
    7. same strides along both axes (\( s_1 = s_2 = s \)),
    8. -
    9. same zero padding along both axes (\( p_1 = p_2 = p \)).
    10. -
    -

    This facilitates the analysis and the visualization, but keep in mind that the -results outlined here also generalize to the N-D and non-square cases. -

    - -









    -

    No zero padding, unit strides

    - -

    The simplest case to analyze is when the kernel just slides across every -position of the input (i.e., \( s = 1 \) and \( p = 0 \)). -

    - -

    For any \( i \) and \( k \), and for \( s = 1 \) and \( p = 0 \),

    -$$ -\begin{equation*} - o = (i - k) + 1. -\end{equation*} -$$ - - -









    -

    Zero padding, unit strides

    - -

    To factor in zero padding (i.e., only restricting to \( s = 1 \)), let's consider -its effect on the effective input size: padding with \( p \) zeros changes the -effective input size from \( i \) to \( i + 2p \). In the general case, we can infer the following -relationship -

    - -

    For any \( i \), \( k \) and \( p \), and for \( s = 1 \),

    -$$ -\begin{equation*} - o = (i - k) + 2p + 1. -\end{equation*} -$$ - - -









    -

    Half (same) padding

    - -

    Having the output size be the same as the input size (i.e., \( o = i \)) can be a -desirable property: -

    - -

    For any \( i \) and for \( k \) odd (\( k = 2n + 1, \quad n \in \mathbb{N} \)), \( s = 1 \) and -\( p = \lfloor k / 2 \rfloor = n \), -

    -$$ -\begin{equation*} -\begin{split} - o &= i + 2 \lfloor k / 2 \rfloor - (k - 1) \\ - &= i + 2n - 2n \\ - &= i. -\end{split} -\end{equation*} -$$ - - -









    -

    Full padding

    - -

    While convolving a kernel generally decreases the output size with -respect to the input size, sometimes the opposite is required. This can be -achieved with proper zero padding: -

    - -

    For any \( i \) and \( k \), and for \( p = k - 1 \) and \( s = 1 \),

    -$$ -\begin{equation*} -\begin{split} - o &= i + 2(k - 1) - (k - 1) \\ - &= i + (k - 1). -\end{split} -\end{equation*} -$$ - -

    This is sometimes referred to as full padding, because in this -setting every possible partial or complete superimposition of the kernel on the -input feature map is taken into account. +the kernel with some other function.











    @@ -1091,29 +1332,608 @@ mean or average pooling, which all share the same idea of aggregating the input locally by applying a non-linearity to the content of some patches.

    -

    Since pooling does not involve -zero padding, the relationship describing the general case is as follows: -

    - -

    For any \( i \), \( k \) and \( s \),

    -$$ -\begin{equation*} - o = \left\lfloor \frac{i - k}{s} \right\rfloor + 1. -\end{equation*} -$$ - -









    Pooling types (From Raschka et al)


    -

    Figure 6: A deep CNN

    +

    Figure 5: A deep CNN

    +









    +

    Building convolutional neural networks in Tensorflow and Keras

    + +

    As discussed above, CNNs are neural networks built from the assumption that the inputs +to the network are 2D images. This is important because the number of features or pixels in images +grows very fast with the image size, and an enormous number of weights and biases are needed in order to build an accurate network. +

    + +

    As before, we still have our input, a hidden layer and an output. What's novel about convolutional networks +are the convolutional and pooling layers stacked in pairs between the input and the hidden layer. +In addition, the data is no longer represented as a 2D feature matrix, instead each input is a number of 2D +matrices, typically 1 for each color dimension (Red, Green, Blue). +

    + +









    +

    Setting it up

    + +

    It means that to represent the entire +dataset of images, we require a 4D matrix or tensor. This tensor has the dimensions: +

    +$$ +(n_{inputs},\, n_{pixels, width},\, n_{pixels, height},\, depth) . +$$ + + +









    +

    The MNIST dataset again

    + +

    The MNIST dataset consists of grayscale images with a pixel size of +\( 28\times 28 \), meaning we require \( 28 \times 28 = 724 \) weights to each +neuron in the first hidden layer. +

    + +

    If we were to analyze images of size \( 128\times 128 \) we would require +\( 128 \times 128 = 16384 \) weights to each neuron. Even worse if we were +dealing with color images, as most images are, we have an image matrix +of size \( 128\times 128 \) for each color dimension (Red, Green, Blue), +meaning 3 times the number of weights \( = 49152 \) are required for every +single neuron in the first hidden layer. +

    + + +









    +

    Strong correlations

    + +

    Images typically have strong local correlations, meaning that a small +part of the image varies little from its neighboring regions. If for +example we have an image of a blue car, we can roughly assume that a +small blue part of the image is surrounded by other blue regions. +

    + +

    Therefore, instead of connecting every single pixel to a neuron in the +first hidden layer, as we have previously done with deep neural +networks, we can instead connect each neuron to a small part of the +image (in all 3 RGB depth dimensions). The size of each small area is +fixed, and known as a receptive. +

    + + + +

    Layers of a CNN

    + +

    The layers of a convolutional neural network arrange neurons in 3D: width, height and depth. +The input image is typically a square matrix of depth 3. +

    + +

    A convolution is performed on the image which outputs +a 3D volume of neurons. The weights to the input are arranged in a number of 2D matrices, known as filters. +

    + +

    Each filter slides along the input image, taking the dot product +between each small part of the image and the filter, in all depth +dimensions. This is then passed through a non-linear function, +typically the Rectified Linear (ReLu) function, which serves as the +activation of the neurons in the first convolutional layer. This is +further passed through a pooling layer, which reduces the size of the +convolutional layer, e.g. by taking the maximum or average across some +small regions, and this serves as input to the next convolutional +layer. +

    + +









    +

    Systematic reduction

    + +

    By systematically reducing the size of the input volume, through +convolution and pooling, the network should create representations of +small parts of the input, and then from them assemble representations +of larger areas. The final pooling layer is flattened to serve as +input to a hidden layer, such that each neuron in the final pooling +layer is connected to every single neuron in the hidden layer. This +then serves as input to the output layer, e.g. a softmax output for +classification. +

    + + +









    +

    Prerequisites: Collect and pre-process data

    + + +
    +
    +
    +
    +
    +
    # import necessary packages
    +import numpy as np
    +import matplotlib.pyplot as plt
    +from sklearn import datasets
    +
    +
    +# ensure the same random numbers appear every time
    +np.random.seed(0)
    +
    +# display images in notebook
    +%matplotlib inline
    +plt.rcParams['figure.figsize'] = (12,12)
    +
    +
    +# download MNIST dataset
    +digits = datasets.load_digits()
    +
    +# define inputs and labels
    +inputs = digits.images
    +labels = digits.target
    +
    +# RGB images have a depth of 3
    +# our images are grayscale so they should have a depth of 1
    +inputs = inputs[:,:,:,np.newaxis]
    +
    +print("inputs = (n_inputs, pixel_width, pixel_height, depth) = " + str(inputs.shape))
    +print("labels = (n_inputs) = " + str(labels.shape))
    +
    +
    +# choose some random images to display
    +n_inputs = len(inputs)
    +indices = np.arange(n_inputs)
    +random_indices = np.random.choice(indices, size=5)
    +
    +for i, image in enumerate(digits.images[random_indices]):
    +    plt.subplot(1, 5, i+1)
    +    plt.axis('off')
    +    plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
    +    plt.title("Label: %d" % digits.target[random_indices[i]])
    +plt.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    Importing Keras and Tensorflow

    + + +
    +
    +
    +
    +
    +
    from tensorflow.keras import datasets, layers, models
    +from tensorflow.keras.layers import Input
    +from tensorflow.keras.models import Sequential      #This allows appending layers to existing models
    +from tensorflow.keras.layers import Dense           #This allows defining the characteristics of a particular layer
    +from tensorflow.keras import optimizers             #This allows using whichever optimiser we want (sgd,adam,RMSprop)
    +from tensorflow.keras import regularizers           #This allows using whichever regularizer we want (l1,l2,l1_l2)
    +from tensorflow.keras.utils import to_categorical   #This allows using categorical cross entropy as the cost function
    +#from tensorflow.keras import Conv2D
    +#from tensorflow.keras import MaxPooling2D
    +#from tensorflow.keras import Flatten
    +
    +from sklearn.model_selection import train_test_split
    +
    +# representation of labels
    +labels = to_categorical(labels)
    +
    +# split into train and test data
    +# one-liner from scikit-learn library
    +train_size = 0.8
    +test_size = 1 - train_size
    +X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,
    +                                                    test_size=test_size)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + + +

    Running with Keras

    + + + +
    +
    +
    +
    +
    +
    def create_convolutional_neural_network_keras(input_shape, receptive_field,
    +                                              n_filters, n_neurons_connected, n_categories,
    +                                              eta, lmbd):
    +    model = Sequential()
    +    model.add(layers.Conv2D(n_filters, (receptive_field, receptive_field), input_shape=input_shape, padding='same',
    +              activation='relu', kernel_regularizer=regularizers.l2(lmbd)))
    +    model.add(layers.MaxPooling2D(pool_size=(2, 2)))
    +    model.add(layers.Flatten())
    +    model.add(layers.Dense(n_neurons_connected, activation='relu', kernel_regularizer=regularizers.l2(lmbd)))
    +    model.add(layers.Dense(n_categories, activation='softmax', kernel_regularizer=regularizers.l2(lmbd)))
    +    
    +    sgd = optimizers.SGD(lr=eta)
    +    model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])
    +    
    +    return model
    +
    +epochs = 100
    +batch_size = 100
    +input_shape = X_train.shape[1:4]
    +receptive_field = 3
    +n_filters = 10
    +n_neurons_connected = 50
    +n_categories = 10
    +
    +eta_vals = np.logspace(-5, 1, 7)
    +lmbd_vals = np.logspace(-5, 1, 7)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    Final part

    + + + +
    +
    +
    +
    +
    +
    CNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
    +        
    +for i, eta in enumerate(eta_vals):
    +    for j, lmbd in enumerate(lmbd_vals):
    +        CNN = create_convolutional_neural_network_keras(input_shape, receptive_field,
    +                                              n_filters, n_neurons_connected, n_categories,
    +                                              eta, lmbd)
    +        CNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0)
    +        scores = CNN.evaluate(X_test, Y_test)
    +        
    +        CNN_keras[i][j] = CNN
    +        
    +        print("Learning rate = ", eta)
    +        print("Lambda = ", lmbd)
    +        print("Test accuracy: %.3f" % scores[1])
    +        print()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    Final visualization

    + + + +
    +
    +
    +
    +
    +
    # visual representation of grid search
    +# uses seaborn heatmap, could probably do this in matplotlib
    +import seaborn as sns
    +
    +sns.set()
    +
    +train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
    +test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
    +
    +for i in range(len(eta_vals)):
    +    for j in range(len(lmbd_vals)):
    +        CNN = CNN_keras[i][j]
    +
    +        train_accuracy[i][j] = CNN.evaluate(X_train, Y_train)[1]
    +        test_accuracy[i][j] = CNN.evaluate(X_test, Y_test)[1]
    +
    +        
    +fig, ax = plt.subplots(figsize = (10, 10))
    +sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
    +ax.set_title("Training Accuracy")
    +ax.set_ylabel("$\eta$")
    +ax.set_xlabel("$\lambda$")
    +plt.show()
    +
    +fig, ax = plt.subplots(figsize = (10, 10))
    +sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
    +ax.set_title("Test Accuracy")
    +ax.set_ylabel("$\eta$")
    +ax.set_xlabel("$\lambda$")
    +plt.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    The CIFAR01 data set

    + +

    The CIFAR10 dataset contains 60,000 color images in 10 classes, with +6,000 images in each class. The dataset is divided into 50,000 +training images and 10,000 testing images. The classes are mutually +exclusive and there is no overlap between them. +

    + + + +
    +
    +
    +
    +
    +
    import tensorflow as tf
    +
    +from tensorflow.keras import datasets, layers, models
    +import matplotlib.pyplot as plt
    +
    +# We import the data set
    +(train_images, train_labels), (test_images, test_labels) = datasets.cifar10.load_data()
    +
    +# Normalize pixel values to be between 0 and 1 by dividing by 255. 
    +train_images, test_images = train_images / 255.0, test_images / 255.0
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    Verifying the data set

    + +

    To verify that the dataset looks correct, let's plot the first 25 images from the training set and display the class name below each image.

    + + + +
    +
    +
    +
    +
    +
    class_names = ['airplane', 'automobile', 'bird', 'cat', 'deer',
    +               'dog', 'frog', 'horse', 'ship', 'truck']
    +plt.figure(figsize=(10,10))
    +for i in range(25):
    +    plt.subplot(5,5,i+1)
    +    plt.xticks([])
    +    plt.yticks([])
    +    plt.grid(False)
    +    plt.imshow(train_images[i], cmap=plt.cm.binary)
    +    # The CIFAR labels happen to be arrays, 
    +    # which is why you need the extra index
    +    plt.xlabel(class_names[train_labels[i][0]])
    +plt.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    Set up the model

    + +

    The 6 lines of code below define the convolutional base using a common pattern: a stack of Conv2D and MaxPooling2D layers.

    + +

    As input, a CNN takes tensors of shape (image_height, image_width, color_channels), ignoring the batch size. If you are new to these dimensions, color_channels refers to (R,G,B). In this example, you will configure our CNN to process inputs of shape (32, 32, 3), which is the format of CIFAR images. You can do this by passing the argument input_shape to our first layer.

    + + + +
    +
    +
    +
    +
    +
    model = models.Sequential()
    +model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)))
    +model.add(layers.MaxPooling2D((2, 2)))
    +model.add(layers.Conv2D(64, (3, 3), activation='relu'))
    +model.add(layers.MaxPooling2D((2, 2)))
    +model.add(layers.Conv2D(64, (3, 3), activation='relu'))
    +
    +# Let's display the architecture of our model so far.
    +
    +model.summary()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    You can see that the output of every Conv2D and MaxPooling2D layer is a 3D tensor of shape (height, width, channels). The width and height dimensions tend to shrink as you go deeper in the network. The number of output channels for each Conv2D layer is controlled by the first argument (e.g., 32 or 64). Typically, as the width and height shrink, you can afford (computationally) to add more output channels in each Conv2D layer.

    + +









    +

    Add Dense layers on top

    + +

    To complete our model, you will feed the last output tensor from the +convolutional base (of shape (4, 4, 64)) into one or more Dense layers +to perform classification. Dense layers take vectors as input (which +are 1D), while the current output is a 3D tensor. First, you will +flatten (or unroll) the 3D output to 1D, then add one or more Dense +layers on top. CIFAR has 10 output classes, so you use a final Dense +layer with 10 outputs and a softmax activation. +

    + + + +
    +
    +
    +
    +
    +
    model.add(layers.Flatten())
    +model.add(layers.Dense(64, activation='relu'))
    +model.add(layers.Dense(10))
    +Here's the complete architecture of our model.
    +
    +model.summary()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    As you can see, our (4, 4, 64) outputs were flattened into vectors of shape (1024) before going through two Dense layers.

    + +









    +

    Compile and train the model

    + + + +
    +
    +
    +
    +
    +
    model.compile(optimizer='adam',
    +              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
    +              metrics=['accuracy'])
    +
    +history = model.fit(train_images, train_labels, epochs=10, 
    +                    validation_data=(test_images, test_labels))
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    Finally, evaluate the model

    + + + +
    +
    +
    +
    +
    +
    plt.plot(history.history['accuracy'], label='accuracy')
    +plt.plot(history.history['val_accuracy'], label = 'val_accuracy')
    +plt.xlabel('Epoch')
    +plt.ylabel('Accuracy')
    +plt.ylim([0.5, 1])
    +plt.legend(loc='lower right')
    +
    +test_loss, test_acc = model.evaluate(test_images,  test_labels, verbose=2)
    +
    +print(test_acc)
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +









    Building our own CNN code

    @@ -1123,6 +1943,8 @@ the codebase and fit a CNN that yields a 99% accuracy on the 28x28 MNIST dataset within reasonable time.

    +The codes here were developed by Eric Reber and Gregor Kajda during spring 2023. +

    The CNN is compatible with all schedulers, cost functions and activation functions discussed in constructing our neural network codes. @@ -1613,28 +2435,28 @@ $$ (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 +

    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 +\( (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: +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]. +(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 +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]. +(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 @@ -1646,7 +2468,7 @@ 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 \) +suppose we have an image \( f \) of dimension \( 6 \times 6 \)

    $$ @@ -1660,7 +2482,7 @@ f = \begin{bmatrix} \end{bmatrix} $$ -

    and a \( 3 \times 3 \) kernel g called a low-pass filter. Note that the +

    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.

    @@ -1675,9 +2497,9 @@ g = \frac{1}{9} $$

    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 +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: +kernel \( g \):

    $$ @@ -1698,21 +2520,21 @@ $$ \frac{9}{9} & \frac{5}{9} & \frac{9}{9} \\ \frac{1}{9} & \frac{5}{9} & \frac{9}{9} \\ \end {bmatrix} -= \textbf{A} += \boldsymbol{A} $$ -

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

    +

    Then, following the multiplication, we summarize all the elements of the resulting matrix \( \boldsymbol{A} \):

    $$ -(f \ast g)[0, 0]= \sum_{i=0}^{2} \sum_{j=0}^{2} a_{i,j} = 5 +(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) \).

    +

    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 +

    Here we use a stride of \( S=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 +\( 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 @@ -1731,18 +2553,23 @@ $$ \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. +

    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 +r =\lfloor \frac{\mathrm{kernel height}}{2} \rfloor \cdot 2 \\ +c =\lfloor \frac{\mathrm{kernel width}}{2} \rfloor \cdot 2 $$ -

    Note the notation \( \lfloor \frac{kernel width}{2} \rfloor \) means that +

    Note the notation \( \lfloor \frac{\mathrm{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 in case \( \frac{\mathrm{kernel width}}{2} \) results in a floating point number.

    @@ -1768,11 +2595,13 @@ $$ 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} +\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. 

    +

    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.~ +

    @@ -1867,9 +2696,10 @@ $$
    -

    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 that is not +rotated by 180 degrees is called cross-correlation, which is normally implemented in most libraries.

    @@ -1929,7 +2759,7 @@ feed forward neural network.
    -
    # Now an example using a real image and first a gaussian low-pass filter and then a sobel filter
    +  
    # 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
    @@ -3956,7 +4786,7 @@ cnn.add_OutputLayer(Building convolutional neural networks in Tensorflow and Keras 
    -
    -

    As discussed above, CNNs are neural networks built from the assumption that the inputs -to the network are 2D images. This is important because the number of features or pixels in images -grows very fast with the image size, and an enormous number of weights and biases are needed in order to build an accurate network. -

    - -

    As before, we still have our input, a hidden layer and an output. What's novel about convolutional networks -are the convolutional and pooling layers stacked in pairs between the input and the hidden layer. -In addition, the data is no longer represented as a 2D feature matrix, instead each input is a number of 2D -matrices, typically 1 for each color dimension (Red, Green, Blue). -

    - -









    -

    Setting it up

    - -

    It means that to represent the entire -dataset of images, we require a 4D matrix or tensor. This tensor has the dimensions: -

    -$$ -(n_{inputs},\, n_{pixels, width},\, n_{pixels, height},\, depth) . -$$ - - -









    -

    The MNIST dataset again

    - -

    The MNIST dataset consists of grayscale images with a pixel size of -\( 28\times 28 \), meaning we require \( 28 \times 28 = 724 \) weights to each -neuron in the first hidden layer. -

    - -

    If we were to analyze images of size \( 128\times 128 \) we would require -\( 128 \times 128 = 16384 \) weights to each neuron. Even worse if we were -dealing with color images, as most images are, we have an image matrix -of size \( 128\times 128 \) for each color dimension (Red, Green, Blue), -meaning 3 times the number of weights \( = 49152 \) are required for every -single neuron in the first hidden layer. -

    - - -









    -

    Strong correlations

    - -

    Images typically have strong local correlations, meaning that a small -part of the image varies little from its neighboring regions. If for -example we have an image of a blue car, we can roughly assume that a -small blue part of the image is surrounded by other blue regions. -

    - -

    Therefore, instead of connecting every single pixel to a neuron in the -first hidden layer, as we have previously done with deep neural -networks, we can instead connect each neuron to a small part of the -image (in all 3 RGB depth dimensions). The size of each small area is -fixed, and known as a receptive. -

    - - - -

    Layers of a CNN

    - -

    The layers of a convolutional neural network arrange neurons in 3D: width, height and depth. -The input image is typically a square matrix of depth 3. -

    - -

    A convolution is performed on the image which outputs -a 3D volume of neurons. The weights to the input are arranged in a number of 2D matrices, known as filters. -

    - -

    Each filter slides along the input image, taking the dot product -between each small part of the image and the filter, in all depth -dimensions. This is then passed through a non-linear function, -typically the Rectified Linear (ReLu) function, which serves as the -activation of the neurons in the first convolutional layer. This is -further passed through a pooling layer, which reduces the size of the -convolutional layer, e.g. by taking the maximum or average across some -small regions, and this serves as input to the next convolutional -layer. -

    - -









    -

    Systematic reduction

    - -

    By systematically reducing the size of the input volume, through -convolution and pooling, the network should create representations of -small parts of the input, and then from them assemble representations -of larger areas. The final pooling layer is flattened to serve as -input to a hidden layer, such that each neuron in the final pooling -layer is connected to every single neuron in the hidden layer. This -then serves as input to the output layer, e.g. a softmax output for -classification. -

    - - -









    -

    Prerequisites: Collect and pre-process data

    - - -
    -
    -
    -
    -
    -
    # import necessary packages
    -import numpy as np
    -import matplotlib.pyplot as plt
    -from sklearn import datasets
    -
    -
    -# ensure the same random numbers appear every time
    -np.random.seed(0)
    -
    -# display images in notebook
    -%matplotlib inline
    -plt.rcParams['figure.figsize'] = (12,12)
    -
    -
    -# download MNIST dataset
    -digits = datasets.load_digits()
    -
    -# define inputs and labels
    -inputs = digits.images
    -labels = digits.target
    -
    -# RGB images have a depth of 3
    -# our images are grayscale so they should have a depth of 1
    -inputs = inputs[:,:,:,np.newaxis]
    -
    -print("inputs = (n_inputs, pixel_width, pixel_height, depth) = " + str(inputs.shape))
    -print("labels = (n_inputs) = " + str(labels.shape))
    -
    -
    -# choose some random images to display
    -n_inputs = len(inputs)
    -indices = np.arange(n_inputs)
    -random_indices = np.random.choice(indices, size=5)
    -
    -for i, image in enumerate(digits.images[random_indices]):
    -    plt.subplot(1, 5, i+1)
    -    plt.axis('off')
    -    plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
    -    plt.title("Label: %d" % digits.target[random_indices[i]])
    -plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    Importing Keras and Tensorflow

    - - -
    -
    -
    -
    -
    -
    from tensorflow.keras import datasets, layers, models
    -from tensorflow.keras.layers import Input
    -from tensorflow.keras.models import Sequential      #This allows appending layers to existing models
    -from tensorflow.keras.layers import Dense           #This allows defining the characteristics of a particular layer
    -from tensorflow.keras import optimizers             #This allows using whichever optimiser we want (sgd,adam,RMSprop)
    -from tensorflow.keras import regularizers           #This allows using whichever regularizer we want (l1,l2,l1_l2)
    -from tensorflow.keras.utils import to_categorical   #This allows using categorical cross entropy as the cost function
    -#from tensorflow.keras import Conv2D
    -#from tensorflow.keras import MaxPooling2D
    -#from tensorflow.keras import Flatten
    -
    -from sklearn.model_selection import train_test_split
    -
    -# representation of labels
    -labels = to_categorical(labels)
    -
    -# split into train and test data
    -# one-liner from scikit-learn library
    -train_size = 0.8
    -test_size = 1 - train_size
    -X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,
    -                                                    test_size=test_size)
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - - -

    Running with Keras

    - - - -
    -
    -
    -
    -
    -
    def create_convolutional_neural_network_keras(input_shape, receptive_field,
    -                                              n_filters, n_neurons_connected, n_categories,
    -                                              eta, lmbd):
    -    model = Sequential()
    -    model.add(layers.Conv2D(n_filters, (receptive_field, receptive_field), input_shape=input_shape, padding='same',
    -              activation='relu', kernel_regularizer=regularizers.l2(lmbd)))
    -    model.add(layers.MaxPooling2D(pool_size=(2, 2)))
    -    model.add(layers.Flatten())
    -    model.add(layers.Dense(n_neurons_connected, activation='relu', kernel_regularizer=regularizers.l2(lmbd)))
    -    model.add(layers.Dense(n_categories, activation='softmax', kernel_regularizer=regularizers.l2(lmbd)))
    -    
    -    sgd = optimizers.SGD(learning_rate=eta)
    -    model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])
    -    
    -    return model
    -
    -epochs = 100
    -batch_size = 100
    -input_shape = X_train.shape[1:4]
    -receptive_field = 3
    -n_filters = 10
    -n_neurons_connected = 50
    -n_categories = 10
    -
    -eta_vals = np.logspace(-5, 1, 7)
    -lmbd_vals = np.logspace(-5, 1, 7)
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    Final part

    - - - -
    -
    -
    -
    -
    -
    CNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)
    -        
    -for i, eta in enumerate(eta_vals):
    -    for j, lmbd in enumerate(lmbd_vals):
    -        CNN = create_convolutional_neural_network_keras(input_shape, receptive_field,
    -                                              n_filters, n_neurons_connected, n_categories,
    -                                              eta, lmbd)
    -        CNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0)
    -        scores = CNN.evaluate(X_test, Y_test)
    -        
    -        CNN_keras[i][j] = CNN
    -        
    -        print("Learning rate = ", eta)
    -        print("Lambda = ", lmbd)
    -        print("Test accuracy: %.3f" % scores[1])
    -        print()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - - -









    -

    Final visualization

    - - - -
    -
    -
    -
    -
    -
    # visual representation of grid search
    -# uses seaborn heatmap, could probably do this in matplotlib
    -import seaborn as sns
    -
    -sns.set()
    -
    -train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
    -test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))
    -
    -for i in range(len(eta_vals)):
    -    for j in range(len(lmbd_vals)):
    -        CNN = CNN_keras[i][j]
    -
    -        train_accuracy[i][j] = CNN.evaluate(X_train, Y_train)[1]
    -        test_accuracy[i][j] = CNN.evaluate(X_test, Y_test)[1]
    -
    -        
    -fig, ax = plt.subplots(figsize = (10, 10))
    -sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis")
    -ax.set_title("Training Accuracy")
    -ax.set_ylabel("$\eta$")
    -ax.set_xlabel("$\lambda$")
    -plt.show()
    -
    -fig, ax = plt.subplots(figsize = (10, 10))
    -sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis")
    -ax.set_title("Test Accuracy")
    -ax.set_ylabel("$\eta$")
    -ax.set_xlabel("$\lambda$")
    -plt.show()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    © 1999-2024, 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 ca0640db1..24586dcc3 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 749eec626..5ddacc548 100644 --- a/doc/pub/week44/ipynb/week44.ipynb +++ b/doc/pub/week44/ipynb/week44.ipynb @@ -2,7 +2,7 @@ "cells": [ { "cell_type": "markdown", - "id": "2f2e45af", + "id": "afaf8390", "metadata": { "editable": true }, @@ -14,7 +14,7 @@ }, { "cell_type": "markdown", - "id": "a72fad3a", + "id": "f17d25d5", "metadata": { "editable": true }, @@ -27,7 +27,7 @@ }, { "cell_type": "markdown", - "id": "f18b2d0e", + "id": "736a723a", "metadata": { "editable": true }, @@ -55,7 +55,7 @@ }, { "cell_type": "markdown", - "id": "6d98e193", + "id": "93caafca", "metadata": { "editable": true }, @@ -71,7 +71,7 @@ }, { "cell_type": "markdown", - "id": "4047cdc3", + "id": "c99e8ca9", "metadata": { "editable": true }, @@ -81,7 +81,7 @@ }, { "cell_type": "markdown", - "id": "dfaf7b2e", + "id": "5a52c2d6", "metadata": { "editable": true }, @@ -108,7 +108,7 @@ }, { "cell_type": "markdown", - "id": "c7006347", + "id": "05ae37f5", "metadata": { "editable": true }, @@ -124,7 +124,7 @@ }, { "cell_type": "markdown", - "id": "ae0e4359", + "id": "e174ca11", "metadata": { "editable": true }, @@ -142,7 +142,7 @@ }, { "cell_type": "markdown", - "id": "8e4de8da", + "id": "a8f5c3af", "metadata": { "editable": true }, @@ -172,7 +172,7 @@ }, { "cell_type": "markdown", - "id": "e5741900", + "id": "e784f567", "metadata": { "editable": true }, @@ -202,7 +202,7 @@ }, { "cell_type": "markdown", - "id": "37f1f2f5", + "id": "d28632ea", "metadata": { "editable": true }, @@ -242,7 +242,7 @@ }, { "cell_type": "markdown", - "id": "74f9a266", + "id": "8fdd2e1e", "metadata": { "editable": true }, @@ -269,7 +269,7 @@ }, { "cell_type": "markdown", - "id": "a18c56c1", + "id": "fe077130", "metadata": { "editable": true }, @@ -281,7 +281,7 @@ }, { "cell_type": "markdown", - "id": "cc22cab9", + "id": "62200bea", "metadata": { "editable": true }, @@ -291,7 +291,7 @@ }, { "cell_type": "markdown", - "id": "ac776ad9", + "id": "64a09aab", "metadata": { "editable": true }, @@ -309,7 +309,7 @@ }, { "cell_type": "markdown", - "id": "6082bd12", + "id": "ec7a27eb", "metadata": { "editable": true }, @@ -338,7 +338,7 @@ }, { "cell_type": "markdown", - "id": "53cb4ec8", + "id": "891c4e18", "metadata": { "editable": true }, @@ -360,7 +360,7 @@ }, { "cell_type": "markdown", - "id": "27ff37df", + "id": "f9a224d5", "metadata": { "editable": true }, @@ -382,7 +382,7 @@ }, { "cell_type": "markdown", - "id": "caa0560a", + "id": "74ebf7e1", "metadata": { "editable": true }, @@ -398,7 +398,7 @@ }, { "cell_type": "markdown", - "id": "e2b649c6", + "id": "127a2805", "metadata": { "editable": true }, @@ -415,7 +415,113 @@ }, { "cell_type": "markdown", - "id": "b9e5408b", + "id": "bdfeefdc", + "metadata": { + "editable": true + }, + "source": [ + "## How to do image compression before the era of deep learning\n", + "\n", + "The singular-value decomposition (SVD) algorithm has been for decades one of the standard ways of compressing images.\n", + "The [lectures on the SVD](https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/chapter2.html#the-singular-value-decomposition) give many of the essential details concerning the SVD.\n", + "\n", + "The orthogonal vectors which are obtained from the SVD, can be used to\n", + "project down the dimensionality of a given image. In the example here\n", + "we gray-scale an image and downsize it.\n", + "\n", + "This recipe relies on us being able to actually perform the SVD. For\n", + "large images, and in particular with many images to reconstruct, using the SVD \n", + "may quickly become an overwhelming task. With the advent of efficient deep\n", + "learning methods like CNNs and later generative methods, these methods\n", + "have become in the last years the premier way of performing image\n", + "analysis. In particular for classification problems with labelled images." + ] + }, + { + "cell_type": "markdown", + "id": "5b9c0de1", + "metadata": { + "editable": true + }, + "source": [ + "## The SVD example" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "id": "36668e14", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "%matplotlib inline\n", + "\n", + "from matplotlib.image import imread\n", + "import matplotlib.pyplot as plt\n", + "import scipy.linalg as ln\n", + "import numpy as np\n", + "import os\n", + "from PIL import Image\n", + "from math import log10, sqrt \n", + "plt.rcParams['figure.figsize'] = [16, 8]\n", + "# Import image\n", + "A = imread(os.path.join(\"figslides/photo1.jpg\"))\n", + "X = A.dot([0.299, 0.5870, 0.114]) # Convert RGB to grayscale\n", + "img = plt.imshow(X)\n", + "# convert to gray\n", + "img.set_cmap('gray')\n", + "plt.axis('off')\n", + "plt.show()\n", + "# Call image size\n", + "print(': %s'%str(X.shape))\n", + "\n", + "\n", + "# split the matrix into U, S, VT\n", + "U, S, VT = np.linalg.svd(X,full_matrices=False)\n", + "S = np.diag(S)\n", + "m = 800 # Image's width\n", + "n = 1200 # Image's height\n", + "j = 0\n", + "# Try compression with different k vectors (these represent projections):\n", + "for k in (5,10, 20, 100,200,400,500):\n", + " # Original size of the image\n", + " originalSize = m * n \n", + " # Size after compressed\n", + " compressedSize = k * (1 + m + n) \n", + " # The projection of the original image\n", + " Xapprox = U[:,:k] @ S[0:k,:k] @ VT[:k,:]\n", + " plt.figure(j+1)\n", + " j += 1\n", + " img = plt.imshow(Xapprox)\n", + " img.set_cmap('gray')\n", + " \n", + " plt.axis('off')\n", + " plt.title('k = ' + str(k))\n", + " plt.show() \n", + " print('Original size of image:')\n", + " print(originalSize)\n", + " print('Compression rate as Compressed image / Original size:')\n", + " ratio = compressedSize * 1.0 / originalSize\n", + " print(ratio)\n", + " print('Compression rate is ' + str( round(ratio * 100 ,2)) + '%' ) \n", + " # Estimate MQA\n", + " x= X.astype(\"float\")\n", + " y=Xapprox.astype(\"float\")\n", + " err = np.sum((x - y) ** 2)\n", + " err /= float(X.shape[0] * Xapprox.shape[1])\n", + " print('The mean-square deviation '+ str(round( err)))\n", + " max_pixel = 255.0\n", + " # Estimate Signal Noise Ratio\n", + " srv = 20 * (log10(max_pixel / sqrt(err)))\n", + " print('Signa to noise ratio '+ str(round(srv)) +'dB')" + ] + }, + { + "cell_type": "markdown", + "id": "68fd7bf4", "metadata": { "editable": true }, @@ -438,7 +544,7 @@ }, { "cell_type": "markdown", - "id": "2c4541a9", + "id": "af30ff6d", "metadata": { "editable": true }, @@ -450,7 +556,7 @@ }, { "cell_type": "markdown", - "id": "c6ceee4f", + "id": "0b6a0a87", "metadata": { "editable": true }, @@ -462,7 +568,7 @@ }, { "cell_type": "markdown", - "id": "728f683d", + "id": "06204c0f", "metadata": { "editable": true }, @@ -474,7 +580,7 @@ }, { "cell_type": "markdown", - "id": "528c85e8", + "id": "f793221b", "metadata": { "editable": true }, @@ -484,7 +590,7 @@ }, { "cell_type": "markdown", - "id": "34e6559a", + "id": "754789c3", "metadata": { "editable": true }, @@ -496,7 +602,7 @@ }, { "cell_type": "markdown", - "id": "cc39daf4", + "id": "edaf2d6b", "metadata": { "editable": true }, @@ -508,7 +614,100 @@ }, { "cell_type": "markdown", - "id": "a538fef9", + "id": "c10e0e6e", + "metadata": { + "editable": true + }, + "source": [ + "## Mathematics of CNNs\n", + "\n", + "The mathematics of CNNs is based on the mathematical operation of\n", + "**convolution**. In mathematics (in particular in functional analysis),\n", + "convolution is represented by mathematical operations (integration,\n", + "summation etc) on two functions in order to produce a third function\n", + "that expresses how the shape of one gets modified by the other.\n", + "Convolution has a plethora of applications in a variety of\n", + "disciplines, spanning from statistics to signal processing, computer\n", + "vision, solutions of differential equations,linear algebra,\n", + "engineering, and yes, machine learning.\n", + "\n", + "Mathematically, convolution is defined as follows (one-dimensional example):\n", + "Let us define a continuous function $y(t)$ given by" + ] + }, + { + "cell_type": "markdown", + "id": "3e21ff12", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "y(t) = \\int x(a) w(t-a) da,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "763cf144", + "metadata": { + "editable": true + }, + "source": [ + "where $x(a)$ represents a so-called input and $w(t-a)$ is normally called the weight function or kernel.\n", + "\n", + "The above integral is written in a more compact form as" + ] + }, + { + "cell_type": "markdown", + "id": "d50d06cc", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "y(t) = \\left(x * w\\right)(t).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "6924641b", + "metadata": { + "editable": true + }, + "source": [ + "The discretized version reads" + ] + }, + { + "cell_type": "markdown", + "id": "187e8990", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "y(t) = \\sum_{a=-\\infty}^{a=\\infty}x(a)w(t-a).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "6470335b", + "metadata": { + "editable": true + }, + "source": [ + "Computing the inverse of the above convolution operations is known as deconvolution and the process is commutative.\n", + "\n", + "How can we use this? And what does it mean? Let us study some familiar examples first." + ] + }, + { + "cell_type": "markdown", + "id": "ec95c776", "metadata": { "editable": true }, @@ -527,7 +726,7 @@ }, { "cell_type": "markdown", - "id": "4936649a", + "id": "d4b3c227", "metadata": { "editable": true }, @@ -539,7 +738,7 @@ }, { "cell_type": "markdown", - "id": "bcc8f865", + "id": "9d58c7b8", "metadata": { "editable": true }, @@ -549,7 +748,7 @@ }, { "cell_type": "markdown", - "id": "914a9307", + "id": "122efa36", "metadata": { "editable": true }, @@ -561,7 +760,7 @@ }, { "cell_type": "markdown", - "id": "a34a624b", + "id": "195156ea", "metadata": { "editable": true }, @@ -571,7 +770,7 @@ }, { "cell_type": "markdown", - "id": "90c3cde7", + "id": "19dc2f3a", "metadata": { "editable": true }, @@ -583,7 +782,7 @@ }, { "cell_type": "markdown", - "id": "5bc6a269", + "id": "4f9f3064", "metadata": { "editable": true }, @@ -596,7 +795,7 @@ }, { "cell_type": "markdown", - "id": "8d72962e", + "id": "478460ae", "metadata": { "editable": true }, @@ -615,7 +814,7 @@ }, { "cell_type": "markdown", - "id": "16256c3c", + "id": "e73dc29f", "metadata": { "editable": true }, @@ -627,7 +826,7 @@ }, { "cell_type": "markdown", - "id": "f4851858", + "id": "5fc26071", "metadata": { "editable": true }, @@ -639,7 +838,7 @@ }, { "cell_type": "markdown", - "id": "c0df4f1d", + "id": "555caa5e", "metadata": { "editable": true }, @@ -649,7 +848,7 @@ }, { "cell_type": "markdown", - "id": "af9edfb7", + "id": "1e18c64b", "metadata": { "editable": true }, @@ -661,7 +860,7 @@ }, { "cell_type": "markdown", - "id": "1c24de9c", + "id": "8f490b21", "metadata": { "editable": true }, @@ -673,7 +872,7 @@ }, { "cell_type": "markdown", - "id": "35cf2246", + "id": "ed3baa45", "metadata": { "editable": true }, @@ -685,17 +884,18 @@ }, { "cell_type": "markdown", - "id": "28b59952", + "id": "2cb35d1f", "metadata": { "editable": true }, "source": [ - "where $m=3$ in our case, the maximum length of the vector $\\alpha$. Note that the vector $\\boldsymbol{\\beta}$ has length $n=4$." + "where $m=3$ in our case, the maximum length of\n", + "the vector $\\alpha$. Note that the vector $\\boldsymbol{\\beta}$ has length $n=4$. Below we will find an even more efficient representation." ] }, { "cell_type": "markdown", - "id": "180983f3", + "id": "b3a4e62a", "metadata": { "editable": true }, @@ -709,7 +909,7 @@ }, { "cell_type": "markdown", - "id": "a69653d6", + "id": "fbc69d73", "metadata": { "editable": true }, @@ -727,18 +927,20 @@ }, { "cell_type": "markdown", - "id": "cacaacab", + "id": "c2692c2d", "metadata": { "editable": true }, "source": [ + "## Commutative process\n", + "\n", "The process is commutative and we can easily see that we can rewrite the multiplication in terms of a matrix holding $\\beta$ and a vector holding $\\alpha$.\n", "In this case we have" ] }, { "cell_type": "markdown", - "id": "761b90f3", + "id": "cdcce1ea", "metadata": { "editable": true }, @@ -756,7 +958,7 @@ }, { "cell_type": "markdown", - "id": "109f2d7f", + "id": "5e82c416", "metadata": { "editable": true }, @@ -765,7 +967,17 @@ "and not implementation purposes. When implementing the above equation\n", "we do not encode (and allocate memory) the matrices explicitely. We\n", "rather code the convolutions in the minimal memory footprint that they\n", - "require.\n", + "require." + ] + }, + { + "cell_type": "markdown", + "id": "066fb9c0", + "metadata": { + "editable": true + }, + "source": [ + "## Toeplitz matrices\n", "\n", "The above matrices are examples of so-called [Toeplitz\n", "matrices](https://link.springer.com/book/10.1007/978-93-86279-04-0). A\n", @@ -776,7 +988,7 @@ }, { "cell_type": "markdown", - "id": "a2bfd662", + "id": "7164a220", "metadata": { "editable": true }, @@ -794,7 +1006,7 @@ }, { "cell_type": "markdown", - "id": "4b1a63ee", + "id": "5b0b6645", "metadata": { "editable": true }, @@ -810,7 +1022,7 @@ }, { "cell_type": "markdown", - "id": "56498e0e", + "id": "78c20ffc", "metadata": { "editable": true }, @@ -825,33 +1037,38 @@ }, { "cell_type": "markdown", - "id": "adcf2b58", + "id": "7d6555e5", "metadata": { "editable": true }, "source": [ "## Generalizing the above one-dimensional case\n", "\n", - "In order to align the above simple case with the more general convolution cases, we rename $\\boldsymbol{\\alpha}$, whose length is $m=3$, with $\\boldsymbol{w}$.\n", - "We will interpret $\\boldsymbol{w}$ as a weight/filter function with which we want to perform the convolution with an input varibale $\\boldsymbol{x}$.\n", - "We replace thus $\\boldsymbol{\\beta}$ with $\\boldsymbol{x}$ and $\\boldsymbol{\\delta}$ with $\\boldsymbol{s}$ and have" + "In order to align the above simple case with the more general\n", + "convolution cases, we rename $\\boldsymbol{\\alpha}$, whose length is $m=3$,\n", + "with $\\boldsymbol{w}$. We will interpret $\\boldsymbol{w}$ as a weight/filter function\n", + "with which we want to perform the convolution with an input variable\n", + "$\\boldsymbol{x}$ of length $n$. We will assume always that the filter\n", + "$\\boldsymbol{w}$ has dimensionality $m \\le n$.\n", + "\n", + "We replace thus $\\boldsymbol{\\beta}$ with $\\boldsymbol{x}$ and $\\boldsymbol{\\delta}$ with $\\boldsymbol{y}$ and have" ] }, { "cell_type": "markdown", - "id": "a89ecd51", + "id": "cb3ae3f4", "metadata": { "editable": true }, "source": [ "$$\n", - "s(i) \\left(x*w\\right)(i)= \\sum_{k=0}^{k=m-1}w(k)x(i-k),\n", + "y(i)= \\left(x*w\\right)(i)= \\sum_{k=0}^{k=m-1}w(k)x(i-k),\n", "$$" ] }, { "cell_type": "markdown", - "id": "836affb6", + "id": "ba84498b", "metadata": { "editable": true }, @@ -862,12 +1079,249 @@ }, { "cell_type": "markdown", - "id": "831d1a03", + "id": "afdd9570", "metadata": { "editable": true }, "source": [ - "## Two-dimensional Objects\n", + "## Memory considerations\n", + "\n", + "This expression leaves us however with some terms with negative\n", + "indices, for example $x(-1)$ and $x(-2)$ which may not be defined. Our\n", + "vector $\\boldsymbol{x}$ has components $x(0)$, $x(1)$, $x(2)$ and $x(3)$.\n", + "\n", + "The index $j$ for $\\boldsymbol{x}$ runs from $j=0$ to $j=3$ since $\\boldsymbol{x}$ is meant to\n", + "represent a third-order polynomial.\n", + "\n", + "Furthermore, the index $i$ runs from $i=0$ to $i=5$ since $\\boldsymbol{y}$\n", + "contains the coefficients of a fifth-order polynomial. When $i=5$ we\n", + "may also have values of $x(4)$ and $x(5)$ which are not defined." + ] + }, + { + "cell_type": "markdown", + "id": "9d8a1259", + "metadata": { + "editable": true + }, + "source": [ + "## Padding\n", + "\n", + "The solution to this is what is called **padding**! We simply define a\n", + "new vector $x$ with two added elements set to zero before $x(0)$ and\n", + "two new elements after $x(3)$ set to zero. That is, we augment the\n", + "length of $\\boldsymbol{x}$ from $n=4$ to $n+2P=8$, where $P=2$ is the padding\n", + "constant (a new hyperparameter), see discussions below as well." + ] + }, + { + "cell_type": "markdown", + "id": "93166a7d", + "metadata": { + "editable": true + }, + "source": [ + "## New vector\n", + "\n", + "We have a new vector defined as $x(0)=0$, $x(1)=0$,\n", + "$x(2)=\\beta_0$, $x(3)=\\beta_1$, $x(4)=\\beta_2$, $x(5)=\\beta_3$,\n", + "$x(6)=0$, and $x(7)=0$.\n", + "\n", + "We have added four new elements, which\n", + "are all zero. The benefit is that we can rewrite the equation for\n", + "$\\boldsymbol{y}$, with $i=0,1,\\dots,5$," + ] + }, + { + "cell_type": "markdown", + "id": "217d00a9", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "y(i) = \\sum_{k=0}^{k=m-1}w(k)x(i+(m-1)-k).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "2dcc48bf", + "metadata": { + "editable": true + }, + "source": [ + "As an example, we have" + ] + }, + { + "cell_type": "markdown", + "id": "28874f6c", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "y(4)=x(6)w(0)+x(5)w(1)+x(4)w(2)=0\\times \\alpha_0+\\beta_3\\alpha_1+\\beta_2\\alpha_2,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "2ba7a9dc", + "metadata": { + "editable": true + }, + "source": [ + "as before except that we have an additional term $x(6)w(0)$, which is zero.\n", + "\n", + "Similarly, for the fifth-order term we have" + ] + }, + { + "cell_type": "markdown", + "id": "4daa6524", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "y(5)=x(7)w(0)+x(6)w(1)+x(5)w(2)=0\\times \\alpha_0+0\\times\\alpha_1+\\beta_3\\alpha_2.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "c5ef900a", + "metadata": { + "editable": true + }, + "source": [ + "The zeroth-order term is" + ] + }, + { + "cell_type": "markdown", + "id": "a8e76abb", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "y(0)=x(2)w(0)+x(1)w(1)+x(0)w(2)=\\beta_0 \\alpha_0+0\\times\\alpha_1+0\\times\\alpha_2=\\alpha_0\\beta_0.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "3c8e17ec", + "metadata": { + "editable": true + }, + "source": [ + "## Rewriting as dot products\n", + "\n", + "If we now flip the filter/weight vector, with the following term as a typical example" + ] + }, + { + "cell_type": "markdown", + "id": "965e447e", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "y(0)=x(2)w(0)+x(1)w(1)+x(0)w(2)=x(2)\\tilde{w}(2)+x(1)\\tilde{w}(1)+x(0)\\tilde{w}(0),\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "53e47b06", + "metadata": { + "editable": true + }, + "source": [ + "with $\\tilde{w}(0)=w(2)$, $\\tilde{w}(1)=w(1)$, and $\\tilde{w}(2)=w(0)$, we can then rewrite the above sum as a dot product of\n", + "$x(i:i+(m-1))\\tilde{w}$ for element $y(i)$, where $x(i:i+(m-1))$ is simply a patch of $\\boldsymbol{x}$ of size $m-1$.\n", + "\n", + "The padding $P$ we have introduced for the convolution stage is just\n", + "another hyperparameter which is introduced as part of the\n", + "architecture. Similarly, below we will also introduce another\n", + "hyperparameter called **Stride** $S$." + ] + }, + { + "cell_type": "markdown", + "id": "b7a66ef0", + "metadata": { + "editable": true + }, + "source": [ + "## Cross correlation\n", + "\n", + "In essentially all applications one uses what is called cross correlation instead of the standard convolution described above.\n", + "This means that multiplication is performed in the same direction and instead of the general expression we have discussed above (with infinite sums)" + ] + }, + { + "cell_type": "markdown", + "id": "bd4feb76", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "y(i) = \\sum_{k=-\\infty}^{k=\\infty}w(k)x(i-k),\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "1b68f20e", + "metadata": { + "editable": true + }, + "source": [ + "we have now" + ] + }, + { + "cell_type": "markdown", + "id": "76daf815", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "y(i) = \\sum_{k=-\\infty}^{k=\\infty}w(k)x(i+k).\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "79ff7b3c", + "metadata": { + "editable": true + }, + "source": [ + "Both TensorFlow and PyTorch (as well as our own code example below),\n", + "implement the last equation, although it is normally referred to as\n", + "convolution. The same padding rules and stride rules discussed below\n", + "apply to this expression as well.\n", + "\n", + "We leave it as an exercise for you to convince yourself that the example we have discussed till now, gives the same final expression using the last expression." + ] + }, + { + "cell_type": "markdown", + "id": "29705589", + "metadata": { + "editable": true + }, + "source": [ + "## Two-dimensional objects\n", "\n", "We are now ready to start studying the discrete convolutions relevant for convolutional neural networks.\n", "We often use convolutions over more than one dimension at a time. If\n", @@ -877,7 +1331,7 @@ }, { "cell_type": "markdown", - "id": "cf94b870", + "id": "8af7b9af", "metadata": { "editable": true }, @@ -889,7 +1343,7 @@ }, { "cell_type": "markdown", - "id": "bc772e6f", + "id": "860db2b8", "metadata": { "editable": true }, @@ -899,7 +1353,7 @@ }, { "cell_type": "markdown", - "id": "27cc1e68", + "id": "3eb3e476", "metadata": { "editable": true }, @@ -911,19 +1365,23 @@ }, { "cell_type": "markdown", - "id": "5da90b0b", + "id": "faf1c3be", "metadata": { "editable": true }, "source": [ - "Normally the latter is more straightforward to implement in a machine larning library since there is less variation in the range of values of $m$ and $n$.\n", + "Normally the latter is more straightforward to implement in a machine\n", + "larning library since there is less variation in the range of values\n", + "of $m$ and $n$.\n", "\n", - "Many deep learning libraries implement cross-correlation instead of convolution (although it is referred to s convolution)" + "As mentioned above, most deep learning libraries implement\n", + "cross-correlation instead of convolution (although it is referred to as\n", + "convolution)" ] }, { "cell_type": "markdown", - "id": "30c98ebe", + "id": "33a2839a", "metadata": { "editable": true }, @@ -935,12 +1393,12 @@ }, { "cell_type": "markdown", - "id": "93e1769f", + "id": "36a0a4cd", "metadata": { "editable": true }, "source": [ - "## CNNs in more detail\n", + "## CNNs in more detail, simple example\n", "\n", "Let assume we have an input matrix $X$ of dimensionality $3\\times 3$\n", "and a $2\\times 2$ filter $W$ given by the following matrices" @@ -948,7 +1406,7 @@ }, { "cell_type": "markdown", - "id": "b3ae8ad4", + "id": "c1d8190e", "metadata": { "editable": true }, @@ -962,7 +1420,7 @@ }, { "cell_type": "markdown", - "id": "1dd2b802", + "id": "d90132aa", "metadata": { "editable": true }, @@ -972,7 +1430,7 @@ }, { "cell_type": "markdown", - "id": "89afce18", + "id": "1bc5f98e", "metadata": { "editable": true }, @@ -985,7 +1443,7 @@ }, { "cell_type": "markdown", - "id": "074722d5", + "id": "125bab1b", "metadata": { "editable": true }, @@ -1000,7 +1458,7 @@ }, { "cell_type": "markdown", - "id": "fae17f03", + "id": "a1cf4eab", "metadata": { "editable": true }, @@ -1012,7 +1470,7 @@ }, { "cell_type": "markdown", - "id": "b172d52a", + "id": "7d134ea5", "metadata": { "editable": true }, @@ -1022,7 +1480,7 @@ }, { "cell_type": "markdown", - "id": "09099568", + "id": "b8b5ba3b", "metadata": { "editable": true }, @@ -1035,7 +1493,7 @@ }, { "cell_type": "markdown", - "id": "c2de9787", + "id": "067c8a61", "metadata": { "editable": true }, @@ -1046,7 +1504,7 @@ }, { "cell_type": "markdown", - "id": "e69bd8be", + "id": "7eabf42d", "metadata": { "editable": true }, @@ -1058,7 +1516,7 @@ }, { "cell_type": "markdown", - "id": "b1d226d4", + "id": "a722d6ed", "metadata": { "editable": true }, @@ -1068,7 +1526,7 @@ }, { "cell_type": "markdown", - "id": "c04b1ec9", + "id": "1719d3d2", "metadata": { "editable": true }, @@ -1083,7 +1541,7 @@ }, { "cell_type": "markdown", - "id": "c719cc67", + "id": "549a1cdd", "metadata": { "editable": true }, @@ -1093,7 +1551,7 @@ }, { "cell_type": "markdown", - "id": "6558bb23", + "id": "e8ad9923", "metadata": { "editable": true }, @@ -1105,7 +1563,7 @@ }, { "cell_type": "markdown", - "id": "3201df64", + "id": "c5d4600d", "metadata": { "editable": true }, @@ -1115,85 +1573,170 @@ }, { "cell_type": "markdown", - "id": "80f20ebd", + "id": "f10091e5", "metadata": { "editable": true }, "source": [ - "## Performing a discrete convolution with padding ([From Raschka et al](https://github.com/rasbt/machine-learning-book))\n", + "## The convolution stage\n", "\n", - "\n", - "\n", - "\n", - "

    Figure 1: A deep CNN

    \n", - "" + "The convolution stage, where we apply different filters $\\boldsymbol{W}$ in\n", + "order to reduce the dimensionality of an image, adds, in addition to\n", + "the weights and biases (to be trained by the back propagation\n", + "algorithm) that define the filters, two new hyperparameters, the so-called\n", + "**padding** $P$ and the stride $S$." ] }, { "cell_type": "markdown", - "id": "a6deca51", + "id": "8e54f0e7", "metadata": { "editable": true }, "source": [ - "## Performing a general discrete convolution ([From Raschka et al](https://github.com/rasbt/machine-learning-book))\n", + "## Finding the number of parameters\n", "\n", - "\n", - "\n", + "In the above example we have an input matrix of dimension $3\\times\n", + "3$. In general we call the input for an input volume and it is defined\n", + "by its width $H_1$, height $H_1$ and depth $D_1$. If we have the\n", + "standard three color channels $D_1=3$.\n", "\n", - "

    Figure 1: A deep CNN

    \n", - "" + "The above example has $W_1=H_1=3$ and $D_1=1$.\n", + "\n", + "When we introduce the filter we have the following additional hyperparameters\n", + "1. $K$ the number of filters. It is common to perform the convolution of the input several times since by experience shrinking the input too fast does not work well\n", + "\n", + "2. $F$ as the filter's spatial extent\n", + "\n", + "3. $S$ as the stride parameter\n", + "\n", + "4. $P$ as the padding parameter\n", + "\n", + "These parameters are defined by the architecture of the network and are not included in the training." ] }, { "cell_type": "markdown", - "id": "85768b9b", + "id": "6822b435", "metadata": { "editable": true }, "source": [ - "## Set of filters\n", + "## New image (or volume)\n", "\n", - "The collection of kernels/filters $W$ defining a discrete convolution has a shape\n", - "corresponding to some permutation of $(n, m, k_1, \\ldots, k_N)$, where" + "Acting with the filter on the input volume produces an output volume\n", + "which is defined by its width $W_2$, its height $H_2$ and its depth\n", + "$D_2$.\n", + "\n", + "These are defined by the following relations" ] }, { "cell_type": "markdown", - "id": "6dc5e06c", + "id": "4e6fef6f", "metadata": { "editable": true }, "source": [ "$$\n", - "\\begin{split}\n", - " n &\\equiv \\text{number of output feature maps},\\\\\n", - " m &\\equiv \\text{number of input feature maps},\\\\\n", - " k_j &\\equiv \\text{kernel size along axis $j$}.\n", - "\\end{split}\n", + "W_2 = \\frac{(W_1-F+2P)}{S}+1,\n", "$$" ] }, { "cell_type": "markdown", - "id": "59832260", + "id": "e06aef00", "metadata": { "editable": true }, "source": [ - "The following properties affect the output size $o_j$ of a convolutional layer\n", - "along axis $j$:\n", + "$$\n", + "H_2 = \\frac{(H_1-F+2P)}{S}+1,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "1ab90aac", + "metadata": { + "editable": true + }, + "source": [ + "and $D_2=K$." + ] + }, + { + "cell_type": "markdown", + "id": "87ac7fd6", + "metadata": { + "editable": true + }, + "source": [ + "## Parameters to train, common settings\n", "\n", - "1. $i_j$: input size along axis $j$,\n", + "With parameter sharing, the convolution involves thus for each filter $F\\times F\\times D_1$ weights plus one bias parameter.\n", "\n", - "2. $k_j$: kernel/filter size along axis $j$,\n", + "In total we have" + ] + }, + { + "cell_type": "markdown", + "id": "36b302f0", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\left(F\\times F\\times D_1)\\right) \\times K+(K\\mathrm{--biases}),\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "81eb0abf", + "metadata": { + "editable": true + }, + "source": [ + "parameters to train by back propagation.\n", "\n", - "3. stride (distance between two consecutive positions of the kernel/filter) along axis $j$,\n", + "It is common to let $K$ come in powers of $2$, that is $32$, $64$, $128$ etc.\n", "\n", - "4. zero padding (number of zeros concatenated at the beginning and at the end of an axis) along axis $j$.\n", + "**Common settings.**\n", "\n", - "For instance, the above examples shows a $2\\times 2$ kernel/filter $\\boldsymbol{W}$ applied to a $3 \\times 3$ input padded with a $0 \\times 0$\n", - "border of zeros using $1 \\times 1$ strides.\n", + "1. $\\begin{array}{c} F=3 & S=1 & P=1 \\end{array}$\n", + "\n", + "2. $\\begin{array}{c} F=5 & S=1 & P=2 \\end{array}$\n", + "\n", + "3. $\\begin{array}{c} F=5 & S=2 & P=\\mathrm{open} \\end{array}$\n", + "\n", + "4. $\\begin{array}{c} F=1 & S=1 & P=0 \\end{array}$" + ] + }, + { + "cell_type": "markdown", + "id": "340ead69", + "metadata": { + "editable": true + }, + "source": [ + "## Examples of CNN setups\n", + "\n", + "Let us assume we have an input volume $V$ given by an image of dimensionality\n", + "$32\\times 32 \\times 3$, that is three color channels and $32\\times 32$ pixels.\n", + "\n", + "We apply a filter of dimension $5\\times 5$ ten times with stride $S=1$ and padding $P=0$.\n", + "\n", + "The output volume is given by $(32-5)/1+1=28$, resulting in ten images\n", + "of dimensionality $28\\times 28\\times 3$.\n", + "\n", + "The total number of parameters to train for each filter is then\n", + "$5\\times 5\\times 3+1$, where the last parameter is the bias. This\n", + "gives us $76$ parameters for each filter, leading to a total of $760$\n", + "parameters for the ten filters.\n", + "\n", + "How many parameters will a filter of dimensionality $3\\times 3$\n", + "(adding color channels) result in if we produce $32$ new images? Use $S=1$ and $P=0$.\n", "\n", "Note that strides constitute a form of **subsampling**. As an alternative to\n", "being interpreted as a measure of how much the kernel/filter is translated, strides\n", @@ -1204,188 +1747,43 @@ }, { "cell_type": "markdown", - "id": "cd657bd8", + "id": "c09104a7", + "metadata": { + "editable": true + }, + "source": [ + "## Summarizing: Performing a general discrete convolution ([From Raschka et al](https://github.com/rasbt/machine-learning-book))\n", + "\n", + "\n", + "\n", + "\n", + "

    Figure 1: A deep CNN

    \n", + "" + ] + }, + { + "cell_type": "markdown", + "id": "c3ee6c93", "metadata": { "editable": true }, "source": [ "## Pooling\n", "\n", - "In addition to discrete convolutions themselves, {\\em pooling\\/} operations\n", + "In addition to discrete convolutions themselves, **pooling** operations\n", "make up another important building block in CNNs. Pooling operations reduce\n", "the size of feature maps by using some function to summarize subregions, such\n", "as taking the average or the maximum value.\n", "\n", "Pooling works by sliding a window across the input and feeding the content of\n", - "the window to a {\\em pooling function}. In some sense, pooling works very much\n", + "the window to a **pooling function**. In some sense, pooling works very much\n", "like a discrete convolution, but replaces the linear combination described by\n", - "the kernel with some other function. Poolin\n", - "provides an example for average pooling, and \n", - "does the same for max pooling.\n", - "\n", - "The following properties affect the output size $o_j$ of a pooling layer\n", - "along axis $j$:\n", - "\n", - "1. $i_j$: input size along axis $j$,\n", - "\n", - "2. $k_j$: pooling window size along axis $j$,\n", - "\n", - "3. $s_j$: stride (distance between two consecutive positions of the pooling window) along axis $j$.\n", - "\n", - "The analysis of the relationship between convolutional layer properties is eased\n", - "by the fact that they don't interact across axes, i.e., the choice of kernel\n", - "size, stride and zero padding along axis $j$ only affects the output size of\n", - "axis $j$. Because of that, we will focus on the following simplified\n", - "setting:\n", - "\n", - "1. 2-D discrete convolutions ($N = 2$),\n", - "\n", - "2. square inputs ($i_1 = i_2 = i$),\n", - "\n", - "3. square kernel size ($k_1 = k_2 = k$),\n", - "\n", - "4. same strides along both axes ($s_1 = s_2 = s$),\n", - "\n", - "5. same zero padding along both axes ($p_1 = p_2 = p$).\n", - "\n", - "This facilitates the analysis and the visualization, but keep in mind that the\n", - "results outlined here also generalize to the N-D and non-square cases." + "the kernel with some other function." ] }, { "cell_type": "markdown", - "id": "c67f706e", - "metadata": { - "editable": true - }, - "source": [ - "## No zero padding, unit strides\n", - "\n", - "The simplest case to analyze is when the kernel just slides across every\n", - "position of the input (i.e., $s = 1$ and $p = 0$).\n", - "\n", - "For any $i$ and $k$, and for $s = 1$ and $p = 0$," - ] - }, - { - "cell_type": "markdown", - "id": "eea17ea9", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "o = (i - k) + 1.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "d4b06ff9", - "metadata": { - "editable": true - }, - "source": [ - "## Zero padding, unit strides\n", - "\n", - "To factor in zero padding (i.e., only restricting to $s = 1$), let's consider\n", - "its effect on the effective input size: padding with $p$ zeros changes the\n", - "effective input size from $i$ to $i + 2p$. In the general case, we can infer the following\n", - "relationship\n", - "\n", - "For any $i$, $k$ and $p$, and for $s = 1$," - ] - }, - { - "cell_type": "markdown", - "id": "2e9e9c2b", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "o = (i - k) + 2p + 1.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "a4dc79e5", - "metadata": { - "editable": true - }, - "source": [ - "## Half (same) padding\n", - "\n", - "Having the output size be the same as the input size (i.e., $o = i$) can be a\n", - "desirable property:\n", - "\n", - "For any $i$ and for $k$ odd ($k = 2n + 1, \\quad n \\in \\mathbb{N}$), $s = 1$ and\n", - "$p = \\lfloor k / 2 \\rfloor = n$," - ] - }, - { - "cell_type": "markdown", - "id": "ebb9e07e", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\begin{split}\n", - " o &= i + 2 \\lfloor k / 2 \\rfloor - (k - 1) \\\\\n", - " &= i + 2n - 2n \\\\\n", - " &= i.\n", - "\\end{split}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "b9efae27", - "metadata": { - "editable": true - }, - "source": [ - "## Full padding\n", - "\n", - "While convolving a kernel generally decreases the output size with\n", - "respect to the input size, sometimes the opposite is required. This can be\n", - "achieved with proper zero padding:\n", - "\n", - "For any $i$ and $k$, and for $p = k - 1$ and $s = 1$," - ] - }, - { - "cell_type": "markdown", - "id": "d4b668df", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "\\begin{split}\n", - " o &= i + 2(k - 1) - (k - 1) \\\\\n", - " &= i + (k - 1).\n", - "\\end{split}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "cc2ad8e0", - "metadata": { - "editable": true - }, - "source": [ - "This is sometimes referred to as full padding, because in this\n", - "setting every possible partial or complete superimposition of the kernel on the\n", - "input feature map is taken into account." - ] - }, - { - "cell_type": "markdown", - "id": "1621bad7", + "id": "33f5dc6c", "metadata": { "editable": true }, @@ -1397,29 +1795,12 @@ "consists in splitting the input in (usually non-overlapping) patches and\n", "outputting the maximum value of each patch. Other kinds of pooling exist, e.g.,\n", "mean or average pooling, which all share the same idea of aggregating the input\n", - "locally by applying a non-linearity to the content of some patches.\n", - "\n", - "Since pooling does not involve\n", - "zero padding, the relationship describing the general case is as follows:\n", - "\n", - "For any $i$, $k$ and $s$," + "locally by applying a non-linearity to the content of some patches." ] }, { "cell_type": "markdown", - "id": "c84460b8", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "o = \\left\\lfloor \\frac{i - k}{s} \\right\\rfloor + 1.\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "cb274711", + "id": "8a792d17", "metadata": { "editable": true }, @@ -1435,7 +1816,608 @@ }, { "cell_type": "markdown", - "id": "2df1cecc", + "id": "ccba7ad4", + "metadata": { + "editable": true + }, + "source": [ + "## Building convolutional neural networks in Tensorflow and Keras\n", + "\n", + "As discussed above, CNNs are neural networks built from the assumption that the inputs\n", + "to the network are 2D images. This is important because the number of features or pixels in images\n", + "grows very fast with the image size, and an enormous number of weights and biases are needed in order to build an accurate network. \n", + "\n", + "As before, we still have our input, a hidden layer and an output. What's novel about convolutional networks\n", + "are the **convolutional** and **pooling** layers stacked in pairs between the input and the hidden layer.\n", + "In addition, the data is no longer represented as a 2D feature matrix, instead each input is a number of 2D\n", + "matrices, typically 1 for each color dimension (Red, Green, Blue)." + ] + }, + { + "cell_type": "markdown", + "id": "13645c6d", + "metadata": { + "editable": true + }, + "source": [ + "## Setting it up\n", + "\n", + "It means that to represent the entire\n", + "dataset of images, we require a 4D matrix or **tensor**. This tensor has the dimensions:" + ] + }, + { + "cell_type": "markdown", + "id": "7dda54d3", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "(n_{inputs},\\, n_{pixels, width},\\, n_{pixels, height},\\, depth) .\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "1912abac", + "metadata": { + "editable": true + }, + "source": [ + "## The MNIST dataset again\n", + "\n", + "The MNIST dataset consists of grayscale images with a pixel size of\n", + "$28\\times 28$, meaning we require $28 \\times 28 = 724$ weights to each\n", + "neuron in the first hidden layer.\n", + "\n", + "If we were to analyze images of size $128\\times 128$ we would require\n", + "$128 \\times 128 = 16384$ weights to each neuron. Even worse if we were\n", + "dealing with color images, as most images are, we have an image matrix\n", + "of size $128\\times 128$ for each color dimension (Red, Green, Blue),\n", + "meaning 3 times the number of weights $= 49152$ are required for every\n", + "single neuron in the first hidden layer." + ] + }, + { + "cell_type": "markdown", + "id": "92d33009", + "metadata": { + "editable": true + }, + "source": [ + "## Strong correlations\n", + "\n", + "Images typically have strong local correlations, meaning that a small\n", + "part of the image varies little from its neighboring regions. If for\n", + "example we have an image of a blue car, we can roughly assume that a\n", + "small blue part of the image is surrounded by other blue regions.\n", + "\n", + "Therefore, instead of connecting every single pixel to a neuron in the\n", + "first hidden layer, as we have previously done with deep neural\n", + "networks, we can instead connect each neuron to a small part of the\n", + "image (in all 3 RGB depth dimensions). The size of each small area is\n", + "fixed, and known as a [receptive](https://en.wikipedia.org/wiki/Receptive_field)." + ] + }, + { + "cell_type": "markdown", + "id": "afdc6174", + "metadata": { + "editable": true + }, + "source": [ + "## Layers of a CNN\n", + "\n", + "The layers of a convolutional neural network arrange neurons in 3D: width, height and depth. \n", + "The input image is typically a square matrix of depth 3. \n", + "\n", + "A **convolution** is performed on the image which outputs\n", + "a 3D volume of neurons. The weights to the input are arranged in a number of 2D matrices, known as **filters**.\n", + "\n", + "Each filter slides along the input image, taking the dot product\n", + "between each small part of the image and the filter, in all depth\n", + "dimensions. This is then passed through a non-linear function,\n", + "typically the **Rectified Linear (ReLu)** function, which serves as the\n", + "activation of the neurons in the first convolutional layer. This is\n", + "further passed through a **pooling layer**, which reduces the size of the\n", + "convolutional layer, e.g. by taking the maximum or average across some\n", + "small regions, and this serves as input to the next convolutional\n", + "layer." + ] + }, + { + "cell_type": "markdown", + "id": "003f75b8", + "metadata": { + "editable": true + }, + "source": [ + "## Systematic reduction\n", + "\n", + "By systematically reducing the size of the input volume, through\n", + "convolution and pooling, the network should create representations of\n", + "small parts of the input, and then from them assemble representations\n", + "of larger areas. The final pooling layer is flattened to serve as\n", + "input to a hidden layer, such that each neuron in the final pooling\n", + "layer is connected to every single neuron in the hidden layer. This\n", + "then serves as input to the output layer, e.g. a softmax output for\n", + "classification." + ] + }, + { + "cell_type": "markdown", + "id": "6d323d3d", + "metadata": { + "editable": true + }, + "source": [ + "## Prerequisites: Collect and pre-process data" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "f386213c", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "# import necessary packages\n", + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "from sklearn import datasets\n", + "\n", + "\n", + "# ensure the same random numbers appear every time\n", + "np.random.seed(0)\n", + "\n", + "# display images in notebook\n", + "%matplotlib inline\n", + "plt.rcParams['figure.figsize'] = (12,12)\n", + "\n", + "\n", + "# download MNIST dataset\n", + "digits = datasets.load_digits()\n", + "\n", + "# define inputs and labels\n", + "inputs = digits.images\n", + "labels = digits.target\n", + "\n", + "# RGB images have a depth of 3\n", + "# our images are grayscale so they should have a depth of 1\n", + "inputs = inputs[:,:,:,np.newaxis]\n", + "\n", + "print(\"inputs = (n_inputs, pixel_width, pixel_height, depth) = \" + str(inputs.shape))\n", + "print(\"labels = (n_inputs) = \" + str(labels.shape))\n", + "\n", + "\n", + "# choose some random images to display\n", + "n_inputs = len(inputs)\n", + "indices = np.arange(n_inputs)\n", + "random_indices = np.random.choice(indices, size=5)\n", + "\n", + "for i, image in enumerate(digits.images[random_indices]):\n", + " plt.subplot(1, 5, i+1)\n", + " plt.axis('off')\n", + " plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')\n", + " plt.title(\"Label: %d\" % digits.target[random_indices[i]])\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "7a38d39a", + "metadata": { + "editable": true + }, + "source": [ + "## Importing Keras and Tensorflow" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "id": "11ec9e2e", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "from tensorflow.keras import datasets, layers, models\n", + "from tensorflow.keras.layers import Input\n", + "from tensorflow.keras.models import Sequential #This allows appending layers to existing models\n", + "from tensorflow.keras.layers import Dense #This allows defining the characteristics of a particular layer\n", + "from tensorflow.keras import optimizers #This allows using whichever optimiser we want (sgd,adam,RMSprop)\n", + "from tensorflow.keras import regularizers #This allows using whichever regularizer we want (l1,l2,l1_l2)\n", + "from tensorflow.keras.utils import to_categorical #This allows using categorical cross entropy as the cost function\n", + "#from tensorflow.keras import Conv2D\n", + "#from tensorflow.keras import MaxPooling2D\n", + "#from tensorflow.keras import Flatten\n", + "\n", + "from sklearn.model_selection import train_test_split\n", + "\n", + "# representation of labels\n", + "labels = to_categorical(labels)\n", + "\n", + "# split into train and test data\n", + "# one-liner from scikit-learn library\n", + "train_size = 0.8\n", + "test_size = 1 - train_size\n", + "X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,\n", + " test_size=test_size)" + ] + }, + { + "cell_type": "markdown", + "id": "d725fcbe", + "metadata": { + "editable": true + }, + "source": [ + "## Running with Keras" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "id": "8d265c27", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "def create_convolutional_neural_network_keras(input_shape, receptive_field,\n", + " n_filters, n_neurons_connected, n_categories,\n", + " eta, lmbd):\n", + " model = Sequential()\n", + " model.add(layers.Conv2D(n_filters, (receptive_field, receptive_field), input_shape=input_shape, padding='same',\n", + " activation='relu', kernel_regularizer=regularizers.l2(lmbd)))\n", + " model.add(layers.MaxPooling2D(pool_size=(2, 2)))\n", + " model.add(layers.Flatten())\n", + " model.add(layers.Dense(n_neurons_connected, activation='relu', kernel_regularizer=regularizers.l2(lmbd)))\n", + " model.add(layers.Dense(n_categories, activation='softmax', kernel_regularizer=regularizers.l2(lmbd)))\n", + " \n", + " sgd = optimizers.SGD(lr=eta)\n", + " model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])\n", + " \n", + " return model\n", + "\n", + "epochs = 100\n", + "batch_size = 100\n", + "input_shape = X_train.shape[1:4]\n", + "receptive_field = 3\n", + "n_filters = 10\n", + "n_neurons_connected = 50\n", + "n_categories = 10\n", + "\n", + "eta_vals = np.logspace(-5, 1, 7)\n", + "lmbd_vals = np.logspace(-5, 1, 7)" + ] + }, + { + "cell_type": "markdown", + "id": "3f66294b", + "metadata": { + "editable": true + }, + "source": [ + "## Final part" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "id": "52313979", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "CNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)\n", + " \n", + "for i, eta in enumerate(eta_vals):\n", + " for j, lmbd in enumerate(lmbd_vals):\n", + " CNN = create_convolutional_neural_network_keras(input_shape, receptive_field,\n", + " n_filters, n_neurons_connected, n_categories,\n", + " eta, lmbd)\n", + " CNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0)\n", + " scores = CNN.evaluate(X_test, Y_test)\n", + " \n", + " CNN_keras[i][j] = CNN\n", + " \n", + " print(\"Learning rate = \", eta)\n", + " print(\"Lambda = \", lmbd)\n", + " print(\"Test accuracy: %.3f\" % scores[1])\n", + " print()" + ] + }, + { + "cell_type": "markdown", + "id": "c0ae00f7", + "metadata": { + "editable": true + }, + "source": [ + "## Final visualization" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "id": "d28b398b", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "# visual representation of grid search\n", + "# uses seaborn heatmap, could probably do this in matplotlib\n", + "import seaborn as sns\n", + "\n", + "sns.set()\n", + "\n", + "train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", + "test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", + "\n", + "for i in range(len(eta_vals)):\n", + " for j in range(len(lmbd_vals)):\n", + " CNN = CNN_keras[i][j]\n", + "\n", + " train_accuracy[i][j] = CNN.evaluate(X_train, Y_train)[1]\n", + " test_accuracy[i][j] = CNN.evaluate(X_test, Y_test)[1]\n", + "\n", + " \n", + "fig, ax = plt.subplots(figsize = (10, 10))\n", + "sns.heatmap(train_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", + "ax.set_title(\"Training Accuracy\")\n", + "ax.set_ylabel(\"$\\eta$\")\n", + "ax.set_xlabel(\"$\\lambda$\")\n", + "plt.show()\n", + "\n", + "fig, ax = plt.subplots(figsize = (10, 10))\n", + "sns.heatmap(test_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", + "ax.set_title(\"Test Accuracy\")\n", + "ax.set_ylabel(\"$\\eta$\")\n", + "ax.set_xlabel(\"$\\lambda$\")\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "957d569f", + "metadata": { + "editable": true + }, + "source": [ + "## The CIFAR01 data set\n", + "\n", + "The CIFAR10 dataset contains 60,000 color images in 10 classes, with\n", + "6,000 images in each class. The dataset is divided into 50,000\n", + "training images and 10,000 testing images. The classes are mutually\n", + "exclusive and there is no overlap between them." + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "id": "875738c6", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "import tensorflow as tf\n", + "\n", + "from tensorflow.keras import datasets, layers, models\n", + "import matplotlib.pyplot as plt\n", + "\n", + "# We import the data set\n", + "(train_images, train_labels), (test_images, test_labels) = datasets.cifar10.load_data()\n", + "\n", + "# Normalize pixel values to be between 0 and 1 by dividing by 255. \n", + "train_images, test_images = train_images / 255.0, test_images / 255.0" + ] + }, + { + "cell_type": "markdown", + "id": "3d02bafa", + "metadata": { + "editable": true + }, + "source": [ + "## Verifying the data set\n", + "\n", + "To verify that the dataset looks correct, let's plot the first 25 images from the training set and display the class name below each image." + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "id": "f6fa2efe", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "class_names = ['airplane', 'automobile', 'bird', 'cat', 'deer',\n", + " 'dog', 'frog', 'horse', 'ship', 'truck']\n", + "plt.figure(figsize=(10,10))\n", + "for i in range(25):\n", + " plt.subplot(5,5,i+1)\n", + " plt.xticks([])\n", + " plt.yticks([])\n", + " plt.grid(False)\n", + " plt.imshow(train_images[i], cmap=plt.cm.binary)\n", + " # The CIFAR labels happen to be arrays, \n", + " # which is why you need the extra index\n", + " plt.xlabel(class_names[train_labels[i][0]])\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "id": "7c5c4a79", + "metadata": { + "editable": true + }, + "source": [ + "## Set up the model\n", + "\n", + "The 6 lines of code below define the convolutional base using a common pattern: a stack of Conv2D and MaxPooling2D layers.\n", + "\n", + "As input, a CNN takes tensors of shape (image_height, image_width, color_channels), ignoring the batch size. If you are new to these dimensions, color_channels refers to (R,G,B). In this example, you will configure our CNN to process inputs of shape (32, 32, 3), which is the format of CIFAR images. You can do this by passing the argument input_shape to our first layer." + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "id": "0849002f", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "model = models.Sequential()\n", + "model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)))\n", + "model.add(layers.MaxPooling2D((2, 2)))\n", + "model.add(layers.Conv2D(64, (3, 3), activation='relu'))\n", + "model.add(layers.MaxPooling2D((2, 2)))\n", + "model.add(layers.Conv2D(64, (3, 3), activation='relu'))\n", + "\n", + "# Let's display the architecture of our model so far.\n", + "\n", + "model.summary()" + ] + }, + { + "cell_type": "markdown", + "id": "42a62b52", + "metadata": { + "editable": true + }, + "source": [ + "You can see that the output of every Conv2D and MaxPooling2D layer is a 3D tensor of shape (height, width, channels). The width and height dimensions tend to shrink as you go deeper in the network. The number of output channels for each Conv2D layer is controlled by the first argument (e.g., 32 or 64). Typically, as the width and height shrink, you can afford (computationally) to add more output channels in each Conv2D layer." + ] + }, + { + "cell_type": "markdown", + "id": "be17ccdf", + "metadata": { + "editable": true + }, + "source": [ + "## Add Dense layers on top\n", + "\n", + "To complete our model, you will feed the last output tensor from the\n", + "convolutional base (of shape (4, 4, 64)) into one or more Dense layers\n", + "to perform classification. Dense layers take vectors as input (which\n", + "are 1D), while the current output is a 3D tensor. First, you will\n", + "flatten (or unroll) the 3D output to 1D, then add one or more Dense\n", + "layers on top. CIFAR has 10 output classes, so you use a final Dense\n", + "layer with 10 outputs and a softmax activation." + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "id": "0a2841f0", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "model.add(layers.Flatten())\n", + "model.add(layers.Dense(64, activation='relu'))\n", + "model.add(layers.Dense(10))\n", + "Here's the complete architecture of our model.\n", + "\n", + "model.summary()" + ] + }, + { + "cell_type": "markdown", + "id": "f70f18a5", + "metadata": { + "editable": true + }, + "source": [ + "As you can see, our (4, 4, 64) outputs were flattened into vectors of shape (1024) before going through two Dense layers." + ] + }, + { + "cell_type": "markdown", + "id": "8ab1a8ab", + "metadata": { + "editable": true + }, + "source": [ + "## Compile and train the model" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "id": "04d76fd5", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "model.compile(optimizer='adam',\n", + " loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n", + " metrics=['accuracy'])\n", + "\n", + "history = model.fit(train_images, train_labels, epochs=10, \n", + " validation_data=(test_images, test_labels))" + ] + }, + { + "cell_type": "markdown", + "id": "5c0392e2", + "metadata": { + "editable": true + }, + "source": [ + "## Finally, evaluate the model" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "id": "2e869c20", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "plt.plot(history.history['accuracy'], label='accuracy')\n", + "plt.plot(history.history['val_accuracy'], label = 'val_accuracy')\n", + "plt.xlabel('Epoch')\n", + "plt.ylabel('Accuracy')\n", + "plt.ylim([0.5, 1])\n", + "plt.legend(loc='lower right')\n", + "\n", + "test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)\n", + "\n", + "print(test_acc)" + ] + }, + { + "cell_type": "markdown", + "id": "66a5e54d", "metadata": { "editable": true }, @@ -1447,6 +2429,8 @@ "the codebase and fit a CNN that yields a 99% accuracy on the 28x28\n", "MNIST dataset within reasonable time.\n", "\n", + "**The codes here were developed by Eric Reber and Gregor Kajda during spring 2023.**\n", + "\n", "The CNN is compatible with all schedulers, cost functions and\n", "activation functions discussed in constructing our neural network\n", "codes.\n", @@ -1466,7 +2450,7 @@ }, { "cell_type": "markdown", - "id": "2fe7b160", + "id": "af73a2bd", "metadata": { "editable": true }, @@ -1490,7 +2474,7 @@ }, { "cell_type": "markdown", - "id": "374dc966", + "id": "9975f54f", "metadata": { "editable": true }, @@ -1512,8 +2496,8 @@ }, { "cell_type": "code", - "execution_count": 1, - "id": "f24a2752", + "execution_count": 13, + "id": "660130ae", "metadata": { "collapsed": false, "editable": true @@ -1654,7 +2638,7 @@ }, { "cell_type": "markdown", - "id": "56000947", + "id": "9f8cf94f", "metadata": { "editable": true }, @@ -1666,8 +2650,8 @@ }, { "cell_type": "code", - "execution_count": 2, - "id": "2d38e983", + "execution_count": 14, + "id": "273ba0b1", "metadata": { "collapsed": false, "editable": true @@ -1680,7 +2664,7 @@ }, { "cell_type": "markdown", - "id": "16b58251", + "id": "154e5891", "metadata": { "editable": true }, @@ -1690,8 +2674,8 @@ }, { "cell_type": "code", - "execution_count": 3, - "id": "e58294f2", + "execution_count": 15, + "id": "8034d8f2", "metadata": { "collapsed": false, "editable": true @@ -1713,7 +2697,7 @@ }, { "cell_type": "markdown", - "id": "ce286b2b", + "id": "f47f75c6", "metadata": { "editable": true }, @@ -1728,8 +2712,8 @@ }, { "cell_type": "code", - "execution_count": 4, - "id": "682d7896", + "execution_count": 16, + "id": "35db1625", "metadata": { "collapsed": false, "editable": true @@ -1776,7 +2760,7 @@ }, { "cell_type": "markdown", - "id": "7b8c38d0", + "id": "446a3378", "metadata": { "editable": true }, @@ -1790,8 +2774,8 @@ }, { "cell_type": "code", - "execution_count": 5, - "id": "da49e588", + "execution_count": 17, + "id": "2df9d962", "metadata": { "collapsed": false, "editable": true @@ -1812,7 +2796,7 @@ }, { "cell_type": "markdown", - "id": "bcaa5376", + "id": "bf534f8c", "metadata": { "editable": true }, @@ -1828,8 +2812,8 @@ }, { "cell_type": "code", - "execution_count": 6, - "id": "68127b5d", + "execution_count": 18, + "id": "a1faf180", "metadata": { "collapsed": false, "editable": true @@ -1888,7 +2872,7 @@ }, { "cell_type": "markdown", - "id": "5d8d2751", + "id": "ace037b0", "metadata": { "editable": true }, @@ -1904,8 +2888,8 @@ }, { "cell_type": "code", - "execution_count": 7, - "id": "11b5c33a", + "execution_count": 19, + "id": "4ab94623", "metadata": { "collapsed": false, "editable": true @@ -1926,7 +2910,7 @@ }, { "cell_type": "markdown", - "id": "9e9909d9", + "id": "156dff4f", "metadata": { "editable": true }, @@ -1943,7 +2927,7 @@ }, { "cell_type": "markdown", - "id": "2d6847cc", + "id": "d4ec39fa", "metadata": { "editable": true }, @@ -1955,42 +2939,42 @@ }, { "cell_type": "markdown", - "id": "7b01aca1", + "id": "f84a7f10", "metadata": { "editable": true }, "source": [ - "Here, f and g are the two functions on which we want to perform an\n", + "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", + "$(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:" + "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": "c5164022", + "id": "e4dec2b6", "metadata": { "editable": true }, "source": [ "$$\n", - "(f \\ast g)[n]=\\sum_{m=0}^{n-1} f[m] g[n-m].\n", + "(f \\ast g)[n]=\\sum_{m=0}^{n-1} f(m) g(n-m).\n", "$$" ] }, { "cell_type": "markdown", - "id": "c64787b1", + "id": "2840d48f", "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", + "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:" @@ -1998,19 +2982,19 @@ }, { "cell_type": "markdown", - "id": "e79a7cc9", + "id": "e8e58c03", "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", + "(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": "089e493f", + "id": "11ea612a", "metadata": { "editable": true }, @@ -2023,12 +3007,12 @@ "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$" + "suppose we have an image $f$ of dimension $6 \\times 6$" ] }, { "cell_type": "markdown", - "id": "61e3dd34", + "id": "836da562", "metadata": { "editable": true }, @@ -2047,19 +3031,19 @@ }, { "cell_type": "markdown", - "id": "63b4d2e4", + "id": "2b3bb8f1", "metadata": { "editable": true }, "source": [ - "and a $3 \\times 3$ kernel *g* called a low-pass filter. Note that the\n", + "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": "0eef7505", + "id": "3f7c208c", "metadata": { "editable": true }, @@ -2076,20 +3060,20 @@ }, { "cell_type": "markdown", - "id": "e243595e", + "id": "3d8b79f4", "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", + "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*:" + "kernel $g$:" ] }, { "cell_type": "markdown", - "id": "686f332f", + "id": "7e21a80b", "metadata": { "editable": true }, @@ -2112,45 +3096,45 @@ "\\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", + "= \\boldsymbol{A}\n", "$$" ] }, { "cell_type": "markdown", - "id": "eb78894f", + "id": "93aab016", "metadata": { "editable": true }, "source": [ - "Then, following the multiplication, we summarize all the elements of the resulting matrix A:" + "Then, following the multiplication, we summarize all the elements of the resulting matrix $\\boldsymbol{A}$:" ] }, { "cell_type": "markdown", - "id": "c9c1becb", + "id": "4e0b557b", "metadata": { "editable": true }, "source": [ "$$\n", - "(f \\ast g)[0, 0]= \\sum_{i=0}^{2} \\sum_{j=0}^{2} a_{i,j} = 5\n", + "(f \\ast g)(0, 0)= \\sum_{i=0}^{2} \\sum_{j=0}^{2} a_{i,j} = 5,\n", "$$" ] }, { "cell_type": "markdown", - "id": "3c417ed5", + "id": "391389d2", "metadata": { "editable": true }, "source": [ - "Which corresponds to the first element of the filtered image $(f \\ast g)$.\n", + "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", + "Here we use a stride of $S=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", + "$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", @@ -2161,7 +3145,7 @@ }, { "cell_type": "markdown", - "id": "826fbbfb", + "id": "2948c748", "metadata": { "editable": true }, @@ -2179,38 +3163,43 @@ }, { "cell_type": "markdown", - "id": "77fd48f4", + "id": "59ccebe4", "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." + "The result is markedly smaller in shape than the original image. This\n", + "occurs when using convolution without first padding the image with\n", + "additional columns and rows, allowing us to keep the original image\n", + "shape after sliding the kernel over the image. How many rows and\n", + "columns we wish to pad the image with depends strictly on the shape of\n", + "the kernel, as we wish to pad the image with $r$ additional rows and\n", + "$c$ additional columns." ] }, { "cell_type": "markdown", - "id": "643942af", + "id": "3ac3ba4b", "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", + "r =\\lfloor \\frac{\\mathrm{kernel height}}{2} \\rfloor \\cdot 2 \\\\\n", + "c =\\lfloor \\frac{\\mathrm{kernel width}}{2} \\rfloor \\cdot 2\n", "$$" ] }, { "cell_type": "markdown", - "id": "2f12dad3", + "id": "60d7d729", "metadata": { "editable": true }, "source": [ - "Note the notation $\\lfloor \\frac{kernel width}{2} \\rfloor$ means that\n", + "Note the notation $\\lfloor \\frac{\\mathrm{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 in case $\\frac{\\mathrm{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", @@ -2227,7 +3216,7 @@ }, { "cell_type": "markdown", - "id": "deafb1c4", + "id": "0f223085", "metadata": { "editable": true }, @@ -2242,25 +3231,26 @@ "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", + "\\end{bmatrix}.\n", "$$" ] }, { "cell_type": "markdown", - "id": "c37c52a4", + "id": "d2a919ef", "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.~" + "Below we have provided code that demonstrates padding and\n", + "convolution. As you will see when we run the code, the size of the\n", + "image will remain unchanged when using padding.~" ] }, { "cell_type": "code", - "execution_count": 8, - "id": "07ad670f", + "execution_count": 20, + "id": "98158090", "metadata": { "collapsed": false, "editable": true @@ -2342,20 +3332,21 @@ }, { "cell_type": "markdown", - "id": "d2f0a30c", + "id": "e386b5f9", "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." + "Fun fact: When filtering images, you will see that convolution\n", + "involves rotating the kernel by 180 degrees. However, this is not the\n", + "case when applying convolution in a CNN, where the same operation that is not\n", + "rotated by 180 degrees is called cross-correlation, which is normally implemented in most libraries." ] }, { "cell_type": "code", - "execution_count": 9, - "id": "69913a2b", + "execution_count": 21, + "id": "b196835c", "metadata": { "collapsed": false, "editable": true @@ -2382,7 +3373,7 @@ }, { "cell_type": "markdown", - "id": "e9edd1cd", + "id": "c598de0f", "metadata": { "editable": true }, @@ -2402,17 +3393,15 @@ }, { "cell_type": "code", - "execution_count": 10, - "id": "7fed274d", + "execution_count": 22, + "id": "1dc54fc6", "metadata": { "collapsed": false, "editable": true }, "outputs": [], "source": [ - "%matplotlib inline\n", - "\n", - "# Now an example using a real image and first a gaussian low-pass filter and then a sobel filter\n", + "# 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", @@ -2455,7 +3444,7 @@ }, { "cell_type": "markdown", - "id": "adeee788", + "id": "8fb0749c", "metadata": { "editable": true }, @@ -2469,8 +3458,8 @@ }, { "cell_type": "code", - "execution_count": 11, - "id": "04b2d320", + "execution_count": 23, + "id": "fedc419c", "metadata": { "collapsed": false, "editable": true @@ -2511,7 +3500,7 @@ }, { "cell_type": "markdown", - "id": "910594b6", + "id": "c8370f0c", "metadata": { "editable": true }, @@ -2552,8 +3541,8 @@ }, { "cell_type": "code", - "execution_count": 12, - "id": "b0d8dd57", + "execution_count": 24, + "id": "d97d0055", "metadata": { "collapsed": false, "editable": true @@ -2839,7 +3828,7 @@ }, { "cell_type": "markdown", - "id": "a25330d9", + "id": "0dfbd0fc", "metadata": { "editable": true }, @@ -2862,7 +3851,7 @@ }, { "cell_type": "markdown", - "id": "942832c8", + "id": "739539f5", "metadata": { "editable": true }, @@ -2874,8 +3863,8 @@ }, { "cell_type": "code", - "execution_count": 13, - "id": "b0f7f972", + "execution_count": 25, + "id": "fb42cade", "metadata": { "collapsed": false, "editable": true @@ -2923,7 +3912,7 @@ }, { "cell_type": "markdown", - "id": "55f5198b", + "id": "2037fef5", "metadata": { "editable": true }, @@ -2945,7 +3934,7 @@ }, { "cell_type": "markdown", - "id": "4b1e24f8", + "id": "ee0b7034", "metadata": { "editable": true }, @@ -2966,8 +3955,8 @@ }, { "cell_type": "code", - "execution_count": 14, - "id": "5e1d05ba", + "execution_count": 26, + "id": "37fdedf3", "metadata": { "collapsed": false, "editable": true @@ -3129,7 +4118,7 @@ }, { "cell_type": "markdown", - "id": "a7030c39", + "id": "dbd0a7e6", "metadata": { "editable": true }, @@ -3149,8 +4138,8 @@ }, { "cell_type": "code", - "execution_count": 15, - "id": "8e5e4192", + "execution_count": 27, + "id": "3196697f", "metadata": { "collapsed": false, "editable": true @@ -3213,7 +4202,7 @@ }, { "cell_type": "markdown", - "id": "92e17b3a", + "id": "7af01737", "metadata": { "editable": true }, @@ -3236,8 +4225,8 @@ }, { "cell_type": "code", - "execution_count": 16, - "id": "0a4d96ef", + "execution_count": 28, + "id": "652a07a7", "metadata": { "collapsed": false, "editable": true @@ -3465,7 +4454,7 @@ }, { "cell_type": "markdown", - "id": "53b36589", + "id": "e7caf94b", "metadata": { "editable": true }, @@ -3485,8 +4474,8 @@ }, { "cell_type": "code", - "execution_count": 17, - "id": "5c4ed6ee", + "execution_count": 29, + "id": "fc2c6d43", "metadata": { "collapsed": false, "editable": true @@ -3790,7 +4779,7 @@ }, { "cell_type": "markdown", - "id": "dbdf86e4", + "id": "20e3247d", "metadata": { "editable": true }, @@ -3802,8 +4791,8 @@ }, { "cell_type": "code", - "execution_count": 18, - "id": "a8c7ea94", + "execution_count": 30, + "id": "7841dc47", "metadata": { "collapsed": false, "editable": true @@ -4338,7 +5327,7 @@ }, { "cell_type": "markdown", - "id": "ecf83f56", + "id": "2cba848d", "metadata": { "editable": true }, @@ -4356,8 +5345,8 @@ }, { "cell_type": "code", - "execution_count": 19, - "id": "ed5a9db7", + "execution_count": 31, + "id": "869f4ea1", "metadata": { "collapsed": false, "editable": true @@ -4370,7 +5359,7 @@ }, { "cell_type": "markdown", - "id": "7ab8be5d", + "id": "b7d283b2", "metadata": { "editable": true }, @@ -4385,8 +5374,8 @@ }, { "cell_type": "code", - "execution_count": 20, - "id": "e88fcc22", + "execution_count": 32, + "id": "795b9ebb", "metadata": { "collapsed": false, "editable": true @@ -4412,7 +5401,7 @@ }, { "cell_type": "markdown", - "id": "e09e4222", + "id": "ba9a8be1", "metadata": { "editable": true }, @@ -4430,13 +5419,13 @@ "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$." + "will use the MNIST dataset and use 10000 $28 \\times 28$ images." ] }, { "cell_type": "code", - "execution_count": 21, - "id": "4a179b95", + "execution_count": 33, + "id": "bb4c98fa", "metadata": { "collapsed": false, "editable": true @@ -4471,7 +5460,7 @@ }, { "cell_type": "markdown", - "id": "878aeb2a", + "id": "97a9484f", "metadata": { "editable": true }, @@ -4489,8 +5478,8 @@ }, { "cell_type": "code", - "execution_count": 22, - "id": "acf28e60", + "execution_count": 34, + "id": "539baa72", "metadata": { "collapsed": false, "editable": true @@ -4518,7 +5507,7 @@ }, { "cell_type": "markdown", - "id": "9efc80ac", + "id": "c7bb6ac0", "metadata": { "editable": true }, @@ -4546,8 +5535,8 @@ }, { "cell_type": "code", - "execution_count": 23, - "id": "395f8612", + "execution_count": 35, + "id": "93e706ae", "metadata": { "collapsed": false, "editable": true @@ -4616,7 +5605,7 @@ }, { "cell_type": "markdown", - "id": "5ab9df29", + "id": "c72032ee", "metadata": { "editable": true }, @@ -4634,7 +5623,7 @@ }, { "cell_type": "markdown", - "id": "c5ffd1f4", + "id": "4ae81157", "metadata": { "editable": true }, @@ -4657,8 +5646,8 @@ }, { "cell_type": "code", - "execution_count": 24, - "id": "44a0b4c1", + "execution_count": 36, + "id": "4d2d2032", "metadata": { "collapsed": false, "editable": true @@ -4689,7 +5678,7 @@ }, { "cell_type": "markdown", - "id": "3ea702d5", + "id": "0b61f114", "metadata": { "editable": true }, @@ -4719,7 +5708,7 @@ }, { "cell_type": "markdown", - "id": "b46fc7ea", + "id": "953ca041", "metadata": { "editable": true }, @@ -4729,8 +5718,8 @@ }, { "cell_type": "code", - "execution_count": 25, - "id": "f9af0bae", + "execution_count": 37, + "id": "6f5e8589", "metadata": { "collapsed": false, "editable": true @@ -4780,7 +5769,7 @@ }, { "cell_type": "markdown", - "id": "f17f130c", + "id": "ba379cac", "metadata": { "editable": true }, @@ -4801,7 +5790,7 @@ }, { "cell_type": "markdown", - "id": "9f3ac382", + "id": "951e4f08", "metadata": { "editable": true }, @@ -4811,8 +5800,8 @@ }, { "cell_type": "code", - "execution_count": 26, - "id": "b71a2395", + "execution_count": 38, + "id": "b23c5570", "metadata": { "collapsed": false, "editable": true @@ -4833,7 +5822,7 @@ }, { "cell_type": "markdown", - "id": "36bdd533", + "id": "ecbe9144", "metadata": { "editable": true }, @@ -4849,381 +5838,6 @@ "to remain cognizant of this fact when utilizing FFT as the primary\n", "optimization technique." ] - }, - { - "cell_type": "markdown", - "id": "ebd1818e", - "metadata": { - "editable": true - }, - "source": [ - "## Building convolutional neural networks in Tensorflow and Keras\n", - "\n", - "As discussed above, CNNs are neural networks built from the assumption that the inputs\n", - "to the network are 2D images. This is important because the number of features or pixels in images\n", - "grows very fast with the image size, and an enormous number of weights and biases are needed in order to build an accurate network. \n", - "\n", - "As before, we still have our input, a hidden layer and an output. What's novel about convolutional networks\n", - "are the **convolutional** and **pooling** layers stacked in pairs between the input and the hidden layer.\n", - "In addition, the data is no longer represented as a 2D feature matrix, instead each input is a number of 2D\n", - "matrices, typically 1 for each color dimension (Red, Green, Blue)." - ] - }, - { - "cell_type": "markdown", - "id": "f5dd4522", - "metadata": { - "editable": true - }, - "source": [ - "## Setting it up\n", - "\n", - "It means that to represent the entire\n", - "dataset of images, we require a 4D matrix or **tensor**. This tensor has the dimensions:" - ] - }, - { - "cell_type": "markdown", - "id": "feffdf95", - "metadata": { - "editable": true - }, - "source": [ - "$$\n", - "(n_{inputs},\\, n_{pixels, width},\\, n_{pixels, height},\\, depth) .\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "id": "736a847b", - "metadata": { - "editable": true - }, - "source": [ - "## The MNIST dataset again\n", - "\n", - "The MNIST dataset consists of grayscale images with a pixel size of\n", - "$28\\times 28$, meaning we require $28 \\times 28 = 724$ weights to each\n", - "neuron in the first hidden layer.\n", - "\n", - "If we were to analyze images of size $128\\times 128$ we would require\n", - "$128 \\times 128 = 16384$ weights to each neuron. Even worse if we were\n", - "dealing with color images, as most images are, we have an image matrix\n", - "of size $128\\times 128$ for each color dimension (Red, Green, Blue),\n", - "meaning 3 times the number of weights $= 49152$ are required for every\n", - "single neuron in the first hidden layer." - ] - }, - { - "cell_type": "markdown", - "id": "e676336d", - "metadata": { - "editable": true - }, - "source": [ - "## Strong correlations\n", - "\n", - "Images typically have strong local correlations, meaning that a small\n", - "part of the image varies little from its neighboring regions. If for\n", - "example we have an image of a blue car, we can roughly assume that a\n", - "small blue part of the image is surrounded by other blue regions.\n", - "\n", - "Therefore, instead of connecting every single pixel to a neuron in the\n", - "first hidden layer, as we have previously done with deep neural\n", - "networks, we can instead connect each neuron to a small part of the\n", - "image (in all 3 RGB depth dimensions). The size of each small area is\n", - "fixed, and known as a [receptive](https://en.wikipedia.org/wiki/Receptive_field)." - ] - }, - { - "cell_type": "markdown", - "id": "714b9066", - "metadata": { - "editable": true - }, - "source": [ - "## Layers of a CNN\n", - "\n", - "The layers of a convolutional neural network arrange neurons in 3D: width, height and depth. \n", - "The input image is typically a square matrix of depth 3. \n", - "\n", - "A **convolution** is performed on the image which outputs\n", - "a 3D volume of neurons. The weights to the input are arranged in a number of 2D matrices, known as **filters**.\n", - "\n", - "Each filter slides along the input image, taking the dot product\n", - "between each small part of the image and the filter, in all depth\n", - "dimensions. This is then passed through a non-linear function,\n", - "typically the **Rectified Linear (ReLu)** function, which serves as the\n", - "activation of the neurons in the first convolutional layer. This is\n", - "further passed through a **pooling layer**, which reduces the size of the\n", - "convolutional layer, e.g. by taking the maximum or average across some\n", - "small regions, and this serves as input to the next convolutional\n", - "layer." - ] - }, - { - "cell_type": "markdown", - "id": "8a5afdec", - "metadata": { - "editable": true - }, - "source": [ - "## Systematic reduction\n", - "\n", - "By systematically reducing the size of the input volume, through\n", - "convolution and pooling, the network should create representations of\n", - "small parts of the input, and then from them assemble representations\n", - "of larger areas. The final pooling layer is flattened to serve as\n", - "input to a hidden layer, such that each neuron in the final pooling\n", - "layer is connected to every single neuron in the hidden layer. This\n", - "then serves as input to the output layer, e.g. a softmax output for\n", - "classification." - ] - }, - { - "cell_type": "markdown", - "id": "f1344e2f", - "metadata": { - "editable": true - }, - "source": [ - "## Prerequisites: Collect and pre-process data" - ] - }, - { - "cell_type": "code", - "execution_count": 27, - "id": "df65e942", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# import necessary packages\n", - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from sklearn import datasets\n", - "\n", - "\n", - "# ensure the same random numbers appear every time\n", - "np.random.seed(0)\n", - "\n", - "# display images in notebook\n", - "%matplotlib inline\n", - "plt.rcParams['figure.figsize'] = (12,12)\n", - "\n", - "\n", - "# download MNIST dataset\n", - "digits = datasets.load_digits()\n", - "\n", - "# define inputs and labels\n", - "inputs = digits.images\n", - "labels = digits.target\n", - "\n", - "# RGB images have a depth of 3\n", - "# our images are grayscale so they should have a depth of 1\n", - "inputs = inputs[:,:,:,np.newaxis]\n", - "\n", - "print(\"inputs = (n_inputs, pixel_width, pixel_height, depth) = \" + str(inputs.shape))\n", - "print(\"labels = (n_inputs) = \" + str(labels.shape))\n", - "\n", - "\n", - "# choose some random images to display\n", - "n_inputs = len(inputs)\n", - "indices = np.arange(n_inputs)\n", - "random_indices = np.random.choice(indices, size=5)\n", - "\n", - "for i, image in enumerate(digits.images[random_indices]):\n", - " plt.subplot(1, 5, i+1)\n", - " plt.axis('off')\n", - " plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')\n", - " plt.title(\"Label: %d\" % digits.target[random_indices[i]])\n", - "plt.show()" - ] - }, - { - "cell_type": "markdown", - "id": "f74d4498", - "metadata": { - "editable": true - }, - "source": [ - "## Importing Keras and Tensorflow" - ] - }, - { - "cell_type": "code", - "execution_count": 28, - "id": "ae32fe9c", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "from tensorflow.keras import datasets, layers, models\n", - "from tensorflow.keras.layers import Input\n", - "from tensorflow.keras.models import Sequential #This allows appending layers to existing models\n", - "from tensorflow.keras.layers import Dense #This allows defining the characteristics of a particular layer\n", - "from tensorflow.keras import optimizers #This allows using whichever optimiser we want (sgd,adam,RMSprop)\n", - "from tensorflow.keras import regularizers #This allows using whichever regularizer we want (l1,l2,l1_l2)\n", - "from tensorflow.keras.utils import to_categorical #This allows using categorical cross entropy as the cost function\n", - "#from tensorflow.keras import Conv2D\n", - "#from tensorflow.keras import MaxPooling2D\n", - "#from tensorflow.keras import Flatten\n", - "\n", - "from sklearn.model_selection import train_test_split\n", - "\n", - "# representation of labels\n", - "labels = to_categorical(labels)\n", - "\n", - "# split into train and test data\n", - "# one-liner from scikit-learn library\n", - "train_size = 0.8\n", - "test_size = 1 - train_size\n", - "X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size,\n", - " test_size=test_size)" - ] - }, - { - "cell_type": "markdown", - "id": "9d13359f", - "metadata": { - "editable": true - }, - "source": [ - "## Running with Keras" - ] - }, - { - "cell_type": "code", - "execution_count": 29, - "id": "c07fca46", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "def create_convolutional_neural_network_keras(input_shape, receptive_field,\n", - " n_filters, n_neurons_connected, n_categories,\n", - " eta, lmbd):\n", - " model = Sequential()\n", - " model.add(layers.Conv2D(n_filters, (receptive_field, receptive_field), input_shape=input_shape, padding='same',\n", - " activation='relu', kernel_regularizer=regularizers.l2(lmbd)))\n", - " model.add(layers.MaxPooling2D(pool_size=(2, 2)))\n", - " model.add(layers.Flatten())\n", - " model.add(layers.Dense(n_neurons_connected, activation='relu', kernel_regularizer=regularizers.l2(lmbd)))\n", - " model.add(layers.Dense(n_categories, activation='softmax', kernel_regularizer=regularizers.l2(lmbd)))\n", - " \n", - " sgd = optimizers.SGD(learning_rate=eta)\n", - " model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])\n", - " \n", - " return model\n", - "\n", - "epochs = 100\n", - "batch_size = 100\n", - "input_shape = X_train.shape[1:4]\n", - "receptive_field = 3\n", - "n_filters = 10\n", - "n_neurons_connected = 50\n", - "n_categories = 10\n", - "\n", - "eta_vals = np.logspace(-5, 1, 7)\n", - "lmbd_vals = np.logspace(-5, 1, 7)" - ] - }, - { - "cell_type": "markdown", - "id": "2b40b4c9", - "metadata": { - "editable": true - }, - "source": [ - "## Final part" - ] - }, - { - "cell_type": "code", - "execution_count": 30, - "id": "e5ef4326", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "CNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object)\n", - " \n", - "for i, eta in enumerate(eta_vals):\n", - " for j, lmbd in enumerate(lmbd_vals):\n", - " CNN = create_convolutional_neural_network_keras(input_shape, receptive_field,\n", - " n_filters, n_neurons_connected, n_categories,\n", - " eta, lmbd)\n", - " CNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0)\n", - " scores = CNN.evaluate(X_test, Y_test)\n", - " \n", - " CNN_keras[i][j] = CNN\n", - " \n", - " print(\"Learning rate = \", eta)\n", - " print(\"Lambda = \", lmbd)\n", - " print(\"Test accuracy: %.3f\" % scores[1])\n", - " print()" - ] - }, - { - "cell_type": "markdown", - "id": "e3bc74cc", - "metadata": { - "editable": true - }, - "source": [ - "## Final visualization" - ] - }, - { - "cell_type": "code", - "execution_count": 31, - "id": "75932707", - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "# visual representation of grid search\n", - "# uses seaborn heatmap, could probably do this in matplotlib\n", - "import seaborn as sns\n", - "\n", - "sns.set()\n", - "\n", - "train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", - "test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals)))\n", - "\n", - "for i in range(len(eta_vals)):\n", - " for j in range(len(lmbd_vals)):\n", - " CNN = CNN_keras[i][j]\n", - "\n", - " train_accuracy[i][j] = CNN.evaluate(X_train, Y_train)[1]\n", - " test_accuracy[i][j] = CNN.evaluate(X_test, Y_test)[1]\n", - "\n", - " \n", - "fig, ax = plt.subplots(figsize = (10, 10))\n", - "sns.heatmap(train_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", - "ax.set_title(\"Training Accuracy\")\n", - "ax.set_ylabel(\"$\\eta$\")\n", - "ax.set_xlabel(\"$\\lambda$\")\n", - "plt.show()\n", - "\n", - "fig, ax = plt.subplots(figsize = (10, 10))\n", - "sns.heatmap(test_accuracy, annot=True, ax=ax, cmap=\"viridis\")\n", - "ax.set_title(\"Test Accuracy\")\n", - "ax.set_ylabel(\"$\\eta$\")\n", - "ax.set_xlabel(\"$\\lambda$\")\n", - "plt.show()" - ] } ], "metadata": {}, diff --git a/doc/src/week44/figslides/photo.jpg b/doc/src/week44/figslides/photo.jpg new file mode 100755 index 000000000..426220598 Binary files /dev/null and b/doc/src/week44/figslides/photo.jpg differ diff --git a/doc/src/week44/week44.do.txt b/doc/src/week44/week44.do.txt index 9641d7d3f..38fd6dac3 100644 --- a/doc/src/week44/week44.do.txt +++ b/doc/src/week44/week44.do.txt @@ -262,6 +262,130 @@ We say we perform a filtering (convolution is the mathematical operation). +!split +===== How to do image compression before the era of deep learning ===== + +The singular-value decomposition (SVD) algorithm has been for decades one of the standard ways of compressing images. +The "lectures on the SVD":"https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/chapter2.html#the-singular-value-decomposition" give many of the essential details concerning the SVD. + +The orthogonal vectors which are obtained from the SVD, can be used to +project down the dimensionality of a given image. In the example here +we gray-scale an image and downsize it. + +This recipe relies on us being able to actually perform the SVD. For +large images, and in particular with many images to reconstruct, using the SVD +may quickly become an overwhelming task. With the advent of efficient deep +learning methods like CNNs and later generative methods, these methods +have become in the last years the premier way of performing image +analysis. In particular for classification problems with labelled images. + +!split +===== The SVD example ===== + +!bc pycod +from matplotlib.image import imread +import matplotlib.pyplot as plt +import scipy.linalg as ln +import numpy as np +import os +from PIL import Image +from math import log10, sqrt +plt.rcParams['figure.figsize'] = [16, 8] +# Import image +A = imread(os.path.join("figslides/photo1.jpg")) +X = A.dot([0.299, 0.5870, 0.114]) # Convert RGB to grayscale +img = plt.imshow(X) +# convert to gray +img.set_cmap('gray') +plt.axis('off') +plt.show() +# Call image size +print(': %s'%str(X.shape)) + + +# split the matrix into U, S, VT +U, S, VT = np.linalg.svd(X,full_matrices=False) +S = np.diag(S) +m = 800 # Image's width +n = 1200 # Image's height +j = 0 +# Try compression with different k vectors (these represent projections): +for k in (5,10, 20, 100,200,400,500): + # Original size of the image + originalSize = m * n + # Size after compressed + compressedSize = k * (1 + m + n) + # The projection of the original image + Xapprox = U[:,:k] @ S[0:k,:k] @ VT[:k,:] + plt.figure(j+1) + j += 1 + img = plt.imshow(Xapprox) + img.set_cmap('gray') + + plt.axis('off') + plt.title('k = ' + str(k)) + plt.show() + print('Original size of image:') + print(originalSize) + print('Compression rate as Compressed image / Original size:') + ratio = compressedSize * 1.0 / originalSize + print(ratio) + print('Compression rate is ' + str( round(ratio * 100 ,2)) + '%' ) + # Estimate MQA + x= X.astype("float") + y=Xapprox.astype("float") + err = np.sum((x - y) ** 2) + err /= float(X.shape[0] * Xapprox.shape[1]) + print('The mean-square deviation '+ str(round( err))) + max_pixel = 255.0 + # Estimate Signal Noise Ratio + srv = 20 * (log10(max_pixel / sqrt(err))) + print('Signa to noise ratio '+ str(round(srv)) +'dB') + +!ec + + + + +!split +===== Mathematics of CNNs ===== + +The mathematics of CNNs is based on the mathematical operation of +_convolution_. In mathematics (in particular in functional analysis), +convolution is represented by mathematical operations (integration, +summation etc) on two functions in order to produce a third function +that expresses how the shape of one gets modified by the other. +Convolution has a plethora of applications in a variety of +disciplines, spanning from statistics to signal processing, computer +vision, solutions of differential equations,linear algebra, +engineering, and yes, machine learning. + +Mathematically, convolution is defined as follows (one-dimensional example): +Let us define a continuous function $y(t)$ given by +!bt +\[ +y(t) = \int x(a) w(t-a) da, +\] +!et +where $x(a)$ represents a so-called input and $w(t-a)$ is normally called the weight function or kernel. + +The above integral is written in a more compact form as +!bt +\[ +y(t) = \left(x * w\right)(t). +\] +!et + +The discretized version reads +!bt +\[ +y(t) = \sum_{a=-\infty}^{a=\infty}x(a)w(t-a). +\] +!et +Computing the inverse of the above convolution operations is known as deconvolution and the process is commutative. + +How can we use this? And what does it mean? Let us study some familiar examples first. + @@ -378,7 +502,8 @@ Although we may have redundant operations with some few zeros for $\beta_i$, we \delta_i = \sum_{k=0}^{k=m-1}\alpha_k\beta_{i-k}, \] !et -where $m=3$ in our case, the maximum length of the vector $\alpha$. Note that the vector $\bm{\beta}$ has length $n=4$. +where $m=3$ in our case, the maximum length of +the vector $\alpha$. Note that the vector $\bm{\beta}$ has length $n=4$. Below we will find an even more efficient representation. !split ===== A more efficient way of coding the above Convolution ===== @@ -399,6 +524,9 @@ as a matrix-vector multiplication \] !et +!split +===== Commutative process ===== + The process is commutative and we can easily see that we can rewrite the multiplication in terms of a matrix holding $\beta$ and a vector holding $\alpha$. In this case we have !bt @@ -421,7 +549,8 @@ require. - +!split +===== Toeplitz matrices ===== The above matrices are examples of so-called "Toeplitz matrices":"https://link.springer.com/book/10.1007/978-93-86279-04-0". A @@ -460,20 +589,131 @@ o "Fourier Transform Layer":"https://www.sciencedirect.com/science/article/pii/S !split ===== Generalizing the above one-dimensional case ===== -In order to align the above simple case with the more general convolution cases, we rename $\bm{\alpha}$, whose length is $m=3$, with $\bm{w}$. -We will interpret $\bm{w}$ as a weight/filter function with which we want to perform the convolution with an input varibale $\bm{x}$. -We replace thus $\bm{\beta}$ with $\bm{x}$ and $\bm{\delta}$ with $\bm{s}$ and have +In order to align the above simple case with the more general +convolution cases, we rename $\bm{\alpha}$, whose length is $m=3$, +with $\bm{w}$. We will interpret $\bm{w}$ as a weight/filter function +with which we want to perform the convolution with an input variable +$\bm{x}$ of length $n$. We will assume always that the filter +$\bm{w}$ has dimensionality $m \le n$. + +We replace thus $\bm{\beta}$ with $\bm{x}$ and $\bm{\delta}$ with $\bm{y}$ and have !bt \[ -s(i) \left(x*w\right)(i)= \sum_{k=0}^{k=m-1}w(k)x(i-k), +y(i)= \left(x*w\right)(i)= \sum_{k=0}^{k=m-1}w(k)x(i-k), \] !et where $m=3$ in our case, the maximum length of the vector $\bm{w}$. Here the symbol $*$ represents the mathematical operation of convolution. +!split +===== Memory considerations ===== -===== Two-dimensional Objects ===== +This expression leaves us however with some terms with negative +indices, for example $x(-1)$ and $x(-2)$ which may not be defined. Our +vector $\bm{x}$ has components $x(0)$, $x(1)$, $x(2)$ and $x(3)$. + +The index $j$ for $\bm{x}$ runs from $j=0$ to $j=3$ since $\bm{x}$ is meant to +represent a third-order polynomial. + +Furthermore, the index $i$ runs from $i=0$ to $i=5$ since $\bm{y}$ +contains the coefficients of a fifth-order polynomial. When $i=5$ we +may also have values of $x(4)$ and $x(5)$ which are not defined. + + +!split +===== Padding ===== + +The solution to this is what is called _padding_! We simply define a +new vector $x$ with two added elements set to zero before $x(0)$ and +two new elements after $x(3)$ set to zero. That is, we augment the +length of $\bm{x}$ from $n=4$ to $n+2P=8$, where $P=2$ is the padding +constant (a new hyperparameter), see discussions below as well. + +!split +===== New vector ===== + +We have a new vector defined as $x(0)=0$, $x(1)=0$, +$x(2)=\beta_0$, $x(3)=\beta_1$, $x(4)=\beta_2$, $x(5)=\beta_3$, +$x(6)=0$, and $x(7)=0$. + + +We have added four new elements, which +are all zero. The benefit is that we can rewrite the equation for +$\bm{y}$, with $i=0,1,\dots,5$, +!bt +\[ +y(i) = \sum_{k=0}^{k=m-1}w(k)x(i+(m-1)-k). +\] +!et + +As an example, we have +!bt +\[ +y(4)=x(6)w(0)+x(5)w(1)+x(4)w(2)=0\times \alpha_0+\beta_3\alpha_1+\beta_2\alpha_2, +\] +!et +as before except that we have an additional term $x(6)w(0)$, which is zero. + +Similarly, for the fifth-order term we have +!bt +\[ +y(5)=x(7)w(0)+x(6)w(1)+x(5)w(2)=0\times \alpha_0+0\times\alpha_1+\beta_3\alpha_2. +\] +!et + +The zeroth-order term is +!bt +\[ +y(0)=x(2)w(0)+x(1)w(1)+x(0)w(2)=\beta_0 \alpha_0+0\times\alpha_1+0\times\alpha_2=\alpha_0\beta_0. +\] +!et + +!split +===== Rewriting as dot products ===== + +If we now flip the filter/weight vector, with the following term as a typical example +!bt +\[ +y(0)=x(2)w(0)+x(1)w(1)+x(0)w(2)=x(2)\tilde{w}(2)+x(1)\tilde{w}(1)+x(0)\tilde{w}(0), +\] +!et +with $\tilde{w}(0)=w(2)$, $\tilde{w}(1)=w(1)$, and $\tilde{w}(2)=w(0)$, we can then rewrite the above sum as a dot product of +$x(i:i+(m-1))\tilde{w}$ for element $y(i)$, where $x(i:i+(m-1))$ is simply a patch of $\bm{x}$ of size $m-1$. + +The padding $P$ we have introduced for the convolution stage is just +another hyperparameter which is introduced as part of the +architecture. Similarly, below we will also introduce another +hyperparameter called _Stride_ $S$. + + +!split +===== Cross correlation ===== + +In essentially all applications one uses what is called cross correlation instead of the standard convolution described above. +This means that multiplication is performed in the same direction and instead of the general expression we have discussed above (with infinite sums) +!bt +\[ +y(i) = \sum_{k=-\infty}^{k=\infty}w(k)x(i-k), +\] +!et +we have now +!bt +\[ +y(i) = \sum_{k=-\infty}^{k=\infty}w(k)x(i+k). +\] +!et + +Both TensorFlow and PyTorch (as well as our own code example below), +implement the last equation, although it is normally referred to as +convolution. The same padding rules and stride rules discussed below +apply to this expression as well. + +We leave it as an exercise for you to convince yourself that the example we have discussed till now, gives the same final expression using the last expression. + + + +===== Two-dimensional objects ===== We are now ready to start studying the discrete convolutions relevant for convolutional neural networks. We often use convolutions over more than one dimension at a time. If @@ -493,10 +733,14 @@ Y(i,j)=(X * W)(i,j) = \sum_m\sum_n X(i-m,j-n)W(m,n). \] !et -Normally the latter is more straightforward to implement in a machine larning library since there is less variation in the range of values of $m$ and $n$. +Normally the latter is more straightforward to implement in a machine +larning library since there is less variation in the range of values +of $m$ and $n$. -Many deep learning libraries implement cross-correlation instead of convolution (although it is referred to s convolution) +As mentioned above, most deep learning libraries implement +cross-correlation instead of convolution (although it is referred to as +convolution) !bt Y(i,j)=(X * W)(i,j) = \sum_m\sum_n X(i+m,j+n)W(m,n). \] @@ -505,7 +749,7 @@ Y(i,j)=(X * W)(i,j) = \sum_m\sum_n X(i+m,j+n)W(m,n). !split -===== CNNs in more detail ===== +===== CNNs in more detail, simple example ===== Let assume we have an input matrix $X$ of dimensionality $3\times 3$ @@ -574,43 +818,93 @@ is now given by $\bm{W}'\bm{X}'$ which is a vector of length $4$ instead of the !split -===== Performing a discrete convolution with padding ("From Raschka et al":"https://github.com/rasbt/machine-learning-book") ===== +===== The convolution stage ===== -FIGURE: [figslides/discreteconv.png, width=500 frac=0.67] A deep CNN +The convolution stage, where we apply different filters $\bm{W}$ in +order to reduce the dimensionality of an image, adds, in addition to +the weights and biases (to be trained by the back propagation +algorithm) that define the filters, two new hyperparameters, the so-called +_padding_ $P$ and the stride $S$. !split -===== Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book") ===== +===== Finding the number of parameters ===== -FIGURE: [figslides/discreteconv1.png, width=500 frac=0.67] A deep CNN +In the above example we have an input matrix of dimension $3\times +3$. In general we call the input for an input volume and it is defined +by its width $H_1$, height $H_1$ and depth $D_1$. If we have the +standard three color channels $D_1=3$. +The above example has $W_1=H_1=3$ and $D_1=1$. + +When we introduce the filter we have the following additional hyperparameters +o $K$ the number of filters. It is common to perform the convolution of the input several times since by experience shrinking the input too fast does not work well +o $F$ as the filter's spatial extent +o $S$ as the stride parameter +o $P$ as the padding parameter + +These parameters are defined by the architecture of the network and are not included in the training. !split -===== Set of filters ===== +===== New image (or volume) ===== -The collection of kernels/filters $W$ defining a discrete convolution has a shape -corresponding to some permutation of $(n, m, k_1, \ldots, k_N)$, where +Acting with the filter on the input volume produces an output volume +which is defined by its width $W_2$, its height $H_2$ and its depth +$D_2$. +These are defined by the following relations !bt -\begin{equation*} -\begin{split} - n &\equiv \text{number of output feature maps},\\ - m &\equiv \text{number of input feature maps},\\ - k_j &\equiv \text{kernel size along axis $j$}. -\end{split} -\end{equation*} +\[ +W_2 = \frac{(W_1-F+2P)}{S}+1, +\] !et +!bt +\[ +H_2 = \frac{(H_1-F+2P)}{S}+1, +\] +!et +and $D_2=K$. -The following properties affect the output size $o_j$ of a convolutional layer -along axis $j$: +!split +===== Parameters to train, common settings ===== -o $i_j$: input size along axis $j$, -o $k_j$: kernel/filter size along axis $j$, -o stride (distance between two consecutive positions of the kernel/filter) along axis $j$, -o zero padding (number of zeros concatenated at the beginning and at the end of an axis) along axis $j$. +With parameter sharing, the convolution involves thus for each filter $F\times F\times D_1$ weights plus one bias parameter. -For instance, the above examples shows a $2\times 2$ kernel/filter $\bm{W}$ applied to a $3 \times 3$ input padded with a $0 \times 0$ -border of zeros using $1 \times 1$ strides. +In total we have +!bt +\[ +\left(F\times F\times D_1)\right) \times K+(K\mathrm{--biases}), +\] +!et +parameters to train by back propagation. + +It is common to let $K$ come in powers of $2$, that is $32$, $64$, $128$ etc. + +!bblock Common settings +o $\begin{array}{c} F=3 & S=1 & P=1 \end{array}$ +o $\begin{array}{c} F=5 & S=1 & P=2 \end{array}$ +o $\begin{array}{c} F=5 & S=2 & P=\mathrm{open} \end{array}$ +o $\begin{array}{c} F=1 & S=1 & P=0 \end{array}$ +!eblock + +!split +===== Examples of CNN setups ===== + +Let us assume we have an input volume $V$ given by an image of dimensionality +$32\times 32 \times 3$, that is three color channels and $32\times 32$ pixels. + +We apply a filter of dimension $5\times 5$ ten times with stride $S=1$ and padding $P=0$. + +The output volume is given by $(32-5)/1+1=28$, resulting in ten images +of dimensionality $28\times 28\times 3$. + +The total number of parameters to train for each filter is then +$5\times 5\times 3+1$, where the last parameter is the bias. This +gives us $76$ parameters for each filter, leading to a total of $760$ +parameters for the ten filters. + +How many parameters will a filter of dimensionality $3\times 3$ +(adding color channels) result in if we produce $32$ new images? Use $S=1$ and $P=0$. Note that strides constitute a form of _subsampling_. As an alternative to being interpreted as a measure of how much the kernel/filter is translated, strides @@ -618,117 +912,29 @@ can also be viewed as how much of the output is retained. For instance, moving the kernel by hops of two is equivalent to moving the kernel by hops of one but retaining only odd output elements. + + +!split +===== Summarizing: Performing a general discrete convolution ("From Raschka et al":"https://github.com/rasbt/machine-learning-book") ===== + +FIGURE: [figslides/discreteconv1.png, width=500 frac=0.67] A deep CNN + + + !split ===== Pooling ===== -In addition to discrete convolutions themselves, {\em pooling\/} operations +In addition to discrete convolutions themselves, _pooling_ operations make up another important building block in CNNs. Pooling operations reduce the size of feature maps by using some function to summarize subregions, such as taking the average or the maximum value. Pooling works by sliding a window across the input and feeding the content of -the window to a {\em pooling function}. In some sense, pooling works very much +the window to a _pooling function_. In some sense, pooling works very much like a discrete convolution, but replaces the linear combination described by -the kernel with some other function. Poolin -provides an example for average pooling, and -does the same for max pooling. - -The following properties affect the output size $o_j$ of a pooling layer -along axis $j$: +the kernel with some other function. -o $i_j$: input size along axis $j$, -o $k_j$: pooling window size along axis $j$, -o $s_j$: stride (distance between two consecutive positions of the pooling window) along axis $j$. - - - -The analysis of the relationship between convolutional layer properties is eased -by the fact that they don't interact across axes, i.e., the choice of kernel -size, stride and zero padding along axis $j$ only affects the output size of -axis $j$. Because of that, we will focus on the following simplified -setting: - - -o 2-D discrete convolutions ($N = 2$), -o square inputs ($i_1 = i_2 = i$), -o square kernel size ($k_1 = k_2 = k$), -o same strides along both axes ($s_1 = s_2 = s$), -o same zero padding along both axes ($p_1 = p_2 = p$). - -This facilitates the analysis and the visualization, but keep in mind that the -results outlined here also generalize to the N-D and non-square cases. - -!split -===== No zero padding, unit strides ===== - -The simplest case to analyze is when the kernel just slides across every -position of the input (i.e., $s = 1$ and $p = 0$). - - - -For any $i$ and $k$, and for $s = 1$ and $p = 0$, -!bt -\begin{equation*} - o = (i - k) + 1. -\end{equation*} -!et - -!split -===== Zero padding, unit strides ===== - -To factor in zero padding (i.e., only restricting to $s = 1$), let's consider -its effect on the effective input size: padding with $p$ zeros changes the -effective input size from $i$ to $i + 2p$. In the general case, we can infer the following -relationship - -For any $i$, $k$ and $p$, and for $s = 1$, -!bt -\begin{equation*} - o = (i - k) + 2p + 1. -\end{equation*} -!et - -!split -===== Half (same) padding ===== - -Having the output size be the same as the input size (i.e., $o = i$) can be a -desirable property: - -For any $i$ and for $k$ odd ($k = 2n + 1, \quad n \in \mathbb{N}$), $s = 1$ and -$p = \lfloor k / 2 \rfloor = n$, -!bt -\begin{equation*} -\begin{split} - o &= i + 2 \lfloor k / 2 \rfloor - (k - 1) \\ - &= i + 2n - 2n \\ - &= i. -\end{split} -\end{equation*} -!et - - -!split -===== Full padding ===== - -While convolving a kernel generally decreases the output size with -respect to the input size, sometimes the opposite is required. This can be -achieved with proper zero padding: - - -For any $i$ and $k$, and for $p = k - 1$ and $s = 1$, -!bt -\begin{equation*} -\begin{split} - o &= i + 2(k - 1) - (k - 1) \\ - &= i + (k - 1). -\end{split} -\end{equation*} -!et - -This is sometimes referred to as full padding, because in this -setting every possible partial or complete superimposition of the kernel on the -input feature map is taken into account. !split ===== Pooling arithmetic ===== @@ -740,16 +946,6 @@ outputting the maximum value of each patch. Other kinds of pooling exist, e.g., mean or average pooling, which all share the same idea of aggregating the input locally by applying a non-linearity to the content of some patches. -Since pooling does not involve -zero padding, the relationship describing the general case is as follows: - - -For any $i$, $k$ and $s$, -!bt -\begin{equation*} - o = \left\lfloor \frac{i - k}{s} \right\rfloor + 1. -\end{equation*} -!et !split ===== Pooling types ("From Raschka et al":"https://github.com/rasbt/machine-learning-book") ===== @@ -758,6 +954,387 @@ FIGURE: [figslides/maxpooling.png, width=500 frac=0.67] A deep CNN +!split +===== Building convolutional neural networks in Tensorflow and Keras ===== + + +As discussed above, CNNs are neural networks built from the assumption that the inputs +to the network are 2D images. This is important because the number of features or pixels in images +grows very fast with the image size, and an enormous number of weights and biases are needed in order to build an accurate network. + +As before, we still have our input, a hidden layer and an output. What's novel about convolutional networks +are the _convolutional_ and _pooling_ layers stacked in pairs between the input and the hidden layer. +In addition, the data is no longer represented as a 2D feature matrix, instead each input is a number of 2D +matrices, typically 1 for each color dimension (Red, Green, Blue). + + +!split +===== Setting it up ===== + +It means that to represent the entire +dataset of images, we require a 4D matrix or _tensor_. This tensor has the dimensions: +!bt +\[ +(n_{inputs},\, n_{pixels, width},\, n_{pixels, height},\, depth) . +\] +!et + +!split +===== The MNIST dataset again ===== + +The MNIST dataset consists of grayscale images with a pixel size of +$28\times 28$, meaning we require $28 \times 28 = 724$ weights to each +neuron in the first hidden layer. + +If we were to analyze images of size $128\times 128$ we would require +$128 \times 128 = 16384$ weights to each neuron. Even worse if we were +dealing with color images, as most images are, we have an image matrix +of size $128\times 128$ for each color dimension (Red, Green, Blue), +meaning 3 times the number of weights $= 49152$ are required for every +single neuron in the first hidden layer. + + +!split +===== Strong correlations ===== + +Images typically have strong local correlations, meaning that a small +part of the image varies little from its neighboring regions. If for +example we have an image of a blue car, we can roughly assume that a +small blue part of the image is surrounded by other blue regions. + +Therefore, instead of connecting every single pixel to a neuron in the +first hidden layer, as we have previously done with deep neural +networks, we can instead connect each neuron to a small part of the +image (in all 3 RGB depth dimensions). The size of each small area is +fixed, and known as a "receptive":"https://en.wikipedia.org/wiki/Receptive_field". + + +!split +===== Layers of a CNN ===== + +The layers of a convolutional neural network arrange neurons in 3D: width, height and depth. +The input image is typically a square matrix of depth 3. + +A _convolution_ is performed on the image which outputs +a 3D volume of neurons. The weights to the input are arranged in a number of 2D matrices, known as _filters_. + + +Each filter slides along the input image, taking the dot product +between each small part of the image and the filter, in all depth +dimensions. This is then passed through a non-linear function, +typically the _Rectified Linear (ReLu)_ function, which serves as the +activation of the neurons in the first convolutional layer. This is +further passed through a _pooling layer_, which reduces the size of the +convolutional layer, e.g. by taking the maximum or average across some +small regions, and this serves as input to the next convolutional +layer. + + +!split +===== Systematic reduction ===== + +By systematically reducing the size of the input volume, through +convolution and pooling, the network should create representations of +small parts of the input, and then from them assemble representations +of larger areas. The final pooling layer is flattened to serve as +input to a hidden layer, such that each neuron in the final pooling +layer is connected to every single neuron in the hidden layer. This +then serves as input to the output layer, e.g. a softmax output for +classification. + + +!split +===== Prerequisites: Collect and pre-process data ===== +!bc pycod +# import necessary packages +import numpy as np +import matplotlib.pyplot as plt +from sklearn import datasets + + +# ensure the same random numbers appear every time +np.random.seed(0) + +# display images in notebook +%matplotlib inline +plt.rcParams['figure.figsize'] = (12,12) + + +# download MNIST dataset +digits = datasets.load_digits() + +# define inputs and labels +inputs = digits.images +labels = digits.target + +# RGB images have a depth of 3 +# our images are grayscale so they should have a depth of 1 +inputs = inputs[:,:,:,np.newaxis] + +print("inputs = (n_inputs, pixel_width, pixel_height, depth) = " + str(inputs.shape)) +print("labels = (n_inputs) = " + str(labels.shape)) + + +# choose some random images to display +n_inputs = len(inputs) +indices = np.arange(n_inputs) +random_indices = np.random.choice(indices, size=5) + +for i, image in enumerate(digits.images[random_indices]): + plt.subplot(1, 5, i+1) + plt.axis('off') + plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest') + plt.title("Label: %d" % digits.target[random_indices[i]]) +plt.show() +!ec + + +!split +===== Importing Keras and Tensorflow ===== +!bc pycod +from tensorflow.keras import datasets, layers, models +from tensorflow.keras.layers import Input +from tensorflow.keras.models import Sequential #This allows appending layers to existing models +from tensorflow.keras.layers import Dense #This allows defining the characteristics of a particular layer +from tensorflow.keras import optimizers #This allows using whichever optimiser we want (sgd,adam,RMSprop) +from tensorflow.keras import regularizers #This allows using whichever regularizer we want (l1,l2,l1_l2) +from tensorflow.keras.utils import to_categorical #This allows using categorical cross entropy as the cost function +#from tensorflow.keras import Conv2D +#from tensorflow.keras import MaxPooling2D +#from tensorflow.keras import Flatten + +from sklearn.model_selection import train_test_split + +# representation of labels +labels = to_categorical(labels) + +# split into train and test data +# one-liner from scikit-learn library +train_size = 0.8 +test_size = 1 - train_size +X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size, + test_size=test_size) +!ec + +!split +===== Running with Keras ===== + +!bc pycod +def create_convolutional_neural_network_keras(input_shape, receptive_field, + n_filters, n_neurons_connected, n_categories, + eta, lmbd): + model = Sequential() + model.add(layers.Conv2D(n_filters, (receptive_field, receptive_field), input_shape=input_shape, padding='same', + activation='relu', kernel_regularizer=regularizers.l2(lmbd))) + model.add(layers.MaxPooling2D(pool_size=(2, 2))) + model.add(layers.Flatten()) + model.add(layers.Dense(n_neurons_connected, activation='relu', kernel_regularizer=regularizers.l2(lmbd))) + model.add(layers.Dense(n_categories, activation='softmax', kernel_regularizer=regularizers.l2(lmbd))) + + sgd = optimizers.SGD(lr=eta) + model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy']) + + return model + +epochs = 100 +batch_size = 100 +input_shape = X_train.shape[1:4] +receptive_field = 3 +n_filters = 10 +n_neurons_connected = 50 +n_categories = 10 + +eta_vals = np.logspace(-5, 1, 7) +lmbd_vals = np.logspace(-5, 1, 7) +!ec + +!split +===== Final part ===== + +!bc pycod +CNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object) + +for i, eta in enumerate(eta_vals): + for j, lmbd in enumerate(lmbd_vals): + CNN = create_convolutional_neural_network_keras(input_shape, receptive_field, + n_filters, n_neurons_connected, n_categories, + eta, lmbd) + CNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0) + scores = CNN.evaluate(X_test, Y_test) + + CNN_keras[i][j] = CNN + + print("Learning rate = ", eta) + print("Lambda = ", lmbd) + print("Test accuracy: %.3f" % scores[1]) + print() +!ec + +!split +===== Final visualization ===== + +!bc pycod +# visual representation of grid search +# uses seaborn heatmap, could probably do this in matplotlib +import seaborn as sns + +sns.set() + +train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals))) +test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals))) + +for i in range(len(eta_vals)): + for j in range(len(lmbd_vals)): + CNN = CNN_keras[i][j] + + train_accuracy[i][j] = CNN.evaluate(X_train, Y_train)[1] + test_accuracy[i][j] = CNN.evaluate(X_test, Y_test)[1] + + +fig, ax = plt.subplots(figsize = (10, 10)) +sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis") +ax.set_title("Training Accuracy") +ax.set_ylabel("$\eta$") +ax.set_xlabel("$\lambda$") +plt.show() + +fig, ax = plt.subplots(figsize = (10, 10)) +sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis") +ax.set_title("Test Accuracy") +ax.set_ylabel("$\eta$") +ax.set_xlabel("$\lambda$") +plt.show() +!ec + + + + +!split +===== The CIFAR01 data set ===== + +The CIFAR10 dataset contains 60,000 color images in 10 classes, with +6,000 images in each class. The dataset is divided into 50,000 +training images and 10,000 testing images. The classes are mutually +exclusive and there is no overlap between them. + +!bc pycod +import tensorflow as tf + +from tensorflow.keras import datasets, layers, models +import matplotlib.pyplot as plt + +# We import the data set +(train_images, train_labels), (test_images, test_labels) = datasets.cifar10.load_data() + +# Normalize pixel values to be between 0 and 1 by dividing by 255. +train_images, test_images = train_images / 255.0, test_images / 255.0 + +!ec + + + +!split +===== Verifying the data set ===== + +To verify that the dataset looks correct, let's plot the first 25 images from the training set and display the class name below each image. + +!bc pycod +class_names = ['airplane', 'automobile', 'bird', 'cat', 'deer', + 'dog', 'frog', 'horse', 'ship', 'truck'] +plt.figure(figsize=(10,10)) +for i in range(25): + plt.subplot(5,5,i+1) + plt.xticks([]) + plt.yticks([]) + plt.grid(False) + plt.imshow(train_images[i], cmap=plt.cm.binary) + # The CIFAR labels happen to be arrays, + # which is why you need the extra index + plt.xlabel(class_names[train_labels[i][0]]) +plt.show() +!ec + +!split +===== Set up the model ===== + +The 6 lines of code below define the convolutional base using a common pattern: a stack of Conv2D and MaxPooling2D layers. + +As input, a CNN takes tensors of shape (image_height, image_width, color_channels), ignoring the batch size. If you are new to these dimensions, color_channels refers to (R,G,B). In this example, you will configure our CNN to process inputs of shape (32, 32, 3), which is the format of CIFAR images. You can do this by passing the argument input_shape to our first layer. + +!bc pycod +model = models.Sequential() +model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3))) +model.add(layers.MaxPooling2D((2, 2))) +model.add(layers.Conv2D(64, (3, 3), activation='relu')) +model.add(layers.MaxPooling2D((2, 2))) +model.add(layers.Conv2D(64, (3, 3), activation='relu')) + +# Let's display the architecture of our model so far. + +model.summary() +!ec + +You can see that the output of every Conv2D and MaxPooling2D layer is a 3D tensor of shape (height, width, channels). The width and height dimensions tend to shrink as you go deeper in the network. The number of output channels for each Conv2D layer is controlled by the first argument (e.g., 32 or 64). Typically, as the width and height shrink, you can afford (computationally) to add more output channels in each Conv2D layer. + + + + +!split +===== Add Dense layers on top ===== + +To complete our model, you will feed the last output tensor from the +convolutional base (of shape (4, 4, 64)) into one or more Dense layers +to perform classification. Dense layers take vectors as input (which +are 1D), while the current output is a 3D tensor. First, you will +flatten (or unroll) the 3D output to 1D, then add one or more Dense +layers on top. CIFAR has 10 output classes, so you use a final Dense +layer with 10 outputs and a softmax activation. + +!bc pycod +model.add(layers.Flatten()) +model.add(layers.Dense(64, activation='relu')) +model.add(layers.Dense(10)) +Here's the complete architecture of our model. + +model.summary() +!ec +As you can see, our (4, 4, 64) outputs were flattened into vectors of shape (1024) before going through two Dense layers. + +!split +===== Compile and train the model ===== + +!bc pycod +model.compile(optimizer='adam', + loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), + metrics=['accuracy']) + +history = model.fit(train_images, train_labels, epochs=10, + validation_data=(test_images, test_labels)) + +!ec + + +!split +===== Finally, evaluate the model ===== + +!bc pycod +plt.plot(history.history['accuracy'], label='accuracy') +plt.plot(history.history['val_accuracy'], label = 'val_accuracy') +plt.xlabel('Epoch') +plt.ylabel('Accuracy') +plt.ylim([0.5, 1]) +plt.legend(loc='lower right') + +test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2) + +print(test_acc) + +!ec + + + + + !split ===== Building our own CNN code ===== @@ -767,6 +1344,8 @@ 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 codes here were developed by Eric Reber and Gregor Kajda during spring 2023._ + The CNN is compatible with all schedulers, cost functions and activation functions discussed in constructing our neural network codes. @@ -1130,29 +1709,29 @@ functions, which is typically expressed as: \] !et -Here, f and g are the two functions on which we want to perform an +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 +$(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: +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]. +(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* +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]. +(f \ast g)(i, j)\sum_{m=0}^{M-1}\sum_{n=0}^{N-1} f(m,n) g(i-m, j-n). \] !et @@ -1164,7 +1743,7 @@ 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$ +suppose we have an image $f$ of dimension $6 \times 6$ !bt \[ @@ -1179,7 +1758,7 @@ f = \begin{bmatrix} \] !et -and a $3 \times 3$ kernel *g* called a low-pass filter. Note that the +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. @@ -1195,9 +1774,9 @@ g = \frac{1}{9} !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 +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*: +kernel $g$: !bt \[ @@ -1218,24 +1797,23 @@ kernel *g*: \frac{9}{9} & \frac{5}{9} & \frac{9}{9} \\ \frac{1}{9} & \frac{5}{9} & \frac{9}{9} \\ \end {bmatrix} -= \textbf{A} += \bm{A} \] !et -Then, following the multiplication, we summarize all the elements of the resulting matrix A: +Then, following the multiplication, we summarize all the elements of the resulting matrix $\bm{A}$: !bt \[ -(f \ast g)[0, 0]= \sum_{i=0}^{2} \sum_{j=0}^{2} a_{i,j} = 5 +(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)$. -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 +Here we use a stride of $S=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* +$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 @@ -1254,19 +1832,25 @@ The full result of the convolution is: \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. + +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 +r =\lfloor \frac{\mathrm{kernel height}}{2} \rfloor \cdot 2 \\ +c =\lfloor \frac{\mathrm{kernel width}}{2} \rfloor \cdot 2 \] !et -Note the notation $\lfloor \frac{kernel width}{2} \rfloor$ means that +Note the notation $\lfloor \frac{\mathrm{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 in case $\frac{\mathrm{kernel width}}{2}$ results in a floating point number. Using those simple equations, we find out by how much we have to @@ -1291,10 +1875,13 @@ zero-padded rows and columns: 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}. \] -\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.~ + +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 @@ -1370,9 +1957,10 @@ 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 that is not +rotated by 180 degrees is called cross-correlation, which is normally implemented in most libraries. !bc pycod @@ -1406,7 +1994,7 @@ CNN is able to use kernels to make better predictions than a regular feed forward neural network. !bc pycod -# Now an example using a real image and first a gaussian low-pass filter and then a sobel filter +# 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 @@ -3235,7 +3823,7 @@ 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$. +will use the MNIST dataset and use 10000 $28 \times 28$ images. !bc pycod from sklearn.datasets import fetch_openml @@ -3530,257 +4118,6 @@ optimization technique. -!split -===== Building convolutional neural networks in Tensorflow and Keras ===== - - -As discussed above, CNNs are neural networks built from the assumption that the inputs -to the network are 2D images. This is important because the number of features or pixels in images -grows very fast with the image size, and an enormous number of weights and biases are needed in order to build an accurate network. - -As before, we still have our input, a hidden layer and an output. What's novel about convolutional networks -are the _convolutional_ and _pooling_ layers stacked in pairs between the input and the hidden layer. -In addition, the data is no longer represented as a 2D feature matrix, instead each input is a number of 2D -matrices, typically 1 for each color dimension (Red, Green, Blue). - - -!split -===== Setting it up ===== - -It means that to represent the entire -dataset of images, we require a 4D matrix or _tensor_. This tensor has the dimensions: -!bt -\[ -(n_{inputs},\, n_{pixels, width},\, n_{pixels, height},\, depth) . -\] -!et - -!split -===== The MNIST dataset again ===== - -The MNIST dataset consists of grayscale images with a pixel size of -$28\times 28$, meaning we require $28 \times 28 = 724$ weights to each -neuron in the first hidden layer. - -If we were to analyze images of size $128\times 128$ we would require -$128 \times 128 = 16384$ weights to each neuron. Even worse if we were -dealing with color images, as most images are, we have an image matrix -of size $128\times 128$ for each color dimension (Red, Green, Blue), -meaning 3 times the number of weights $= 49152$ are required for every -single neuron in the first hidden layer. - - -!split -===== Strong correlations ===== - -Images typically have strong local correlations, meaning that a small -part of the image varies little from its neighboring regions. If for -example we have an image of a blue car, we can roughly assume that a -small blue part of the image is surrounded by other blue regions. - -Therefore, instead of connecting every single pixel to a neuron in the -first hidden layer, as we have previously done with deep neural -networks, we can instead connect each neuron to a small part of the -image (in all 3 RGB depth dimensions). The size of each small area is -fixed, and known as a "receptive":"https://en.wikipedia.org/wiki/Receptive_field". - - -!split -===== Layers of a CNN ===== - -The layers of a convolutional neural network arrange neurons in 3D: width, height and depth. -The input image is typically a square matrix of depth 3. - -A _convolution_ is performed on the image which outputs -a 3D volume of neurons. The weights to the input are arranged in a number of 2D matrices, known as _filters_. - - -Each filter slides along the input image, taking the dot product -between each small part of the image and the filter, in all depth -dimensions. This is then passed through a non-linear function, -typically the _Rectified Linear (ReLu)_ function, which serves as the -activation of the neurons in the first convolutional layer. This is -further passed through a _pooling layer_, which reduces the size of the -convolutional layer, e.g. by taking the maximum or average across some -small regions, and this serves as input to the next convolutional -layer. - - -!split -===== Systematic reduction ===== - -By systematically reducing the size of the input volume, through -convolution and pooling, the network should create representations of -small parts of the input, and then from them assemble representations -of larger areas. The final pooling layer is flattened to serve as -input to a hidden layer, such that each neuron in the final pooling -layer is connected to every single neuron in the hidden layer. This -then serves as input to the output layer, e.g. a softmax output for -classification. - - -!split -===== Prerequisites: Collect and pre-process data ===== -!bc pycod -# import necessary packages -import numpy as np -import matplotlib.pyplot as plt -from sklearn import datasets - - -# ensure the same random numbers appear every time -np.random.seed(0) - -# display images in notebook -%matplotlib inline -plt.rcParams['figure.figsize'] = (12,12) - - -# download MNIST dataset -digits = datasets.load_digits() - -# define inputs and labels -inputs = digits.images -labels = digits.target - -# RGB images have a depth of 3 -# our images are grayscale so they should have a depth of 1 -inputs = inputs[:,:,:,np.newaxis] - -print("inputs = (n_inputs, pixel_width, pixel_height, depth) = " + str(inputs.shape)) -print("labels = (n_inputs) = " + str(labels.shape)) - - -# choose some random images to display -n_inputs = len(inputs) -indices = np.arange(n_inputs) -random_indices = np.random.choice(indices, size=5) - -for i, image in enumerate(digits.images[random_indices]): - plt.subplot(1, 5, i+1) - plt.axis('off') - plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest') - plt.title("Label: %d" % digits.target[random_indices[i]]) -plt.show() -!ec - - -!split -===== Importing Keras and Tensorflow ===== -!bc pycod -from tensorflow.keras import datasets, layers, models -from tensorflow.keras.layers import Input -from tensorflow.keras.models import Sequential #This allows appending layers to existing models -from tensorflow.keras.layers import Dense #This allows defining the characteristics of a particular layer -from tensorflow.keras import optimizers #This allows using whichever optimiser we want (sgd,adam,RMSprop) -from tensorflow.keras import regularizers #This allows using whichever regularizer we want (l1,l2,l1_l2) -from tensorflow.keras.utils import to_categorical #This allows using categorical cross entropy as the cost function -#from tensorflow.keras import Conv2D -#from tensorflow.keras import MaxPooling2D -#from tensorflow.keras import Flatten - -from sklearn.model_selection import train_test_split - -# representation of labels -labels = to_categorical(labels) - -# split into train and test data -# one-liner from scikit-learn library -train_size = 0.8 -test_size = 1 - train_size -X_train, X_test, Y_train, Y_test = train_test_split(inputs, labels, train_size=train_size, - test_size=test_size) -!ec - -!split -===== Running with Keras ===== - -!bc pycod -def create_convolutional_neural_network_keras(input_shape, receptive_field, - n_filters, n_neurons_connected, n_categories, - eta, lmbd): - model = Sequential() - model.add(layers.Conv2D(n_filters, (receptive_field, receptive_field), input_shape=input_shape, padding='same', - activation='relu', kernel_regularizer=regularizers.l2(lmbd))) - model.add(layers.MaxPooling2D(pool_size=(2, 2))) - model.add(layers.Flatten()) - model.add(layers.Dense(n_neurons_connected, activation='relu', kernel_regularizer=regularizers.l2(lmbd))) - model.add(layers.Dense(n_categories, activation='softmax', kernel_regularizer=regularizers.l2(lmbd))) - - sgd = optimizers.SGD(learning_rate=eta) - model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy']) - - return model - -epochs = 100 -batch_size = 100 -input_shape = X_train.shape[1:4] -receptive_field = 3 -n_filters = 10 -n_neurons_connected = 50 -n_categories = 10 - -eta_vals = np.logspace(-5, 1, 7) -lmbd_vals = np.logspace(-5, 1, 7) -!ec - -!split -===== Final part ===== - -!bc pycod -CNN_keras = np.zeros((len(eta_vals), len(lmbd_vals)), dtype=object) - -for i, eta in enumerate(eta_vals): - for j, lmbd in enumerate(lmbd_vals): - CNN = create_convolutional_neural_network_keras(input_shape, receptive_field, - n_filters, n_neurons_connected, n_categories, - eta, lmbd) - CNN.fit(X_train, Y_train, epochs=epochs, batch_size=batch_size, verbose=0) - scores = CNN.evaluate(X_test, Y_test) - - CNN_keras[i][j] = CNN - - print("Learning rate = ", eta) - print("Lambda = ", lmbd) - print("Test accuracy: %.3f" % scores[1]) - print() -!ec - -!split -===== Final visualization ===== - -!bc pycod -# visual representation of grid search -# uses seaborn heatmap, could probably do this in matplotlib -import seaborn as sns - -sns.set() - -train_accuracy = np.zeros((len(eta_vals), len(lmbd_vals))) -test_accuracy = np.zeros((len(eta_vals), len(lmbd_vals))) - -for i in range(len(eta_vals)): - for j in range(len(lmbd_vals)): - CNN = CNN_keras[i][j] - - train_accuracy[i][j] = CNN.evaluate(X_train, Y_train)[1] - test_accuracy[i][j] = CNN.evaluate(X_test, Y_test)[1] - - -fig, ax = plt.subplots(figsize = (10, 10)) -sns.heatmap(train_accuracy, annot=True, ax=ax, cmap="viridis") -ax.set_title("Training Accuracy") -ax.set_ylabel("$\eta$") -ax.set_xlabel("$\lambda$") -plt.show() - -fig, ax = plt.subplots(figsize = (10, 10)) -sns.heatmap(test_accuracy, annot=True, ax=ax, cmap="viridis") -ax.set_title("Test Accuracy") -ax.set_ylabel("$\eta$") -ax.set_xlabel("$\lambda$") -plt.show() -!ec