3874 lines
250 KiB
HTML
3874 lines
250 KiB
HTML
<!--
|
|
Automatically generated HTML file from DocOnce source
|
|
(https://github.com/hplgit/doconce/)
|
|
-->
|
|
<html>
|
|
<head>
|
|
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
|
|
<meta name="generator" content="DocOnce: https://github.com/hplgit/doconce/" />
|
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
<meta name="description" content="Week 43: Solving Differential Equations with Deep Learning and Dimensionality Reduction methods">
|
|
|
|
<title>Week 43: Solving Differential Equations with Deep Learning and Dimensionality Reduction methods</title>
|
|
|
|
|
|
<style type="text/css">
|
|
/* bloodish style */
|
|
|
|
body {
|
|
font-family: Helvetica, Verdana, Arial, Sans-serif;
|
|
color: #404040;
|
|
background: #ffffff;
|
|
}
|
|
h1 { font-size: 1.8em; color: #8A0808; }
|
|
h2 { font-size: 1.6em; color: #8A0808; }
|
|
h3 { font-size: 1.4em; color: #8A0808; }
|
|
h4 { color: #8A0808; }
|
|
a { color: #8A0808; text-decoration:none; }
|
|
tt { font-family: "Courier New", Courier; }
|
|
/* pre style removed because it will interfer with pygments */
|
|
p { text-indent: 0px; }
|
|
hr { border: 0; width: 80%; border-bottom: 1px solid #aaa}
|
|
p.caption { width: 80%; font-style: normal; text-align: left; }
|
|
hr.figure { border: 0; width: 80%; border-bottom: 1px solid #aaa}
|
|
.alert-text-small { font-size: 80%; }
|
|
.alert-text-large { font-size: 130%; }
|
|
.alert-text-normal { font-size: 90%; }
|
|
.alert {
|
|
padding:8px 35px 8px 14px; margin-bottom:18px;
|
|
text-shadow:0 1px 0 rgba(255,255,255,0.5);
|
|
border:1px solid #bababa;
|
|
border-radius: 4px;
|
|
-webkit-border-radius: 4px;
|
|
-moz-border-radius: 4px;
|
|
color: #555;
|
|
background-color: #f8f8f8;
|
|
background-position: 10px 5px;
|
|
background-repeat: no-repeat;
|
|
background-size: 38px;
|
|
padding-left: 55px;
|
|
width: 75%;
|
|
}
|
|
.alert-block {padding-top:14px; padding-bottom:14px}
|
|
.alert-block > p, .alert-block > ul {margin-bottom:1em}
|
|
.alert li {margin-top: 1em}
|
|
.alert-block p+p {margin-top:5px}
|
|
.alert-notice { background-image: url(https://cdn.rawgit.com/hplgit/doconce/master/bundled/html_images/small_gray_notice.png); }
|
|
.alert-summary { background-image:url(https://cdn.rawgit.com/hplgit/doconce/master/bundled/html_images/small_gray_summary.png); }
|
|
.alert-warning { background-image: url(https://cdn.rawgit.com/hplgit/doconce/master/bundled/html_images/small_gray_warning.png); }
|
|
.alert-question {background-image:url(https://cdn.rawgit.com/hplgit/doconce/master/bundled/html_images/small_gray_question.png); }
|
|
|
|
div { text-align: justify; text-justify: inter-word; }
|
|
</style>
|
|
|
|
|
|
</head>
|
|
|
|
<!-- tocinfo
|
|
{'highest level': 2,
|
|
'sections': [('Plans for week 43', 2, None, '___sec0'),
|
|
('Recurrent Neural Networks', 2, None, '___sec1'),
|
|
('Solving ODEs with Deep Learning', 2, None, '___sec2'),
|
|
('Ordinary Differential Equations', 2, None, '___sec3'),
|
|
('The trial solution', 2, None, '___sec4'),
|
|
('Minimization process', 2, None, '___sec5'),
|
|
('Minimizing the cost function using gradient descent and '
|
|
'automatic differentiation',
|
|
2,
|
|
None,
|
|
'___sec6'),
|
|
('Example: Exponential decay', 2, None, '___sec7'),
|
|
('The function to solve for', 2, None, '___sec8'),
|
|
('The trial solution', 2, None, '___sec9'),
|
|
('Setup of Network', 2, None, '___sec10'),
|
|
('Reformulating the problem', 2, None, '___sec11'),
|
|
('More technicalities', 2, None, '___sec12'),
|
|
('More details', 2, None, '___sec13'),
|
|
('A possible implementation of a neural network',
|
|
2,
|
|
None,
|
|
'___sec14'),
|
|
('Technicalities', 2, None, '___sec15'),
|
|
('Final technicalities I', 2, None, '___sec16'),
|
|
('Final technicalities II', 2, None, '___sec17'),
|
|
('Final technicalities III', 2, None, '___sec18'),
|
|
('Final technicalities IV', 2, None, '___sec19'),
|
|
('Back propagation', 2, None, '___sec20'),
|
|
('Gradient descent', 2, None, '___sec21'),
|
|
('The code for solving the ODE', 2, None, '___sec22'),
|
|
('The network with one input layer, specified number of hidden '
|
|
'layers, and one output layer',
|
|
2,
|
|
None,
|
|
'___sec23'),
|
|
('Example: Population growth', 2, None, '___sec24'),
|
|
('Setting up the problem', 2, None, '___sec25'),
|
|
('The trial solution', 2, None, '___sec26'),
|
|
('The program using Autograd', 2, None, '___sec27'),
|
|
('Using forward Euler to solve the ODE', 2, None, '___sec28'),
|
|
('Example: Solving the one dimensional Poisson equation',
|
|
2,
|
|
None,
|
|
'___sec29'),
|
|
('The specific equation to solve for', 2, None, '___sec30'),
|
|
('Solving the equation using Autograd', 2, None, '___sec31'),
|
|
('Comparing with a numerical scheme', 2, None, '___sec32'),
|
|
('Setting up the code', 2, None, '___sec33'),
|
|
('Partial Differential Equations', 2, None, '___sec34'),
|
|
('Type of problem', 2, None, '___sec35'),
|
|
('Network requirements', 2, None, '___sec36'),
|
|
('More details', 2, None, '___sec37'),
|
|
('Example: The diffusion equation', 2, None, '___sec38'),
|
|
('Defining the problem', 2, None, '___sec39'),
|
|
('Setting up the network using Autograd', 2, None, '___sec40'),
|
|
('Setting up the network using Autograd; The trial solution',
|
|
2,
|
|
None,
|
|
'___sec41'),
|
|
('Why the jacobian?', 2, None, '___sec42'),
|
|
('Setting up the network using Autograd; The full program',
|
|
2,
|
|
None,
|
|
'___sec43'),
|
|
('Example: Solving the wave equation with Neural Networks',
|
|
2,
|
|
None,
|
|
'___sec44'),
|
|
('The problem to solve for', 2, None, '___sec45'),
|
|
('The trial solution', 2, None, '___sec46'),
|
|
('The analytical solution', 2, None, '___sec47'),
|
|
('Solving the wave equation - the full program using Autograd',
|
|
2,
|
|
None,
|
|
'___sec48'),
|
|
('Resources on differential equations and deep learning',
|
|
2,
|
|
None,
|
|
'___sec49'),
|
|
('Friday, Principal Component Analysis', 2, None, '___sec50'),
|
|
('Basic ideas of the Principal Component Analysis (PCA)',
|
|
2,
|
|
None,
|
|
'___sec51'),
|
|
('Introducing the Covariance and Correlation functions',
|
|
2,
|
|
None,
|
|
'___sec52'),
|
|
('Correlation Function and Design/Feature Matrix',
|
|
2,
|
|
None,
|
|
'___sec53'),
|
|
('Covariance Matrix Examples', 2, None, '___sec54'),
|
|
('Correlation Matrix', 2, None, '___sec55'),
|
|
('Correlation Matrix with Pandas', 2, None, '___sec56'),
|
|
('Correlation Matrix with Pandas and the Franke function',
|
|
2,
|
|
None,
|
|
'___sec57'),
|
|
('Rewriting the Covariance and/or Correlation Matrix',
|
|
2,
|
|
None,
|
|
'___sec58'),
|
|
('Towards the PCA theorem', 2, None, '___sec59'),
|
|
('The Algorithm before the Theorem', 2, None, '___sec60'),
|
|
('Writing our own PCA code', 2, None, '___sec61'),
|
|
('Compute the sample mean and center the data',
|
|
3,
|
|
None,
|
|
'___sec62'),
|
|
('Compute the sample covariance', 3, None, '___sec63'),
|
|
('Diagonalize the sample covariance matrix to obtain the '
|
|
'principal components',
|
|
3,
|
|
None,
|
|
'___sec64'),
|
|
('Classical PCA Theorem', 2, None, '___sec65'),
|
|
('Proof of the PCA Theorem', 2, None, '___sec66'),
|
|
('PCA Proof continued', 2, None, '___sec67'),
|
|
('The final step', 2, None, '___sec68'),
|
|
('Geometric Interpretation and link with Singular Value '
|
|
'Decomposition',
|
|
2,
|
|
None,
|
|
'___sec69'),
|
|
('Principal Component Analysis', 2, None, '___sec70'),
|
|
('PCA and scikit-learn', 2, None, '___sec71'),
|
|
('Back to the Cancer Data', 2, None, '___sec72'),
|
|
('More on the PCA', 2, None, '___sec73'),
|
|
('Incremental PCA', 2, None, '___sec74'),
|
|
('Randomized PCA', 2, None, '___sec75'),
|
|
('Kernel PCA', 2, None, '___sec76'),
|
|
('LLE', 2, None, '___sec77'),
|
|
('Other techniques', 2, None, '___sec78')]}
|
|
end of tocinfo -->
|
|
|
|
<body>
|
|
|
|
|
|
|
|
<script type="text/x-mathjax-config">
|
|
MathJax.Hub.Config({
|
|
TeX: {
|
|
equationNumbers: { autoNumber: "AMS" },
|
|
extensions: ["AMSmath.js", "AMSsymbols.js", "autobold.js", "color.js"]
|
|
}
|
|
});
|
|
</script>
|
|
<script type="text/javascript" async
|
|
src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
|
|
</script>
|
|
|
|
|
|
|
|
|
|
<!-- ------------------- main content ---------------------- -->
|
|
|
|
|
|
|
|
<center><h1>Week 43: Solving Differential Equations with Deep Learning and Dimensionality Reduction methods</h1></center> <!-- document title -->
|
|
|
|
<p>
|
|
<!-- author(s): Morten Hjorth-Jensen -->
|
|
|
|
<center>
|
|
<b>Morten Hjorth-Jensen</b> [1, 2]
|
|
</center>
|
|
|
|
<p>
|
|
<!-- institution(s) -->
|
|
|
|
<center>[1] <b>Department of Physics, University of Oslo</b></center>
|
|
<center>[2] <b>Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University</b></center>
|
|
<br>
|
|
<p>
|
|
<center><h4>Oct 26, 2020</h4></center> <!-- date -->
|
|
<br>
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec0">Plans for week 43 </h2>
|
|
|
|
<ul>
|
|
<li> Thursday: Wrapping up Recurrent Neural Networks and solving differential equations. <a href="https://www.uio.no/studier/emner/matnat/fys/FYS-STK4155/h20/forelesningsvideoer/LectureOctober22.mp4?vrtx=view-as-webpage" target="_blank">Video of Lecture October 22</a></li>
|
|
<li> Friday: Principal Component Analysis and Dimensionality Reduction. <a href="https://www.uio.no/studier/emner/matnat/fys/FYS-STK4155/h20/forelesningsvideoer/LectureOctober23.mp4?vrtx=view-as-webpage" target="_blank">Video of Lecture October 23</a></li>
|
|
</ul>
|
|
|
|
We will also study the usage of <a href="https://www.youtube.com/watch?v=fRf4l5qaX1M&ab_channel=AlexSmola" target="_blank">Autograd</a> in computing gradients for deep learning. For the documentation of Autograd and examples see the lectures slides from <a href="https://compphysics.github.io/MachineLearning/doc/pub/week40/html/week40.html" target="_blank">week 40</a> and the <a href="https://github.com/HIPS/autograd" target="_blank">Autograd documentation</a>.
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec1">Recurrent Neural Networks </h2>
|
|
|
|
<p>
|
|
<a href="https://www.youtube.com/watch?v=SEnXr6v2ifU&ab_channel=AlexanderAmini" target="_blank">Overview video</a>.
|
|
See also lecture on Thursday October 22 and examples from <a href="https://compphysics.github.io/MachineLearning/doc/pub/week42/html/week42.html" target="_blank">week 42</a>.
|
|
|
|
<p>
|
|
<a href="https://www.uio.no/studier/emner/matnat/ifi/IN5400/v20/material/week10/in5400_2020_week10_recurrent_neural_network.pdf" target="_blank">IN5400 at UiO Lecture</a>
|
|
|
|
<p>
|
|
<a href="https://www.youtube.com/watch?v=6niqTuYFZLQ&list=PLzUTmXVwsnXod6WNdg57Yc3zFx_f-RYsq&index=10&ab_channel=StanfordUniversitySchoolofEngineering" target="_blank">CS231 at Stanford Lecture</a>
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec2">Solving ODEs with Deep Learning </h2>
|
|
|
|
<p>
|
|
The Universal Approximation Theorem states that a neural network can
|
|
approximate any function at a single hidden layer along with one input
|
|
and output layer to any given precision.
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec3">Ordinary Differential Equations </h2>
|
|
|
|
<p>
|
|
An ordinary differential equation (ODE) is an equation involving functions having one variable.
|
|
|
|
<p>
|
|
In general, an ordinary differential equation looks like
|
|
|
|
$$
|
|
\begin{equation} \label{ode}
|
|
f\left(x, \, g(x), \, g'(x), \, g''(x), \, \dots \, , \, g^{(n)}(x)\right) = 0
|
|
\end{equation}
|
|
$$
|
|
|
|
<p>
|
|
where \( g(x) \) is the function to find, and \( g^{(n)}(x) \) is the \( n \)-th derivative of \( g(x) \).
|
|
|
|
<p>
|
|
The \( f\left(x, g(x), g'(x), g''(x), \, \dots \, , g^{(n)}(x)\right) \) is just a way to write that there is an expression involving \( x \) and \( g(x), \ g'(x), \ g''(x), \, \dots \, , \text{ and } g^{(n)}(x) \) on the left side of the equality sign in \eqref{ode}.
|
|
The highest order of derivative, that is the value of \( n \), determines to the order of the equation.
|
|
The equation is referred to as a \( n \)-th order ODE.
|
|
Along with \eqref{ode}, some additional conditions of the function \( g(x) \) are typically given
|
|
for the solution to be unique.
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec4">The trial solution </h2>
|
|
|
|
<p>
|
|
Let the trial solution \( g_t(x) \) be
|
|
|
|
$$
|
|
\begin{equation}
|
|
g_t(x) = h_1(x) + h_2(x,N(x,P))
|
|
\label{_auto1}
|
|
\end{equation}
|
|
$$
|
|
|
|
<p>
|
|
where \( h_1(x) \) is a function that makes \( g_t(x) \) satisfy a given set
|
|
of conditions, \( N(x,P) \) a neural network with weights and biases
|
|
described by \( P \) and \( h_2(x, N(x,P)) \) some expression involving the
|
|
neural network. The role of the function \( h_2(x, N(x,P)) \), is to
|
|
ensure that the output from \( N(x,P) \) is zero when \( g_t(x) \) is
|
|
evaluated at the values of \( x \) where the given conditions must be
|
|
satisfied. The function \( h_1(x) \) should alone make \( g_t(x) \) satisfy
|
|
the conditions.
|
|
|
|
<p>
|
|
But what about the network \( N(x,P) \)?
|
|
|
|
<p>
|
|
As described previously, an optimization method could be used to minimize the parameters of a neural network, that being its weights and biases, through backward propagation.
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec5">Minimization process </h2>
|
|
|
|
<p>
|
|
For the minimization to be defined, we need to have a cost function at hand to minimize.
|
|
|
|
<p>
|
|
It is given that \( f\left(x, \, g(x), \, g'(x), \, g''(x), \, \dots \, , \, g^{(n)}(x)\right) \) should be equal to zero in \eqref{ode}.
|
|
We can choose to consider the mean squared error as the cost function for an input \( x \).
|
|
Since we are looking at one input, the cost function is just \( f \) squared.
|
|
The cost function \( c\left(x, P \right) \) can therefore be expressed as
|
|
|
|
$$
|
|
C\left(x, P\right) = \big(f\left(x, \, g(x), \, g'(x), \, g''(x), \, \dots \, , \, g^{(n)}(x)\right)\big)^2
|
|
$$
|
|
|
|
<p>
|
|
If \( N \) inputs are given as a vector \( \boldsymbol{x} \) with elements \( x_i \) for \( i = 1,\dots,N \),
|
|
the cost function becomes
|
|
|
|
$$
|
|
\begin{equation} \label{cost}
|
|
C\left(\boldsymbol{x}, P\right) = \frac{1}{N} \sum_{i=1}^N \big(f\left(x_i, \, g(x_i), \, g'(x_i), \, g''(x_i), \, \dots \, , \, g^{(n)}(x_i)\right)\big)^2
|
|
\end{equation}
|
|
$$
|
|
|
|
<p>
|
|
The neural net should then find the parameters \( P \) that minimizes the cost function in
|
|
\eqref{cost} for a set of \( N \) training samples \( x_i \).
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec6">Minimizing the cost function using gradient descent and automatic differentiation </h2>
|
|
|
|
<p>
|
|
To perform the minimization using gradient descent, the gradient of \( C\left(\boldsymbol{x}, P\right) \) is needed.
|
|
It might happen so that finding an analytical expression of the gradient of \( C(\boldsymbol{x}, P) \) from \eqref{cost} gets too messy, depending on which cost function one desires to use.
|
|
|
|
<p>
|
|
Luckily, there exists libraries that makes the job for us through automatic differentiation.
|
|
Automatic differentiation is a method of finding the derivatives numerically with very high precision.
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec7">Example: Exponential decay </h2>
|
|
|
|
<p>
|
|
An exponential decay of a quantity \( g(x) \) is described by the equation
|
|
|
|
$$
|
|
\begin{equation} \label{solve_expdec}
|
|
g'(x) = -\gamma g(x)
|
|
\end{equation}
|
|
$$
|
|
|
|
<p>
|
|
with \( g(0) = g_0 \) for some chosen initial value \( g_0 \).
|
|
|
|
<p>
|
|
The analytical solution of \eqref{solve_expdec} is
|
|
|
|
$$
|
|
\begin{equation}
|
|
g(x) = g_0 \exp\left(-\gamma x\right)
|
|
\label{_auto2}
|
|
\end{equation}
|
|
$$
|
|
|
|
<p>
|
|
Having an analytical solution at hand, it is possible to use it to compare how well a neural network finds a solution of \eqref{solve_expdec}.
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec8">The function to solve for </h2>
|
|
|
|
<p>
|
|
The program will use a neural network to solve
|
|
|
|
$$
|
|
\begin{equation} \label{solveode}
|
|
g'(x) = -\gamma g(x)
|
|
\end{equation}
|
|
$$
|
|
|
|
<p>
|
|
where \( g(0) = g_0 \) with \( \gamma \) and \( g_0 \) being some chosen values.
|
|
|
|
<p>
|
|
In this example, \( \gamma = 2 \) and \( g_0 = 10 \).
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec9">The trial solution </h2>
|
|
To begin with, a trial solution \( g_t(t) \) must be chosen. A general trial solution for ordinary differential equations could be
|
|
|
|
$$
|
|
g_t(x, P) = h_1(x) + h_2(x, N(x, P))
|
|
$$
|
|
|
|
<p>
|
|
with \( h_1(x) \) ensuring that \( g_t(x) \) satisfies some conditions and \( h_2(x,N(x, P)) \) an expression involving \( x \) and the output from the neural network \( N(x,P) \) with \( P \) being the collection of the weights and biases for each layer. For now, it is assumed that the network consists of one input layer, one hidden layer, and one output layer.
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec10">Setup of Network </h2>
|
|
|
|
<p>
|
|
In this network, there are no weights and bias at the input layer, so \( P = \{ P_{\text{hidden}}, P_{\text{output}} \} \).
|
|
If there are \( N_{\text{hidden} } \) neurons in the hidden layer, then \( P_{\text{hidden}} \) is a \( N_{\text{hidden} } \times (1 + N_{\text{input}}) \) matrix, given that there are \( N_{\text{input}} \) neurons in the input layer.
|
|
|
|
<p>
|
|
The first column in \( P_{\text{hidden} } \) represents the bias for each neuron in the hidden layer and the second column represents the weights for each neuron in the hidden layer from the input layer.
|
|
If there are \( N_{\text{output} } \) neurons in the output layer, then \( P_{\text{output}} \) is a \( N_{\text{output} } \times (1 + N_{\text{hidden} }) \) matrix.
|
|
|
|
<p>
|
|
Its first column represents the bias of each neuron and the remaining columns represents the weights to each neuron.
|
|
|
|
<p>
|
|
It is given that \( g(0) = g_0 \). The trial solution must fulfill this condition to be a proper solution of \eqref{solveode}. A possible way to ensure that \( g_t(0, P) = g_0 \), is to let \( F(N(x,P)) = x \cdot N(x,P) \) and \( A(x) = g_0 \). This gives the following trial solution:
|
|
|
|
$$
|
|
\begin{equation} \label{trial}
|
|
g_t(x, P) = g_0 + x \cdot N(x, P)
|
|
\end{equation}
|
|
$$
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec11">Reformulating the problem </h2>
|
|
|
|
<p>
|
|
We wish that our neural network manages to minimize a given cost function.
|
|
|
|
<p>
|
|
A reformulation of out equation, \eqref{solveode}, must therefore be done,
|
|
such that it describes the problem a neural network can solve for.
|
|
|
|
<p>
|
|
The neural network must find the set of weights and biases \( P \) such that the trial solution in \eqref{trial} satisfies \eqref{solveode}.
|
|
|
|
<p>
|
|
The trial solution
|
|
|
|
$$
|
|
g_t(x, P) = g_0 + x \cdot N(x, P)
|
|
$$
|
|
|
|
<p>
|
|
has been chosen such that it already solves the condition \( g(0) = g_0 \). What remains, is to find \( P \) such that
|
|
|
|
$$
|
|
\begin{equation} \label{nnmin}
|
|
g_t'(x, P) = - \gamma g_t(x, P)
|
|
\end{equation}
|
|
$$
|
|
|
|
<p>
|
|
is fulfilled as <em>best as possible</em>.
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec12">More technicalities </h2>
|
|
|
|
<p>
|
|
The left hand side and right hand side of \eqref{nnmin} must be computed separately, and then the neural network must choose weights and biases, contained in \( P \), such that the sides are equal as best as possible.
|
|
This means that the absolute or squared difference between the sides must be as close to zero, ideally equal to zero.
|
|
In this case, the difference squared shows to be an appropriate measurement of how erroneous the trial solution is with respect to \( P \) of the neural network.
|
|
|
|
<p>
|
|
This gives the following cost function our neural network must solve for:
|
|
|
|
$$
|
|
\min_{P}\Big\{ \big(g_t'(x, P) - ( -\gamma g_t(x, P) \big)^2 \Big\}
|
|
$$
|
|
|
|
<p>
|
|
(the notation \( \min_{P}\{ f(x, P) \} \) means that we desire to find \( P \) that yields the minimum of \( f(x, P) \))
|
|
|
|
<p>
|
|
or, in terms of weights and biases for the hidden and output layer in our network:
|
|
|
|
$$
|
|
\min_{P_{\text{hidden} }, \ P_{\text{output} }}\Big\{ \big(g_t'(x, \{ P_{\text{hidden} }, P_{\text{output} }\}) - ( -\gamma g_t(x, \{ P_{\text{hidden} }, P_{\text{output} }\}) \big)^2 \Big\}
|
|
$$
|
|
|
|
<p>
|
|
for an input value \( x \).
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec13">More details </h2>
|
|
|
|
<p>
|
|
If the neural network evaluates \( g_t(x, P) \) at more values for \( x \), say \( N \) values \( x_i \) for \( i = 1, \dots, N \), then the <em>total</em> error to minimize becomes
|
|
|
|
$$
|
|
\begin{equation} \label{min}
|
|
\min_{P}\Big\{\frac{1}{N} \sum_{i=1}^N \big(g_t'(x_i, P) - ( -\gamma g_t(x_i, P) \big)^2 \Big\}
|
|
\end{equation}
|
|
$$
|
|
|
|
<p>
|
|
Letting \( \boldsymbol{x} \) be a vector with elements \( x_i \) and \( C(\boldsymbol{x}, P) = \frac{1}{N} \sum_i \big(g_t'(x_i, P) - ( -\gamma g_t(x_i, P) \big)^2 \) denote the cost function, the minimization problem that our network must solve, becomes
|
|
|
|
$$
|
|
\min_{P} C(\boldsymbol{x}, P)
|
|
$$
|
|
|
|
<p>
|
|
In terms of \( P_{\text{hidden} } \) and \( P_{\text{output} } \), this could also be expressed as
|
|
|
|
$$
|
|
\min_{P_{\text{hidden} }, \ P_{\text{output} }} C(\boldsymbol{x}, \{P_{\text{hidden} }, P_{\text{output} }\})
|
|
$$
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec14">A possible implementation of a neural network </h2>
|
|
|
|
<p>
|
|
For simplicity, it is assumed that the input is an array \( \boldsymbol{x} = (x_1, \dots, x_N) \) with \( N \) elements. It is at these points the neural network should find \( P \) such that it fulfills \eqref{min}.
|
|
|
|
<p>
|
|
First, the neural network must feed forward the inputs.
|
|
This means that \( \boldsymbol{x}s \) must be passed through an input layer, a hidden layer and a output layer. The input layer in this case, does not need to process the data any further.
|
|
The input layer will consist of \( N_{\text{input} } \) neurons, passing its element to each neuron in the hidden layer. The number of neurons in the hidden layer will be \( N_{\text{hidden} } \).
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec15">Technicalities </h2>
|
|
|
|
<p>
|
|
For the \( i \)-th in the hidden layer with weight \( w_i^{\text{hidden} } \) and bias \( b_i^{\text{hidden} } \), the weighting from the \( j \)-th neuron at the input layer is:
|
|
|
|
$$
|
|
\begin{aligned}
|
|
z_{i,j}^{\text{hidden}} &= b_i^{\text{hidden}} + w_i^{\text{hidden}}x_j \\
|
|
&=
|
|
\begin{pmatrix}
|
|
b_i^{\text{hidden}} & w_i^{\text{hidden}}
|
|
\end{pmatrix}
|
|
\begin{pmatrix}
|
|
1 \\
|
|
x_j
|
|
\end{pmatrix}
|
|
\end{aligned}
|
|
$$
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec16">Final technicalities I </h2>
|
|
|
|
<p>
|
|
The result after weighting the inputs at the \( i \)-th hidden neuron can be written as a vector:
|
|
|
|
$$
|
|
\begin{aligned}
|
|
\boldsymbol{z}_{i}^{\text{hidden}} &= \Big( b_i^{\text{hidden}} + w_i^{\text{hidden}}x_1 , \ b_i^{\text{hidden}} + w_i^{\text{hidden}} x_2, \ \dots \, , \ b_i^{\text{hidden}} + w_i^{\text{hidden}} x_N\Big) \\
|
|
&=
|
|
\begin{pmatrix}
|
|
b_i^{\text{hidden}} & w_i^{\text{hidden}}
|
|
\end{pmatrix}
|
|
\begin{pmatrix}
|
|
1 & 1 & \dots & 1 \\
|
|
x_1 & x_2 & \dots & x_N
|
|
\end{pmatrix} \\
|
|
&= \boldsymbol{p}_{i, \text{hidden}}^T X
|
|
\end{aligned}
|
|
$$
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec17">Final technicalities II </h2>
|
|
|
|
<p>
|
|
The vector \( \boldsymbol{p}_{i, \text{hidden}}^T \) constitutes each row in \( P_{\text{hidden} } \), which contains the weights for the neural network to minimize according to \eqref{min}.
|
|
|
|
<p>
|
|
After having found \( \boldsymbol{z}_{i}^{\text{hidden}} \) for every \( i \)-th neuron within the hidden layer, the vector will be sent to an activation function \( a_i(\boldsymbol{z}) \).
|
|
|
|
<p>
|
|
In this example, the sigmoid function has been chosen to be the activation function for each hidden neuron:
|
|
|
|
$$
|
|
f(z) = \frac{1}{1 + \exp{(-z)}}
|
|
$$
|
|
|
|
<p>
|
|
It is possible to use other activations functions for the hidden layer also.
|
|
|
|
<p>
|
|
The output \( \boldsymbol{x}_i^{\text{hidden}} \) from each \( i \)-th hidden neuron is:
|
|
|
|
$$
|
|
\boldsymbol{x}_i^{\text{hidden} } = f\big( \boldsymbol{z}_{i}^{\text{hidden}} \big)
|
|
$$
|
|
|
|
<p>
|
|
The outputs \( \boldsymbol{x}_i^{\text{hidden} } \) are then sent to the output layer.
|
|
|
|
<p>
|
|
The output layer consists of one neuron in this case, and combines the
|
|
output from each of the neurons in the hidden layers. The output layer
|
|
combines the results from the hidden layer using some weights \( w_i^{\text{output}} \)
|
|
and biases \( b_i^{\text{output}} \). In this case,
|
|
it is assumes that the number of neurons in the output layer is one.
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec18">Final technicalities III </h2>
|
|
|
|
<p>
|
|
The procedure of weighting the output neuron \( j \) in the hidden layer to the \( i \)-th neuron in the output layer is similar as for the hidden layer described previously.
|
|
|
|
$$
|
|
\begin{aligned}
|
|
z_{1,j}^{\text{output}} & =
|
|
\begin{pmatrix}
|
|
b_1^{\text{output}} & \boldsymbol{w}_1^{\text{output}}
|
|
\end{pmatrix}
|
|
\begin{pmatrix}
|
|
1 \\
|
|
\boldsymbol{x}_j^{\text{hidden}}
|
|
\end{pmatrix}
|
|
\end{aligned}
|
|
$$
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec19">Final technicalities IV </h2>
|
|
|
|
<p>
|
|
Expressing \( z_{1,j}^{\text{output}} \) as a vector gives the following way of weighting the inputs from the hidden layer:
|
|
|
|
$$
|
|
\boldsymbol{z}_{1}^{\text{output}} =
|
|
\begin{pmatrix}
|
|
b_1^{\text{output}} & \boldsymbol{w}_1^{\text{output}}
|
|
\end{pmatrix}
|
|
\begin{pmatrix}
|
|
1 & 1 & \dots & 1 \\
|
|
\boldsymbol{x}_1^{\text{hidden}} & \boldsymbol{x}_2^{\text{hidden}} & \dots & \boldsymbol{x}_N^{\text{hidden}}
|
|
\end{pmatrix}
|
|
$$
|
|
|
|
<p>
|
|
In this case we seek a continuous range of values since we are approximating a function. This means that after computing \( \boldsymbol{z}_{1}^{\text{output}} \) the neural network has finished its feed forward step, and \( \boldsymbol{z}_{1}^{\text{output}} \) is the final output of the network.
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec20">Back propagation </h2>
|
|
|
|
<p>
|
|
The next step is to decide how the parameters should be changed such that they minimize the cost function.
|
|
|
|
<p>
|
|
The chosen cost function for this problem is
|
|
|
|
$$
|
|
C(\boldsymbol{x}, P) = \frac{1}{N} \sum_i \big(g_t'(x_i, P) - ( -\gamma g_t(x_i, P) \big)^2
|
|
$$
|
|
|
|
<p>
|
|
In order to minimize the cost function, an optimization method must be chosen.
|
|
|
|
<p>
|
|
Here, gradient descent with a constant step size has been chosen.
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec21">Gradient descent </h2>
|
|
|
|
<p>
|
|
The idea of the gradient descent algorithm is to update parameters in
|
|
a direction where the cost function decreases goes to a minimum.
|
|
|
|
<p>
|
|
In general, the update of some parameters \( \boldsymbol{\omega} \) given a cost
|
|
function defined by some weights \( \boldsymbol{\omega} \), \( C(\boldsymbol{x},
|
|
\boldsymbol{\omega}) \), goes as follows:
|
|
|
|
$$
|
|
\boldsymbol{\omega}_{\text{new} } = \boldsymbol{\omega} - \lambda \nabla_{\boldsymbol{\omega}} C(\boldsymbol{x}, \boldsymbol{\omega})
|
|
$$
|
|
|
|
<p>
|
|
for a number of iterations or until $ \big|\big| \boldsymbol{\omega}_{\text{new} } - \boldsymbol{\omega} \big|\big|$ becomes smaller than some given tolerance.
|
|
|
|
<p>
|
|
The value of \( \lambda \) decides how large steps the algorithm must take
|
|
in the direction of $ \nabla_{\boldsymbol{\omega}} C(\boldsymbol{x}, \boldsymbol{\omega})$.
|
|
The notation \( \nabla_{\boldsymbol{\omega}} \) express the gradient with respect
|
|
to the elements in \( \boldsymbol{\omega} \).
|
|
|
|
<p>
|
|
In our case, we have to minimize the cost function \( C(\boldsymbol{x}, P) \) with
|
|
respect to the two sets of weights and biases, that is for the hidden
|
|
layer \( P_{\text{hidden} } \) and for the output layer \( P_{\text{output}
|
|
} \) .
|
|
|
|
<p>
|
|
This means that \( P_{\text{hidden} } \) and \( P_{\text{output} } \) is updated by
|
|
|
|
$$
|
|
\begin{aligned}
|
|
P_{\text{hidden},\text{new}} &= P_{\text{hidden}} - \lambda \nabla_{P_{\text{hidden}}} C(\boldsymbol{x}, P) \\
|
|
P_{\text{output},\text{new}} &= P_{\text{output}} - \lambda \nabla_{P_{\text{output}}} C(\boldsymbol{x}, P)
|
|
\end{aligned}
|
|
$$
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec22">The code for solving the ODE </h2>
|
|
|
|
<p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">autograd.numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">autograd</span> <span style="color: #008000; font-weight: bold">import</span> grad, elementwise_grad
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">autograd.numpy.random</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">npr</span>
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">matplotlib</span> <span style="color: #008000; font-weight: bold">import</span> pyplot <span style="color: #008000; font-weight: bold">as</span> plt
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">sigmoid</span>(z):
|
|
<span style="color: #008000; font-weight: bold">return</span> <span style="color: #666666">1/</span>(<span style="color: #666666">1</span> <span style="color: #666666">+</span> np<span style="color: #666666">.</span>exp(<span style="color: #666666">-</span>z))
|
|
|
|
<span style="color: #408080; font-style: italic"># Assuming one input, hidden, and output layer</span>
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">neural_network</span>(params, x):
|
|
|
|
<span style="color: #408080; font-style: italic"># Find the weights (including and biases) for the hidden and output layer.</span>
|
|
<span style="color: #408080; font-style: italic"># Assume that params is a list of parameters for each layer.</span>
|
|
<span style="color: #408080; font-style: italic"># The biases are the first element for each array in params,</span>
|
|
<span style="color: #408080; font-style: italic"># and the weights are the remaning elements in each array in params.</span>
|
|
|
|
w_hidden <span style="color: #666666">=</span> params[<span style="color: #666666">0</span>]
|
|
w_output <span style="color: #666666">=</span> params[<span style="color: #666666">1</span>]
|
|
|
|
<span style="color: #408080; font-style: italic"># Assumes input x being an one-dimensional array</span>
|
|
num_values <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(x)
|
|
x <span style="color: #666666">=</span> x<span style="color: #666666">.</span>reshape(<span style="color: #666666">-1</span>, num_values)
|
|
|
|
<span style="color: #408080; font-style: italic"># Assume that the input layer does nothing to the input x</span>
|
|
x_input <span style="color: #666666">=</span> x
|
|
|
|
<span style="color: #408080; font-style: italic">## Hidden layer:</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Add a row of ones to include bias</span>
|
|
x_input <span style="color: #666666">=</span> np<span style="color: #666666">.</span>concatenate((np<span style="color: #666666">.</span>ones((<span style="color: #666666">1</span>,num_values)), x_input ), axis <span style="color: #666666">=</span> <span style="color: #666666">0</span>)
|
|
|
|
z_hidden <span style="color: #666666">=</span> np<span style="color: #666666">.</span>matmul(w_hidden, x_input)
|
|
x_hidden <span style="color: #666666">=</span> sigmoid(z_hidden)
|
|
|
|
<span style="color: #408080; font-style: italic">## Output layer:</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Include bias:</span>
|
|
x_hidden <span style="color: #666666">=</span> np<span style="color: #666666">.</span>concatenate((np<span style="color: #666666">.</span>ones((<span style="color: #666666">1</span>,num_values)), x_hidden ), axis <span style="color: #666666">=</span> <span style="color: #666666">0</span>)
|
|
|
|
z_output <span style="color: #666666">=</span> np<span style="color: #666666">.</span>matmul(w_output, x_hidden)
|
|
x_output <span style="color: #666666">=</span> z_output
|
|
|
|
<span style="color: #008000; font-weight: bold">return</span> x_output
|
|
|
|
<span style="color: #408080; font-style: italic"># The trial solution using the deep neural network:</span>
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">g_trial</span>(x,params, g0 <span style="color: #666666">=</span> <span style="color: #666666">10</span>):
|
|
<span style="color: #008000; font-weight: bold">return</span> g0 <span style="color: #666666">+</span> x<span style="color: #666666">*</span>neural_network(params,x)
|
|
|
|
<span style="color: #408080; font-style: italic"># The right side of the ODE:</span>
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">g</span>(x, g_trial, gamma <span style="color: #666666">=</span> <span style="color: #666666">2</span>):
|
|
<span style="color: #008000; font-weight: bold">return</span> <span style="color: #666666">-</span>gamma<span style="color: #666666">*</span>g_trial
|
|
|
|
<span style="color: #408080; font-style: italic"># The cost function:</span>
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">cost_function</span>(P, x):
|
|
|
|
<span style="color: #408080; font-style: italic"># Evaluate the trial function with the current parameters P</span>
|
|
g_t <span style="color: #666666">=</span> g_trial(x,P)
|
|
|
|
<span style="color: #408080; font-style: italic"># Find the derivative w.r.t x of the neural network</span>
|
|
d_net_out <span style="color: #666666">=</span> elementwise_grad(neural_network,<span style="color: #666666">1</span>)(P,x)
|
|
|
|
<span style="color: #408080; font-style: italic"># Find the derivative w.r.t x of the trial function</span>
|
|
d_g_t <span style="color: #666666">=</span> elementwise_grad(g_trial,<span style="color: #666666">0</span>)(x,P)
|
|
|
|
<span style="color: #408080; font-style: italic"># The right side of the ODE</span>
|
|
func <span style="color: #666666">=</span> g(x, g_t)
|
|
|
|
err_sqr <span style="color: #666666">=</span> (d_g_t <span style="color: #666666">-</span> func)<span style="color: #666666">**2</span>
|
|
cost_sum <span style="color: #666666">=</span> np<span style="color: #666666">.</span>sum(err_sqr)
|
|
|
|
<span style="color: #008000; font-weight: bold">return</span> cost_sum <span style="color: #666666">/</span> np<span style="color: #666666">.</span>size(err_sqr)
|
|
|
|
<span style="color: #408080; font-style: italic"># Solve the exponential decay ODE using neural network with one input, hidden, and output layer</span>
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">solve_ode_neural_network</span>(x, num_neurons_hidden, num_iter, lmb):
|
|
<span style="color: #408080; font-style: italic">## Set up initial weights and biases</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># For the hidden layer</span>
|
|
p0 <span style="color: #666666">=</span> npr<span style="color: #666666">.</span>randn(num_neurons_hidden, <span style="color: #666666">2</span> )
|
|
|
|
<span style="color: #408080; font-style: italic"># For the output layer</span>
|
|
p1 <span style="color: #666666">=</span> npr<span style="color: #666666">.</span>randn(<span style="color: #666666">1</span>, num_neurons_hidden <span style="color: #666666">+</span> <span style="color: #666666">1</span> ) <span style="color: #408080; font-style: italic"># +1 since bias is included</span>
|
|
|
|
P <span style="color: #666666">=</span> [p0, p1]
|
|
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">'Initial cost: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">'</span><span style="color: #666666">%</span>cost_function(P, x))
|
|
|
|
<span style="color: #408080; font-style: italic">## Start finding the optimal weights using gradient descent</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Find the Python function that represents the gradient of the cost function</span>
|
|
<span style="color: #408080; font-style: italic"># w.r.t the 0-th input argument -- that is the weights and biases in the hidden and output layer</span>
|
|
cost_function_grad <span style="color: #666666">=</span> grad(cost_function,<span style="color: #666666">0</span>)
|
|
|
|
<span style="color: #408080; font-style: italic"># Let the update be done num_iter times</span>
|
|
<span style="color: #008000; font-weight: bold">for</span> i <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(num_iter):
|
|
<span style="color: #408080; font-style: italic"># Evaluate the gradient at the current weights and biases in P.</span>
|
|
<span style="color: #408080; font-style: italic"># The cost_grad consist now of two arrays;</span>
|
|
<span style="color: #408080; font-style: italic"># one for the gradient w.r.t P_hidden and</span>
|
|
<span style="color: #408080; font-style: italic"># one for the gradient w.r.t P_output</span>
|
|
cost_grad <span style="color: #666666">=</span> cost_function_grad(P, x)
|
|
|
|
P[<span style="color: #666666">0</span>] <span style="color: #666666">=</span> P[<span style="color: #666666">0</span>] <span style="color: #666666">-</span> lmb <span style="color: #666666">*</span> cost_grad[<span style="color: #666666">0</span>]
|
|
P[<span style="color: #666666">1</span>] <span style="color: #666666">=</span> P[<span style="color: #666666">1</span>] <span style="color: #666666">-</span> lmb <span style="color: #666666">*</span> cost_grad[<span style="color: #666666">1</span>]
|
|
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">'Final cost: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">'</span><span style="color: #666666">%</span>cost_function(P, x))
|
|
|
|
<span style="color: #008000; font-weight: bold">return</span> P
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">g_analytic</span>(x, gamma <span style="color: #666666">=</span> <span style="color: #666666">2</span>, g0 <span style="color: #666666">=</span> <span style="color: #666666">10</span>):
|
|
<span style="color: #008000; font-weight: bold">return</span> g0<span style="color: #666666">*</span>np<span style="color: #666666">.</span>exp(<span style="color: #666666">-</span>gamma<span style="color: #666666">*</span>x)
|
|
|
|
<span style="color: #408080; font-style: italic"># Solve the given problem</span>
|
|
<span style="color: #008000; font-weight: bold">if</span> <span style="color: #19177C">__name__</span> <span style="color: #666666">==</span> <span style="color: #BA2121">'__main__'</span>:
|
|
<span style="color: #408080; font-style: italic"># Set seed such that the weight are initialized</span>
|
|
<span style="color: #408080; font-style: italic"># with same weights and biases for every run.</span>
|
|
npr<span style="color: #666666">.</span>seed(<span style="color: #666666">15</span>)
|
|
|
|
<span style="color: #408080; font-style: italic">## Decide the vales of arguments to the function to solve</span>
|
|
N <span style="color: #666666">=</span> <span style="color: #666666">10</span>
|
|
x <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linspace(<span style="color: #666666">0</span>, <span style="color: #666666">1</span>, N)
|
|
|
|
<span style="color: #408080; font-style: italic">## Set up the initial parameters</span>
|
|
num_hidden_neurons <span style="color: #666666">=</span> <span style="color: #666666">10</span>
|
|
num_iter <span style="color: #666666">=</span> <span style="color: #666666">10000</span>
|
|
lmb <span style="color: #666666">=</span> <span style="color: #666666">0.001</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Use the network</span>
|
|
P <span style="color: #666666">=</span> solve_ode_neural_network(x, num_hidden_neurons, num_iter, lmb)
|
|
|
|
<span style="color: #408080; font-style: italic"># Print the deviation from the trial solution and true solution</span>
|
|
res <span style="color: #666666">=</span> g_trial(x,P)
|
|
res_analytical <span style="color: #666666">=</span> g_analytic(x)
|
|
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">'Max absolute difference: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">'</span><span style="color: #666666">%</span>np<span style="color: #666666">.</span>max(np<span style="color: #666666">.</span>abs(res <span style="color: #666666">-</span> res_analytical)))
|
|
|
|
<span style="color: #408080; font-style: italic"># Plot the results</span>
|
|
plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">10</span>,<span style="color: #666666">10</span>))
|
|
|
|
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">'Performance of neural network solving an ODE compared to the analytical solution'</span>)
|
|
plt<span style="color: #666666">.</span>plot(x, res_analytical)
|
|
plt<span style="color: #666666">.</span>plot(x, res[<span style="color: #666666">0</span>,:])
|
|
plt<span style="color: #666666">.</span>legend([<span style="color: #BA2121">'analytical'</span>,<span style="color: #BA2121">'nn'</span>])
|
|
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">'x'</span>)
|
|
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">'g(x)'</span>)
|
|
plt<span style="color: #666666">.</span>show()
|
|
</pre></div>
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec23">The network with one input layer, specified number of hidden layers, and one output layer </h2>
|
|
|
|
<p>
|
|
It is also possible to extend the construction of our network into a more general one, allowing the network to contain more than one hidden layers.
|
|
|
|
<p>
|
|
The number of neurons within each hidden layer are given as a list of integers in the program below.
|
|
|
|
<p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">autograd.numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">autograd</span> <span style="color: #008000; font-weight: bold">import</span> grad, elementwise_grad
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">autograd.numpy.random</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">npr</span>
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">matplotlib</span> <span style="color: #008000; font-weight: bold">import</span> pyplot <span style="color: #008000; font-weight: bold">as</span> plt
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">sigmoid</span>(z):
|
|
<span style="color: #008000; font-weight: bold">return</span> <span style="color: #666666">1/</span>(<span style="color: #666666">1</span> <span style="color: #666666">+</span> np<span style="color: #666666">.</span>exp(<span style="color: #666666">-</span>z))
|
|
|
|
<span style="color: #408080; font-style: italic"># The neural network with one input layer and one output layer,</span>
|
|
<span style="color: #408080; font-style: italic"># but with number of hidden layers specified by the user.</span>
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">deep_neural_network</span>(deep_params, x):
|
|
<span style="color: #408080; font-style: italic"># N_hidden is the number of hidden layers</span>
|
|
|
|
N_hidden <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(deep_params) <span style="color: #666666">-</span> <span style="color: #666666">1</span> <span style="color: #408080; font-style: italic"># -1 since params consists of</span>
|
|
<span style="color: #408080; font-style: italic"># parameters to all the hidden</span>
|
|
<span style="color: #408080; font-style: italic"># layers AND the output layer.</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Assumes input x being an one-dimensional array</span>
|
|
num_values <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(x)
|
|
x <span style="color: #666666">=</span> x<span style="color: #666666">.</span>reshape(<span style="color: #666666">-1</span>, num_values)
|
|
|
|
<span style="color: #408080; font-style: italic"># Assume that the input layer does nothing to the input x</span>
|
|
x_input <span style="color: #666666">=</span> x
|
|
|
|
<span style="color: #408080; font-style: italic"># Due to multiple hidden layers, define a variable referencing to the</span>
|
|
<span style="color: #408080; font-style: italic"># output of the previous layer:</span>
|
|
x_prev <span style="color: #666666">=</span> x_input
|
|
|
|
<span style="color: #408080; font-style: italic">## Hidden layers:</span>
|
|
|
|
<span style="color: #008000; font-weight: bold">for</span> l <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(N_hidden):
|
|
<span style="color: #408080; font-style: italic"># From the list of parameters P; find the correct weigths and bias for this layer</span>
|
|
w_hidden <span style="color: #666666">=</span> deep_params[l]
|
|
|
|
<span style="color: #408080; font-style: italic"># Add a row of ones to include bias</span>
|
|
x_prev <span style="color: #666666">=</span> np<span style="color: #666666">.</span>concatenate((np<span style="color: #666666">.</span>ones((<span style="color: #666666">1</span>,num_values)), x_prev ), axis <span style="color: #666666">=</span> <span style="color: #666666">0</span>)
|
|
|
|
z_hidden <span style="color: #666666">=</span> np<span style="color: #666666">.</span>matmul(w_hidden, x_prev)
|
|
x_hidden <span style="color: #666666">=</span> sigmoid(z_hidden)
|
|
|
|
<span style="color: #408080; font-style: italic"># Update x_prev such that next layer can use the output from this layer</span>
|
|
x_prev <span style="color: #666666">=</span> x_hidden
|
|
|
|
<span style="color: #408080; font-style: italic">## Output layer:</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Get the weights and bias for this layer</span>
|
|
w_output <span style="color: #666666">=</span> deep_params[<span style="color: #666666">-1</span>]
|
|
|
|
<span style="color: #408080; font-style: italic"># Include bias:</span>
|
|
x_prev <span style="color: #666666">=</span> np<span style="color: #666666">.</span>concatenate((np<span style="color: #666666">.</span>ones((<span style="color: #666666">1</span>,num_values)), x_prev), axis <span style="color: #666666">=</span> <span style="color: #666666">0</span>)
|
|
|
|
z_output <span style="color: #666666">=</span> np<span style="color: #666666">.</span>matmul(w_output, x_prev)
|
|
x_output <span style="color: #666666">=</span> z_output
|
|
|
|
<span style="color: #008000; font-weight: bold">return</span> x_output
|
|
|
|
<span style="color: #408080; font-style: italic"># The trial solution using the deep neural network:</span>
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">g_trial_deep</span>(x,params, g0 <span style="color: #666666">=</span> <span style="color: #666666">10</span>):
|
|
<span style="color: #008000; font-weight: bold">return</span> g0 <span style="color: #666666">+</span> x<span style="color: #666666">*</span>deep_neural_network(params, x)
|
|
|
|
<span style="color: #408080; font-style: italic"># The right side of the ODE:</span>
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">g</span>(x, g_trial, gamma <span style="color: #666666">=</span> <span style="color: #666666">2</span>):
|
|
<span style="color: #008000; font-weight: bold">return</span> <span style="color: #666666">-</span>gamma<span style="color: #666666">*</span>g_trial
|
|
|
|
<span style="color: #408080; font-style: italic"># The same cost function as before, but calls deep_neural_network instead.</span>
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">cost_function_deep</span>(P, x):
|
|
|
|
<span style="color: #408080; font-style: italic"># Evaluate the trial function with the current parameters P</span>
|
|
g_t <span style="color: #666666">=</span> g_trial_deep(x,P)
|
|
|
|
<span style="color: #408080; font-style: italic"># Find the derivative w.r.t x of the neural network</span>
|
|
d_net_out <span style="color: #666666">=</span> elementwise_grad(deep_neural_network,<span style="color: #666666">1</span>)(P,x)
|
|
|
|
<span style="color: #408080; font-style: italic"># Find the derivative w.r.t x of the trial function</span>
|
|
d_g_t <span style="color: #666666">=</span> elementwise_grad(g_trial_deep,<span style="color: #666666">0</span>)(x,P)
|
|
|
|
<span style="color: #408080; font-style: italic"># The right side of the ODE</span>
|
|
func <span style="color: #666666">=</span> g(x, g_t)
|
|
|
|
err_sqr <span style="color: #666666">=</span> (d_g_t <span style="color: #666666">-</span> func)<span style="color: #666666">**2</span>
|
|
cost_sum <span style="color: #666666">=</span> np<span style="color: #666666">.</span>sum(err_sqr)
|
|
|
|
<span style="color: #008000; font-weight: bold">return</span> cost_sum <span style="color: #666666">/</span> np<span style="color: #666666">.</span>size(err_sqr)
|
|
|
|
<span style="color: #408080; font-style: italic"># Solve the exponential decay ODE using neural network with one input and one output layer,</span>
|
|
<span style="color: #408080; font-style: italic"># but with specified number of hidden layers from the user.</span>
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">solve_ode_deep_neural_network</span>(x, num_neurons, num_iter, lmb):
|
|
<span style="color: #408080; font-style: italic"># num_hidden_neurons is now a list of number of neurons within each hidden layer</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># The number of elements in the list num_hidden_neurons thus represents</span>
|
|
<span style="color: #408080; font-style: italic"># the number of hidden layers.</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Find the number of hidden layers:</span>
|
|
N_hidden <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(num_neurons)
|
|
|
|
<span style="color: #408080; font-style: italic">## Set up initial weights and biases</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Initialize the list of parameters:</span>
|
|
P <span style="color: #666666">=</span> [<span style="color: #008000; font-weight: bold">None</span>]<span style="color: #666666">*</span>(N_hidden <span style="color: #666666">+</span> <span style="color: #666666">1</span>) <span style="color: #408080; font-style: italic"># + 1 to include the output layer</span>
|
|
|
|
P[<span style="color: #666666">0</span>] <span style="color: #666666">=</span> npr<span style="color: #666666">.</span>randn(num_neurons[<span style="color: #666666">0</span>], <span style="color: #666666">2</span> )
|
|
<span style="color: #008000; font-weight: bold">for</span> l <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(<span style="color: #666666">1</span>,N_hidden):
|
|
P[l] <span style="color: #666666">=</span> npr<span style="color: #666666">.</span>randn(num_neurons[l], num_neurons[l<span style="color: #666666">-1</span>] <span style="color: #666666">+</span> <span style="color: #666666">1</span>) <span style="color: #408080; font-style: italic"># +1 to include bias</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># For the output layer</span>
|
|
P[<span style="color: #666666">-1</span>] <span style="color: #666666">=</span> npr<span style="color: #666666">.</span>randn(<span style="color: #666666">1</span>, num_neurons[<span style="color: #666666">-1</span>] <span style="color: #666666">+</span> <span style="color: #666666">1</span> ) <span style="color: #408080; font-style: italic"># +1 since bias is included</span>
|
|
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">'Initial cost: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">'</span><span style="color: #666666">%</span>cost_function_deep(P, x))
|
|
|
|
<span style="color: #408080; font-style: italic">## Start finding the optimal weights using gradient descent</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Find the Python function that represents the gradient of the cost function</span>
|
|
<span style="color: #408080; font-style: italic"># w.r.t the 0-th input argument -- that is the weights and biases in the hidden and output layer</span>
|
|
cost_function_deep_grad <span style="color: #666666">=</span> grad(cost_function_deep,<span style="color: #666666">0</span>)
|
|
|
|
<span style="color: #408080; font-style: italic"># Let the update be done num_iter times</span>
|
|
<span style="color: #008000; font-weight: bold">for</span> i <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(num_iter):
|
|
<span style="color: #408080; font-style: italic"># Evaluate the gradient at the current weights and biases in P.</span>
|
|
<span style="color: #408080; font-style: italic"># The cost_grad consist now of N_hidden + 1 arrays; the gradient w.r.t the weights and biases</span>
|
|
<span style="color: #408080; font-style: italic"># in the hidden layers and output layers evaluated at x.</span>
|
|
cost_deep_grad <span style="color: #666666">=</span> cost_function_deep_grad(P, x)
|
|
|
|
<span style="color: #008000; font-weight: bold">for</span> l <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(N_hidden<span style="color: #666666">+1</span>):
|
|
P[l] <span style="color: #666666">=</span> P[l] <span style="color: #666666">-</span> lmb <span style="color: #666666">*</span> cost_deep_grad[l]
|
|
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">'Final cost: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">'</span><span style="color: #666666">%</span>cost_function_deep(P, x))
|
|
|
|
<span style="color: #008000; font-weight: bold">return</span> P
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">g_analytic</span>(x, gamma <span style="color: #666666">=</span> <span style="color: #666666">2</span>, g0 <span style="color: #666666">=</span> <span style="color: #666666">10</span>):
|
|
<span style="color: #008000; font-weight: bold">return</span> g0<span style="color: #666666">*</span>np<span style="color: #666666">.</span>exp(<span style="color: #666666">-</span>gamma<span style="color: #666666">*</span>x)
|
|
|
|
<span style="color: #408080; font-style: italic"># Solve the given problem</span>
|
|
<span style="color: #008000; font-weight: bold">if</span> <span style="color: #19177C">__name__</span> <span style="color: #666666">==</span> <span style="color: #BA2121">'__main__'</span>:
|
|
npr<span style="color: #666666">.</span>seed(<span style="color: #666666">15</span>)
|
|
|
|
<span style="color: #408080; font-style: italic">## Decide the vales of arguments to the function to solve</span>
|
|
N <span style="color: #666666">=</span> <span style="color: #666666">10</span>
|
|
x <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linspace(<span style="color: #666666">0</span>, <span style="color: #666666">1</span>, N)
|
|
|
|
<span style="color: #408080; font-style: italic">## Set up the initial parameters</span>
|
|
num_hidden_neurons <span style="color: #666666">=</span> np<span style="color: #666666">.</span>array([<span style="color: #666666">10</span>,<span style="color: #666666">10</span>])
|
|
num_iter <span style="color: #666666">=</span> <span style="color: #666666">10000</span>
|
|
lmb <span style="color: #666666">=</span> <span style="color: #666666">0.001</span>
|
|
|
|
P <span style="color: #666666">=</span> solve_ode_deep_neural_network(x, num_hidden_neurons, num_iter, lmb)
|
|
|
|
res <span style="color: #666666">=</span> g_trial_deep(x,P)
|
|
res_analytical <span style="color: #666666">=</span> g_analytic(x)
|
|
|
|
plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">10</span>,<span style="color: #666666">10</span>))
|
|
|
|
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">'Performance of a deep neural network solving an ODE compared to the analytical solution'</span>)
|
|
plt<span style="color: #666666">.</span>plot(x, res_analytical)
|
|
plt<span style="color: #666666">.</span>plot(x, res[<span style="color: #666666">0</span>,:])
|
|
plt<span style="color: #666666">.</span>legend([<span style="color: #BA2121">'analytical'</span>,<span style="color: #BA2121">'dnn'</span>])
|
|
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">'g(x)'</span>)
|
|
plt<span style="color: #666666">.</span>show()
|
|
</pre></div>
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec24">Example: Population growth </h2>
|
|
|
|
<p>
|
|
A logistic model of population growth assumes that a population converges toward an equilibrium.
|
|
The population growth can be modeled by
|
|
|
|
$$
|
|
\begin{equation} \label{log}
|
|
g'(t) = \alpha g(t)(A - g(t))
|
|
\end{equation}
|
|
$$
|
|
|
|
<p>
|
|
where \( g(t) \) is the population density at time \( t \), \( \alpha > 0 \) the growth rate and \( A > 0 \) is the maximum population number in the environment.
|
|
Also, at \( t = 0 \) the population has the size \( g(0) = g_0 \), where \( g_0 \) is some chosen constant.
|
|
|
|
<p>
|
|
In this example, similar network as for the exponential decay using Autograd has been used to solve the equation. However, as the implementation might suffer from e.g numerical instability
|
|
and high execution time (this might be more apparent in the examples solving PDEs),
|
|
using a library like TensorFlow is recommended.
|
|
Here, we stay with a more simple approach and implement for comparison, the simple forward Euler method.
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec25">Setting up the problem </h2>
|
|
|
|
<p>
|
|
Here, we will model a population \( g(t) \) in an environment having carrying capacity \( A \).
|
|
The population follows the model
|
|
|
|
$$
|
|
\begin{equation} \label{solveode_population}
|
|
g'(t) = \alpha g(t)(A - g(t))
|
|
\end{equation}
|
|
$$
|
|
|
|
<p>
|
|
where \( g(0) = g_0 \).
|
|
|
|
<p>
|
|
In this example, we let \( \alpha = 2 \), \( A = 1 \), and \( g_0 = 1.2 \).
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec26">The trial solution </h2>
|
|
|
|
<p>
|
|
We will get a slightly different trial solution, as the boundary conditions are different
|
|
compared to the case for exponential decay.
|
|
|
|
<p>
|
|
A possible trial solution satisfying the condition \( g(0) = g_0 \) could be
|
|
|
|
$$
|
|
h_1(t) = g_0 + t \cdot N(t,P)
|
|
$$
|
|
|
|
<p>
|
|
with \( N(t,P) \) being the output from the neural network with weights and biases for each layer collected in the set \( P \).
|
|
|
|
<p>
|
|
The analytical solution is
|
|
|
|
$$
|
|
g(t) = \frac{Ag_0}{g_0 + (A - g_0)\exp(-\alpha A t)}
|
|
$$
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec27">The program using Autograd </h2>
|
|
|
|
<p>
|
|
The network will be the similar as for the exponential decay example, but with some small modifications for our problem.
|
|
|
|
<p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">autograd.numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">autograd</span> <span style="color: #008000; font-weight: bold">import</span> grad, elementwise_grad
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">autograd.numpy.random</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">npr</span>
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">matplotlib</span> <span style="color: #008000; font-weight: bold">import</span> pyplot <span style="color: #008000; font-weight: bold">as</span> plt
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">sigmoid</span>(z):
|
|
<span style="color: #008000; font-weight: bold">return</span> <span style="color: #666666">1/</span>(<span style="color: #666666">1</span> <span style="color: #666666">+</span> np<span style="color: #666666">.</span>exp(<span style="color: #666666">-</span>z))
|
|
|
|
<span style="color: #408080; font-style: italic"># Function to get the parameters.</span>
|
|
<span style="color: #408080; font-style: italic"># Done such that one can easily change the paramaters after one's liking.</span>
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">get_parameters</span>():
|
|
alpha <span style="color: #666666">=</span> <span style="color: #666666">2</span>
|
|
A <span style="color: #666666">=</span> <span style="color: #666666">1</span>
|
|
g0 <span style="color: #666666">=</span> <span style="color: #666666">1.2</span>
|
|
<span style="color: #008000; font-weight: bold">return</span> alpha, A, g0
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">deep_neural_network</span>(P, x):
|
|
<span style="color: #408080; font-style: italic"># N_hidden is the number of hidden layers</span>
|
|
N_hidden <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(P) <span style="color: #666666">-</span> <span style="color: #666666">1</span> <span style="color: #408080; font-style: italic"># -1 since params consist of parameters to all the hidden layers AND the output layer</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Assumes input x being an one-dimensional array</span>
|
|
num_values <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(x)
|
|
x <span style="color: #666666">=</span> x<span style="color: #666666">.</span>reshape(<span style="color: #666666">-1</span>, num_values)
|
|
|
|
<span style="color: #408080; font-style: italic"># Assume that the input layer does nothing to the input x</span>
|
|
x_input <span style="color: #666666">=</span> x
|
|
|
|
<span style="color: #408080; font-style: italic"># Due to multiple hidden layers, define a variable referencing to the</span>
|
|
<span style="color: #408080; font-style: italic"># output of the previous layer:</span>
|
|
x_prev <span style="color: #666666">=</span> x_input
|
|
|
|
<span style="color: #408080; font-style: italic">## Hidden layers:</span>
|
|
|
|
<span style="color: #008000; font-weight: bold">for</span> l <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(N_hidden):
|
|
<span style="color: #408080; font-style: italic"># From the list of parameters P; find the correct weigths and bias for this layer</span>
|
|
w_hidden <span style="color: #666666">=</span> P[l]
|
|
|
|
<span style="color: #408080; font-style: italic"># Add a row of ones to include bias</span>
|
|
x_prev <span style="color: #666666">=</span> np<span style="color: #666666">.</span>concatenate((np<span style="color: #666666">.</span>ones((<span style="color: #666666">1</span>,num_values)), x_prev ), axis <span style="color: #666666">=</span> <span style="color: #666666">0</span>)
|
|
|
|
z_hidden <span style="color: #666666">=</span> np<span style="color: #666666">.</span>matmul(w_hidden, x_prev)
|
|
x_hidden <span style="color: #666666">=</span> sigmoid(z_hidden)
|
|
|
|
<span style="color: #408080; font-style: italic"># Update x_prev such that next layer can use the output from this layer</span>
|
|
x_prev <span style="color: #666666">=</span> x_hidden
|
|
|
|
<span style="color: #408080; font-style: italic">## Output layer:</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Get the weights and bias for this layer</span>
|
|
w_output <span style="color: #666666">=</span> P[<span style="color: #666666">-1</span>]
|
|
|
|
<span style="color: #408080; font-style: italic"># Include bias:</span>
|
|
x_prev <span style="color: #666666">=</span> np<span style="color: #666666">.</span>concatenate((np<span style="color: #666666">.</span>ones((<span style="color: #666666">1</span>,num_values)), x_prev), axis <span style="color: #666666">=</span> <span style="color: #666666">0</span>)
|
|
|
|
z_output <span style="color: #666666">=</span> np<span style="color: #666666">.</span>matmul(w_output, x_prev)
|
|
x_output <span style="color: #666666">=</span> z_output
|
|
|
|
<span style="color: #008000; font-weight: bold">return</span> x_output
|
|
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">cost_function_deep</span>(P, x):
|
|
|
|
<span style="color: #408080; font-style: italic"># Evaluate the trial function with the current parameters P</span>
|
|
g_t <span style="color: #666666">=</span> g_trial_deep(x,P)
|
|
|
|
<span style="color: #408080; font-style: italic"># Find the derivative w.r.t x of the trial function</span>
|
|
d_g_t <span style="color: #666666">=</span> elementwise_grad(g_trial_deep,<span style="color: #666666">0</span>)(x,P)
|
|
|
|
<span style="color: #408080; font-style: italic"># The right side of the ODE</span>
|
|
func <span style="color: #666666">=</span> f(x, g_t)
|
|
|
|
err_sqr <span style="color: #666666">=</span> (d_g_t <span style="color: #666666">-</span> func)<span style="color: #666666">**2</span>
|
|
cost_sum <span style="color: #666666">=</span> np<span style="color: #666666">.</span>sum(err_sqr)
|
|
|
|
<span style="color: #008000; font-weight: bold">return</span> cost_sum <span style="color: #666666">/</span> np<span style="color: #666666">.</span>size(err_sqr)
|
|
|
|
<span style="color: #408080; font-style: italic"># The right side of the ODE:</span>
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">f</span>(x, g_trial):
|
|
alpha,A, g0 <span style="color: #666666">=</span> get_parameters()
|
|
<span style="color: #008000; font-weight: bold">return</span> alpha<span style="color: #666666">*</span>g_trial<span style="color: #666666">*</span>(A <span style="color: #666666">-</span> g_trial)
|
|
|
|
<span style="color: #408080; font-style: italic"># The trial solution using the deep neural network:</span>
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">g_trial_deep</span>(x, params):
|
|
alpha,A, g0 <span style="color: #666666">=</span> get_parameters()
|
|
<span style="color: #008000; font-weight: bold">return</span> g0 <span style="color: #666666">+</span> x<span style="color: #666666">*</span>deep_neural_network(params,x)
|
|
|
|
<span style="color: #408080; font-style: italic"># The analytical solution:</span>
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">g_analytic</span>(t):
|
|
alpha,A, g0 <span style="color: #666666">=</span> get_parameters()
|
|
<span style="color: #008000; font-weight: bold">return</span> A<span style="color: #666666">*</span>g0<span style="color: #666666">/</span>(g0 <span style="color: #666666">+</span> (A <span style="color: #666666">-</span> g0)<span style="color: #666666">*</span>np<span style="color: #666666">.</span>exp(<span style="color: #666666">-</span>alpha<span style="color: #666666">*</span>A<span style="color: #666666">*</span>t))
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">solve_ode_deep_neural_network</span>(x, num_neurons, num_iter, lmb):
|
|
<span style="color: #408080; font-style: italic"># num_hidden_neurons is now a list of number of neurons within each hidden layer</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Find the number of hidden layers:</span>
|
|
N_hidden <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(num_neurons)
|
|
|
|
<span style="color: #408080; font-style: italic">## Set up initial weigths and biases</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Initialize the list of parameters:</span>
|
|
P <span style="color: #666666">=</span> [<span style="color: #008000; font-weight: bold">None</span>]<span style="color: #666666">*</span>(N_hidden <span style="color: #666666">+</span> <span style="color: #666666">1</span>) <span style="color: #408080; font-style: italic"># + 1 to include the output layer</span>
|
|
|
|
P[<span style="color: #666666">0</span>] <span style="color: #666666">=</span> npr<span style="color: #666666">.</span>randn(num_neurons[<span style="color: #666666">0</span>], <span style="color: #666666">2</span> )
|
|
<span style="color: #008000; font-weight: bold">for</span> l <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(<span style="color: #666666">1</span>,N_hidden):
|
|
P[l] <span style="color: #666666">=</span> npr<span style="color: #666666">.</span>randn(num_neurons[l], num_neurons[l<span style="color: #666666">-1</span>] <span style="color: #666666">+</span> <span style="color: #666666">1</span>) <span style="color: #408080; font-style: italic"># +1 to include bias</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># For the output layer</span>
|
|
P[<span style="color: #666666">-1</span>] <span style="color: #666666">=</span> npr<span style="color: #666666">.</span>randn(<span style="color: #666666">1</span>, num_neurons[<span style="color: #666666">-1</span>] <span style="color: #666666">+</span> <span style="color: #666666">1</span> ) <span style="color: #408080; font-style: italic"># +1 since bias is included</span>
|
|
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">'Initial cost: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">'</span><span style="color: #666666">%</span>cost_function_deep(P, x))
|
|
|
|
<span style="color: #408080; font-style: italic">## Start finding the optimal weigths using gradient descent</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Find the Python function that represents the gradient of the cost function</span>
|
|
<span style="color: #408080; font-style: italic"># w.r.t the 0-th input argument -- that is the weights and biases in the hidden and output layer</span>
|
|
cost_function_deep_grad <span style="color: #666666">=</span> grad(cost_function_deep,<span style="color: #666666">0</span>)
|
|
|
|
<span style="color: #408080; font-style: italic"># Let the update be done num_iter times</span>
|
|
<span style="color: #008000; font-weight: bold">for</span> i <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(num_iter):
|
|
<span style="color: #408080; font-style: italic"># Evaluate the gradient at the current weights and biases in P.</span>
|
|
<span style="color: #408080; font-style: italic"># The cost_grad consist now of N_hidden + 1 arrays; the gradient w.r.t the weights and biases</span>
|
|
<span style="color: #408080; font-style: italic"># in the hidden layers and output layers evaluated at x.</span>
|
|
cost_deep_grad <span style="color: #666666">=</span> cost_function_deep_grad(P, x)
|
|
|
|
<span style="color: #008000; font-weight: bold">for</span> l <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(N_hidden<span style="color: #666666">+1</span>):
|
|
P[l] <span style="color: #666666">=</span> P[l] <span style="color: #666666">-</span> lmb <span style="color: #666666">*</span> cost_deep_grad[l]
|
|
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">'Final cost: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">'</span><span style="color: #666666">%</span>cost_function_deep(P, x))
|
|
|
|
<span style="color: #008000; font-weight: bold">return</span> P
|
|
|
|
<span style="color: #008000; font-weight: bold">if</span> <span style="color: #19177C">__name__</span> <span style="color: #666666">==</span> <span style="color: #BA2121">'__main__'</span>:
|
|
npr<span style="color: #666666">.</span>seed(<span style="color: #666666">4155</span>)
|
|
|
|
<span style="color: #408080; font-style: italic">## Decide the vales of arguments to the function to solve</span>
|
|
Nt <span style="color: #666666">=</span> <span style="color: #666666">10</span>
|
|
T <span style="color: #666666">=</span> <span style="color: #666666">1</span>
|
|
t <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linspace(<span style="color: #666666">0</span>,T, Nt)
|
|
|
|
<span style="color: #408080; font-style: italic">## Set up the initial parameters</span>
|
|
num_hidden_neurons <span style="color: #666666">=</span> [<span style="color: #666666">100</span>, <span style="color: #666666">50</span>, <span style="color: #666666">25</span>]
|
|
num_iter <span style="color: #666666">=</span> <span style="color: #666666">1000</span>
|
|
lmb <span style="color: #666666">=</span> <span style="color: #666666">1e-3</span>
|
|
|
|
P <span style="color: #666666">=</span> solve_ode_deep_neural_network(t, num_hidden_neurons, num_iter, lmb)
|
|
|
|
g_dnn_ag <span style="color: #666666">=</span> g_trial_deep(t,P)
|
|
g_analytical <span style="color: #666666">=</span> g_analytic(t)
|
|
|
|
<span style="color: #408080; font-style: italic"># Find the maximum absolute difference between the solutons:</span>
|
|
diff_ag <span style="color: #666666">=</span> np<span style="color: #666666">.</span>max(np<span style="color: #666666">.</span>abs(g_dnn_ag <span style="color: #666666">-</span> g_analytical))
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"The max absolute difference between the solutions is: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">"</span><span style="color: #666666">%</span>diff_ag)
|
|
|
|
plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">10</span>,<span style="color: #666666">10</span>))
|
|
|
|
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">'Performance of neural network solving an ODE compared to the analytical solution'</span>)
|
|
plt<span style="color: #666666">.</span>plot(t, g_analytical)
|
|
plt<span style="color: #666666">.</span>plot(t, g_dnn_ag[<span style="color: #666666">0</span>,:])
|
|
plt<span style="color: #666666">.</span>legend([<span style="color: #BA2121">'analytical'</span>,<span style="color: #BA2121">'nn'</span>])
|
|
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">'t'</span>)
|
|
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">'g(t)'</span>)
|
|
|
|
plt<span style="color: #666666">.</span>show()
|
|
</pre></div>
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec28">Using forward Euler to solve the ODE </h2>
|
|
|
|
<p>
|
|
A straightforward way of solving an ODE numerically, is to use Euler's method.
|
|
|
|
<p>
|
|
Euler's method uses Taylor series to approximate the value at a function \( f \) at a step \( \Delta x \) from \( x \):
|
|
|
|
$$
|
|
f(x + \Delta x) \approx f(x) + \Delta x f'(x)
|
|
$$
|
|
|
|
<p>
|
|
In our case, using Euler's method to approximate the value of \( g \) at a step \( \Delta t \) from \( t \) yields
|
|
|
|
$$
|
|
\begin{aligned}
|
|
g(t + \Delta t) &\approx g(t) + \Delta t g'(t) \\
|
|
&= g(t) + \Delta t \big(\alpha g(t)(A - g(t))\big)
|
|
\end{aligned}
|
|
$$
|
|
|
|
along with the condition that \( g(0) = g_0 \).
|
|
|
|
<p>
|
|
Let \( t_i = i \cdot \Delta t \) where \( \Delta t = \frac{T}{N_t-1} \) where \( T \) is the final time our solver must solve for and \( N_t \) the number of values for \( t \in [0, T] \) for \( i = 0, \dots, N_t-1 \).
|
|
|
|
<p>
|
|
For \( i \geq 1 \), we have that
|
|
$$
|
|
\begin{aligned}
|
|
t_i &= i\Delta t \\
|
|
&= (i - 1)\Delta t + \Delta t \\
|
|
&= t_{i-1} + \Delta t
|
|
\end{aligned}
|
|
$$
|
|
|
|
<p>
|
|
Now, if \( g_i = g(t_i) \) then
|
|
|
|
$$
|
|
\begin{equation}
|
|
\begin{aligned}
|
|
g_i &= g(t_i) \\
|
|
&= g(t_{i-1} + \Delta t) \\
|
|
&\approx g(t_{i-1}) + \Delta t \big(\alpha g(t_{i-1})(A - g(t_{i-1}))\big) \\
|
|
&= g_{i-1} + \Delta t \big(\alpha g_{i-1}(A - g_{i-1})\big)
|
|
\end{aligned}
|
|
\end{equation} \label{odenum}
|
|
$$
|
|
|
|
for \( i \geq 1 \) and \( g_0 = g(t_0) = g(0) = g_0 \).
|
|
|
|
<p>
|
|
Equation \eqref{odenum} could be implemented in the following way,
|
|
extending the program that uses the network using Autograd:
|
|
|
|
<p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span><span style="color: #408080; font-style: italic"># Assume that all function definitions from the example program using Autograd</span>
|
|
<span style="color: #408080; font-style: italic"># are located here.</span>
|
|
|
|
<span style="color: #008000; font-weight: bold">if</span> <span style="color: #19177C">__name__</span> <span style="color: #666666">==</span> <span style="color: #BA2121">'__main__'</span>:
|
|
npr<span style="color: #666666">.</span>seed(<span style="color: #666666">4155</span>)
|
|
|
|
<span style="color: #408080; font-style: italic">## Decide the vales of arguments to the function to solve</span>
|
|
Nt <span style="color: #666666">=</span> <span style="color: #666666">10</span>
|
|
T <span style="color: #666666">=</span> <span style="color: #666666">1</span>
|
|
t <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linspace(<span style="color: #666666">0</span>,T, Nt)
|
|
|
|
<span style="color: #408080; font-style: italic">## Set up the initial parameters</span>
|
|
num_hidden_neurons <span style="color: #666666">=</span> [<span style="color: #666666">100</span>,<span style="color: #666666">50</span>,<span style="color: #666666">25</span>]
|
|
num_iter <span style="color: #666666">=</span> <span style="color: #666666">1000</span>
|
|
lmb <span style="color: #666666">=</span> <span style="color: #666666">1e-3</span>
|
|
|
|
P <span style="color: #666666">=</span> solve_ode_deep_neural_network(t, num_hidden_neurons, num_iter, lmb)
|
|
|
|
g_dnn_ag <span style="color: #666666">=</span> g_trial_deep(t,P)
|
|
g_analytical <span style="color: #666666">=</span> g_analytic(t)
|
|
|
|
<span style="color: #408080; font-style: italic"># Find the maximum absolute difference between the solutons:</span>
|
|
diff_ag <span style="color: #666666">=</span> np<span style="color: #666666">.</span>max(np<span style="color: #666666">.</span>abs(g_dnn_ag <span style="color: #666666">-</span> g_analytical))
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"The max absolute difference between the solutions is: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">"</span><span style="color: #666666">%</span>diff_ag)
|
|
|
|
plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">10</span>,<span style="color: #666666">10</span>))
|
|
|
|
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">'Performance of neural network solving an ODE compared to the analytical solution'</span>)
|
|
plt<span style="color: #666666">.</span>plot(t, g_analytical)
|
|
plt<span style="color: #666666">.</span>plot(t, g_dnn_ag[<span style="color: #666666">0</span>,:])
|
|
plt<span style="color: #666666">.</span>legend([<span style="color: #BA2121">'analytical'</span>,<span style="color: #BA2121">'nn'</span>])
|
|
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">'t'</span>)
|
|
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">'g(t)'</span>)
|
|
|
|
<span style="color: #408080; font-style: italic">## Find an approximation to the funtion using forward Euler</span>
|
|
|
|
alpha, A, g0 <span style="color: #666666">=</span> get_parameters()
|
|
dt <span style="color: #666666">=</span> T<span style="color: #666666">/</span>(Nt <span style="color: #666666">-</span> <span style="color: #666666">1</span>)
|
|
|
|
<span style="color: #408080; font-style: italic"># Perform forward Euler to solve the ODE</span>
|
|
g_euler <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(Nt)
|
|
g_euler[<span style="color: #666666">0</span>] <span style="color: #666666">=</span> g0
|
|
|
|
<span style="color: #008000; font-weight: bold">for</span> i <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(<span style="color: #666666">1</span>,Nt):
|
|
g_euler[i] <span style="color: #666666">=</span> g_euler[i<span style="color: #666666">-1</span>] <span style="color: #666666">+</span> dt<span style="color: #666666">*</span>(alpha<span style="color: #666666">*</span>g_euler[i<span style="color: #666666">-1</span>]<span style="color: #666666">*</span>(A <span style="color: #666666">-</span> g_euler[i<span style="color: #666666">-1</span>]))
|
|
|
|
<span style="color: #408080; font-style: italic"># Print the errors done by each method</span>
|
|
diff1 <span style="color: #666666">=</span> np<span style="color: #666666">.</span>max(np<span style="color: #666666">.</span>abs(g_euler <span style="color: #666666">-</span> g_analytical))
|
|
diff2 <span style="color: #666666">=</span> np<span style="color: #666666">.</span>max(np<span style="color: #666666">.</span>abs(g_dnn_ag[<span style="color: #666666">0</span>,:] <span style="color: #666666">-</span> g_analytical))
|
|
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">'Max absolute difference between Euler method and analytical: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">'</span><span style="color: #666666">%</span>diff1)
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">'Max absolute difference between deep neural network and analytical: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">'</span><span style="color: #666666">%</span>diff2)
|
|
|
|
<span style="color: #408080; font-style: italic"># Plot results</span>
|
|
plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">10</span>,<span style="color: #666666">10</span>))
|
|
|
|
plt<span style="color: #666666">.</span>plot(t,g_euler)
|
|
plt<span style="color: #666666">.</span>plot(t,g_analytical)
|
|
plt<span style="color: #666666">.</span>plot(t,g_dnn_ag[<span style="color: #666666">0</span>,:])
|
|
|
|
plt<span style="color: #666666">.</span>legend([<span style="color: #BA2121">'euler'</span>,<span style="color: #BA2121">'analytical'</span>,<span style="color: #BA2121">'dnn'</span>])
|
|
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">'Time t'</span>)
|
|
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">'g(t)'</span>)
|
|
|
|
plt<span style="color: #666666">.</span>show()
|
|
</pre></div>
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec29">Example: Solving the one dimensional Poisson equation </h2>
|
|
|
|
<p>
|
|
The Poisson equation for \( g(x) \) in one dimension is
|
|
|
|
$$
|
|
\begin{equation} \label{poisson}
|
|
-g''(x) = f(x)
|
|
\end{equation}
|
|
$$
|
|
|
|
<p>
|
|
where \( f(x) \) is a given function for \( x \in (0,1) \).
|
|
|
|
<p>
|
|
The conditions that \( g(x) \) is chosen to fulfill, are
|
|
$$
|
|
\begin{align*}
|
|
g(0) &= 0 \\
|
|
g(1) &= 0
|
|
\end{align*}
|
|
$$
|
|
|
|
<p>
|
|
This equation can be solved numerically using programs where e.g Autograd and TensorFlow are used.
|
|
The results from the networks can then be compared to the analytical solution.
|
|
In addition, it could be interesting to see how a typical method for numerically solving second order ODEs compares to the neural networks.
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec30">The specific equation to solve for </h2>
|
|
|
|
<p>
|
|
Here, the function \( g(x) \) to solve for follows the equation
|
|
|
|
$$
|
|
-g''(x) = f(x),\qquad x \in (0,1)
|
|
$$
|
|
|
|
<p>
|
|
where \( f(x) \) is a given function, along with the chosen conditions
|
|
|
|
$$
|
|
\begin{aligned}
|
|
g(0) = g(1) = 0
|
|
\end{aligned}\label{cond}
|
|
$$
|
|
|
|
<p>
|
|
In this example, we consider the case when \( f(x) = (3x + x^2)\exp(x) \).
|
|
|
|
<p>
|
|
For this case, a possible trial solution satisfying the conditions could be
|
|
|
|
$$
|
|
g_t(x) = x \cdot (1-x) \cdot N(P,x)
|
|
$$
|
|
|
|
<p>
|
|
The analytical solution for this problem is
|
|
|
|
$$
|
|
g(x) = x(1 - x)\exp(x)
|
|
$$
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec31">Solving the equation using Autograd </h2>
|
|
|
|
<p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">autograd.numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">autograd</span> <span style="color: #008000; font-weight: bold">import</span> grad, elementwise_grad
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">autograd.numpy.random</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">npr</span>
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">matplotlib</span> <span style="color: #008000; font-weight: bold">import</span> pyplot <span style="color: #008000; font-weight: bold">as</span> plt
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">sigmoid</span>(z):
|
|
<span style="color: #008000; font-weight: bold">return</span> <span style="color: #666666">1/</span>(<span style="color: #666666">1</span> <span style="color: #666666">+</span> np<span style="color: #666666">.</span>exp(<span style="color: #666666">-</span>z))
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">deep_neural_network</span>(deep_params, x):
|
|
<span style="color: #408080; font-style: italic"># N_hidden is the number of hidden layers</span>
|
|
N_hidden <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(deep_params) <span style="color: #666666">-</span> <span style="color: #666666">1</span> <span style="color: #408080; font-style: italic"># -1 since params consist of parameters to all the hidden layers AND the output layer</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Assumes input x being an one-dimensional array</span>
|
|
num_values <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(x)
|
|
x <span style="color: #666666">=</span> x<span style="color: #666666">.</span>reshape(<span style="color: #666666">-1</span>, num_values)
|
|
|
|
<span style="color: #408080; font-style: italic"># Assume that the input layer does nothing to the input x</span>
|
|
x_input <span style="color: #666666">=</span> x
|
|
|
|
<span style="color: #408080; font-style: italic"># Due to multiple hidden layers, define a variable referencing to the</span>
|
|
<span style="color: #408080; font-style: italic"># output of the previous layer:</span>
|
|
x_prev <span style="color: #666666">=</span> x_input
|
|
|
|
<span style="color: #408080; font-style: italic">## Hidden layers:</span>
|
|
|
|
<span style="color: #008000; font-weight: bold">for</span> l <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(N_hidden):
|
|
<span style="color: #408080; font-style: italic"># From the list of parameters P; find the correct weigths and bias for this layer</span>
|
|
w_hidden <span style="color: #666666">=</span> deep_params[l]
|
|
|
|
<span style="color: #408080; font-style: italic"># Add a row of ones to include bias</span>
|
|
x_prev <span style="color: #666666">=</span> np<span style="color: #666666">.</span>concatenate((np<span style="color: #666666">.</span>ones((<span style="color: #666666">1</span>,num_values)), x_prev ), axis <span style="color: #666666">=</span> <span style="color: #666666">0</span>)
|
|
|
|
z_hidden <span style="color: #666666">=</span> np<span style="color: #666666">.</span>matmul(w_hidden, x_prev)
|
|
x_hidden <span style="color: #666666">=</span> sigmoid(z_hidden)
|
|
|
|
<span style="color: #408080; font-style: italic"># Update x_prev such that next layer can use the output from this layer</span>
|
|
x_prev <span style="color: #666666">=</span> x_hidden
|
|
|
|
<span style="color: #408080; font-style: italic">## Output layer:</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Get the weights and bias for this layer</span>
|
|
w_output <span style="color: #666666">=</span> deep_params[<span style="color: #666666">-1</span>]
|
|
|
|
<span style="color: #408080; font-style: italic"># Include bias:</span>
|
|
x_prev <span style="color: #666666">=</span> np<span style="color: #666666">.</span>concatenate((np<span style="color: #666666">.</span>ones((<span style="color: #666666">1</span>,num_values)), x_prev), axis <span style="color: #666666">=</span> <span style="color: #666666">0</span>)
|
|
|
|
z_output <span style="color: #666666">=</span> np<span style="color: #666666">.</span>matmul(w_output, x_prev)
|
|
x_output <span style="color: #666666">=</span> z_output
|
|
|
|
<span style="color: #008000; font-weight: bold">return</span> x_output
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">solve_ode_deep_neural_network</span>(x, num_neurons, num_iter, lmb):
|
|
<span style="color: #408080; font-style: italic"># num_hidden_neurons is now a list of number of neurons within each hidden layer</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Find the number of hidden layers:</span>
|
|
N_hidden <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(num_neurons)
|
|
|
|
<span style="color: #408080; font-style: italic">## Set up initial weigths and biases</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Initialize the list of parameters:</span>
|
|
P <span style="color: #666666">=</span> [<span style="color: #008000; font-weight: bold">None</span>]<span style="color: #666666">*</span>(N_hidden <span style="color: #666666">+</span> <span style="color: #666666">1</span>) <span style="color: #408080; font-style: italic"># + 1 to include the output layer</span>
|
|
|
|
P[<span style="color: #666666">0</span>] <span style="color: #666666">=</span> npr<span style="color: #666666">.</span>randn(num_neurons[<span style="color: #666666">0</span>], <span style="color: #666666">2</span> )
|
|
<span style="color: #008000; font-weight: bold">for</span> l <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(<span style="color: #666666">1</span>,N_hidden):
|
|
P[l] <span style="color: #666666">=</span> npr<span style="color: #666666">.</span>randn(num_neurons[l], num_neurons[l<span style="color: #666666">-1</span>] <span style="color: #666666">+</span> <span style="color: #666666">1</span>) <span style="color: #408080; font-style: italic"># +1 to include bias</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># For the output layer</span>
|
|
P[<span style="color: #666666">-1</span>] <span style="color: #666666">=</span> npr<span style="color: #666666">.</span>randn(<span style="color: #666666">1</span>, num_neurons[<span style="color: #666666">-1</span>] <span style="color: #666666">+</span> <span style="color: #666666">1</span> ) <span style="color: #408080; font-style: italic"># +1 since bias is included</span>
|
|
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">'Initial cost: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">'</span><span style="color: #666666">%</span>cost_function_deep(P, x))
|
|
|
|
<span style="color: #408080; font-style: italic">## Start finding the optimal weigths using gradient descent</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Find the Python function that represents the gradient of the cost function</span>
|
|
<span style="color: #408080; font-style: italic"># w.r.t the 0-th input argument -- that is the weights and biases in the hidden and output layer</span>
|
|
cost_function_deep_grad <span style="color: #666666">=</span> grad(cost_function_deep,<span style="color: #666666">0</span>)
|
|
|
|
<span style="color: #408080; font-style: italic"># Let the update be done num_iter times</span>
|
|
<span style="color: #008000; font-weight: bold">for</span> i <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(num_iter):
|
|
<span style="color: #408080; font-style: italic"># Evaluate the gradient at the current weights and biases in P.</span>
|
|
<span style="color: #408080; font-style: italic"># The cost_grad consist now of N_hidden + 1 arrays; the gradient w.r.t the weights and biases</span>
|
|
<span style="color: #408080; font-style: italic"># in the hidden layers and output layers evaluated at x.</span>
|
|
cost_deep_grad <span style="color: #666666">=</span> cost_function_deep_grad(P, x)
|
|
|
|
<span style="color: #008000; font-weight: bold">for</span> l <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(N_hidden<span style="color: #666666">+1</span>):
|
|
P[l] <span style="color: #666666">=</span> P[l] <span style="color: #666666">-</span> lmb <span style="color: #666666">*</span> cost_deep_grad[l]
|
|
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">'Final cost: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">'</span><span style="color: #666666">%</span>cost_function_deep(P, x))
|
|
|
|
<span style="color: #008000; font-weight: bold">return</span> P
|
|
|
|
<span style="color: #408080; font-style: italic">## Set up the cost function specified for this Poisson equation:</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># The right side of the ODE</span>
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">f</span>(x):
|
|
<span style="color: #008000; font-weight: bold">return</span> (<span style="color: #666666">3*</span>x <span style="color: #666666">+</span> x<span style="color: #666666">**2</span>)<span style="color: #666666">*</span>np<span style="color: #666666">.</span>exp(x)
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">cost_function_deep</span>(P, x):
|
|
|
|
<span style="color: #408080; font-style: italic"># Evaluate the trial function with the current parameters P</span>
|
|
g_t <span style="color: #666666">=</span> g_trial_deep(x,P)
|
|
|
|
<span style="color: #408080; font-style: italic"># Find the derivative w.r.t x of the trial function</span>
|
|
d2_g_t <span style="color: #666666">=</span> elementwise_grad(elementwise_grad(g_trial_deep,<span style="color: #666666">0</span>))(x,P)
|
|
|
|
right_side <span style="color: #666666">=</span> f(x)
|
|
|
|
err_sqr <span style="color: #666666">=</span> (<span style="color: #666666">-</span>d2_g_t <span style="color: #666666">-</span> right_side)<span style="color: #666666">**2</span>
|
|
cost_sum <span style="color: #666666">=</span> np<span style="color: #666666">.</span>sum(err_sqr)
|
|
|
|
<span style="color: #008000; font-weight: bold">return</span> cost_sum<span style="color: #666666">/</span>np<span style="color: #666666">.</span>size(err_sqr)
|
|
|
|
<span style="color: #408080; font-style: italic"># The trial solution:</span>
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">g_trial_deep</span>(x,P):
|
|
<span style="color: #008000; font-weight: bold">return</span> x<span style="color: #666666">*</span>(<span style="color: #666666">1-</span>x)<span style="color: #666666">*</span>deep_neural_network(P,x)
|
|
|
|
<span style="color: #408080; font-style: italic"># The analytic solution;</span>
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">g_analytic</span>(x):
|
|
<span style="color: #008000; font-weight: bold">return</span> x<span style="color: #666666">*</span>(<span style="color: #666666">1-</span>x)<span style="color: #666666">*</span>np<span style="color: #666666">.</span>exp(x)
|
|
|
|
<span style="color: #008000; font-weight: bold">if</span> <span style="color: #19177C">__name__</span> <span style="color: #666666">==</span> <span style="color: #BA2121">'__main__'</span>:
|
|
npr<span style="color: #666666">.</span>seed(<span style="color: #666666">4155</span>)
|
|
|
|
<span style="color: #408080; font-style: italic">## Decide the vales of arguments to the function to solve</span>
|
|
Nx <span style="color: #666666">=</span> <span style="color: #666666">10</span>
|
|
x <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linspace(<span style="color: #666666">0</span>,<span style="color: #666666">1</span>, Nx)
|
|
|
|
<span style="color: #408080; font-style: italic">## Set up the initial parameters</span>
|
|
num_hidden_neurons <span style="color: #666666">=</span> [<span style="color: #666666">200</span>,<span style="color: #666666">100</span>]
|
|
num_iter <span style="color: #666666">=</span> <span style="color: #666666">1000</span>
|
|
lmb <span style="color: #666666">=</span> <span style="color: #666666">1e-3</span>
|
|
|
|
P <span style="color: #666666">=</span> solve_ode_deep_neural_network(x, num_hidden_neurons, num_iter, lmb)
|
|
|
|
g_dnn_ag <span style="color: #666666">=</span> g_trial_deep(x,P)
|
|
g_analytical <span style="color: #666666">=</span> g_analytic(x)
|
|
|
|
<span style="color: #408080; font-style: italic"># Find the maximum absolute difference between the solutons:</span>
|
|
max_diff <span style="color: #666666">=</span> np<span style="color: #666666">.</span>max(np<span style="color: #666666">.</span>abs(g_dnn_ag <span style="color: #666666">-</span> g_analytical))
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"The max absolute difference between the solutions is: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">"</span><span style="color: #666666">%</span>max_diff)
|
|
|
|
plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">10</span>,<span style="color: #666666">10</span>))
|
|
|
|
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">'Performance of neural network solving an ODE compared to the analytical solution'</span>)
|
|
plt<span style="color: #666666">.</span>plot(x, g_analytical)
|
|
plt<span style="color: #666666">.</span>plot(x, g_dnn_ag[<span style="color: #666666">0</span>,:])
|
|
plt<span style="color: #666666">.</span>legend([<span style="color: #BA2121">'analytical'</span>,<span style="color: #BA2121">'nn'</span>])
|
|
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">'x'</span>)
|
|
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">'g(x)'</span>)
|
|
plt<span style="color: #666666">.</span>show()
|
|
</pre></div>
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec32">Comparing with a numerical scheme </h2>
|
|
|
|
<p>
|
|
The Poisson equation is possible to solve using Taylor series to approximate the second derivative.
|
|
|
|
<p>
|
|
Using Taylor series, the second derivative can be expressed as
|
|
|
|
$$
|
|
g''(x) = \frac{g(x + \Delta x) - 2g(x) + g(x-\Delta x)}{\Delta x^2} + E_{\Delta x}(x)
|
|
$$
|
|
|
|
<p>
|
|
where \( \Delta x \) is a small step size and \( E_{\Delta x}(x) \) being the error term.
|
|
|
|
<p>
|
|
Looking away from the error terms gives an approximation to the second derivative:
|
|
|
|
$$
|
|
\begin{equation} \label{approx}
|
|
g''(x) \approx \frac{g(x + \Delta x) - 2g(x) + g(x-\Delta x)}{\Delta x^2}
|
|
\end{equation}
|
|
$$
|
|
|
|
<p>
|
|
If \( x_i = i \Delta x = x_{i-1} + \Delta x \) and \( g_i = g(x_i) \) for \( i = 1,\dots N_x - 2 \) with \( N_x \) being the number of values for \( x \), \eqref{approx} becomes
|
|
|
|
$$
|
|
\begin{aligned}
|
|
g''(x_i) &\approx \frac{g(x_i + \Delta x) - 2g(x_i) + g(x_i -\Delta x)}{\Delta x^2} \\
|
|
&= \frac{g_{i+1} - 2g_i + g_{i-1}}{\Delta x^2}
|
|
\end{aligned}
|
|
$$
|
|
|
|
<p>
|
|
Since we know from our problem that
|
|
|
|
$$
|
|
\begin{aligned}
|
|
-g''(x) &= f(x) \\
|
|
&= (3x + x^2)\exp(x)
|
|
\end{aligned}
|
|
$$
|
|
|
|
<p>
|
|
along with the conditions \( g(0) = g(1) = 0 \),
|
|
the following scheme can be used to find an approximate solution for \( g(x) \) numerically:
|
|
|
|
$$
|
|
\begin{equation}
|
|
\begin{aligned}
|
|
-\Big( \frac{g_{i+1} - 2g_i + g_{i-1}}{\Delta x^2} \Big) &= f(x_i) \\
|
|
-g_{i+1} + 2g_i - g_{i-1} &= \Delta x^2 f(x_i)
|
|
\end{aligned}
|
|
\end{equation} \label{odesys}
|
|
$$
|
|
|
|
<p>
|
|
for \( i = 1, \dots, N_x - 2 \) where \( g_0 = g_{N_x - 1} = 0 \) and \( f(x_i) = (3x_i + x_i^2)\exp(x_i) \), which is given for our specific problem.
|
|
|
|
<p>
|
|
The equation can be rewritten into a matrix equation:
|
|
|
|
$$
|
|
\begin{aligned}
|
|
\begin{pmatrix}
|
|
2 & -1 & 0 & \dots & 0 \\
|
|
-1 & 2 & -1 & \dots & 0 \\
|
|
\vdots & & \ddots & & \vdots \\
|
|
0 & \dots & -1 & 2 & -1 \\
|
|
0 & \dots & 0 & -1 & 2\\
|
|
\end{pmatrix}
|
|
\begin{pmatrix}
|
|
g_1 \\
|
|
g_2 \\
|
|
\vdots \\
|
|
g_{N_x - 3} \\
|
|
g_{N_x - 2}
|
|
\end{pmatrix}
|
|
&=
|
|
\Delta x^2
|
|
\begin{pmatrix}
|
|
f(x_1) \\
|
|
f(x_2) \\
|
|
\vdots \\
|
|
f(x_{N_x - 3}) \\
|
|
f(x_{N_x - 2})
|
|
\end{pmatrix} \\
|
|
\boldsymbol{A}\boldsymbol{g} &= \boldsymbol{f},
|
|
\end{aligned}
|
|
$$
|
|
|
|
<p>
|
|
which makes it possible to solve for the vector \( \boldsymbol{g} \).
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec33">Setting up the code </h2>
|
|
|
|
<p>
|
|
We can then compare the result from this numerical scheme with the output from our network using Autograd:
|
|
|
|
<p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">autograd.numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">autograd</span> <span style="color: #008000; font-weight: bold">import</span> grad, elementwise_grad
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">autograd.numpy.random</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">npr</span>
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">matplotlib</span> <span style="color: #008000; font-weight: bold">import</span> pyplot <span style="color: #008000; font-weight: bold">as</span> plt
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">sigmoid</span>(z):
|
|
<span style="color: #008000; font-weight: bold">return</span> <span style="color: #666666">1/</span>(<span style="color: #666666">1</span> <span style="color: #666666">+</span> np<span style="color: #666666">.</span>exp(<span style="color: #666666">-</span>z))
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">deep_neural_network</span>(deep_params, x):
|
|
<span style="color: #408080; font-style: italic"># N_hidden is the number of hidden layers</span>
|
|
N_hidden <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(deep_params) <span style="color: #666666">-</span> <span style="color: #666666">1</span> <span style="color: #408080; font-style: italic"># -1 since params consist of parameters to all the hidden layers AND the output layer</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Assumes input x being an one-dimensional array</span>
|
|
num_values <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(x)
|
|
x <span style="color: #666666">=</span> x<span style="color: #666666">.</span>reshape(<span style="color: #666666">-1</span>, num_values)
|
|
|
|
<span style="color: #408080; font-style: italic"># Assume that the input layer does nothing to the input x</span>
|
|
x_input <span style="color: #666666">=</span> x
|
|
|
|
<span style="color: #408080; font-style: italic"># Due to multiple hidden layers, define a variable referencing to the</span>
|
|
<span style="color: #408080; font-style: italic"># output of the previous layer:</span>
|
|
x_prev <span style="color: #666666">=</span> x_input
|
|
|
|
<span style="color: #408080; font-style: italic">## Hidden layers:</span>
|
|
|
|
<span style="color: #008000; font-weight: bold">for</span> l <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(N_hidden):
|
|
<span style="color: #408080; font-style: italic"># From the list of parameters P; find the correct weigths and bias for this layer</span>
|
|
w_hidden <span style="color: #666666">=</span> deep_params[l]
|
|
|
|
<span style="color: #408080; font-style: italic"># Add a row of ones to include bias</span>
|
|
x_prev <span style="color: #666666">=</span> np<span style="color: #666666">.</span>concatenate((np<span style="color: #666666">.</span>ones((<span style="color: #666666">1</span>,num_values)), x_prev ), axis <span style="color: #666666">=</span> <span style="color: #666666">0</span>)
|
|
|
|
z_hidden <span style="color: #666666">=</span> np<span style="color: #666666">.</span>matmul(w_hidden, x_prev)
|
|
x_hidden <span style="color: #666666">=</span> sigmoid(z_hidden)
|
|
|
|
<span style="color: #408080; font-style: italic"># Update x_prev such that next layer can use the output from this layer</span>
|
|
x_prev <span style="color: #666666">=</span> x_hidden
|
|
|
|
<span style="color: #408080; font-style: italic">## Output layer:</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Get the weights and bias for this layer</span>
|
|
w_output <span style="color: #666666">=</span> deep_params[<span style="color: #666666">-1</span>]
|
|
|
|
<span style="color: #408080; font-style: italic"># Include bias:</span>
|
|
x_prev <span style="color: #666666">=</span> np<span style="color: #666666">.</span>concatenate((np<span style="color: #666666">.</span>ones((<span style="color: #666666">1</span>,num_values)), x_prev), axis <span style="color: #666666">=</span> <span style="color: #666666">0</span>)
|
|
|
|
z_output <span style="color: #666666">=</span> np<span style="color: #666666">.</span>matmul(w_output, x_prev)
|
|
x_output <span style="color: #666666">=</span> z_output
|
|
|
|
<span style="color: #008000; font-weight: bold">return</span> x_output
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">solve_ode_deep_neural_network</span>(x, num_neurons, num_iter, lmb):
|
|
<span style="color: #408080; font-style: italic"># num_hidden_neurons is now a list of number of neurons within each hidden layer</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Find the number of hidden layers:</span>
|
|
N_hidden <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(num_neurons)
|
|
|
|
<span style="color: #408080; font-style: italic">## Set up initial weigths and biases</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Initialize the list of parameters:</span>
|
|
P <span style="color: #666666">=</span> [<span style="color: #008000; font-weight: bold">None</span>]<span style="color: #666666">*</span>(N_hidden <span style="color: #666666">+</span> <span style="color: #666666">1</span>) <span style="color: #408080; font-style: italic"># + 1 to include the output layer</span>
|
|
|
|
P[<span style="color: #666666">0</span>] <span style="color: #666666">=</span> npr<span style="color: #666666">.</span>randn(num_neurons[<span style="color: #666666">0</span>], <span style="color: #666666">2</span> )
|
|
<span style="color: #008000; font-weight: bold">for</span> l <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(<span style="color: #666666">1</span>,N_hidden):
|
|
P[l] <span style="color: #666666">=</span> npr<span style="color: #666666">.</span>randn(num_neurons[l], num_neurons[l<span style="color: #666666">-1</span>] <span style="color: #666666">+</span> <span style="color: #666666">1</span>) <span style="color: #408080; font-style: italic"># +1 to include bias</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># For the output layer</span>
|
|
P[<span style="color: #666666">-1</span>] <span style="color: #666666">=</span> npr<span style="color: #666666">.</span>randn(<span style="color: #666666">1</span>, num_neurons[<span style="color: #666666">-1</span>] <span style="color: #666666">+</span> <span style="color: #666666">1</span> ) <span style="color: #408080; font-style: italic"># +1 since bias is included</span>
|
|
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">'Initial cost: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">'</span><span style="color: #666666">%</span>cost_function_deep(P, x))
|
|
|
|
<span style="color: #408080; font-style: italic">## Start finding the optimal weigths using gradient descent</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Find the Python function that represents the gradient of the cost function</span>
|
|
<span style="color: #408080; font-style: italic"># w.r.t the 0-th input argument -- that is the weights and biases in the hidden and output layer</span>
|
|
cost_function_deep_grad <span style="color: #666666">=</span> grad(cost_function_deep,<span style="color: #666666">0</span>)
|
|
|
|
<span style="color: #408080; font-style: italic"># Let the update be done num_iter times</span>
|
|
<span style="color: #008000; font-weight: bold">for</span> i <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(num_iter):
|
|
<span style="color: #408080; font-style: italic"># Evaluate the gradient at the current weights and biases in P.</span>
|
|
<span style="color: #408080; font-style: italic"># The cost_grad consist now of N_hidden + 1 arrays; the gradient w.r.t the weights and biases</span>
|
|
<span style="color: #408080; font-style: italic"># in the hidden layers and output layers evaluated at x.</span>
|
|
cost_deep_grad <span style="color: #666666">=</span> cost_function_deep_grad(P, x)
|
|
|
|
<span style="color: #008000; font-weight: bold">for</span> l <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(N_hidden<span style="color: #666666">+1</span>):
|
|
P[l] <span style="color: #666666">=</span> P[l] <span style="color: #666666">-</span> lmb <span style="color: #666666">*</span> cost_deep_grad[l]
|
|
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">'Final cost: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">'</span><span style="color: #666666">%</span>cost_function_deep(P, x))
|
|
|
|
<span style="color: #008000; font-weight: bold">return</span> P
|
|
|
|
<span style="color: #408080; font-style: italic">## Set up the cost function specified for this Poisson equation:</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># The right side of the ODE</span>
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">f</span>(x):
|
|
<span style="color: #008000; font-weight: bold">return</span> (<span style="color: #666666">3*</span>x <span style="color: #666666">+</span> x<span style="color: #666666">**2</span>)<span style="color: #666666">*</span>np<span style="color: #666666">.</span>exp(x)
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">cost_function_deep</span>(P, x):
|
|
|
|
<span style="color: #408080; font-style: italic"># Evaluate the trial function with the current parameters P</span>
|
|
g_t <span style="color: #666666">=</span> g_trial_deep(x,P)
|
|
|
|
<span style="color: #408080; font-style: italic"># Find the derivative w.r.t x of the trial function</span>
|
|
d2_g_t <span style="color: #666666">=</span> elementwise_grad(elementwise_grad(g_trial_deep,<span style="color: #666666">0</span>))(x,P)
|
|
|
|
right_side <span style="color: #666666">=</span> f(x)
|
|
|
|
err_sqr <span style="color: #666666">=</span> (<span style="color: #666666">-</span>d2_g_t <span style="color: #666666">-</span> right_side)<span style="color: #666666">**2</span>
|
|
cost_sum <span style="color: #666666">=</span> np<span style="color: #666666">.</span>sum(err_sqr)
|
|
|
|
<span style="color: #008000; font-weight: bold">return</span> cost_sum<span style="color: #666666">/</span>np<span style="color: #666666">.</span>size(err_sqr)
|
|
|
|
<span style="color: #408080; font-style: italic"># The trial solution:</span>
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">g_trial_deep</span>(x,P):
|
|
<span style="color: #008000; font-weight: bold">return</span> x<span style="color: #666666">*</span>(<span style="color: #666666">1-</span>x)<span style="color: #666666">*</span>deep_neural_network(P,x)
|
|
|
|
<span style="color: #408080; font-style: italic"># The analytic solution;</span>
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">g_analytic</span>(x):
|
|
<span style="color: #008000; font-weight: bold">return</span> x<span style="color: #666666">*</span>(<span style="color: #666666">1-</span>x)<span style="color: #666666">*</span>np<span style="color: #666666">.</span>exp(x)
|
|
|
|
<span style="color: #008000; font-weight: bold">if</span> <span style="color: #19177C">__name__</span> <span style="color: #666666">==</span> <span style="color: #BA2121">'__main__'</span>:
|
|
npr<span style="color: #666666">.</span>seed(<span style="color: #666666">4155</span>)
|
|
|
|
<span style="color: #408080; font-style: italic">## Decide the vales of arguments to the function to solve</span>
|
|
Nx <span style="color: #666666">=</span> <span style="color: #666666">10</span>
|
|
x <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linspace(<span style="color: #666666">0</span>,<span style="color: #666666">1</span>, Nx)
|
|
|
|
<span style="color: #408080; font-style: italic">## Set up the initial parameters</span>
|
|
num_hidden_neurons <span style="color: #666666">=</span> [<span style="color: #666666">200</span>,<span style="color: #666666">100</span>]
|
|
num_iter <span style="color: #666666">=</span> <span style="color: #666666">1000</span>
|
|
lmb <span style="color: #666666">=</span> <span style="color: #666666">1e-3</span>
|
|
|
|
P <span style="color: #666666">=</span> solve_ode_deep_neural_network(x, num_hidden_neurons, num_iter, lmb)
|
|
|
|
g_dnn_ag <span style="color: #666666">=</span> g_trial_deep(x,P)
|
|
g_analytical <span style="color: #666666">=</span> g_analytic(x)
|
|
|
|
<span style="color: #408080; font-style: italic"># Find the maximum absolute difference between the solutons:</span>
|
|
|
|
plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">10</span>,<span style="color: #666666">10</span>))
|
|
|
|
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">'Performance of neural network solving an ODE compared to the analytical solution'</span>)
|
|
plt<span style="color: #666666">.</span>plot(x, g_analytical)
|
|
plt<span style="color: #666666">.</span>plot(x, g_dnn_ag[<span style="color: #666666">0</span>,:])
|
|
plt<span style="color: #666666">.</span>legend([<span style="color: #BA2121">'analytical'</span>,<span style="color: #BA2121">'nn'</span>])
|
|
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">'x'</span>)
|
|
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">'g(x)'</span>)
|
|
|
|
<span style="color: #408080; font-style: italic">## Perform the computation using the numerical scheme</span>
|
|
|
|
dx <span style="color: #666666">=</span> <span style="color: #666666">1/</span>(Nx <span style="color: #666666">-</span> <span style="color: #666666">1</span>)
|
|
|
|
<span style="color: #408080; font-style: italic"># Set up the matrix A</span>
|
|
A <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros((Nx<span style="color: #666666">-2</span>,Nx<span style="color: #666666">-2</span>))
|
|
|
|
A[<span style="color: #666666">0</span>,<span style="color: #666666">0</span>] <span style="color: #666666">=</span> <span style="color: #666666">2</span>
|
|
A[<span style="color: #666666">0</span>,<span style="color: #666666">1</span>] <span style="color: #666666">=</span> <span style="color: #666666">-1</span>
|
|
|
|
<span style="color: #008000; font-weight: bold">for</span> i <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(<span style="color: #666666">1</span>,Nx<span style="color: #666666">-3</span>):
|
|
A[i,i<span style="color: #666666">-1</span>] <span style="color: #666666">=</span> <span style="color: #666666">-1</span>
|
|
A[i,i] <span style="color: #666666">=</span> <span style="color: #666666">2</span>
|
|
A[i,i<span style="color: #666666">+1</span>] <span style="color: #666666">=</span> <span style="color: #666666">-1</span>
|
|
|
|
A[Nx <span style="color: #666666">-</span> <span style="color: #666666">3</span>, Nx <span style="color: #666666">-</span> <span style="color: #666666">4</span>] <span style="color: #666666">=</span> <span style="color: #666666">-1</span>
|
|
A[Nx <span style="color: #666666">-</span> <span style="color: #666666">3</span>, Nx <span style="color: #666666">-</span> <span style="color: #666666">3</span>] <span style="color: #666666">=</span> <span style="color: #666666">2</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Set up the vector f</span>
|
|
f_vec <span style="color: #666666">=</span> dx<span style="color: #666666">**2</span> <span style="color: #666666">*</span> f(x[<span style="color: #666666">1</span>:<span style="color: #666666">-1</span>])
|
|
|
|
<span style="color: #408080; font-style: italic"># Solve the equation</span>
|
|
g_res <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linalg<span style="color: #666666">.</span>solve(A,f_vec)
|
|
|
|
g_vec <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(Nx)
|
|
g_vec[<span style="color: #666666">1</span>:<span style="color: #666666">-1</span>] <span style="color: #666666">=</span> g_res
|
|
|
|
<span style="color: #408080; font-style: italic"># Print the differences between each method</span>
|
|
max_diff1 <span style="color: #666666">=</span> np<span style="color: #666666">.</span>max(np<span style="color: #666666">.</span>abs(g_dnn_ag <span style="color: #666666">-</span> g_analytical))
|
|
max_diff2 <span style="color: #666666">=</span> np<span style="color: #666666">.</span>max(np<span style="color: #666666">.</span>abs(g_vec <span style="color: #666666">-</span> g_analytical))
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"The max absolute difference between the analytical solution and DNN Autograd: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">"</span><span style="color: #666666">%</span>max_diff1)
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"The max absolute difference between the analytical solution and numerical scheme: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">"</span><span style="color: #666666">%</span>max_diff2)
|
|
|
|
<span style="color: #408080; font-style: italic"># Plot the results</span>
|
|
plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">10</span>,<span style="color: #666666">10</span>))
|
|
|
|
plt<span style="color: #666666">.</span>plot(x,g_vec)
|
|
plt<span style="color: #666666">.</span>plot(x,g_analytical)
|
|
plt<span style="color: #666666">.</span>plot(x,g_dnn_ag[<span style="color: #666666">0</span>,:])
|
|
|
|
plt<span style="color: #666666">.</span>legend([<span style="color: #BA2121">'numerical scheme'</span>,<span style="color: #BA2121">'analytical'</span>,<span style="color: #BA2121">'dnn'</span>])
|
|
plt<span style="color: #666666">.</span>show()
|
|
</pre></div>
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec34">Partial Differential Equations </h2>
|
|
|
|
<p>
|
|
A partial differential equation (PDE) has a solution here the function
|
|
is defined by multiple variables. The equation may involve all kinds
|
|
of combinations of which variables the function is differentiated with
|
|
respect to.
|
|
|
|
<p>
|
|
In general, a partial differential equation for a function \( g(x_1,\dots,x_N) \) with \( N \) variables may be expressed as
|
|
|
|
$$
|
|
\begin{equation} \label{PDE}
|
|
f\left(x_1, \, \dots \, , x_N, \frac{\partial g(x_1,\dots,x_N) }{\partial x_1}, \dots , \frac{\partial g(x_1,\dots,x_N) }{\partial x_N}, \frac{\partial g(x_1,\dots,x_N) }{\partial x_1\partial x_2}, \, \dots \, , \frac{\partial^n g(x_1,\dots,x_N) }{\partial x_N^n} \right) = 0
|
|
\end{equation}
|
|
$$
|
|
|
|
<p>
|
|
where \( f \) is an expression involving all kinds of possible mixed derivatives of \( g(x_1,\dots,x_N) \) up to an order \( n \). In order for the solution to be unique, some additional conditions must also be given.
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec35">Type of problem </h2>
|
|
|
|
<p>
|
|
The problem our network must solve for, is similar to the ODE case.
|
|
We must have a trial solution \( g_t \) at hand.
|
|
|
|
<p>
|
|
For instance, the trial solution could be expressed as
|
|
$$
|
|
\begin{align*}
|
|
g_t(x_1,\dots,x_N) = h_1(x_1,\dots,x_N) + h_2(x_1,\dots,x_N,N(x_1,\dots,x_N,P))
|
|
\end{align*}
|
|
$$
|
|
|
|
where \( h_1(x_1,\dots,x_N) \) is a function that ensures \( g_t(x_1,\dots,x_N) \) satisfies some given conditions.
|
|
The neural network \( N(x_1,\dots,x_N,P) \) has weights and biases described by \( P \) and \( h_2(x_1,\dots,x_N,N(x_1,\dots,x_N,P)) \) is an expression using the output from the neural network in some way.
|
|
|
|
<p>
|
|
The role of the function \( h_2(x_1,\dots,x_N,N(x_1,\dots,x_N,P)) \), is to ensure that the output of \( N(x_1,\dots,x_N,P) \) is zero when \( g_t(x_1,\dots,x_N) \) is evaluated at the values of \( x_1,\dots,x_N \) where the given conditions must be satisfied. The function \( h_1(x_1,\dots,x_N) \) should alone make \( g_t(x_1,\dots,x_N) \) satisfy the conditions.
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec36">Network requirements </h2>
|
|
|
|
<p>
|
|
The network tries then the minimize the cost function following the
|
|
same ideas as described for the ODE case, but now with more than one
|
|
variables to consider. The concept still remains the same; find a set
|
|
of parameters \( P \) such that the expression \( f \) in \eqref{PDE} is as
|
|
close to zero as possible.
|
|
|
|
<p>
|
|
As for the ODE case, the cost function is the mean squared error that
|
|
the network must try to minimize. The cost function for the network to
|
|
minimize is
|
|
|
|
$$
|
|
\begin{equation*}
|
|
C\left(x_1, \dots, x_N, P\right) = \left( f\left(x_1, \, \dots \, , x_N, \frac{\partial g(x_1,\dots,x_N) }{\partial x_1}, \dots , \frac{\partial g(x_1,\dots,x_N) }{\partial x_N}, \frac{\partial g(x_1,\dots,x_N) }{\partial x_1\partial x_2}, \, \dots \, , \frac{\partial^n g(x_1,\dots,x_N) }{\partial x_N^n} \right) \right)^2
|
|
\end{equation*}
|
|
$$
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec37">More details </h2>
|
|
|
|
<p>
|
|
If we let \( \boldsymbol{x} = \big( x_1, \dots, x_N \big) \) be an array containing the values for \( x_1, \dots, x_N \) respectively, the cost function can be reformulated into the following:
|
|
$$
|
|
C\left(\boldsymbol{x}, P\right) = f\left( \left( \boldsymbol{x}, \frac{\partial g(\boldsymbol{x}) }{\partial x_1}, \dots , \frac{\partial g(\boldsymbol{x}) }{\partial x_N}, \frac{\partial g(\boldsymbol{x}) }{\partial x_1\partial x_2}, \, \dots \, , \frac{\partial^n g(\boldsymbol{x}) }{\partial x_N^n} \right) \right)^2
|
|
$$
|
|
|
|
<p>
|
|
If we also have \( M \) different sets of values for \( x_1, \dots, x_N \), that is \( \boldsymbol{x}_i = \big(x_1^{(i)}, \dots, x_N^{(i)}\big) \) for \( i = 1,\dots,M \) being the rows in matrix \( X \), the cost function can be generalized into
|
|
$$
|
|
\begin{equation*}
|
|
C\left(X, P \right) = \sum_{i=1}^M f\left( \left( \boldsymbol{x}_i, \frac{\partial g(\boldsymbol{x}_i) }{\partial x_1}, \dots , \frac{\partial g(\boldsymbol{x}_i) }{\partial x_N}, \frac{\partial g(\boldsymbol{x}_i) }{\partial x_1\partial x_2}, \, \dots \, , \frac{\partial^n g(\boldsymbol{x}_i) }{\partial x_N^n} \right) \right)^2.
|
|
\end{equation*}
|
|
$$
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec38">Example: The diffusion equation </h2>
|
|
|
|
<p>
|
|
In one spatial dimension, the equation reads
|
|
$$
|
|
\begin{equation*}
|
|
\frac{\partial g(x,t)}{\partial t} = \frac{\partial^2 g(x,t)}{\partial x^2}
|
|
\end{equation*}
|
|
$$
|
|
|
|
<p>
|
|
where a possible choice of conditions are
|
|
$$
|
|
\begin{align*}
|
|
g(0,t) &= 0 ,\qquad t \geq 0 \\
|
|
g(1,t) &= 0, \qquad t \geq 0 \\
|
|
g(x,0) &= u(x),\qquad x\in [0,1]
|
|
\end{align*}
|
|
$$
|
|
|
|
with \( u(x) \) being some given function.
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec39">Defining the problem </h2>
|
|
|
|
<p>
|
|
For this case, we want to find \( g(x,t) \) such that
|
|
|
|
$$
|
|
\begin{equation}
|
|
\frac{\partial g(x,t)}{\partial t} = \frac{\partial^2 g(x,t)}{\partial x^2}
|
|
\end{equation} \label{diffonedim}
|
|
$$
|
|
|
|
<p>
|
|
and
|
|
|
|
$$
|
|
\begin{align*}
|
|
g(0,t) &= 0 ,\qquad t \geq 0 \\
|
|
g(1,t) &= 0, \qquad t \geq 0 \\
|
|
g(x,0) &= u(x),\qquad x\in [0,1]
|
|
\end{align*}
|
|
$$
|
|
|
|
with \( u(x) = \sin(\pi x) \).
|
|
|
|
<p>
|
|
First, let us set up the deep neural network.
|
|
The deep neural network will follow the same structure as discussed in the examples solving the ODEs.
|
|
First, we will look into how Autograd could be used in a network tailored to solve for bivariate functions.
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec40">Setting up the network using Autograd </h2>
|
|
|
|
<p>
|
|
The only change to do here, is to extend our network such that
|
|
functions of multiple parameters are correctly handled. In this case
|
|
we have two variables in our function to solve for, that is time \( t \)
|
|
and position \( x \). The variables will be represented by a
|
|
one-dimensional array in the program. The program will evaluate the
|
|
network at each possible pair \( (x,t) \), given an array for the desired
|
|
\( x \)-values and \( t \)-values to approximate the solution at.
|
|
|
|
<p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span><span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">sigmoid</span>(z):
|
|
<span style="color: #008000; font-weight: bold">return</span> <span style="color: #666666">1/</span>(<span style="color: #666666">1</span> <span style="color: #666666">+</span> np<span style="color: #666666">.</span>exp(<span style="color: #666666">-</span>z))
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">deep_neural_network</span>(deep_params, x):
|
|
<span style="color: #408080; font-style: italic"># x is now a point and a 1D numpy array; make it a column vector</span>
|
|
num_coordinates <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(x,<span style="color: #666666">0</span>)
|
|
x <span style="color: #666666">=</span> x<span style="color: #666666">.</span>reshape(num_coordinates,<span style="color: #666666">-1</span>)
|
|
|
|
num_points <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(x,<span style="color: #666666">1</span>)
|
|
|
|
<span style="color: #408080; font-style: italic"># N_hidden is the number of hidden layers</span>
|
|
N_hidden <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(deep_params) <span style="color: #666666">-</span> <span style="color: #666666">1</span> <span style="color: #408080; font-style: italic"># -1 since params consist of parameters to all the hidden layers AND the output layer</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Assume that the input layer does nothing to the input x</span>
|
|
x_input <span style="color: #666666">=</span> x
|
|
x_prev <span style="color: #666666">=</span> x_input
|
|
|
|
<span style="color: #408080; font-style: italic">## Hidden layers:</span>
|
|
|
|
<span style="color: #008000; font-weight: bold">for</span> l <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(N_hidden):
|
|
<span style="color: #408080; font-style: italic"># From the list of parameters P; find the correct weigths and bias for this layer</span>
|
|
w_hidden <span style="color: #666666">=</span> deep_params[l]
|
|
|
|
<span style="color: #408080; font-style: italic"># Add a row of ones to include bias</span>
|
|
x_prev <span style="color: #666666">=</span> np<span style="color: #666666">.</span>concatenate((np<span style="color: #666666">.</span>ones((<span style="color: #666666">1</span>,num_points)), x_prev ), axis <span style="color: #666666">=</span> <span style="color: #666666">0</span>)
|
|
|
|
z_hidden <span style="color: #666666">=</span> np<span style="color: #666666">.</span>matmul(w_hidden, x_prev)
|
|
x_hidden <span style="color: #666666">=</span> sigmoid(z_hidden)
|
|
|
|
<span style="color: #408080; font-style: italic"># Update x_prev such that next layer can use the output from this layer</span>
|
|
x_prev <span style="color: #666666">=</span> x_hidden
|
|
|
|
<span style="color: #408080; font-style: italic">## Output layer:</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Get the weights and bias for this layer</span>
|
|
w_output <span style="color: #666666">=</span> deep_params[<span style="color: #666666">-1</span>]
|
|
|
|
<span style="color: #408080; font-style: italic"># Include bias:</span>
|
|
x_prev <span style="color: #666666">=</span> np<span style="color: #666666">.</span>concatenate((np<span style="color: #666666">.</span>ones((<span style="color: #666666">1</span>,num_points)), x_prev), axis <span style="color: #666666">=</span> <span style="color: #666666">0</span>)
|
|
|
|
z_output <span style="color: #666666">=</span> np<span style="color: #666666">.</span>matmul(w_output, x_prev)
|
|
x_output <span style="color: #666666">=</span> z_output
|
|
|
|
<span style="color: #008000; font-weight: bold">return</span> x_output[<span style="color: #666666">0</span>][<span style="color: #666666">0</span>]
|
|
</pre></div>
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec41">Setting up the network using Autograd; The trial solution </h2>
|
|
|
|
<p>
|
|
The cost function must then iterate through the given arrays
|
|
containing values for \( x \) and \( t \), defines a point \( (x,t) \) the deep
|
|
neural network and the trial solution is evaluated at, and then finds
|
|
the Jacobian of the trial solution.
|
|
|
|
<p>
|
|
A possible trial solution for this PDE is
|
|
|
|
$$
|
|
g_t(x,t) = h_1(x,t) + x(1-x)tN(x,t,P)
|
|
$$
|
|
|
|
<p>
|
|
with \( A(x,t) \) being a function ensuring that \( g_t(x,t) \) satisfies our given conditions, and \( N(x,t,P) \) being the output from the deep neural network using weights and biases for each layer from \( P \).
|
|
|
|
<p>
|
|
To fulfill the conditions, \( A(x,t) \) could be:
|
|
|
|
$$
|
|
h_1(x,t) = (1-t)\Big(u(x) - \big((1-x)u(0) + x u(1)\big)\Big) = (1-t)u(x) = (1-t)\sin(\pi x)
|
|
$$
|
|
since \( (0) = u(1) = 0 \) and \( u(x) = \sin(\pi x) \).
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec42">Why the jacobian? </h2>
|
|
|
|
<p>
|
|
The Jacobian is used because the program must find the derivative of
|
|
the trial solution with respect to \( x \) and \( t \).
|
|
|
|
<p>
|
|
This gives the necessity of computing the Jacobian matrix, as we want
|
|
to evaluate the gradient with respect to \( x \) and \( t \) (note that the
|
|
Jacobian of a scalar-valued multivariate function is simply its
|
|
gradient).
|
|
|
|
<p>
|
|
In Autograd, the differentiation is by default done with respect to
|
|
the first input argument of your Python function. Since the points is
|
|
an array representing \( x \) and \( t \), the Jacobian is calculated using
|
|
the values of \( x \) and \( t \).
|
|
|
|
<p>
|
|
To find the second derivative with respect to \( x \) and \( t \), the
|
|
Jacobian can be found for the second time. The result is a Hessian
|
|
matrix, which is the matrix containing all the possible second order
|
|
mixed derivatives of \( g(x,t) \).
|
|
|
|
<p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span><span style="color: #408080; font-style: italic"># Set up the trial function:</span>
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">u</span>(x):
|
|
<span style="color: #008000; font-weight: bold">return</span> np<span style="color: #666666">.</span>sin(np<span style="color: #666666">.</span>pi<span style="color: #666666">*</span>x)
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">g_trial</span>(point,P):
|
|
x,t <span style="color: #666666">=</span> point
|
|
<span style="color: #008000; font-weight: bold">return</span> (<span style="color: #666666">1-</span>t)<span style="color: #666666">*</span>u(x) <span style="color: #666666">+</span> x<span style="color: #666666">*</span>(<span style="color: #666666">1-</span>x)<span style="color: #666666">*</span>t<span style="color: #666666">*</span>deep_neural_network(P,point)
|
|
|
|
<span style="color: #408080; font-style: italic"># The right side of the ODE:</span>
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">f</span>(point):
|
|
<span style="color: #008000; font-weight: bold">return</span> <span style="color: #666666">0.</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># The cost function:</span>
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">cost_function</span>(P, x, t):
|
|
cost_sum <span style="color: #666666">=</span> <span style="color: #666666">0</span>
|
|
|
|
g_t_jacobian_func <span style="color: #666666">=</span> jacobian(g_trial)
|
|
g_t_hessian_func <span style="color: #666666">=</span> hessian(g_trial)
|
|
|
|
<span style="color: #008000; font-weight: bold">for</span> x_ <span style="color: #AA22FF; font-weight: bold">in</span> x:
|
|
<span style="color: #008000; font-weight: bold">for</span> t_ <span style="color: #AA22FF; font-weight: bold">in</span> t:
|
|
point <span style="color: #666666">=</span> np<span style="color: #666666">.</span>array([x_,t_])
|
|
|
|
g_t <span style="color: #666666">=</span> g_trial(point,P)
|
|
g_t_jacobian <span style="color: #666666">=</span> g_t_jacobian_func(point,P)
|
|
g_t_hessian <span style="color: #666666">=</span> g_t_hessian_func(point,P)
|
|
|
|
g_t_dt <span style="color: #666666">=</span> g_t_jacobian[<span style="color: #666666">1</span>]
|
|
g_t_d2x <span style="color: #666666">=</span> g_t_hessian[<span style="color: #666666">0</span>][<span style="color: #666666">0</span>]
|
|
|
|
func <span style="color: #666666">=</span> f(point)
|
|
|
|
err_sqr <span style="color: #666666">=</span> ( (g_t_dt <span style="color: #666666">-</span> g_t_d2x) <span style="color: #666666">-</span> func)<span style="color: #666666">**2</span>
|
|
cost_sum <span style="color: #666666">+=</span> err_sqr
|
|
|
|
<span style="color: #008000; font-weight: bold">return</span> cost_sum
|
|
</pre></div>
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec43">Setting up the network using Autograd; The full program </h2>
|
|
|
|
<p>
|
|
Having set up the network, along with the trial solution and cost function, we can now see how the deep neural network performs by comparing the results to the analytical solution.
|
|
|
|
<p>
|
|
The analytical solution of our problem is
|
|
|
|
$$
|
|
g(x,t) = \exp(-\pi^2 t)\sin(\pi x)
|
|
$$
|
|
|
|
<p>
|
|
A possible way to implement a neural network solving the PDE, is given below.
|
|
Be aware, though, that it is fairly slow for the parameters used.
|
|
A better result is possible, but requires more iterations, and thus longer time to complete.
|
|
|
|
<p>
|
|
Indeed, the program below is not optimal in its implementation, but rather serves as an example on how to implement and use a neural network to solve a PDE.
|
|
Using TensorFlow results in a much better execution time. Try it!
|
|
|
|
<p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">autograd.numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">autograd</span> <span style="color: #008000; font-weight: bold">import</span> jacobian,hessian,grad
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">autograd.numpy.random</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">npr</span>
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">matplotlib</span> <span style="color: #008000; font-weight: bold">import</span> cm
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">matplotlib</span> <span style="color: #008000; font-weight: bold">import</span> pyplot <span style="color: #008000; font-weight: bold">as</span> plt
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">mpl_toolkits.mplot3d</span> <span style="color: #008000; font-weight: bold">import</span> axes3d
|
|
|
|
<span style="color: #408080; font-style: italic">## Set up the network</span>
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">sigmoid</span>(z):
|
|
<span style="color: #008000; font-weight: bold">return</span> <span style="color: #666666">1/</span>(<span style="color: #666666">1</span> <span style="color: #666666">+</span> np<span style="color: #666666">.</span>exp(<span style="color: #666666">-</span>z))
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">deep_neural_network</span>(deep_params, x):
|
|
<span style="color: #408080; font-style: italic"># x is now a point and a 1D numpy array; make it a column vector</span>
|
|
num_coordinates <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(x,<span style="color: #666666">0</span>)
|
|
x <span style="color: #666666">=</span> x<span style="color: #666666">.</span>reshape(num_coordinates,<span style="color: #666666">-1</span>)
|
|
|
|
num_points <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(x,<span style="color: #666666">1</span>)
|
|
|
|
<span style="color: #408080; font-style: italic"># N_hidden is the number of hidden layers</span>
|
|
N_hidden <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(deep_params) <span style="color: #666666">-</span> <span style="color: #666666">1</span> <span style="color: #408080; font-style: italic"># -1 since params consist of parameters to all the hidden layers AND the output layer</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Assume that the input layer does nothing to the input x</span>
|
|
x_input <span style="color: #666666">=</span> x
|
|
x_prev <span style="color: #666666">=</span> x_input
|
|
|
|
<span style="color: #408080; font-style: italic">## Hidden layers:</span>
|
|
|
|
<span style="color: #008000; font-weight: bold">for</span> l <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(N_hidden):
|
|
<span style="color: #408080; font-style: italic"># From the list of parameters P; find the correct weigths and bias for this layer</span>
|
|
w_hidden <span style="color: #666666">=</span> deep_params[l]
|
|
|
|
<span style="color: #408080; font-style: italic"># Add a row of ones to include bias</span>
|
|
x_prev <span style="color: #666666">=</span> np<span style="color: #666666">.</span>concatenate((np<span style="color: #666666">.</span>ones((<span style="color: #666666">1</span>,num_points)), x_prev ), axis <span style="color: #666666">=</span> <span style="color: #666666">0</span>)
|
|
|
|
z_hidden <span style="color: #666666">=</span> np<span style="color: #666666">.</span>matmul(w_hidden, x_prev)
|
|
x_hidden <span style="color: #666666">=</span> sigmoid(z_hidden)
|
|
|
|
<span style="color: #408080; font-style: italic"># Update x_prev such that next layer can use the output from this layer</span>
|
|
x_prev <span style="color: #666666">=</span> x_hidden
|
|
|
|
<span style="color: #408080; font-style: italic">## Output layer:</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Get the weights and bias for this layer</span>
|
|
w_output <span style="color: #666666">=</span> deep_params[<span style="color: #666666">-1</span>]
|
|
|
|
<span style="color: #408080; font-style: italic"># Include bias:</span>
|
|
x_prev <span style="color: #666666">=</span> np<span style="color: #666666">.</span>concatenate((np<span style="color: #666666">.</span>ones((<span style="color: #666666">1</span>,num_points)), x_prev), axis <span style="color: #666666">=</span> <span style="color: #666666">0</span>)
|
|
|
|
z_output <span style="color: #666666">=</span> np<span style="color: #666666">.</span>matmul(w_output, x_prev)
|
|
x_output <span style="color: #666666">=</span> z_output
|
|
|
|
<span style="color: #008000; font-weight: bold">return</span> x_output[<span style="color: #666666">0</span>][<span style="color: #666666">0</span>]
|
|
|
|
<span style="color: #408080; font-style: italic">## Define the trial solution and cost function</span>
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">u</span>(x):
|
|
<span style="color: #008000; font-weight: bold">return</span> np<span style="color: #666666">.</span>sin(np<span style="color: #666666">.</span>pi<span style="color: #666666">*</span>x)
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">g_trial</span>(point,P):
|
|
x,t <span style="color: #666666">=</span> point
|
|
<span style="color: #008000; font-weight: bold">return</span> (<span style="color: #666666">1-</span>t)<span style="color: #666666">*</span>u(x) <span style="color: #666666">+</span> x<span style="color: #666666">*</span>(<span style="color: #666666">1-</span>x)<span style="color: #666666">*</span>t<span style="color: #666666">*</span>deep_neural_network(P,point)
|
|
|
|
<span style="color: #408080; font-style: italic"># The right side of the ODE:</span>
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">f</span>(point):
|
|
<span style="color: #008000; font-weight: bold">return</span> <span style="color: #666666">0.</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># The cost function:</span>
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">cost_function</span>(P, x, t):
|
|
cost_sum <span style="color: #666666">=</span> <span style="color: #666666">0</span>
|
|
|
|
g_t_jacobian_func <span style="color: #666666">=</span> jacobian(g_trial)
|
|
g_t_hessian_func <span style="color: #666666">=</span> hessian(g_trial)
|
|
|
|
<span style="color: #008000; font-weight: bold">for</span> x_ <span style="color: #AA22FF; font-weight: bold">in</span> x:
|
|
<span style="color: #008000; font-weight: bold">for</span> t_ <span style="color: #AA22FF; font-weight: bold">in</span> t:
|
|
point <span style="color: #666666">=</span> np<span style="color: #666666">.</span>array([x_,t_])
|
|
|
|
g_t <span style="color: #666666">=</span> g_trial(point,P)
|
|
g_t_jacobian <span style="color: #666666">=</span> g_t_jacobian_func(point,P)
|
|
g_t_hessian <span style="color: #666666">=</span> g_t_hessian_func(point,P)
|
|
|
|
g_t_dt <span style="color: #666666">=</span> g_t_jacobian[<span style="color: #666666">1</span>]
|
|
g_t_d2x <span style="color: #666666">=</span> g_t_hessian[<span style="color: #666666">0</span>][<span style="color: #666666">0</span>]
|
|
|
|
func <span style="color: #666666">=</span> f(point)
|
|
|
|
err_sqr <span style="color: #666666">=</span> ( (g_t_dt <span style="color: #666666">-</span> g_t_d2x) <span style="color: #666666">-</span> func)<span style="color: #666666">**2</span>
|
|
cost_sum <span style="color: #666666">+=</span> err_sqr
|
|
|
|
<span style="color: #008000; font-weight: bold">return</span> cost_sum <span style="color: #666666">/</span>( np<span style="color: #666666">.</span>size(x)<span style="color: #666666">*</span>np<span style="color: #666666">.</span>size(t) )
|
|
|
|
<span style="color: #408080; font-style: italic">## For comparison, define the analytical solution</span>
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">g_analytic</span>(point):
|
|
x,t <span style="color: #666666">=</span> point
|
|
<span style="color: #008000; font-weight: bold">return</span> np<span style="color: #666666">.</span>exp(<span style="color: #666666">-</span>np<span style="color: #666666">.</span>pi<span style="color: #666666">**2*</span>t)<span style="color: #666666">*</span>np<span style="color: #666666">.</span>sin(np<span style="color: #666666">.</span>pi<span style="color: #666666">*</span>x)
|
|
|
|
<span style="color: #408080; font-style: italic">## Set up a function for training the network to solve for the equation</span>
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">solve_pde_deep_neural_network</span>(x,t, num_neurons, num_iter, lmb):
|
|
<span style="color: #408080; font-style: italic">## Set up initial weigths and biases</span>
|
|
N_hidden <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(num_neurons)
|
|
|
|
<span style="color: #408080; font-style: italic">## Set up initial weigths and biases</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Initialize the list of parameters:</span>
|
|
P <span style="color: #666666">=</span> [<span style="color: #008000; font-weight: bold">None</span>]<span style="color: #666666">*</span>(N_hidden <span style="color: #666666">+</span> <span style="color: #666666">1</span>) <span style="color: #408080; font-style: italic"># + 1 to include the output layer</span>
|
|
|
|
P[<span style="color: #666666">0</span>] <span style="color: #666666">=</span> npr<span style="color: #666666">.</span>randn(num_neurons[<span style="color: #666666">0</span>], <span style="color: #666666">2</span> <span style="color: #666666">+</span> <span style="color: #666666">1</span> ) <span style="color: #408080; font-style: italic"># 2 since we have two points, +1 to include bias</span>
|
|
<span style="color: #008000; font-weight: bold">for</span> l <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(<span style="color: #666666">1</span>,N_hidden):
|
|
P[l] <span style="color: #666666">=</span> npr<span style="color: #666666">.</span>randn(num_neurons[l], num_neurons[l<span style="color: #666666">-1</span>] <span style="color: #666666">+</span> <span style="color: #666666">1</span>) <span style="color: #408080; font-style: italic"># +1 to include bias</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># For the output layer</span>
|
|
P[<span style="color: #666666">-1</span>] <span style="color: #666666">=</span> npr<span style="color: #666666">.</span>randn(<span style="color: #666666">1</span>, num_neurons[<span style="color: #666666">-1</span>] <span style="color: #666666">+</span> <span style="color: #666666">1</span> ) <span style="color: #408080; font-style: italic"># +1 since bias is included</span>
|
|
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">'Initial cost: '</span>,cost_function(P, x, t))
|
|
|
|
cost_function_grad <span style="color: #666666">=</span> grad(cost_function,<span style="color: #666666">0</span>)
|
|
|
|
<span style="color: #408080; font-style: italic"># Let the update be done num_iter times</span>
|
|
<span style="color: #008000; font-weight: bold">for</span> i <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(num_iter):
|
|
cost_grad <span style="color: #666666">=</span> cost_function_grad(P, x , t)
|
|
|
|
<span style="color: #008000; font-weight: bold">for</span> l <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(N_hidden<span style="color: #666666">+1</span>):
|
|
P[l] <span style="color: #666666">=</span> P[l] <span style="color: #666666">-</span> lmb <span style="color: #666666">*</span> cost_grad[l]
|
|
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">'Final cost: '</span>,cost_function(P, x, t))
|
|
|
|
<span style="color: #008000; font-weight: bold">return</span> P
|
|
|
|
<span style="color: #008000; font-weight: bold">if</span> <span style="color: #19177C">__name__</span> <span style="color: #666666">==</span> <span style="color: #BA2121">'__main__'</span>:
|
|
<span style="color: #408080; font-style: italic">### Use the neural network:</span>
|
|
npr<span style="color: #666666">.</span>seed(<span style="color: #666666">15</span>)
|
|
|
|
<span style="color: #408080; font-style: italic">## Decide the vales of arguments to the function to solve</span>
|
|
Nx <span style="color: #666666">=</span> <span style="color: #666666">10</span>; Nt <span style="color: #666666">=</span> <span style="color: #666666">10</span>
|
|
x <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linspace(<span style="color: #666666">0</span>, <span style="color: #666666">1</span>, Nx)
|
|
t <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linspace(<span style="color: #666666">0</span>,<span style="color: #666666">1</span>,Nt)
|
|
|
|
<span style="color: #408080; font-style: italic">## Set up the parameters for the network</span>
|
|
num_hidden_neurons <span style="color: #666666">=</span> [<span style="color: #666666">100</span>, <span style="color: #666666">25</span>]
|
|
num_iter <span style="color: #666666">=</span> <span style="color: #666666">250</span>
|
|
lmb <span style="color: #666666">=</span> <span style="color: #666666">0.01</span>
|
|
|
|
P <span style="color: #666666">=</span> solve_pde_deep_neural_network(x,t, num_hidden_neurons, num_iter, lmb)
|
|
|
|
<span style="color: #408080; font-style: italic">## Store the results</span>
|
|
g_dnn_ag <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros((Nx, Nt))
|
|
G_analytical <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros((Nx, Nt))
|
|
<span style="color: #008000; font-weight: bold">for</span> i,x_ <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">enumerate</span>(x):
|
|
<span style="color: #008000; font-weight: bold">for</span> j, t_ <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">enumerate</span>(t):
|
|
point <span style="color: #666666">=</span> np<span style="color: #666666">.</span>array([x_, t_])
|
|
g_dnn_ag[i,j] <span style="color: #666666">=</span> g_trial(point,P)
|
|
|
|
G_analytical[i,j] <span style="color: #666666">=</span> g_analytic(point)
|
|
|
|
<span style="color: #408080; font-style: italic"># Find the map difference between the analytical and the computed solution</span>
|
|
diff_ag <span style="color: #666666">=</span> np<span style="color: #666666">.</span>abs(g_dnn_ag <span style="color: #666666">-</span> G_analytical)
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">'Max absolute difference between the analytical solution and the network: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">'</span><span style="color: #666666">%</span>np<span style="color: #666666">.</span>max(diff_ag))
|
|
|
|
<span style="color: #408080; font-style: italic">## Plot the solutions in two dimensions, that being in position and time</span>
|
|
|
|
T,X <span style="color: #666666">=</span> np<span style="color: #666666">.</span>meshgrid(t,x)
|
|
|
|
fig <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">10</span>,<span style="color: #666666">10</span>))
|
|
ax <span style="color: #666666">=</span> fig<span style="color: #666666">.</span>gca(projection<span style="color: #666666">=</span><span style="color: #BA2121">'3d'</span>)
|
|
ax<span style="color: #666666">.</span>set_title(<span style="color: #BA2121">'Solution from the deep neural network w/ </span><span style="color: #BB6688; font-weight: bold">%d</span><span style="color: #BA2121"> layer'</span><span style="color: #666666">%</span><span style="color: #008000">len</span>(num_hidden_neurons))
|
|
s <span style="color: #666666">=</span> ax<span style="color: #666666">.</span>plot_surface(T,X,g_dnn_ag,linewidth<span style="color: #666666">=0</span>,antialiased<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">False</span>,cmap<span style="color: #666666">=</span>cm<span style="color: #666666">.</span>viridis)
|
|
ax<span style="color: #666666">.</span>set_xlabel(<span style="color: #BA2121">'Time $t$'</span>)
|
|
ax<span style="color: #666666">.</span>set_ylabel(<span style="color: #BA2121">'Position $x$'</span>);
|
|
|
|
|
|
fig <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">10</span>,<span style="color: #666666">10</span>))
|
|
ax <span style="color: #666666">=</span> fig<span style="color: #666666">.</span>gca(projection<span style="color: #666666">=</span><span style="color: #BA2121">'3d'</span>)
|
|
ax<span style="color: #666666">.</span>set_title(<span style="color: #BA2121">'Analytical solution'</span>)
|
|
s <span style="color: #666666">=</span> ax<span style="color: #666666">.</span>plot_surface(T,X,G_analytical,linewidth<span style="color: #666666">=0</span>,antialiased<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">False</span>,cmap<span style="color: #666666">=</span>cm<span style="color: #666666">.</span>viridis)
|
|
ax<span style="color: #666666">.</span>set_xlabel(<span style="color: #BA2121">'Time $t$'</span>)
|
|
ax<span style="color: #666666">.</span>set_ylabel(<span style="color: #BA2121">'Position $x$'</span>);
|
|
|
|
fig <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">10</span>,<span style="color: #666666">10</span>))
|
|
ax <span style="color: #666666">=</span> fig<span style="color: #666666">.</span>gca(projection<span style="color: #666666">=</span><span style="color: #BA2121">'3d'</span>)
|
|
ax<span style="color: #666666">.</span>set_title(<span style="color: #BA2121">'Difference'</span>)
|
|
s <span style="color: #666666">=</span> ax<span style="color: #666666">.</span>plot_surface(T,X,diff_ag,linewidth<span style="color: #666666">=0</span>,antialiased<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">False</span>,cmap<span style="color: #666666">=</span>cm<span style="color: #666666">.</span>viridis)
|
|
ax<span style="color: #666666">.</span>set_xlabel(<span style="color: #BA2121">'Time $t$'</span>)
|
|
ax<span style="color: #666666">.</span>set_ylabel(<span style="color: #BA2121">'Position $x$'</span>);
|
|
|
|
<span style="color: #408080; font-style: italic">## Take some slices of the 3D plots just to see the solutions at particular times</span>
|
|
indx1 <span style="color: #666666">=</span> <span style="color: #666666">0</span>
|
|
indx2 <span style="color: #666666">=</span> <span style="color: #008000">int</span>(Nt<span style="color: #666666">/2</span>)
|
|
indx3 <span style="color: #666666">=</span> Nt<span style="color: #666666">-1</span>
|
|
|
|
t1 <span style="color: #666666">=</span> t[indx1]
|
|
t2 <span style="color: #666666">=</span> t[indx2]
|
|
t3 <span style="color: #666666">=</span> t[indx3]
|
|
|
|
<span style="color: #408080; font-style: italic"># Slice the results from the DNN</span>
|
|
res1 <span style="color: #666666">=</span> g_dnn_ag[:,indx1]
|
|
res2 <span style="color: #666666">=</span> g_dnn_ag[:,indx2]
|
|
res3 <span style="color: #666666">=</span> g_dnn_ag[:,indx3]
|
|
|
|
<span style="color: #408080; font-style: italic"># Slice the analytical results</span>
|
|
res_analytical1 <span style="color: #666666">=</span> G_analytical[:,indx1]
|
|
res_analytical2 <span style="color: #666666">=</span> G_analytical[:,indx2]
|
|
res_analytical3 <span style="color: #666666">=</span> G_analytical[:,indx3]
|
|
|
|
<span style="color: #408080; font-style: italic"># Plot the slices</span>
|
|
plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">10</span>,<span style="color: #666666">10</span>))
|
|
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">"Computed solutions at time = </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">"</span><span style="color: #666666">%</span>t1)
|
|
plt<span style="color: #666666">.</span>plot(x, res1)
|
|
plt<span style="color: #666666">.</span>plot(x,res_analytical1)
|
|
plt<span style="color: #666666">.</span>legend([<span style="color: #BA2121">'dnn'</span>,<span style="color: #BA2121">'analytical'</span>])
|
|
|
|
plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">10</span>,<span style="color: #666666">10</span>))
|
|
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">"Computed solutions at time = </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">"</span><span style="color: #666666">%</span>t2)
|
|
plt<span style="color: #666666">.</span>plot(x, res2)
|
|
plt<span style="color: #666666">.</span>plot(x,res_analytical2)
|
|
plt<span style="color: #666666">.</span>legend([<span style="color: #BA2121">'dnn'</span>,<span style="color: #BA2121">'analytical'</span>])
|
|
|
|
plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">10</span>,<span style="color: #666666">10</span>))
|
|
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">"Computed solutions at time = </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">"</span><span style="color: #666666">%</span>t3)
|
|
plt<span style="color: #666666">.</span>plot(x, res3)
|
|
plt<span style="color: #666666">.</span>plot(x,res_analytical3)
|
|
plt<span style="color: #666666">.</span>legend([<span style="color: #BA2121">'dnn'</span>,<span style="color: #BA2121">'analytical'</span>])
|
|
|
|
plt<span style="color: #666666">.</span>show()
|
|
</pre></div>
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec44">Example: Solving the wave equation with Neural Networks </h2>
|
|
|
|
<p>
|
|
The wave equation is
|
|
$$
|
|
\begin{equation*}
|
|
\frac{\partial^2 g(x,t)}{\partial t^2} = c^2\frac{\partial^2 g(x,t)}{\partial x^2}
|
|
\end{equation*}
|
|
$$
|
|
|
|
<p>
|
|
with \( c \) being the specified wave speed.
|
|
|
|
<p>
|
|
Here, the chosen conditions are
|
|
$$
|
|
\begin{align*}
|
|
g(0,t) &= 0 \\
|
|
g(1,t) &= 0 \\
|
|
g(x,0) &= u(x) \\
|
|
\frac{\partial g(x,t)}{\partial t} \Big |_{t = 0} &= v(x)
|
|
\end{align*}
|
|
$$
|
|
|
|
where \( \frac{\partial g(x,t)}{\partial t} \Big |_{t = 0} \) means the derivative of \( g(x,t) \) with respect to \( t \) is evaluated at \( t = 0 \), and \( u(x) \) and \( v(x) \) being given functions.
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec45">The problem to solve for </h2>
|
|
|
|
<p>
|
|
The wave equation to solve for, is
|
|
|
|
$$
|
|
\begin{equation} \label{wave}
|
|
\frac{\partial^2 g(x,t)}{\partial t^2} = c^2 \frac{\partial^2 g(x,t)}{\partial x^2}
|
|
\end{equation}
|
|
$$
|
|
|
|
<p>
|
|
where \( c \) is the given wave speed.
|
|
The chosen conditions for this equation are
|
|
|
|
$$
|
|
\begin{aligned}
|
|
g(0,t) &= 0, &t \geq 0 \\
|
|
g(1,t) &= 0, &t \geq 0 \\
|
|
g(x,0) &= u(x), &x\in[0,1] \\
|
|
\frac{\partial g(x,t)}{\partial t}\Big |_{t = 0} &= v(x), &x \in [0,1]
|
|
\end{aligned} \label{condwave}
|
|
$$
|
|
|
|
<p>
|
|
In this example, let \( c = 1 \) and \( u(x) = \sin(\pi x) \) and \( v(x) = -\pi\sin(\pi x) \).
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec46">The trial solution </h2>
|
|
Setting up the network is done in similar matter as for the example of solving the diffusion equation.
|
|
The only things we have to change, is the trial solution such that it satisfies the conditions from \eqref{condwave} and the cost function.
|
|
|
|
<p>
|
|
The trial solution becomes slightly different since we have other conditions than in the example of solving the diffusion equation. Here, a possible trial solution \( g_t(x,t) \) is
|
|
|
|
$$
|
|
g_t(x,t) = h_1(x,t) + x(1-x)t^2N(x,t,P)
|
|
$$
|
|
|
|
<p>
|
|
where
|
|
|
|
$$
|
|
h_1(x,t) = (1-t^2)u(x) + tv(x)
|
|
$$
|
|
|
|
<p>
|
|
Note that this trial solution satisfies the conditions only if \( u(0) = v(0) = u(1) = v(1) = 0 \), which is the case in this example.
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec47">The analytical solution </h2>
|
|
|
|
<p>
|
|
The analytical solution for our specific problem, is
|
|
|
|
$$
|
|
g(x,t) = \sin(\pi x)\cos(\pi t) - \sin(\pi x)\sin(\pi t)
|
|
$$
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec48">Solving the wave equation - the full program using Autograd </h2>
|
|
|
|
<p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">autograd.numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">autograd</span> <span style="color: #008000; font-weight: bold">import</span> hessian,grad
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">autograd.numpy.random</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">npr</span>
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">matplotlib</span> <span style="color: #008000; font-weight: bold">import</span> cm
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">matplotlib</span> <span style="color: #008000; font-weight: bold">import</span> pyplot <span style="color: #008000; font-weight: bold">as</span> plt
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">mpl_toolkits.mplot3d</span> <span style="color: #008000; font-weight: bold">import</span> axes3d
|
|
|
|
<span style="color: #408080; font-style: italic">## Set up the trial function:</span>
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">u</span>(x):
|
|
<span style="color: #008000; font-weight: bold">return</span> np<span style="color: #666666">.</span>sin(np<span style="color: #666666">.</span>pi<span style="color: #666666">*</span>x)
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">v</span>(x):
|
|
<span style="color: #008000; font-weight: bold">return</span> <span style="color: #666666">-</span>np<span style="color: #666666">.</span>pi<span style="color: #666666">*</span>np<span style="color: #666666">.</span>sin(np<span style="color: #666666">.</span>pi<span style="color: #666666">*</span>x)
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">h1</span>(point):
|
|
x,t <span style="color: #666666">=</span> point
|
|
<span style="color: #008000; font-weight: bold">return</span> (<span style="color: #666666">1</span> <span style="color: #666666">-</span> t<span style="color: #666666">**2</span>)<span style="color: #666666">*</span>u(x) <span style="color: #666666">+</span> t<span style="color: #666666">*</span>v(x)
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">g_trial</span>(point,P):
|
|
x,t <span style="color: #666666">=</span> point
|
|
<span style="color: #008000; font-weight: bold">return</span> h1(point) <span style="color: #666666">+</span> x<span style="color: #666666">*</span>(<span style="color: #666666">1-</span>x)<span style="color: #666666">*</span>t<span style="color: #666666">**2*</span>deep_neural_network(P,point)
|
|
|
|
<span style="color: #408080; font-style: italic">## Define the cost function</span>
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">cost_function</span>(P, x, t):
|
|
cost_sum <span style="color: #666666">=</span> <span style="color: #666666">0</span>
|
|
|
|
g_t_hessian_func <span style="color: #666666">=</span> hessian(g_trial)
|
|
|
|
<span style="color: #008000; font-weight: bold">for</span> x_ <span style="color: #AA22FF; font-weight: bold">in</span> x:
|
|
<span style="color: #008000; font-weight: bold">for</span> t_ <span style="color: #AA22FF; font-weight: bold">in</span> t:
|
|
point <span style="color: #666666">=</span> np<span style="color: #666666">.</span>array([x_,t_])
|
|
|
|
g_t_hessian <span style="color: #666666">=</span> g_t_hessian_func(point,P)
|
|
|
|
g_t_d2x <span style="color: #666666">=</span> g_t_hessian[<span style="color: #666666">0</span>][<span style="color: #666666">0</span>]
|
|
g_t_d2t <span style="color: #666666">=</span> g_t_hessian[<span style="color: #666666">1</span>][<span style="color: #666666">1</span>]
|
|
|
|
err_sqr <span style="color: #666666">=</span> ( (g_t_d2t <span style="color: #666666">-</span> g_t_d2x) )<span style="color: #666666">**2</span>
|
|
cost_sum <span style="color: #666666">+=</span> err_sqr
|
|
|
|
<span style="color: #008000; font-weight: bold">return</span> cost_sum <span style="color: #666666">/</span> (np<span style="color: #666666">.</span>size(t) <span style="color: #666666">*</span> np<span style="color: #666666">.</span>size(x))
|
|
|
|
<span style="color: #408080; font-style: italic">## The neural network</span>
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">sigmoid</span>(z):
|
|
<span style="color: #008000; font-weight: bold">return</span> <span style="color: #666666">1/</span>(<span style="color: #666666">1</span> <span style="color: #666666">+</span> np<span style="color: #666666">.</span>exp(<span style="color: #666666">-</span>z))
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">deep_neural_network</span>(deep_params, x):
|
|
<span style="color: #408080; font-style: italic"># x is now a point and a 1D numpy array; make it a column vector</span>
|
|
num_coordinates <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(x,<span style="color: #666666">0</span>)
|
|
x <span style="color: #666666">=</span> x<span style="color: #666666">.</span>reshape(num_coordinates,<span style="color: #666666">-1</span>)
|
|
|
|
num_points <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(x,<span style="color: #666666">1</span>)
|
|
|
|
<span style="color: #408080; font-style: italic"># N_hidden is the number of hidden layers</span>
|
|
N_hidden <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(deep_params) <span style="color: #666666">-</span> <span style="color: #666666">1</span> <span style="color: #408080; font-style: italic"># -1 since params consist of parameters to all the hidden layers AND the output layer</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Assume that the input layer does nothing to the input x</span>
|
|
x_input <span style="color: #666666">=</span> x
|
|
x_prev <span style="color: #666666">=</span> x_input
|
|
|
|
<span style="color: #408080; font-style: italic">## Hidden layers:</span>
|
|
|
|
<span style="color: #008000; font-weight: bold">for</span> l <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(N_hidden):
|
|
<span style="color: #408080; font-style: italic"># From the list of parameters P; find the correct weigths and bias for this layer</span>
|
|
w_hidden <span style="color: #666666">=</span> deep_params[l]
|
|
|
|
<span style="color: #408080; font-style: italic"># Add a row of ones to include bias</span>
|
|
x_prev <span style="color: #666666">=</span> np<span style="color: #666666">.</span>concatenate((np<span style="color: #666666">.</span>ones((<span style="color: #666666">1</span>,num_points)), x_prev ), axis <span style="color: #666666">=</span> <span style="color: #666666">0</span>)
|
|
|
|
z_hidden <span style="color: #666666">=</span> np<span style="color: #666666">.</span>matmul(w_hidden, x_prev)
|
|
x_hidden <span style="color: #666666">=</span> sigmoid(z_hidden)
|
|
|
|
<span style="color: #408080; font-style: italic"># Update x_prev such that next layer can use the output from this layer</span>
|
|
x_prev <span style="color: #666666">=</span> x_hidden
|
|
|
|
<span style="color: #408080; font-style: italic">## Output layer:</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Get the weights and bias for this layer</span>
|
|
w_output <span style="color: #666666">=</span> deep_params[<span style="color: #666666">-1</span>]
|
|
|
|
<span style="color: #408080; font-style: italic"># Include bias:</span>
|
|
x_prev <span style="color: #666666">=</span> np<span style="color: #666666">.</span>concatenate((np<span style="color: #666666">.</span>ones((<span style="color: #666666">1</span>,num_points)), x_prev), axis <span style="color: #666666">=</span> <span style="color: #666666">0</span>)
|
|
|
|
z_output <span style="color: #666666">=</span> np<span style="color: #666666">.</span>matmul(w_output, x_prev)
|
|
x_output <span style="color: #666666">=</span> z_output
|
|
|
|
<span style="color: #008000; font-weight: bold">return</span> x_output[<span style="color: #666666">0</span>][<span style="color: #666666">0</span>]
|
|
|
|
<span style="color: #408080; font-style: italic">## The analytical solution</span>
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">g_analytic</span>(point):
|
|
x,t <span style="color: #666666">=</span> point
|
|
<span style="color: #008000; font-weight: bold">return</span> np<span style="color: #666666">.</span>sin(np<span style="color: #666666">.</span>pi<span style="color: #666666">*</span>x)<span style="color: #666666">*</span>np<span style="color: #666666">.</span>cos(np<span style="color: #666666">.</span>pi<span style="color: #666666">*</span>t) <span style="color: #666666">-</span> np<span style="color: #666666">.</span>sin(np<span style="color: #666666">.</span>pi<span style="color: #666666">*</span>x)<span style="color: #666666">*</span>np<span style="color: #666666">.</span>sin(np<span style="color: #666666">.</span>pi<span style="color: #666666">*</span>t)
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">solve_pde_deep_neural_network</span>(x,t, num_neurons, num_iter, lmb):
|
|
<span style="color: #408080; font-style: italic">## Set up initial weigths and biases</span>
|
|
N_hidden <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(num_neurons)
|
|
|
|
<span style="color: #408080; font-style: italic">## Set up initial weigths and biases</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Initialize the list of parameters:</span>
|
|
P <span style="color: #666666">=</span> [<span style="color: #008000; font-weight: bold">None</span>]<span style="color: #666666">*</span>(N_hidden <span style="color: #666666">+</span> <span style="color: #666666">1</span>) <span style="color: #408080; font-style: italic"># + 1 to include the output layer</span>
|
|
|
|
P[<span style="color: #666666">0</span>] <span style="color: #666666">=</span> npr<span style="color: #666666">.</span>randn(num_neurons[<span style="color: #666666">0</span>], <span style="color: #666666">2</span> <span style="color: #666666">+</span> <span style="color: #666666">1</span> ) <span style="color: #408080; font-style: italic"># 2 since we have two points, +1 to include bias</span>
|
|
<span style="color: #008000; font-weight: bold">for</span> l <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(<span style="color: #666666">1</span>,N_hidden):
|
|
P[l] <span style="color: #666666">=</span> npr<span style="color: #666666">.</span>randn(num_neurons[l], num_neurons[l<span style="color: #666666">-1</span>] <span style="color: #666666">+</span> <span style="color: #666666">1</span>) <span style="color: #408080; font-style: italic"># +1 to include bias</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># For the output layer</span>
|
|
P[<span style="color: #666666">-1</span>] <span style="color: #666666">=</span> npr<span style="color: #666666">.</span>randn(<span style="color: #666666">1</span>, num_neurons[<span style="color: #666666">-1</span>] <span style="color: #666666">+</span> <span style="color: #666666">1</span> ) <span style="color: #408080; font-style: italic"># +1 since bias is included</span>
|
|
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">'Initial cost: '</span>,cost_function(P, x, t))
|
|
|
|
cost_function_grad <span style="color: #666666">=</span> grad(cost_function,<span style="color: #666666">0</span>)
|
|
|
|
<span style="color: #408080; font-style: italic"># Let the update be done num_iter times</span>
|
|
<span style="color: #008000; font-weight: bold">for</span> i <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(num_iter):
|
|
cost_grad <span style="color: #666666">=</span> cost_function_grad(P, x , t)
|
|
|
|
<span style="color: #008000; font-weight: bold">for</span> l <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(N_hidden<span style="color: #666666">+1</span>):
|
|
P[l] <span style="color: #666666">=</span> P[l] <span style="color: #666666">-</span> lmb <span style="color: #666666">*</span> cost_grad[l]
|
|
|
|
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">'Final cost: '</span>,cost_function(P, x, t))
|
|
|
|
<span style="color: #008000; font-weight: bold">return</span> P
|
|
|
|
<span style="color: #008000; font-weight: bold">if</span> <span style="color: #19177C">__name__</span> <span style="color: #666666">==</span> <span style="color: #BA2121">'__main__'</span>:
|
|
<span style="color: #408080; font-style: italic">### Use the neural network:</span>
|
|
npr<span style="color: #666666">.</span>seed(<span style="color: #666666">15</span>)
|
|
|
|
<span style="color: #408080; font-style: italic">## Decide the vales of arguments to the function to solve</span>
|
|
Nx <span style="color: #666666">=</span> <span style="color: #666666">10</span>; Nt <span style="color: #666666">=</span> <span style="color: #666666">10</span>
|
|
x <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linspace(<span style="color: #666666">0</span>, <span style="color: #666666">1</span>, Nx)
|
|
t <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linspace(<span style="color: #666666">0</span>,<span style="color: #666666">1</span>,Nt)
|
|
|
|
<span style="color: #408080; font-style: italic">## Set up the parameters for the network</span>
|
|
num_hidden_neurons <span style="color: #666666">=</span> [<span style="color: #666666">50</span>,<span style="color: #666666">20</span>]
|
|
num_iter <span style="color: #666666">=</span> <span style="color: #666666">1000</span>
|
|
lmb <span style="color: #666666">=</span> <span style="color: #666666">0.01</span>
|
|
|
|
P <span style="color: #666666">=</span> solve_pde_deep_neural_network(x,t, num_hidden_neurons, num_iter, lmb)
|
|
|
|
<span style="color: #408080; font-style: italic">## Store the results</span>
|
|
res <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros((Nx, Nt))
|
|
res_analytical <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros((Nx, Nt))
|
|
<span style="color: #008000; font-weight: bold">for</span> i,x_ <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">enumerate</span>(x):
|
|
<span style="color: #008000; font-weight: bold">for</span> j, t_ <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">enumerate</span>(t):
|
|
point <span style="color: #666666">=</span> np<span style="color: #666666">.</span>array([x_, t_])
|
|
res[i,j] <span style="color: #666666">=</span> g_trial(point,P)
|
|
|
|
res_analytical[i,j] <span style="color: #666666">=</span> g_analytic(point)
|
|
|
|
diff <span style="color: #666666">=</span> np<span style="color: #666666">.</span>abs(res <span style="color: #666666">-</span> res_analytical)
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"Max difference between analytical and solution from nn: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">"</span><span style="color: #666666">%</span>np<span style="color: #666666">.</span>max(diff))
|
|
|
|
<span style="color: #408080; font-style: italic">## Plot the solutions in two dimensions, that being in position and time</span>
|
|
|
|
T,X <span style="color: #666666">=</span> np<span style="color: #666666">.</span>meshgrid(t,x)
|
|
|
|
fig <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">10</span>,<span style="color: #666666">10</span>))
|
|
ax <span style="color: #666666">=</span> fig<span style="color: #666666">.</span>gca(projection<span style="color: #666666">=</span><span style="color: #BA2121">'3d'</span>)
|
|
ax<span style="color: #666666">.</span>set_title(<span style="color: #BA2121">'Solution from the deep neural network w/ </span><span style="color: #BB6688; font-weight: bold">%d</span><span style="color: #BA2121"> layer'</span><span style="color: #666666">%</span><span style="color: #008000">len</span>(num_hidden_neurons))
|
|
s <span style="color: #666666">=</span> ax<span style="color: #666666">.</span>plot_surface(T,X,res,linewidth<span style="color: #666666">=0</span>,antialiased<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">False</span>,cmap<span style="color: #666666">=</span>cm<span style="color: #666666">.</span>viridis)
|
|
ax<span style="color: #666666">.</span>set_xlabel(<span style="color: #BA2121">'Time $t$'</span>)
|
|
ax<span style="color: #666666">.</span>set_ylabel(<span style="color: #BA2121">'Position $x$'</span>);
|
|
|
|
|
|
fig <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">10</span>,<span style="color: #666666">10</span>))
|
|
ax <span style="color: #666666">=</span> fig<span style="color: #666666">.</span>gca(projection<span style="color: #666666">=</span><span style="color: #BA2121">'3d'</span>)
|
|
ax<span style="color: #666666">.</span>set_title(<span style="color: #BA2121">'Analytical solution'</span>)
|
|
s <span style="color: #666666">=</span> ax<span style="color: #666666">.</span>plot_surface(T,X,res_analytical,linewidth<span style="color: #666666">=0</span>,antialiased<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">False</span>,cmap<span style="color: #666666">=</span>cm<span style="color: #666666">.</span>viridis)
|
|
ax<span style="color: #666666">.</span>set_xlabel(<span style="color: #BA2121">'Time $t$'</span>)
|
|
ax<span style="color: #666666">.</span>set_ylabel(<span style="color: #BA2121">'Position $x$'</span>);
|
|
|
|
|
|
fig <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">10</span>,<span style="color: #666666">10</span>))
|
|
ax <span style="color: #666666">=</span> fig<span style="color: #666666">.</span>gca(projection<span style="color: #666666">=</span><span style="color: #BA2121">'3d'</span>)
|
|
ax<span style="color: #666666">.</span>set_title(<span style="color: #BA2121">'Difference'</span>)
|
|
s <span style="color: #666666">=</span> ax<span style="color: #666666">.</span>plot_surface(T,X,diff,linewidth<span style="color: #666666">=0</span>,antialiased<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">False</span>,cmap<span style="color: #666666">=</span>cm<span style="color: #666666">.</span>viridis)
|
|
ax<span style="color: #666666">.</span>set_xlabel(<span style="color: #BA2121">'Time $t$'</span>)
|
|
ax<span style="color: #666666">.</span>set_ylabel(<span style="color: #BA2121">'Position $x$'</span>);
|
|
|
|
<span style="color: #408080; font-style: italic">## Take some slices of the 3D plots just to see the solutions at particular times</span>
|
|
indx1 <span style="color: #666666">=</span> <span style="color: #666666">0</span>
|
|
indx2 <span style="color: #666666">=</span> <span style="color: #008000">int</span>(Nt<span style="color: #666666">/2</span>)
|
|
indx3 <span style="color: #666666">=</span> Nt<span style="color: #666666">-1</span>
|
|
|
|
t1 <span style="color: #666666">=</span> t[indx1]
|
|
t2 <span style="color: #666666">=</span> t[indx2]
|
|
t3 <span style="color: #666666">=</span> t[indx3]
|
|
|
|
<span style="color: #408080; font-style: italic"># Slice the results from the DNN</span>
|
|
res1 <span style="color: #666666">=</span> res[:,indx1]
|
|
res2 <span style="color: #666666">=</span> res[:,indx2]
|
|
res3 <span style="color: #666666">=</span> res[:,indx3]
|
|
|
|
<span style="color: #408080; font-style: italic"># Slice the analytical results</span>
|
|
res_analytical1 <span style="color: #666666">=</span> res_analytical[:,indx1]
|
|
res_analytical2 <span style="color: #666666">=</span> res_analytical[:,indx2]
|
|
res_analytical3 <span style="color: #666666">=</span> res_analytical[:,indx3]
|
|
|
|
<span style="color: #408080; font-style: italic"># Plot the slices</span>
|
|
plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">10</span>,<span style="color: #666666">10</span>))
|
|
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">"Computed solutions at time = </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">"</span><span style="color: #666666">%</span>t1)
|
|
plt<span style="color: #666666">.</span>plot(x, res1)
|
|
plt<span style="color: #666666">.</span>plot(x,res_analytical1)
|
|
plt<span style="color: #666666">.</span>legend([<span style="color: #BA2121">'dnn'</span>,<span style="color: #BA2121">'analytical'</span>])
|
|
|
|
plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">10</span>,<span style="color: #666666">10</span>))
|
|
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">"Computed solutions at time = </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">"</span><span style="color: #666666">%</span>t2)
|
|
plt<span style="color: #666666">.</span>plot(x, res2)
|
|
plt<span style="color: #666666">.</span>plot(x,res_analytical2)
|
|
plt<span style="color: #666666">.</span>legend([<span style="color: #BA2121">'dnn'</span>,<span style="color: #BA2121">'analytical'</span>])
|
|
|
|
plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">10</span>,<span style="color: #666666">10</span>))
|
|
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">"Computed solutions at time = </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">"</span><span style="color: #666666">%</span>t3)
|
|
plt<span style="color: #666666">.</span>plot(x, res3)
|
|
plt<span style="color: #666666">.</span>plot(x,res_analytical3)
|
|
plt<span style="color: #666666">.</span>legend([<span style="color: #BA2121">'dnn'</span>,<span style="color: #BA2121">'analytical'</span>])
|
|
|
|
plt<span style="color: #666666">.</span>show()
|
|
</pre></div>
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec49">Resources on differential equations and deep learning </h2>
|
|
|
|
<ol>
|
|
<li> <a href="https://pdfs.semanticscholar.org/d061/df393e0e8fbfd0ea24976458b7d42419040d.pdf" target="_blank">Artificial neural networks for solving ordinary and partial differential equations by I.E. Lagaris et al</a></li>
|
|
<li> <a href="https://becominghuman.ai/neural-networks-for-solving-differential-equations-fa230ac5e04c" target="_blank">Neural networks for solving differential equations by A. Honchar</a></li>
|
|
<li> <a href="http://cs229.stanford.edu/proj2013/ChiaramonteKiener-SolvingDifferentialEquationsUsingNeuralNetworks.pdf" target="_blank">Solving differential equations using neural networks by M.M Chiaramonte and M. Kiener</a></li>
|
|
<li> <a href="https://www.springer.com/us/book/9783540225515" target="_blank">Introduction to Partial Differential Equations by A. Tveito, R. Winther</a></li>
|
|
</ol>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec50">Friday, Principal Component Analysis </h2>
|
|
|
|
<p>
|
|
<a href="https://www.youtube.com/watch?v=fkf4IBRSeEc&ab_channel=SteveBrunton" target="_blank">Overview video</a>
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec51">Basic ideas of the Principal Component Analysis (PCA) </h2>
|
|
|
|
<p>
|
|
The principal component analysis deals with the problem of fitting a
|
|
low-dimensional affine subspace \( S \) of dimension \( d \) much smaller than
|
|
the total dimension \( D \) of the problem at hand (our data
|
|
set). Mathematically it can be formulated as a statistical problem or
|
|
a geometric problem. In our discussion of the theorem for the
|
|
classical PCA, we will stay with a statistical approach.
|
|
Historically, the PCA was first formulated in a statistical setting in order to estimate the principal component of a multivariate random variable.
|
|
|
|
<p>
|
|
We have a data set defined by a design/feature matrix \( \boldsymbol{X} \) (see below for its definition)
|
|
|
|
<ul>
|
|
<li> Each data point is determined by \( p \) extrinsic (measurement) variables</li>
|
|
<li> We may want to ask the following question: Are there fewer intrinsic variables (say \( d < < p \)) that still approximately describe the data?</li>
|
|
<li> If so, these intrinsic variables may tell us something important and finding these intrinsic variables is what dimension reduction methods do.</li>
|
|
</ul>
|
|
|
|
A good read is for example <a href="https://www.springer.com/gp/book/9780387878102" target="_blank">Vidal, Ma and Sastry</a>.
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec52">Introducing the Covariance and Correlation functions </h2>
|
|
|
|
<p>
|
|
Before we discuss the PCA theorem, we need to remind ourselves about
|
|
the definition of the covariance and the correlation function. These are quantities
|
|
|
|
<p>
|
|
Suppose we have defined two vectors
|
|
\( \hat{x} \) and \( \hat{y} \) with \( n \) elements each. The covariance matrix \( \boldsymbol{C} \) is defined as
|
|
$$
|
|
\boldsymbol{C}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} \mathrm{cov}[\boldsymbol{x},\boldsymbol{x}] & \mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] \\
|
|
\mathrm{cov}[\boldsymbol{y},\boldsymbol{x}] & \mathrm{cov}[\boldsymbol{y},\boldsymbol{y}] \\
|
|
\end{bmatrix},
|
|
$$
|
|
|
|
where for example
|
|
$$
|
|
\mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] =\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})(y_i- \overline{y}).
|
|
$$
|
|
|
|
With this definition and recalling that the variance is defined as
|
|
$$
|
|
\mathrm{var}[\boldsymbol{x}]=\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})^2,
|
|
$$
|
|
|
|
we can rewrite the covariance matrix as
|
|
$$
|
|
\boldsymbol{C}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} \mathrm{var}[\boldsymbol{x}] & \mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] \\
|
|
\mathrm{cov}[\boldsymbol{x},\boldsymbol{y}] & \mathrm{var}[\boldsymbol{y}] \\
|
|
\end{bmatrix}.
|
|
$$
|
|
|
|
<p>
|
|
The covariance takes values between zero and infinity and may thus
|
|
lead to problems with loss of numerical precision for particularly
|
|
large values. It is common to scale the covariance matrix by
|
|
introducing instead the correlation matrix defined via the so-called
|
|
correlation function
|
|
|
|
$$
|
|
\mathrm{corr}[\boldsymbol{x},\boldsymbol{y}]=\frac{\mathrm{cov}[\boldsymbol{x},\boldsymbol{y}]}{\sqrt{\mathrm{var}[\boldsymbol{x}] \mathrm{var}[\boldsymbol{y}]}}.
|
|
$$
|
|
|
|
<p>
|
|
The correlation function is then given by values \( \mathrm{corr}[\boldsymbol{x},\boldsymbol{y}]
|
|
\in [-1,1] \). This avoids eventual problems with too large values. We
|
|
can then define the correlation matrix for the two vectors \( \boldsymbol{x} \)
|
|
and \( \boldsymbol{y} \) as
|
|
|
|
$$
|
|
\boldsymbol{K}[\boldsymbol{x},\boldsymbol{y}] = \begin{bmatrix} 1 & \mathrm{corr}[\boldsymbol{x},\boldsymbol{y}] \\
|
|
\mathrm{corr}[\boldsymbol{y},\boldsymbol{x}] & 1 \\
|
|
\end{bmatrix},
|
|
$$
|
|
|
|
<p>
|
|
In the above example this is the function we constructed using <b>pandas</b>.
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec53">Correlation Function and Design/Feature Matrix </h2>
|
|
|
|
<p>
|
|
In our derivation of the various regression algorithms like <b>Ordinary Least Squares</b> or <b>Ridge regression</b>
|
|
we defined the design/feature matrix \( \boldsymbol{X} \) as
|
|
|
|
$$
|
|
\boldsymbol{X}=\begin{bmatrix}
|
|
x_{0,0} & x_{0,1} & x_{0,2}& \dots & \dots x_{0,p-1}\\
|
|
x_{1,0} & x_{1,1} & x_{1,2}& \dots & \dots x_{1,p-1}\\
|
|
x_{2,0} & x_{2,1} & x_{2,2}& \dots & \dots x_{2,p-1}\\
|
|
\dots & \dots & \dots & \dots \dots & \dots \\
|
|
x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \dots & \dots x_{n-2,p-1}\\
|
|
x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \dots & \dots x_{n-1,p-1}\\
|
|
\end{bmatrix},
|
|
$$
|
|
|
|
with \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \), with the predictors/features \( p \) refering to the column numbers and the
|
|
entries \( n \) being the row elements.
|
|
We can rewrite the design/feature matrix in terms of its column vectors as
|
|
$$
|
|
\boldsymbol{X}=\begin{bmatrix} \boldsymbol{x}_0 & \boldsymbol{x}_1 & \boldsymbol{x}_2 & \dots & \dots & \boldsymbol{x}_{p-1}\end{bmatrix},
|
|
$$
|
|
|
|
with a given vector
|
|
$$
|
|
\boldsymbol{x}_i^T = \begin{bmatrix}x_{0,i} & x_{1,i} & x_{2,i}& \dots & \dots x_{n-1,i}\end{bmatrix}.
|
|
$$
|
|
|
|
<p>
|
|
With these definitions, we can now rewrite our \( 2\times 2 \)
|
|
correaltion/covariance matrix in terms of a moe general design/feature
|
|
matrix \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \). This leads to a \( p\times p \)
|
|
covariance matrix for the vectors \( \boldsymbol{x}_i \) with \( i=0,1,\dots,p-1 \)
|
|
|
|
$$
|
|
\boldsymbol{C}[\boldsymbol{x}] = \begin{bmatrix}
|
|
\mathrm{var}[\boldsymbol{x}_0] & \mathrm{cov}[\boldsymbol{x}_0,\boldsymbol{x}_1] & \mathrm{cov}[\boldsymbol{x}_0,\boldsymbol{x}_2] & \dots & \dots & \mathrm{cov}[\boldsymbol{x}_0,\boldsymbol{x}_{p-1}]\\
|
|
\mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_0] & \mathrm{var}[\boldsymbol{x}_1] & \mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_2] & \dots & \dots & \mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_{p-1}]\\
|
|
\mathrm{cov}[\boldsymbol{x}_2,\boldsymbol{x}_0] & \mathrm{cov}[\boldsymbol{x}_2,\boldsymbol{x}_1] & \mathrm{var}[\boldsymbol{x}_2] & \dots & \dots & \mathrm{cov}[\boldsymbol{x}_2,\boldsymbol{x}_{p-1}]\\
|
|
\dots & \dots & \dots & \dots & \dots & \dots \\
|
|
\dots & \dots & \dots & \dots & \dots & \dots \\
|
|
\mathrm{cov}[\boldsymbol{x}_{p-1},\boldsymbol{x}_0] & \mathrm{cov}[\boldsymbol{x}_{p-1},\boldsymbol{x}_1] & \mathrm{cov}[\boldsymbol{x}_{p-1},\boldsymbol{x}_{2}] & \dots & \dots & \mathrm{var}[\boldsymbol{x}_{p-1}]\\
|
|
\end{bmatrix},
|
|
$$
|
|
|
|
and the correlation matrix
|
|
$$
|
|
\boldsymbol{K}[\boldsymbol{x}] = \begin{bmatrix}
|
|
1 & \mathrm{corr}[\boldsymbol{x}_0,\boldsymbol{x}_1] & \mathrm{corr}[\boldsymbol{x}_0,\boldsymbol{x}_2] & \dots & \dots & \mathrm{corr}[\boldsymbol{x}_0,\boldsymbol{x}_{p-1}]\\
|
|
\mathrm{corr}[\boldsymbol{x}_1,\boldsymbol{x}_0] & 1 & \mathrm{corr}[\boldsymbol{x}_1,\boldsymbol{x}_2] & \dots & \dots & \mathrm{corr}[\boldsymbol{x}_1,\boldsymbol{x}_{p-1}]\\
|
|
\mathrm{corr}[\boldsymbol{x}_2,\boldsymbol{x}_0] & \mathrm{corr}[\boldsymbol{x}_2,\boldsymbol{x}_1] & 1 & \dots & \dots & \mathrm{corr}[\boldsymbol{x}_2,\boldsymbol{x}_{p-1}]\\
|
|
\dots & \dots & \dots & \dots & \dots & \dots \\
|
|
\dots & \dots & \dots & \dots & \dots & \dots \\
|
|
\mathrm{corr}[\boldsymbol{x}_{p-1},\boldsymbol{x}_0] & \mathrm{corr}[\boldsymbol{x}_{p-1},\boldsymbol{x}_1] & \mathrm{corr}[\boldsymbol{x}_{p-1},\boldsymbol{x}_{2}] & \dots & \dots & 1\\
|
|
\end{bmatrix},
|
|
$$
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec54">Covariance Matrix Examples </h2>
|
|
|
|
<p>
|
|
The Numpy function <b>np.cov</b> calculates the covariance elements using
|
|
the factor \( 1/(n-1) \) instead of \( 1/n \) since it assumes we do not have
|
|
the exact mean values. The following simple function uses the
|
|
<b>np.vstack</b> function which takes each vector of dimension \( 1\times n \)
|
|
and produces a \( 2\times n \) matrix \( \boldsymbol{W} \)
|
|
|
|
$$
|
|
\boldsymbol{W} = \begin{bmatrix} x_0 & y_0 \\
|
|
x_1 & y_1 \\
|
|
x_2 & y_2\\
|
|
\dots & \dots \\
|
|
x_{n-2} & y_{n-2}\\
|
|
x_{n-1} & y_{n-1} &
|
|
\end{bmatrix},
|
|
$$
|
|
|
|
<p>
|
|
which in turn is converted into into the \( 2\times 2 \) covariance matrix
|
|
\( \boldsymbol{C} \) via the Numpy function <b>np.cov()</b>. We note that we can also calculate
|
|
the mean value of each set of samples \( \boldsymbol{x} \) etc using the Numpy
|
|
function <b>np.mean(x)</b>. We can also extract the eigenvalues of the
|
|
covariance matrix through the <b>np.linalg.eig()</b> function.
|
|
|
|
<p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span><span style="color: #408080; font-style: italic"># Importing various packages</span>
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
|
|
n <span style="color: #666666">=</span> <span style="color: #666666">100</span>
|
|
x <span style="color: #666666">=</span> np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>normal(size<span style="color: #666666">=</span>n)
|
|
<span style="color: #008000">print</span>(np<span style="color: #666666">.</span>mean(x))
|
|
y <span style="color: #666666">=</span> <span style="color: #666666">4+3*</span>x<span style="color: #666666">+</span>np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>normal(size<span style="color: #666666">=</span>n)
|
|
<span style="color: #008000">print</span>(np<span style="color: #666666">.</span>mean(y))
|
|
W <span style="color: #666666">=</span> np<span style="color: #666666">.</span>vstack((x, y))
|
|
C <span style="color: #666666">=</span> np<span style="color: #666666">.</span>cov(W)
|
|
<span style="color: #008000">print</span>(C)
|
|
</pre></div>
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec55">Correlation Matrix </h2>
|
|
|
|
<p>
|
|
The previous example can be converted into the correlation matrix by
|
|
simply scaling the matrix elements with the variances. We should also
|
|
subtract the mean values for each column. This leads to the following
|
|
code which sets up the correlations matrix for the previous example in
|
|
a more brute force way. Here we scale the mean values for each column of the design matrix, calculate the relevant mean values and variances and then finally set up the \( 2\times 2 \) correlation matrix (since we have only two vectors).
|
|
|
|
<p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
|
|
n <span style="color: #666666">=</span> <span style="color: #666666">100</span>
|
|
<span style="color: #408080; font-style: italic"># define two vectors </span>
|
|
x <span style="color: #666666">=</span> np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>random(size<span style="color: #666666">=</span>n)
|
|
y <span style="color: #666666">=</span> <span style="color: #666666">4+3*</span>x<span style="color: #666666">+</span>np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>normal(size<span style="color: #666666">=</span>n)
|
|
<span style="color: #408080; font-style: italic">#scaling the x and y vectors </span>
|
|
x <span style="color: #666666">=</span> x <span style="color: #666666">-</span> np<span style="color: #666666">.</span>mean(x)
|
|
y <span style="color: #666666">=</span> y <span style="color: #666666">-</span> np<span style="color: #666666">.</span>mean(y)
|
|
variance_x <span style="color: #666666">=</span> np<span style="color: #666666">.</span>sum(x<span style="color: #AA22FF">@x</span>)<span style="color: #666666">/</span>n
|
|
variance_y <span style="color: #666666">=</span> np<span style="color: #666666">.</span>sum(y<span style="color: #AA22FF">@y</span>)<span style="color: #666666">/</span>n
|
|
<span style="color: #008000">print</span>(variance_x)
|
|
<span style="color: #008000">print</span>(variance_y)
|
|
cov_xy <span style="color: #666666">=</span> np<span style="color: #666666">.</span>sum(x<span style="color: #AA22FF">@y</span>)<span style="color: #666666">/</span>n
|
|
cov_xx <span style="color: #666666">=</span> np<span style="color: #666666">.</span>sum(x<span style="color: #AA22FF">@x</span>)<span style="color: #666666">/</span>n
|
|
cov_yy <span style="color: #666666">=</span> np<span style="color: #666666">.</span>sum(y<span style="color: #AA22FF">@y</span>)<span style="color: #666666">/</span>n
|
|
C <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros((<span style="color: #666666">2</span>,<span style="color: #666666">2</span>))
|
|
C[<span style="color: #666666">0</span>,<span style="color: #666666">0</span>]<span style="color: #666666">=</span> cov_xx<span style="color: #666666">/</span>variance_x
|
|
C[<span style="color: #666666">1</span>,<span style="color: #666666">1</span>]<span style="color: #666666">=</span> cov_yy<span style="color: #666666">/</span>variance_y
|
|
C[<span style="color: #666666">0</span>,<span style="color: #666666">1</span>]<span style="color: #666666">=</span> cov_xy<span style="color: #666666">/</span>np<span style="color: #666666">.</span>sqrt(variance_y<span style="color: #666666">*</span>variance_x)
|
|
C[<span style="color: #666666">1</span>,<span style="color: #666666">0</span>]<span style="color: #666666">=</span> C[<span style="color: #666666">0</span>,<span style="color: #666666">1</span>]
|
|
<span style="color: #008000">print</span>(C)
|
|
</pre></div>
|
|
<p>
|
|
We see that the matrix elements along the diagonal are one as they
|
|
should be and that the matrix is symmetric. Furthermore, diagonalizing
|
|
this matrix we easily see that it is a positive definite matrix.
|
|
|
|
<p>
|
|
The above procedure with <b>numpy</b> can be made more compact if we use <b>pandas</b>.
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec56">Correlation Matrix with Pandas </h2>
|
|
|
|
<p>
|
|
We whow here how we can set up the correlation matrix using <b>pandas</b>, as done in this simple code
|
|
<p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">pandas</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">pd</span>
|
|
n <span style="color: #666666">=</span> <span style="color: #666666">10</span>
|
|
x <span style="color: #666666">=</span> np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>normal(size<span style="color: #666666">=</span>n)
|
|
x <span style="color: #666666">=</span> x <span style="color: #666666">-</span> np<span style="color: #666666">.</span>mean(x)
|
|
y <span style="color: #666666">=</span> <span style="color: #666666">4+3*</span>x<span style="color: #666666">+</span>np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>normal(size<span style="color: #666666">=</span>n)
|
|
y <span style="color: #666666">=</span> y <span style="color: #666666">-</span> np<span style="color: #666666">.</span>mean(y)
|
|
X <span style="color: #666666">=</span> (np<span style="color: #666666">.</span>vstack((x, y)))<span style="color: #666666">.</span>T
|
|
<span style="color: #008000">print</span>(X)
|
|
Xpd <span style="color: #666666">=</span> pd<span style="color: #666666">.</span>DataFrame(X)
|
|
<span style="color: #008000">print</span>(Xpd)
|
|
correlation_matrix <span style="color: #666666">=</span> Xpd<span style="color: #666666">.</span>corr()
|
|
<span style="color: #008000">print</span>(correlation_matrix)
|
|
</pre></div>
|
|
<p>
|
|
We expand this model to the Franke function discussed above.
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec57">Correlation Matrix with Pandas and the Franke function </h2>
|
|
|
|
<p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span><span style="color: #408080; font-style: italic"># Common imports</span>
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">pandas</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">pd</span>
|
|
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">FrankeFunction</span>(x,y):
|
|
term1 <span style="color: #666666">=</span> <span style="color: #666666">0.75*</span>np<span style="color: #666666">.</span>exp(<span style="color: #666666">-</span>(<span style="color: #666666">0.25*</span>(<span style="color: #666666">9*</span>x<span style="color: #666666">-2</span>)<span style="color: #666666">**2</span>) <span style="color: #666666">-</span> <span style="color: #666666">0.25*</span>((<span style="color: #666666">9*</span>y<span style="color: #666666">-2</span>)<span style="color: #666666">**2</span>))
|
|
term2 <span style="color: #666666">=</span> <span style="color: #666666">0.75*</span>np<span style="color: #666666">.</span>exp(<span style="color: #666666">-</span>((<span style="color: #666666">9*</span>x<span style="color: #666666">+1</span>)<span style="color: #666666">**2</span>)<span style="color: #666666">/49.0</span> <span style="color: #666666">-</span> <span style="color: #666666">0.1*</span>(<span style="color: #666666">9*</span>y<span style="color: #666666">+1</span>))
|
|
term3 <span style="color: #666666">=</span> <span style="color: #666666">0.5*</span>np<span style="color: #666666">.</span>exp(<span style="color: #666666">-</span>(<span style="color: #666666">9*</span>x<span style="color: #666666">-7</span>)<span style="color: #666666">**2/4.0</span> <span style="color: #666666">-</span> <span style="color: #666666">0.25*</span>((<span style="color: #666666">9*</span>y<span style="color: #666666">-3</span>)<span style="color: #666666">**2</span>))
|
|
term4 <span style="color: #666666">=</span> <span style="color: #666666">-0.2*</span>np<span style="color: #666666">.</span>exp(<span style="color: #666666">-</span>(<span style="color: #666666">9*</span>x<span style="color: #666666">-4</span>)<span style="color: #666666">**2</span> <span style="color: #666666">-</span> (<span style="color: #666666">9*</span>y<span style="color: #666666">-7</span>)<span style="color: #666666">**2</span>)
|
|
<span style="color: #008000; font-weight: bold">return</span> term1 <span style="color: #666666">+</span> term2 <span style="color: #666666">+</span> term3 <span style="color: #666666">+</span> term4
|
|
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">create_X</span>(x, y, n ):
|
|
<span style="color: #008000; font-weight: bold">if</span> <span style="color: #008000">len</span>(x<span style="color: #666666">.</span>shape) <span style="color: #666666">></span> <span style="color: #666666">1</span>:
|
|
x <span style="color: #666666">=</span> np<span style="color: #666666">.</span>ravel(x)
|
|
y <span style="color: #666666">=</span> np<span style="color: #666666">.</span>ravel(y)
|
|
|
|
N <span style="color: #666666">=</span> <span style="color: #008000">len</span>(x)
|
|
l <span style="color: #666666">=</span> <span style="color: #008000">int</span>((n<span style="color: #666666">+1</span>)<span style="color: #666666">*</span>(n<span style="color: #666666">+2</span>)<span style="color: #666666">/2</span>) <span style="color: #408080; font-style: italic"># Number of elements in beta</span>
|
|
X <span style="color: #666666">=</span> np<span style="color: #666666">.</span>ones((N,l))
|
|
|
|
<span style="color: #008000; font-weight: bold">for</span> i <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(<span style="color: #666666">1</span>,n<span style="color: #666666">+1</span>):
|
|
q <span style="color: #666666">=</span> <span style="color: #008000">int</span>((i)<span style="color: #666666">*</span>(i<span style="color: #666666">+1</span>)<span style="color: #666666">/2</span>)
|
|
<span style="color: #008000; font-weight: bold">for</span> k <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(i<span style="color: #666666">+1</span>):
|
|
X[:,q<span style="color: #666666">+</span>k] <span style="color: #666666">=</span> (x<span style="color: #666666">**</span>(i<span style="color: #666666">-</span>k))<span style="color: #666666">*</span>(y<span style="color: #666666">**</span>k)
|
|
|
|
<span style="color: #008000; font-weight: bold">return</span> X
|
|
|
|
|
|
<span style="color: #408080; font-style: italic"># Making meshgrid of datapoints and compute Franke's function</span>
|
|
n <span style="color: #666666">=</span> <span style="color: #666666">4</span>
|
|
N <span style="color: #666666">=</span> <span style="color: #666666">100</span>
|
|
x <span style="color: #666666">=</span> np<span style="color: #666666">.</span>sort(np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>uniform(<span style="color: #666666">0</span>, <span style="color: #666666">1</span>, N))
|
|
y <span style="color: #666666">=</span> np<span style="color: #666666">.</span>sort(np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>uniform(<span style="color: #666666">0</span>, <span style="color: #666666">1</span>, N))
|
|
z <span style="color: #666666">=</span> FrankeFunction(x, y)
|
|
X <span style="color: #666666">=</span> create_X(x, y, n<span style="color: #666666">=</span>n)
|
|
|
|
Xpd <span style="color: #666666">=</span> pd<span style="color: #666666">.</span>DataFrame(X)
|
|
<span style="color: #408080; font-style: italic"># subtract the mean values and set up the covariance matrix</span>
|
|
Xpd <span style="color: #666666">=</span> Xpd <span style="color: #666666">-</span> Xpd<span style="color: #666666">.</span>mean()
|
|
covariance_matrix <span style="color: #666666">=</span> Xpd<span style="color: #666666">.</span>cov()
|
|
<span style="color: #008000">print</span>(covariance_matrix)
|
|
</pre></div>
|
|
<p>
|
|
We note here that the covariance is zero for the first rows and
|
|
columns since all matrix elements in the design matrix were set to one
|
|
(we are fitting the function in terms of a polynomial of degree \( n \)). We would however not include the intercept
|
|
and wee can simply
|
|
drop these elements and construct a correlation
|
|
matrix without them.
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec58">Rewriting the Covariance and/or Correlation Matrix </h2>
|
|
|
|
<p>
|
|
We can rewrite the covariance matrix in a more compact form in terms of the design/feature matrix \( \boldsymbol{X} \) as
|
|
$$
|
|
\boldsymbol{C}[\boldsymbol{x}] = \frac{1}{n}\boldsymbol{X}^T\boldsymbol{X}= \mathbb{E}[\boldsymbol{X}^T\boldsymbol{X}].
|
|
$$
|
|
|
|
<p>
|
|
To see this let us simply look at a design matrix \( \boldsymbol{X}\in {\mathbb{R}}^{2\times 2} \)
|
|
$$
|
|
\boldsymbol{X}=\begin{bmatrix}
|
|
x_{00} & x_{01}\\
|
|
x_{10} & x_{11}\\
|
|
\end{bmatrix}=\begin{bmatrix}
|
|
\boldsymbol{x}_{0} & \boldsymbol{x}_{1}\\
|
|
\end{bmatrix}.
|
|
$$
|
|
|
|
<p>
|
|
If we then compute the expectation value
|
|
$$
|
|
\mathbb{E}[\boldsymbol{X}^T\boldsymbol{X}] = \frac{1}{n}\boldsymbol{X}^T\boldsymbol{X}=\begin{bmatrix}
|
|
x_{00}^2+x_{01}^2 & x_{00}x_{10}+x_{01}x_{11}\\
|
|
x_{10}x_{00}+x_{11}x_{01} & x_{10}^2+x_{11}^2\\
|
|
\end{bmatrix},
|
|
$$
|
|
|
|
which is just
|
|
$$
|
|
\boldsymbol{C}[\boldsymbol{x}_0,\boldsymbol{x}_1] = \boldsymbol{C}[\boldsymbol{x}]=\begin{bmatrix} \mathrm{var}[\boldsymbol{x}_0] & \mathrm{cov}[\boldsymbol{x}_0,\boldsymbol{x}_1] \\
|
|
\mathrm{cov}[\boldsymbol{x}_1,\boldsymbol{x}_0] & \mathrm{var}[\boldsymbol{x}_1] \\
|
|
\end{bmatrix},
|
|
$$
|
|
|
|
where we wrote $$\boldsymbol{C}[\boldsymbol{x}_0,\boldsymbol{x}_1] = \boldsymbol{C}[\boldsymbol{x}]$$ to indicate that this the covariance of the vectors \( \boldsymbol{x} \) of the design/feature matrix \( \boldsymbol{X} \).
|
|
|
|
<p>
|
|
It is easy to generalize this to a matrix \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \).
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec59">Towards the PCA theorem </h2>
|
|
|
|
<p>
|
|
We have that the covariance matrix (the correlation matrix involves a simple rescaling) is given as
|
|
$$
|
|
\boldsymbol{C}[\boldsymbol{x}] = \frac{1}{n}\boldsymbol{X}^T\boldsymbol{X}= \mathbb{E}[\boldsymbol{X}^T\boldsymbol{X}].
|
|
$$
|
|
|
|
Let us now assume that we can perform a series of orthogonal transformations where we employ some orthogonal matrices \( \boldsymbol{S} \).
|
|
These matrices are defined as \( \boldsymbol{S}\in {\mathbb{R}}^{p\times p} \) and obey the orthogonality requirements \( \boldsymbol{S}\boldsymbol{S}^T=\boldsymbol{S}^T\boldsymbol{S}=\boldsymbol{I} \). The matrix can be written out in terms of the column vectors \( \boldsymbol{s}_i \) as \( \boldsymbol{S}=[\boldsymbol{s}_0,\boldsymbol{s}_1,\dots,\boldsymbol{s}_{p-1}] \) and \( \boldsymbol{s}_i \in {\mathbb{R}}^{p} \).
|
|
|
|
<p>
|
|
Assume also that there is a transformation \( \boldsymbol{S}^T\boldsymbol{C}[\boldsymbol{x}]\boldsymbol{S}=\boldsymbol{C}[\boldsymbol{y}] \) such that the new matrix \( \boldsymbol{C}[\boldsymbol{y}] \) is diagonal with elements \( [\lambda_0,\lambda_1,\lambda_2,\dots,\lambda_{p-1}] \).
|
|
|
|
<p>
|
|
That is we have
|
|
$$
|
|
\boldsymbol{C}[\boldsymbol{y}] = \mathbb{E}[\boldsymbol{S}^T\boldsymbol{X}^T\boldsymbol{X}T\boldsymbol{S}]=\boldsymbol{S}^T\boldsymbol{C}[\boldsymbol{x}]\boldsymbol{S},
|
|
$$
|
|
|
|
since the matrix \( \boldsymbol{S} \) is not a data dependent matrix. Multiplying with \( \boldsymbol{S} \) from the left we have
|
|
$$
|
|
\boldsymbol{S}\boldsymbol{C}[\boldsymbol{y}] = \boldsymbol{C}[\boldsymbol{x}]\boldsymbol{S},
|
|
$$
|
|
|
|
and since \( \boldsymbol{C}[\boldsymbol{y}] \) is diagonal we have for a given eigenvalue \( i \) of the covariance matrix that
|
|
|
|
$$
|
|
\boldsymbol{S}_i\lambda_i = \boldsymbol{C}[\boldsymbol{x}]\boldsymbol{S}_i.
|
|
$$
|
|
|
|
<p>
|
|
In the derivation of the PCA theorem we will assume that the eigenvalues are ordered in descending order, that is
|
|
\( \lambda_0 > \lambda_1 > \dots > \lambda_{p-1} \).
|
|
|
|
<p>
|
|
The eigenvalues tell us then how much we need to stretch the
|
|
corresponding eigenvectors. Dimensions with large eigenvalues have
|
|
thus large variations (large variance) and define therefore useful
|
|
dimensions. The data points are more spread out in the direction of
|
|
these eigenvectors. Smaller eigenvalues mean on the other hand that
|
|
the corresponding eigenvectors are shrunk accordingly and the data
|
|
points are tightly bunched together and there is not much variation in
|
|
these specific directions. Hopefully then we could leave it out
|
|
dimensions where the eigenvalues are very small. If \( p \) is very large,
|
|
we could then aim at reducing \( p \) to \( l < < p \) and handle only \( l \)
|
|
features/predictors.
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec60">The Algorithm before theorem </h2>
|
|
|
|
<p>
|
|
Here's how we would proceed in setting up the algorithm for the PCA, see also discussion below here.
|
|
|
|
<ul>
|
|
<li> Set up the datapoints for the design/feature matrix \( \boldsymbol{X} \) with \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \), with the predictors/features \( p \) referring to the column numbers and the entries \( n \) being the row elements.</li>
|
|
</ul>
|
|
|
|
$$
|
|
\boldsymbol{X}=\begin{bmatrix}
|
|
x_{0,0} & x_{0,1} & x_{0,2}& \dots & \dots x_{0,p-1}\\
|
|
x_{1,0} & x_{1,1} & x_{1,2}& \dots & \dots x_{1,p-1}\\
|
|
x_{2,0} & x_{2,1} & x_{2,2}& \dots & \dots x_{2,p-1}\\
|
|
\dots & \dots & \dots & \dots \dots & \dots \\
|
|
x_{n-2,0} & x_{n-2,1} & x_{n-2,2}& \dots & \dots x_{n-2,p-1}\\
|
|
x_{n-1,0} & x_{n-1,1} & x_{n-1,2}& \dots & \dots x_{n-1,p-1}\\
|
|
\end{bmatrix},
|
|
$$
|
|
|
|
|
|
<ul>
|
|
<li> Center the data by subtracting the mean value for each column. This leads to a new matrix \( \boldsymbol{X}\rightarrow \overline{\boldsymbol{X}} \).</li>
|
|
<li> Compute then the covariance/correlation matrix \( \mathbb{E}[\overline{\boldsymbol{X}}^T\overline{\boldsymbol{X}}] \).</li>
|
|
<li> Find the eigenpairs of \( \boldsymbol{C} \) with eigenvalues \( [\lambda_0,\lambda_1,\dots,\lambda_{p-1}] \) and eigenvectors \( [\boldsymbol{s}_0,\boldsymbol{s}_1,\dots,\boldsymbol{s}_{p-1}] \).</li>
|
|
<li> Order the eigenvalue (and the eigenvectors accordingly) in order of decreasing eigenvalues.</li>
|
|
<li> Keep only those \( l \) eigenvalues larger than a selected threshold value, discarding thus \( p-l \) features since we expect small variations in the data here.</li>
|
|
</ul>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec61">Writing our own PCA code </h2>
|
|
|
|
<p>
|
|
We will use a simple example first with two-dimensional data
|
|
drawn from a multivariate normal distribution with the following mean and covariance matrix (we have fixed these quantities but will play around with them below):
|
|
$$
|
|
\mu = (-1,2) \qquad \Sigma = \begin{bmatrix} 4 & 2 \\
|
|
2 & 2
|
|
\end{bmatrix}
|
|
$$
|
|
|
|
Note that the mean refers to each column of data.
|
|
We will generate \( n = 10000 \) points \( X = \{ x_1, \ldots, x_N \} \) from
|
|
this distribution, and store them in the \( 1000 \times 2 \) matrix \( \boldsymbol{X} \). This is our design matrix where we have forced the covariance and mean values to take specific values.
|
|
|
|
<p>
|
|
The following Python code aids in setting up the data and writing out the design matrix.
|
|
Note that the function <b>multivariate</b> returns also the covariance discussed above and that it is defined by dividing by \( n-1 \) instead of \( n \).
|
|
<p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">pandas</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">pd</span>
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">matplotlib.pyplot</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">plt</span>
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">IPython.display</span> <span style="color: #008000; font-weight: bold">import</span> display
|
|
n <span style="color: #666666">=</span> <span style="color: #666666">10000</span>
|
|
mean <span style="color: #666666">=</span> (<span style="color: #666666">-1</span>, <span style="color: #666666">2</span>)
|
|
cov <span style="color: #666666">=</span> [[<span style="color: #666666">4</span>, <span style="color: #666666">2</span>], [<span style="color: #666666">2</span>, <span style="color: #666666">2</span>]]
|
|
X <span style="color: #666666">=</span> np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>multivariate_normal(mean, cov, n)
|
|
</pre></div>
|
|
<p>
|
|
Now we are going to implement the PCA algorithm. We will break it down into various substeps.
|
|
|
|
<h3 id="___sec62">Compute the sample mean and center the data </h3>
|
|
|
|
<p>
|
|
The first step of PCA is to compute the sample mean of the data and use it to center the data. Recall that the sample mean is
|
|
$$
|
|
\mu_n = \frac{1}{n} \sum_{i=1}^n x_i
|
|
$$
|
|
|
|
and the mean-centered data \( \bar{X} = \{ \bar{x}_1, \ldots, \bar{x}_n \} \) takes the form
|
|
$$
|
|
\bar{x}_i = x_i - \mu_n.
|
|
$$
|
|
|
|
When you are done with these steps, print out \( \mu_n \) to verify it is
|
|
close to \( \mu \) and plot your mean centered data to verify it is
|
|
centered at the origin!
|
|
The following code elements perform these operations using <b>pandas</b> or using our own functionality for doing so. The latter, using <b>numpy</b> is rather simple through the <b>mean()</b> function.
|
|
<p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span>df <span style="color: #666666">=</span> pd<span style="color: #666666">.</span>DataFrame(X)
|
|
<span style="color: #408080; font-style: italic"># Pandas does the centering for us</span>
|
|
df <span style="color: #666666">=</span> df <span style="color: #666666">-</span>df<span style="color: #666666">.</span>mean()
|
|
<span style="color: #408080; font-style: italic"># we center it ourselves</span>
|
|
X_centered <span style="color: #666666">=</span> X <span style="color: #666666">-</span> X<span style="color: #666666">.</span>mean(axis<span style="color: #666666">=0</span>)
|
|
</pre></div>
|
|
<p>
|
|
Alternatively, we could use the functions we discussed
|
|
earlier for scaling the data set. That is, we could have used the
|
|
<b>StandardScaler</b> function in <b>Scikit-Learn</b>, a function which ensures
|
|
that for each feature/predictor we study the mean value is zero and
|
|
the variance is one (every column in the design/feature matrix). You
|
|
would then not get the same results, since we divide by the
|
|
variance. The diagonal covariance matrix elements will then be one,
|
|
while the non-diagonal ones need to be divided by \( 2\sqrt{2} \) for our
|
|
specific case.
|
|
|
|
<h3 id="___sec63">Compute the sample covariance </h3>
|
|
|
|
<p>
|
|
Now we are going to use the mean centered data to compute the sample covariance of the data by using the following equation
|
|
$$
|
|
\begin{equation*}
|
|
\Sigma_n = \frac{1}{n-1} \sum_{i=1}^n \bar{x}_i^T \bar{x}_i = \frac{1}{n-1} \sum_{i=1}^n (x_i - \mu_n)^T (x_i - \mu_n)
|
|
\end{equation*}
|
|
$$
|
|
|
|
where the data points \( x_i \in \mathbb{R}^p \) (here in this example \( p = 2 \)) are column vectors and \( x^T \) is the transpose of \( x \).
|
|
We can write our own code or simply use either the functionaly of <b>numpy</b> or that of <b>pandas</b>, as follows
|
|
<p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span><span style="color: #008000">print</span>(df<span style="color: #666666">.</span>cov())
|
|
<span style="color: #008000">print</span>(np<span style="color: #666666">.</span>cov(X_centered<span style="color: #666666">.</span>T))
|
|
</pre></div>
|
|
<p>
|
|
Note that the way we define the covariance matrix here has a factor \( n-1 \) instead of \( n \). This is included in the <b>cov()</b> function by <b>numpy</b> and <b>pandas</b>.
|
|
Our own code here is not very elegant and asks for obvious improvements. It is tailored to this specific \( 2\times 2 \) covariance matrix.
|
|
<p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span><span style="color: #408080; font-style: italic"># extract the relevant columns from the centered design matrix of dim n x 2</span>
|
|
x <span style="color: #666666">=</span> X_centered[:,<span style="color: #666666">0</span>]
|
|
y <span style="color: #666666">=</span> X_centered[:,<span style="color: #666666">1</span>]
|
|
Cov <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros((<span style="color: #666666">2</span>,<span style="color: #666666">2</span>))
|
|
Cov[<span style="color: #666666">0</span>,<span style="color: #666666">1</span>] <span style="color: #666666">=</span> np<span style="color: #666666">.</span>sum(x<span style="color: #666666">.</span>T<span style="color: #AA22FF">@y</span>)<span style="color: #666666">/</span>(n<span style="color: #666666">-1.0</span>)
|
|
Cov[<span style="color: #666666">0</span>,<span style="color: #666666">0</span>] <span style="color: #666666">=</span> np<span style="color: #666666">.</span>sum(x<span style="color: #666666">.</span>T<span style="color: #AA22FF">@x</span>)<span style="color: #666666">/</span>(n<span style="color: #666666">-1.0</span>)
|
|
Cov[<span style="color: #666666">1</span>,<span style="color: #666666">1</span>] <span style="color: #666666">=</span> np<span style="color: #666666">.</span>sum(y<span style="color: #666666">.</span>T<span style="color: #AA22FF">@y</span>)<span style="color: #666666">/</span>(n<span style="color: #666666">-1.0</span>)
|
|
Cov[<span style="color: #666666">1</span>,<span style="color: #666666">0</span>]<span style="color: #666666">=</span> Cov[<span style="color: #666666">0</span>,<span style="color: #666666">1</span>]
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"Centered covariance using own code"</span>)
|
|
<span style="color: #008000">print</span>(Cov)
|
|
plt<span style="color: #666666">.</span>plot(x, y, <span style="color: #BA2121">'x'</span>)
|
|
plt<span style="color: #666666">.</span>axis(<span style="color: #BA2121">'equal'</span>)
|
|
plt<span style="color: #666666">.</span>show()
|
|
</pre></div>
|
|
<p>
|
|
Depending on the number of points \( n \), we will get results that are close to the covariance values defined above.
|
|
The plot shows how the data are clustered around a line with slope close to one. Is this expected? Try to change the covariance and the mean values. For example, try to make the variance of the first element much larger than that of the second diagonal element. Try also to shrink the covariance (the non-diagonal elements) and see how the data points are distributed.
|
|
|
|
<h3 id="___sec64">Diagonalize the sample covariance matrix to obtain the principal components </h3>
|
|
|
|
<p>
|
|
Now we are ready to solve for the principal components! To do so we
|
|
diagonalize the sample covariance matrix \( \Sigma \). We can use the
|
|
function <b>np.linalg.eig</b> to do so. It will return the eigenvalues and
|
|
eigenvectors of \( \Sigma \). Once we have these we can perform the
|
|
following tasks:
|
|
|
|
<ul>
|
|
<li> We compute the percentage of the total variance captured by the first principal component</li>
|
|
<li> We plot the mean centered data and lines along the first and second principal components</li>
|
|
<li> Then we project the mean centered data onto the first and second principal components, and plot the projected data.</li>
|
|
<li> Finally, we approximate the data as</li>
|
|
</ul>
|
|
|
|
$$
|
|
\begin{equation*}
|
|
x_i \approx \tilde{x}_i = \mu_n + \langle x_i, v_0 \rangle v_0
|
|
\end{equation*}
|
|
$$
|
|
|
|
where \( v_0 \) is the first principal component.
|
|
|
|
<p>
|
|
Collecting all these steps we can write our own PCA function and
|
|
compare this with the functionality included in <b>Scikit-Learn</b>.
|
|
|
|
<p>
|
|
The code here outlines some of the elements we could include in the
|
|
analysis. Feel free to extend upon this in order to address the above
|
|
questions.
|
|
|
|
<p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span><span style="color: #408080; font-style: italic"># diagonalize and obtain eigenvalues, not necessarily sorted</span>
|
|
EigValues, EigVectors <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linalg<span style="color: #666666">.</span>eig(Cov)
|
|
<span style="color: #408080; font-style: italic"># sort eigenvectors and eigenvalues</span>
|
|
<span style="color: #408080; font-style: italic">#permute = EigValues.argsort()</span>
|
|
<span style="color: #408080; font-style: italic">#EigValues = EigValues[permute]</span>
|
|
<span style="color: #408080; font-style: italic">#EigVectors = EigVectors[:,permute]</span>
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"Eigenvalues of Covariance matrix"</span>)
|
|
<span style="color: #008000; font-weight: bold">for</span> i <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(<span style="color: #666666">2</span>):
|
|
<span style="color: #008000">print</span>(EigValues[i])
|
|
FirstEigvector <span style="color: #666666">=</span> EigVectors[:,<span style="color: #666666">0</span>]
|
|
SecondEigvector <span style="color: #666666">=</span> EigVectors[:,<span style="color: #666666">1</span>]
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"First eigenvector"</span>)
|
|
<span style="color: #008000">print</span>(FirstEigvector)
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"Second eigenvector"</span>)
|
|
<span style="color: #008000">print</span>(SecondEigvector)
|
|
<span style="color: #408080; font-style: italic">#thereafter we do a PCA with Scikit-learn</span>
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.decomposition</span> <span style="color: #008000; font-weight: bold">import</span> PCA
|
|
pca <span style="color: #666666">=</span> PCA(n_components <span style="color: #666666">=</span> <span style="color: #666666">2</span>)
|
|
X2Dsl <span style="color: #666666">=</span> pca<span style="color: #666666">.</span>fit_transform(X)
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"Eigenvector of largest eigenvalue"</span>)
|
|
<span style="color: #008000">print</span>(pca<span style="color: #666666">.</span>components_<span style="color: #666666">.</span>T[:, <span style="color: #666666">0</span>])
|
|
</pre></div>
|
|
<p>
|
|
This code does not contain all the above elements, but it shows how we can use <b>Scikit-Learn</b> to extract the eigenvector which corresponds to the largest eigenvalue. Try to address the questions we pose before the above code. Try also to change the values of the covariance matrix by making one of the diagonal elements much larger than the other. What do you observe then?
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec65">Classical PCA Theorem </h2>
|
|
|
|
<p>
|
|
We assume now that we have a design matrix \( \boldsymbol{X} \) which has been
|
|
centered as discussed above. For the sake of simplicity we skip the
|
|
overline symbol. The matrix is defined in terms of the various column
|
|
vectors \( [\boldsymbol{x}_0,\boldsymbol{x}_1,\dots, \boldsymbol{x}_{p-1}] \) each with dimension
|
|
\( \boldsymbol{x}\in {\mathbb{R}}^{n} \).
|
|
|
|
<p>
|
|
The PCA theorem states that minimizing the above reconstruction error
|
|
corresponds to setting \( \boldsymbol{W}=\boldsymbol{S} \), the orthogonal matrix which
|
|
diagonalizes the empirical covariance(correlation) matrix. The optimal
|
|
low-dimensional encoding of the data is then given by a set of vectors
|
|
\( \boldsymbol{z}_i \) with at most \( l \) vectors, with \( l < < p \), defined by the
|
|
orthogonal projection of the data onto the columns spanned by the
|
|
eigenvectors of the covariance(correlations matrix).
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec66">Proof of the PCA Theorem </h2>
|
|
|
|
<p>
|
|
To show the PCA theorem let us start with the assumption that there is one vector \( \boldsymbol{s}_0 \) which corresponds to a solution which minimized the reconstruction error \( J \). This is an orthogonal vector. It means that we now approximate the reconstruction error in terms of \( \boldsymbol{w}_0 \) and \( \boldsymbol{z}_0 \) as
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec67">PCA Proof continued </h2>
|
|
|
|
<p>
|
|
We are almost there, we have obtained a relation between minimizing
|
|
the reconstruction error and the variance and the covariance
|
|
matrix. Minimizing the error is equivalent to maximizing the variance
|
|
of the projected data.
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec68">The final step </h2>
|
|
|
|
<p>
|
|
We could trivially maximize the variance of the projection (and
|
|
thereby minimize the error in the reconstruction function) by letting
|
|
the norm-2 of \( \boldsymbol{w}_0 \) go to infinity. However, this norm since we
|
|
want the matrix \( \boldsymbol{W} \) to be an orthogonal matrix, is constrained by
|
|
\( \vert\vert \boldsymbol{w}_0 \vert\vert_2^2=1 \). Imposing this condition via a
|
|
Lagrange multiplier we can then in turn maximize
|
|
|
|
$$
|
|
J(\boldsymbol{w}_0)= \boldsymbol{w}_0^T\boldsymbol{C}[\boldsymbol{x}]\boldsymbol{w}_0+\lambda_0(1-\boldsymbol{w}_0^T\boldsymbol{w}_0).
|
|
$$
|
|
|
|
Taking the derivative with respect to \( \boldsymbol{w}_0 \) we obtain
|
|
|
|
$$
|
|
\frac{\partial J(\boldsymbol{w}_0)}{\partial \boldsymbol{w}_0}= 2\boldsymbol{C}[\boldsymbol{x}]\boldsymbol{w}_0-2\lambda_0\boldsymbol{w}_0=0,
|
|
$$
|
|
|
|
meaning that
|
|
$$
|
|
\boldsymbol{C}[\boldsymbol{x}]\boldsymbol{w}_0=\lambda_0\boldsymbol{w}_0.
|
|
$$
|
|
|
|
<b>The direction that maximizes the variance (or minimizes the construction error) is an eigenvector of the covariance matrix</b>! If we left multiply with \( \boldsymbol{w}_0^T \) we have the variance of the projected data is
|
|
$$
|
|
\boldsymbol{w}_0^T\boldsymbol{C}[\boldsymbol{x}]\boldsymbol{w}_0=\lambda_0.
|
|
$$
|
|
|
|
<p>
|
|
If we want to maximize the variance (minimize the construction error)
|
|
we simply pick the eigenvector of the covariance matrix with the
|
|
largest eigenvalue. This establishes the link between the minimization
|
|
of the reconstruction function \( J \) in terms of an orthogonal matrix
|
|
and the maximization of the variance and thereby the covariance of our
|
|
observations encoded in the design/feature matrix \( \boldsymbol{X} \).
|
|
|
|
<p>
|
|
The proof
|
|
for the other eigenvectors \( \boldsymbol{w}_1,\boldsymbol{w}_2,\dots \) can be
|
|
established by applying the above arguments and using the fact that
|
|
our basis of eigenvectors is orthogonal, see <a href="https://mitpress.mit.edu/books/machine-learning-1" target="_blank">Murphy chapter
|
|
12.2</a>. The
|
|
discussion in chapter 12.2 of Murphy's text has also a nice link with
|
|
the Singular Value Decomposition theorem. For categorical data, see
|
|
chapter 12.4 and discussion therein.
|
|
|
|
<p>
|
|
For more details, see for example <a href="https://www.springer.com/gp/book/9780387878102" target="_blank">Vidal, Ma and Sastry, chapter 2</a>.
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec69">Geometric Interpretation and link with Singular Value Decomposition </h2>
|
|
|
|
<p>
|
|
For a detailed demonstration of the geometric interpretation, see <a href="https://www.springer.com/gp/book/9780387878102" target="_blank">Vidal, Ma and Sastry, section 2.1.2</a>.
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec70">Principal Component Analysis </h2>
|
|
|
|
<p>
|
|
Principal Component Analysis (PCA) is by far the most popular dimensionality reduction algorithm.
|
|
First it identifies the hyperplane that lies closest to the data, and then it projects the data onto it.
|
|
|
|
<p>
|
|
The following Python code uses NumPy’s <b>svd()</b> function to obtain all the principal components of the
|
|
training set, then extracts the first two principal components. First we center the data using either <b>pandas</b> or our own code
|
|
<p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">pandas</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">pd</span>
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">IPython.display</span> <span style="color: #008000; font-weight: bold">import</span> display
|
|
np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>seed(<span style="color: #666666">100</span>)
|
|
<span style="color: #408080; font-style: italic"># setting up a 10 x 5 vanilla matrix </span>
|
|
rows <span style="color: #666666">=</span> <span style="color: #666666">10</span>
|
|
cols <span style="color: #666666">=</span> <span style="color: #666666">5</span>
|
|
X <span style="color: #666666">=</span> np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>randn(rows,cols)
|
|
df <span style="color: #666666">=</span> pd<span style="color: #666666">.</span>DataFrame(X)
|
|
<span style="color: #408080; font-style: italic"># Pandas does the centering for us</span>
|
|
df <span style="color: #666666">=</span> df <span style="color: #666666">-</span>df<span style="color: #666666">.</span>mean()
|
|
display(df)
|
|
|
|
<span style="color: #408080; font-style: italic"># we center it ourselves</span>
|
|
X_centered <span style="color: #666666">=</span> X <span style="color: #666666">-</span> X<span style="color: #666666">.</span>mean(axis<span style="color: #666666">=0</span>)
|
|
<span style="color: #408080; font-style: italic"># Then check the difference between pandas and our own set up</span>
|
|
<span style="color: #008000">print</span>(X_centered<span style="color: #666666">-</span>df)
|
|
<span style="color: #408080; font-style: italic">#Now we do an SVD</span>
|
|
U, s, V <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linalg<span style="color: #666666">.</span>svd(X_centered)
|
|
c1 <span style="color: #666666">=</span> V<span style="color: #666666">.</span>T[:, <span style="color: #666666">0</span>]
|
|
c2 <span style="color: #666666">=</span> V<span style="color: #666666">.</span>T[:, <span style="color: #666666">1</span>]
|
|
W2 <span style="color: #666666">=</span> V<span style="color: #666666">.</span>T[:, :<span style="color: #666666">2</span>]
|
|
X2D <span style="color: #666666">=</span> X_centered<span style="color: #666666">.</span>dot(W2)
|
|
<span style="color: #008000">print</span>(X2D)
|
|
</pre></div>
|
|
<p>
|
|
PCA assumes that the dataset is centered around the origin. Scikit-Learn’s PCA classes take care of centering
|
|
the data for you. However, if you implement PCA yourself (as in the preceding example), or if you use other libraries, don’t
|
|
forget to center the data first.
|
|
|
|
<p>
|
|
Once you have identified all the principal components, you can reduce the dimensionality of the dataset
|
|
down to \( d \) dimensions by projecting it onto the hyperplane defined by the first \( d \) principal components.
|
|
Selecting this hyperplane ensures that the projection will preserve as much variance as possible.
|
|
<p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span>W2 <span style="color: #666666">=</span> V<span style="color: #666666">.</span>T[:, :<span style="color: #666666">2</span>]
|
|
X2D <span style="color: #666666">=</span> X_centered<span style="color: #666666">.</span>dot(W2)
|
|
</pre></div>
|
|
<p>
|
|
<!-- !split -->
|
|
|
|
<h2 id="___sec71">PCA and scikit-learn </h2>
|
|
|
|
<p>
|
|
Scikit-Learn’s PCA class implements PCA using SVD decomposition just like we did before. The
|
|
following code applies PCA to reduce the dimensionality of the dataset down to two dimensions (note
|
|
that it automatically takes care of centering the data):
|
|
<p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span><span style="color: #408080; font-style: italic">#thereafter we do a PCA with Scikit-learn</span>
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.decomposition</span> <span style="color: #008000; font-weight: bold">import</span> PCA
|
|
pca <span style="color: #666666">=</span> PCA(n_components <span style="color: #666666">=</span> <span style="color: #666666">2</span>)
|
|
X2D <span style="color: #666666">=</span> pca<span style="color: #666666">.</span>fit_transform(X)
|
|
<span style="color: #008000">print</span>(X2D)
|
|
</pre></div>
|
|
<p>
|
|
After fitting the PCA transformer to the dataset, you can access the principal components using the
|
|
components variable (note that it contains the PCs as horizontal vectors, so, for example, the first
|
|
principal component is equal to
|
|
<p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span>pca<span style="color: #666666">.</span>components_<span style="color: #666666">.</span>T[:, <span style="color: #666666">0</span>]
|
|
</pre></div>
|
|
<p>
|
|
Another very useful piece of information is the explained variance ratio of each principal component,
|
|
available via the \( explained\_variance\_ratio \) variable. It indicates the proportion of the dataset’s
|
|
variance that lies along the axis of each principal component.
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec72">Back to the Cancer Data </h2>
|
|
We can now repeat the above but applied to real data, in this case our breast cancer data.
|
|
Here we compute performance scores on the training data using logistic regression.
|
|
<p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">matplotlib.pyplot</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">plt</span>
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.model_selection</span> <span style="color: #008000; font-weight: bold">import</span> train_test_split
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.datasets</span> <span style="color: #008000; font-weight: bold">import</span> load_breast_cancer
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.linear_model</span> <span style="color: #008000; font-weight: bold">import</span> LogisticRegression
|
|
cancer <span style="color: #666666">=</span> load_breast_cancer()
|
|
|
|
X_train, X_test, y_train, y_test <span style="color: #666666">=</span> train_test_split(cancer<span style="color: #666666">.</span>data,cancer<span style="color: #666666">.</span>target,random_state<span style="color: #666666">=0</span>)
|
|
|
|
logreg <span style="color: #666666">=</span> LogisticRegression()
|
|
logreg<span style="color: #666666">.</span>fit(X_train, y_train)
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"Train set accuracy from Logistic Regression: </span><span style="color: #BB6688; font-weight: bold">{:.2f}</span><span style="color: #BA2121">"</span><span style="color: #666666">.</span>format(logreg<span style="color: #666666">.</span>score(X_train,y_train)))
|
|
<span style="color: #408080; font-style: italic"># We scale the data</span>
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.preprocessing</span> <span style="color: #008000; font-weight: bold">import</span> StandardScaler
|
|
scaler <span style="color: #666666">=</span> StandardScaler()
|
|
scaler<span style="color: #666666">.</span>fit(X_train)
|
|
X_train_scaled <span style="color: #666666">=</span> scaler<span style="color: #666666">.</span>transform(X_train)
|
|
X_test_scaled <span style="color: #666666">=</span> scaler<span style="color: #666666">.</span>transform(X_test)
|
|
<span style="color: #408080; font-style: italic"># Then perform again a log reg fit</span>
|
|
logreg<span style="color: #666666">.</span>fit(X_train_scaled, y_train)
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"Train set accuracy scaled data: </span><span style="color: #BB6688; font-weight: bold">{:.2f}</span><span style="color: #BA2121">"</span><span style="color: #666666">.</span>format(logreg<span style="color: #666666">.</span>score(X_train_scaled,y_train)))
|
|
<span style="color: #408080; font-style: italic">#thereafter we do a PCA with Scikit-learn</span>
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.decomposition</span> <span style="color: #008000; font-weight: bold">import</span> PCA
|
|
pca <span style="color: #666666">=</span> PCA(n_components <span style="color: #666666">=</span> <span style="color: #666666">2</span>)
|
|
X2D_train <span style="color: #666666">=</span> pca<span style="color: #666666">.</span>fit_transform(X_train_scaled)
|
|
<span style="color: #408080; font-style: italic"># and finally compute the log reg fit and the score on the training data </span>
|
|
logreg<span style="color: #666666">.</span>fit(X2D_train,y_train)
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"Train set accuracy scaled and PCA data: </span><span style="color: #BB6688; font-weight: bold">{:.2f}</span><span style="color: #BA2121">"</span><span style="color: #666666">.</span>format(logreg<span style="color: #666666">.</span>score(X2D_train,y_train)))
|
|
</pre></div>
|
|
<p>
|
|
We see that our training data after the PCA decomposition has a performance similar to the non-scaled data.
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec73">More on the PCA </h2>
|
|
|
|
<p>
|
|
Instead of arbitrarily choosing the number of dimensions to reduce down to, it is generally preferable to
|
|
choose the number of dimensions that add up to a sufficiently large portion of the variance (e.g., 95%).
|
|
Unless, of course, you are reducing dimensionality for data visualization — in that case you will
|
|
generally want to reduce the dimensionality down to 2 or 3.
|
|
The following code computes PCA without reducing dimensionality, then computes the minimum number
|
|
of dimensions required to preserve 95% of the training set’s variance:
|
|
<p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span>pca <span style="color: #666666">=</span> PCA()
|
|
pca<span style="color: #666666">.</span>fit(X)
|
|
cumsum <span style="color: #666666">=</span> np<span style="color: #666666">.</span>cumsum(pca<span style="color: #666666">.</span>explained_variance_ratio_)
|
|
d <span style="color: #666666">=</span> np<span style="color: #666666">.</span>argmax(cumsum <span style="color: #666666">>=</span> <span style="color: #666666">0.95</span>) <span style="color: #666666">+</span> <span style="color: #666666">1</span>
|
|
</pre></div>
|
|
<p>
|
|
You could then set \( n\_components=d \) and run PCA again. However, there is a much better option: instead
|
|
of specifying the number of principal components you want to preserve, you can set \( n\_components \) to be
|
|
a float between 0.0 and 1.0, indicating the ratio of variance you wish to preserve:
|
|
<p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span>pca <span style="color: #666666">=</span> PCA(n_components<span style="color: #666666">=0.95</span>)
|
|
X_reduced <span style="color: #666666">=</span> pca<span style="color: #666666">.</span>fit_transform(X)
|
|
</pre></div>
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec74">Incremental PCA </h2>
|
|
|
|
<p>
|
|
One problem with the preceding implementation of PCA is that it requires the whole training set to fit in
|
|
memory in order for the SVD algorithm to run. Fortunately, Incremental PCA (IPCA) algorithms have
|
|
been developed: you can split the training set into mini-batches and feed an IPCA algorithm one minibatch
|
|
at a time. This is useful for large training sets, and also to apply PCA online (i.e., on the fly, as new
|
|
instances arrive).
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec75">Randomized PCA </h2>
|
|
|
|
<p>
|
|
Scikit-Learn offers yet another option to perform PCA, called Randomized PCA. This is a stochastic
|
|
algorithm that quickly finds an approximation of the first d principal components. Its computational
|
|
complexity is \( O(m \times d^2)+O(d^3) \), instead of \( O(m \times n^2) + O(n^3) \), so it is dramatically faster than the
|
|
previous algorithms when \( d \) is much smaller than \( n \).
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec76">Kernel PCA </h2>
|
|
<div class="alert alert-block alert-block alert-text-normal">
|
|
<b></b>
|
|
<p>
|
|
|
|
<p>
|
|
The kernel trick is a mathematical technique that implicitly maps instances into a
|
|
very high-dimensional space (called the feature space), enabling nonlinear classification and regression
|
|
with Support Vector Machines. Recall that a linear decision boundary in the high-dimensional feature
|
|
space corresponds to a complex nonlinear decision boundary in the original space.
|
|
It turns out that the same trick can be applied to PCA, making it possible to perform complex nonlinear
|
|
projections for dimensionality reduction. This is called Kernel PCA (kPCA). It is often good at
|
|
preserving clusters of instances after projection, or sometimes even unrolling datasets that lie close to a
|
|
twisted manifold.
|
|
For example, the following code uses Scikit-Learn’s KernelPCA class to perform kPCA with an
|
|
<p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span><span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.decomposition</span> <span style="color: #008000; font-weight: bold">import</span> KernelPCA
|
|
rbf_pca <span style="color: #666666">=</span> KernelPCA(n_components <span style="color: #666666">=</span> <span style="color: #666666">2</span>, kernel<span style="color: #666666">=</span><span style="color: #BA2121">"rbf"</span>, gamma<span style="color: #666666">=0.04</span>)
|
|
X_reduced <span style="color: #666666">=</span> rbf_pca<span style="color: #666666">.</span>fit_transform(X)
|
|
</pre></div>
|
|
|
|
</div>
|
|
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec77">LLE </h2>
|
|
|
|
<p>
|
|
Locally Linear Embedding (LLE) is another very powerful nonlinear dimensionality reduction
|
|
(NLDR) technique. It is a Manifold Learning technique that does not rely on projections like the previous
|
|
algorithms. In a nutshell, LLE works by first measuring how each training instance linearly relates to its
|
|
closest neighbors (c.n.), and then looking for a low-dimensional representation of the training set where
|
|
these local relationships are best preserved (more details shortly).
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="___sec78">Other techniques </h2>
|
|
|
|
<p>
|
|
There are many other dimensionality reduction techniques, several of which are available in Scikit-Learn.
|
|
|
|
<p>
|
|
Here are some of the most popular:
|
|
|
|
<ul>
|
|
<li> <b>Multidimensional Scaling (MDS)</b> reduces dimensionality while trying to preserve the distances between the instances.</li>
|
|
<li> <b>Isomap</b> creates a graph by connecting each instance to its nearest neighbors, then reduces dimensionality while trying to preserve the geodesic distances between the instances.</li>
|
|
<li> <b>t-Distributed Stochastic Neighbor Embedding</b> (t-SNE) reduces dimensionality while trying to keep similar instances close and dissimilar instances apart. It is mostly used for visualization, in particular to visualize clusters of instances in high-dimensional space (e.g., to visualize the MNIST images in 2D).</li>
|
|
<li> Linear Discriminant Analysis (LDA) is actually a classification algorithm, but during training it learns the most discriminative axes between the classes, and these axes can then be used to define a hyperplane onto which to project the data. The benefit is that the projection will keep classes as far apart as possible, so LDA is a good technique to reduce dimensionality before running another classification algorithm such as a Support Vector Machine (SVM) classifier discussed in the SVM lectures.</li>
|
|
</ul>
|
|
|
|
|
|
<!-- ------------------- end of main content --------------- -->
|
|
|
|
|
|
<center style="font-size:80%">
|
|
<!-- copyright --> © 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
|
|
</center>
|
|
|
|
|
|
</body>
|
|
</html>
|
|
|
|
|