3.5 MiB
Week 44, Convolutional Neural Networks (CNN)
Morten Hjorth-Jensen, Department of Physics, University of Oslo and Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
Date: October 30-November 3
Plan for week 44
Material for the active learning sessions on Tuesday and Wednesday.
-
Exercise on writing your own neural network code, application to the OR and XOR gates, see notes from last week
-
The exercise this week is a continuation from last week
-
Discussion of project 2
Material for the lecture on Thursday November 2, 2023.
-
Convolutional Neural Networks
-
Readings and Videos:
-
These lecture notes
-
For a more in depth discussion on neural networks we recommend Goodfellow et al chapter 9. See also chapter 11 and 12 on practicalities and applications
-
Reading suggestions for implementation of CNNs: Aurelien Geron's chapter 13.
-
And Lecture material on CNNs.
Material for Lecture Thursday November 2
Convolutional Neural Networks (recognizing images)
Convolutional neural networks (CNNs) were developed during the last decade of the previous century, with a focus on character recognition tasks. Nowadays, CNNs are a central element in the spectacular success of deep learning methods. The success in for example image classifications have made them a central tool for most machine learning practitioners.
CNNs are very similar to ordinary Neural Networks. They are made up of neurons that have learnable weights and biases. Each neuron receives some inputs, performs a dot product and optionally follows it with a non-linearity. The whole network still expresses a single differentiable score function: from the raw image pixels on one end to class scores at the other. And they still have a loss function (for example Softmax) on the last (fully-connected) layer and all the tips/tricks we developed for learning regular Neural Networks still apply (back propagation, gradient descent etc etc).
What is the Difference
CNN architectures make the explicit assumption that the inputs are images, which allows us to encode certain properties into the architecture. These then make the forward function more efficient to implement and vastly reduce the amount of parameters in the network.
Neural Networks vs CNNs
Neural networks are defined as affine transformations, that is a vector is received as input and is multiplied with a matrix of so-called weights (our unknown paramters) to produce an output (to which a bias vector is usually added before passing the result through a nonlinear activation function). This is applicable to any type of input, be it an image, a sound clip or an unordered collection of features: whatever their dimensionality, their representation can always be flattened into a vector before the transformation.
Why CNNS for images, sound files, medical images from CT scans etc?
However, when we consider images, sound clips and many other similar kinds of data, these data have an intrinsic structure. More formally, they share these important properties:
-
They are stored as multi-dimensional arrays (think of the pixels of a figure) .
-
They feature one or more axes for which ordering matters (e.g., width and height axes for an image, time axis for a sound clip).
-
One axis, called the channel axis, is used to access different views of the data (e.g., the red, green and blue channels of a color image, or the left and right channels of a stereo audio track).
These properties are not exploited when an affine transformation is applied; in fact, all the axes are treated in the same way and the topological information is not taken into account. Still, taking advantage of the implicit structure of the data may prove very handy in solving some tasks, like computer vision and speech recognition, and in these cases it would be best to preserve it. This is where discrete convolutions come into play.
A discrete convolution is a linear transformation that preserves this notion of ordering. It is sparse (only a few input units contribute to a given output unit) and reuses parameters (the same weights are applied to multiple locations in the input).
Regular NNs don’t scale well to full images
As an example, consider
an image of size 32\times 32\times 3 (32 wide, 32 high, 3 color channels), so a
single fully-connected neuron in a first hidden layer of a regular
Neural Network would have 32\times 32\times 3 = 3072 weights. This amount still
seems manageable, but clearly this fully-connected structure does not
scale to larger images. For example, an image of more respectable
size, say 200\times 200\times 3, would lead to neurons that have
200\times 200\times 3 = 120,000 weights.
We could have several such neurons, and the parameters would add up quickly! Clearly, this full connectivity is wasteful and the huge number of parameters would quickly lead to possible overfitting.
Figure 1: A regular 3-layer Neural Network.
3D volumes of neurons
Convolutional Neural Networks take advantage of the fact that the input consists of images and they constrain the architecture in a more sensible way.
In particular, unlike a regular Neural Network, the layers of a CNN have neurons arranged in 3 dimensions: width, height, depth. (Note that the word depth here refers to the third dimension of an activation volume, not to the depth of a full Neural Network, which can refer to the total number of layers in a network.)
To understand it better, the above example of an image
with an input volume of
activations has dimensions 32\times 32\times 3 (width, height,
depth respectively).
The neurons in a layer will
only be connected to a small region of the layer before it, instead of
all of the neurons in a fully-connected manner. Moreover, the final
output layer could for this specific image have dimensions 1\times 1 \times 10,
because by the
end of the CNN architecture we will reduce the full image into a
single vector of class scores, arranged along the depth
dimension.
Figure 1: A CNN arranges its neurons in three dimensions (width, height, depth), as visualized in one of the layers. Every layer of a CNN transforms the 3D input volume to a 3D output volume of neuron activations. In this example, the red input layer holds the image, so its width and height would be the dimensions of the image, and the depth would be 3 (Red, Green, Blue channels).
Layers used to build CNNs
A simple CNN is a sequence of layers, and every layer of a CNN transforms one volume of activations to another through a differentiable function. We use three main types of layers to build CNN architectures: Convolutional Layer, Pooling Layer, and Fully-Connected Layer (exactly as seen in regular Neural Networks). We will stack these layers to form a full CNN architecture.
A simple CNN for image classification could have the architecture:
-
INPUT (
32\times 32 \times 3) will hold the raw pixel values of the image, in this case an image of width 32, height 32, and with three color channels R,G,B. -
CONV (convolutional )layer will compute the output of neurons that are connected to local regions in the input, each computing a dot product between their weights and a small region they are connected to in the input volume. This may result in volume such as
[32\times 32\times 12]if we decided to use 12 filters. -
RELU layer will apply an elementwise activation function, such as the
max(0,x)thresholding at zero. This leaves the size of the volume unchanged ([32\times 32\times 12]). -
POOL (pooling) layer will perform a downsampling operation along the spatial dimensions (width, height), resulting in volume such as
[16\times 16\times 12]. -
FC (i.e. fully-connected) layer will compute the class scores, resulting in volume of size
[1\times 1\times 10], where each of the 10 numbers correspond to a class score, such as among the 10 categories of the MNIST images we considered above . As with ordinary Neural Networks and as the name implies, each neuron in this layer will be connected to all the numbers in the previous volume.
Transforming images
CNNs transform the original image layer by layer from the original pixel values to the final class scores.
Observe that some layers contain parameters and other don’t. In particular, the CNN layers perform transformations that are a function of not only the activations in the input volume, but also of the parameters (the weights and biases of the neurons). On the other hand, the RELU/POOL layers will implement a fixed function. The parameters in the CONV/FC layers will be trained with gradient descent so that the class scores that the CNN computes are consistent with the labels in the training set for each image.
CNNs in brief
In summary:
-
A CNN architecture is in the simplest case a list of Layers that transform the image volume into an output volume (e.g. holding the class scores)
-
There are a few distinct types of Layers (e.g. CONV/FC/RELU/POOL are by far the most popular)
-
Each Layer accepts an input 3D volume and transforms it to an output 3D volume through a differentiable function
-
Each Layer may or may not have parameters (e.g. CONV/FC do, RELU/POOL don’t)
-
Each Layer may or may not have additional hyperparameters (e.g. CONV/FC/POOL do, RELU doesn’t)
For more material on convolutional networks, we strongly recommend the course CS231 which is taught at Stanford University (consistently ranked as one of the top computer science programs in the world). Michael Nielsen's book is a must read, in particular chapter 6 which deals with CNNs.
The textbook by Goodfellow et al, see chapter 9 contains an in depth discussion as well.
Key Idea
A dense neural network is representd by an affine operation (like matrix-matrix multiplication) where all parameters are included.
The key idea in CNNs for say imaging is that in images neighbor pixels tend to be related! So we connect only neighboring neurons in the input instead of connecting all with the first hidden layer.
We say we perform a filtering (convolution is the mathematical operation).
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 operation (integration, summation etc) on two function 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.
How can we use this? And what does it mean? Let us study some familiar examples first.
Convolution Examples: Polynomial multiplication
We have already met such an example in project 1 when we tried to set up the design matrix for a two-dimensional function. This was an example of polynomial multiplication. Let us recast such a problem in terms of the convolution operation. Let us look a the following polynomials to second and third order, respectively:
p(t) = \alpha_0+\alpha_1 t+\alpha_2 t^2,
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.
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_1\beta_0\\
\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}.
Do you see a potential drawback with these equations?
A more efficient way of coding the above Convolution
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{\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}.
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.
Does the number of floating point operations change here when we use the commutative property?
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 discussed
below, 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.
Convolution Examples: Principle of Superposition and Periodic Forces (Fourier Transforms)
For problems with so-called harmonic oscillations, given by for example the following differential equation
m\frac{d^2x}{dt^2}+\eta\frac{dx}{dt}+x(t)=F(t),
where F(t) is an applied external force acting on the system (often
called a driving force), one can use the theory of Fourier
transformations to find the solutions of this type of equations.
If one has several driving forces, F(t)=\sum_n F_n(t), one can find
the particular solution x_{pn}(t) to the above differential equation for each F_n. The particular
solution for the entire driving force is then given by a series like
\begin{equation}
x_p(t)=\sum_nx_{pn}(t).
\label{_auto1} \tag{1}
\end{equation}
This is known as the principle of superposition. It only applies when
the homogenous equation is linear.
Superposition is especially useful when F(t) can be written
as a sum of sinusoidal terms, because the solutions for each
sinusoidal (sine or cosine) term is analytic.
Driving forces are often periodic, even when they are not
sinusoidal. Periodicity implies that for some time t our function repeats itself periodically after a period \tau, that is
\begin{eqnarray}
F(t+\tau)=F(t).
\end{eqnarray}
One example of a non-sinusoidal periodic force is a square wave. Many components in electric circuits are non-linear, for example diodes. This makes many wave forms non-sinusoidal even when the circuits are being driven by purely sinusoidal sources.
Simple Code Example
The code here shows a typical example of such a square wave generated
using the functionality included in the scipy Python package. We
have used a period of \tau=0.2.
%matplotlib inline
import numpy as np
import math
from scipy import signal
import matplotlib.pyplot as plt
# number of points
n = 500
# start and final times
t0 = 0.0
tn = 1.0
# Period
t = np.linspace(t0, tn, n, endpoint=False)
SqrSignal = np.zeros(n)
SqrSignal = 1.0+signal.square(2*np.pi*5*t)
plt.plot(t, SqrSignal)
plt.ylim(-0.5, 2.5)
plt.show()For the sinusoidal example the
period is \tau=2\pi/\omega. However, higher harmonics can also
satisfy the periodicity requirement. In general, any force that
satisfies the periodicity requirement can be expressed as a sum over
harmonics,
\begin{equation}
F(t)=\frac{f_0}{2}+\sum_{n>0} f_n\cos(2n\pi t/\tau)+g_n\sin(2n\pi t/\tau).
\label{_auto2} \tag{2}
\end{equation}
Wrapping up Fourier transforms
We can write down the answer for
x_{pn}(t), by substituting f_n/m or g_n/m for F_0/m. By
writing each factor 2n\pi t/\tau as n\omega t, with $\omega\equiv
2\pi/\tau$,
\begin{equation}
\label{eq:fourierdef1} \tag{3}
F(t)=\frac{f_0}{2}+\sum_{n>0}f_n\cos(n\omega t)+g_n\sin(n\omega t).
\end{equation}
The solutions for x(t) then come from replacing \omega with
n\omega for each term in the particular solution,
\begin{eqnarray}
x_p(t)&=&\frac{f_0}{2k}+\sum_{n>0} \alpha_n\cos(n\omega t-\delta_n)+\beta_n\sin(n\omega t-\delta_n),\\
\nonumber
\alpha_n&=&\frac{f_n/m}{\sqrt{((n\omega)^2-\omega_0^2)+4\beta^2n^2\omega^2}},\\
\nonumber
\beta_n&=&\frac{g_n/m}{\sqrt{((n\omega)^2-\omega_0^2)+4\beta^2n^2\omega^2}},\\
\nonumber
\delta_n&=&\tan^{-1}\left(\frac{2\beta n\omega}{\omega_0^2-n^2\omega^2}\right).
\end{eqnarray}
Finding the Coefficients
Because the forces have been applied for a long time, any non-zero
damping eliminates the homogenous parts of the solution. We need then
only consider the particular solution for each n.
The problem is considered solved if one can find expressions for the
coefficients f_n and g_n, even though the solutions are expressed
as an infinite sum. The coefficients can be extracted from the
function F(t) by
\begin{eqnarray}
\label{eq:fourierdef2} \tag{4}
f_n&=&\frac{2}{\tau}\int_{-\tau/2}^{\tau/2} dt~F(t)\cos(2n\pi t/\tau),\\
\nonumber
g_n&=&\frac{2}{\tau}\int_{-\tau/2}^{\tau/2} dt~F(t)\sin(2n\pi t/\tau).
\end{eqnarray}
f_n=\frac{2}{\tau}\int_{-\tau/2}^{\tau/2} dt~\left\{\frac{f_0}{2}+\sum_{m>0}f_m\cos(m\omega t)+g_m\sin(m\omega t)\right\}\cos(n\omega t).
Immediately, one can throw away all the terms with g_m because they
convolute an even and an odd function. The term with f_0/2
disappears because \cos(n\omega t) is equally positive and negative
over the interval and will integrate to zero. For all the terms
f_m\cos(m\omega t) appearing in the sum, one can use angle addition
formulas to see that $\cos(m\omega t)\cos(n\omega
t)=(1/2)(\cos[(m+n)\omega t]+\cos[(m-n)\omega t]$. This will integrate
to zero unless m=n. In that case the m=n term gives
\begin{equation}
\int_{-\tau/2}^{\tau/2}dt~\cos^2(m\omega t)=\frac{\tau}{2},
\label{_auto3} \tag{5}
\end{equation}
and
f_n=\frac{2}{\tau}\int_{-\tau/2}^{\tau/2} dt~f_n/2=f_n.
The same method can be used to check for the consistency of g_n.
Final words on Fourier Transforms
The code here uses the Fourier series applied to a
square wave signal. The code here
visualizes the various approximations given by Fourier series compared
with a square wave with period T=0.2 (dimensionless time), width 0.1 and max value of the force F=2. We
see that when we increase the number of components in the Fourier
series, the Fourier series approximation gets closer and closer to the
square wave signal.
import numpy as np
import math
from scipy import signal
import matplotlib.pyplot as plt
# number of points
n = 500
# start and final times
t0 = 0.0
tn = 1.0
# Period
T =0.2
# Max value of square signal
Fmax= 2.0
# Width of signal
Width = 0.1
t = np.linspace(t0, tn, n, endpoint=False)
SqrSignal = np.zeros(n)
FourierSeriesSignal = np.zeros(n)
SqrSignal = 1.0+signal.square(2*np.pi*5*t+np.pi*Width/T)
a0 = Fmax*Width/T
FourierSeriesSignal = a0
Factor = 2.0*Fmax/np.pi
for i in range(1,500):
FourierSeriesSignal += Factor/(i)*np.sin(np.pi*i*Width/T)*np.cos(i*t*2*np.pi/T)
plt.plot(t, SqrSignal)
plt.plot(t, FourierSeriesSignal)
plt.ylim(-0.5, 2.5)
plt.show()Fourier transforms and convolution
We can use Fourier transforms in our studies of convolution as well. To see this, assume we have two functions f and g and their corresponding Fourier transforms \hat{f} and \hat{g}. We remind the reader that the Fourier transform reads (say for the function f)
\hat{f}(y)=\boldsymbol{F}[f(y)]=\frac{1}{2\pi}\int_{-\infty}^{\infty} d\omega \exp{-i\omega y} f(\omega),
and similarly we have
\hat{g}(y)=\boldsymbol{F}[g(y)]=\frac{1}{2\pi}\int_{-\infty}^{\infty} d\omega \exp{-i\omega y} g(\omega).
The inverse Fourier transform is given by
\boldsymbol{F}^{-1}[g(y)]=\frac{1}{2\pi}\int_{-\infty}^{\infty} d\omega \exp{i\omega y} g(\omega).
The inverse Fourier transform of the product of the two functions \hat{f}\hat{g} can be written as
\boldsymbol{F}^{-1}[(\hat{f}\hat{g})(x)]=\frac{1}{2\pi}\int_{-\infty}^{\infty} d\omega \exp{i\omega x} \hat{f}(\omega)\hat{g}(\omega).
We can rewrite the latter as
\boldsymbol{F}^{-1}[(\hat{f}\hat{g})(x)]=\int_{-\infty}^{\infty} d\omega \exp{i\omega x} \hat{f}(\omega)\left[\frac{1}{2\pi}\int_{-\infty}^{\infty}g(y)dy \exp{-i\omega y}\right]=\frac{1}{2\pi}\int_{-\infty}^{\infty}dy g(y)\int_{-\infty}^{\infty} d\omega \hat{f}(\omega) \exp{i\omega(x- y)},
which is simply
\boldsymbol{F}^{-1}[(\hat{f}\hat{g})(x)]=\int_{-\infty}^{\infty}dy g(y)f(x-y)=(f*g)(x),
the convolution of the functions f and g.
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 I as input, we can have a filter
defined by a two-dimensional kernel K. This leads to an output S
S_(i,j)=(I * K)(i,j) = \sum_m\sum_n I(m,n)K(i-m,j-n).
Convolution is a commutatitave process, which means we can rewrite this equation as
S_(i,j)=(I * K)(i,j) = \sum_m\sum_n I(i-m,j-n)K(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)
S_(i,j)=(I * K)(i,j) = \sum_m\sum_n I(i+m,j+n)K(m,n).
More on Dimensionalities
In fields like signal processing (and imaging as well), one designs so-called filters. These filters are defined by the convolutions and are often hand-crafted. One may specify filters for smoothing, edge detection, frequency reshaping, and similar operations. However with neural networks the idea is to automatically learn the filters and use many of them in conjunction with non-linear operations (activation functions).
As an example consider a neural network operating on sound sequence
data. Assume that we an input vector \boldsymbol{x} of length d=10^6. We
construct then a neural network with onle hidden layer only with
10^4 nodes. This means that we will have a weight matrix with
10^4\times 10^6=10^{10} weights to be determined, together with 10^4 biases.
Assume furthermore that we have an output layer which is meant to train whether the sound sequence represents a human voice (true) or something else (false).
It means that we have only one output node. But since this output node connects to 10^4 nodes in the hidden layer, there are in total 10^4 weights to be determined for the output layer, plus one bias. In total we have
\mathrm{NumberParameters}=10^{10}+10^4+10^4+1 \approx 10^{10},
that is ten billion parameters to determine.
Further Dimensionality Remarks
In today’s architecture one can train such neural networks, however this is a huge number of parameters for the task at hand. In general, it is a very wasteful and inefficient use of dense matrices as parameters. Just as importantly, such trained network parameters are very specific for the type of input data on which they were trained and the network is not likely to generalize easily to variations in the input.
The main principles that justify convolutions is locality of information and repetion of patterns within the signal. Sound samples of the input in adjacent spots are much more likely to affect each other than those that are very far away. Similarly, sounds are repeated in multiple times in the signal. While slightly simplistic, reasoning about such a sound example demonstrates this. The same principles then apply to images and other similar data.
CNNs in more detail
Let assume we have an input matrix I of dimensionality 3\times 3
and a 2\times 2 filter W given by the following matrices
\boldsymbol{I}=\begin{bmatrix}i_{00} & i_{01} & i_{02} \\
i_{10} & i_{11} & i_{12} \\
i_{20} & i_{21} & i_{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 I.
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 i_{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
S_(i,j)=(I * W)(i,j) = \sum_m\sum_n I(i-m,j-n)W(m,n),
and obtain
\boldsymbol{S}=\begin{bmatrix}i_{00}w_{00}+i_{01}w_{01}+i_{10}w_{10}+i_{11}w_{11} & i_{01}w_{00}+i_{02}w_{01}+i_{11}w_{10}+i_{12}w_{11} \\
i_{10}w_{00}+i_{11}w_{01}+i_{20}w_{10}+i_{21}w_{11} & i_{11}w_{00}+i_{12}w_{01}+i_{21}w_{10}+i_{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{I}' of length 9 and
a matrix \boldsymbol{W}' with dimension 4\times 9 as
\boldsymbol{I}'=\begin{bmatrix}i_{00} \\ i_{01} \\ i_{02} \\ i_{10} \\ i_{11} \\ i_{12} \\ i_{20} \\ i_{21} \\ i_{22} \end{bmatrix},

