Files
2018-11-12 14:40:37 +01:00

3253 lines
229 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="description" content="Data Analysis and Machine Learning: Using Neural networks to solve ODEs and PDEs">
<title>Data Analysis and Machine Learning: Using Neural networks to solve ODEs and PDEs</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}
div { text-align: justify; text-justify: inter-word; }
</style>
</head>
<!-- tocinfo
{'highest level': 2,
'sections': [('Differential equations', 2, None, '___sec0'),
('Description of the equation to solve for', 2, None, '___sec1'),
('Ordinary Differential Equations', 2, None, '___sec2'),
('The trial solution', 2, None, '___sec3'),
('Minimizing the cost function using gradient descent and '
'automatic differentiation',
2,
None,
'___sec4'),
('Example: Exponential decay and setting up the network using '
'Autograd',
2,
None,
'___sec5'),
('The function to solve for', 2, None, '___sec6'),
('The trial solution', 2, None, '___sec7'),
('Reformulating the problem', 2, None, '___sec8'),
('A possible implementation of a neural network using Autograd',
2,
None,
'___sec9'),
('Backpropagation using Autograd', 2, None, '___sec10'),
('Gradient descent', 2, None, '___sec11'),
('The network with one input, hidden, and output layer',
2,
None,
'___sec12'),
('The network with one input layer, specified number of hidden '
'layers, and one output layer output layer',
2,
None,
'___sec13'),
('Example: Population growth, comparing Autograd, TensorFlow, '
"and Euler's scheme",
2,
None,
'___sec14'),
('Setting up the problem', 2, None, '___sec15'),
('The trial solution', 2, None, '___sec16'),
('The program using Autograd', 2, None, '___sec17'),
('Using forward Euler to solve the ODE', 2, None, '___sec18'),
('Using TensorFlow to model logistic population growth',
2,
None,
'___sec19'),
('The general program flow in TensorFlow', 2, None, '___sec20'),
('Program flow in TensorFlow - Construction phase',
2,
None,
'___sec21'),
('Program flow in TensorFlow - Execution phase',
2,
None,
'___sec22'),
('The full program modeling logistic population growth using '
'TensorFlow',
2,
None,
'___sec23'),
('Example: Solving the one dimensional Poisson equation using '
'Autograd and TensorFlow',
2,
None,
'___sec24'),
('The specific equation to solve for', 2, None, '___sec25'),
('Solving the equation using Autograd', 2, None, '___sec26'),
('Comparing with a numerical scheme', 2, None, '___sec27'),
('Using gradient descent in TensorFlow to solve Poisson equation',
2,
None,
'___sec28'),
('Using a different optimization algorithm implemented in '
'TensorFlow to solve Poisson equation',
2,
None,
'___sec29'),
('Partial Differential Equations', 2, None, '___sec30'),
('Example: The diffusion equation', 2, None, '___sec31'),
('Defining the problem', 2, None, '___sec32'),
('Setting up the network using Autograd', 2, None, '___sec33'),
('Setting up the network using Autograd; The trial solution',
2,
None,
'___sec34'),
('Setting up the network using Autograd; The full program',
2,
None,
'___sec35'),
('Example: Solving the wave equation using Autograd and '
'TensorFlow',
2,
None,
'___sec36'),
('The problem to solve for', 2, None, '___sec37'),
('The trial solution', 2, None, '___sec38'),
('The analytical solution', 2, None, '___sec39'),
('Solving the wave equation - the full program using Autograd',
2,
None,
'___sec40'),
('Solving the wave equation - the full program using TensorFlow',
2,
None,
'___sec41'),
('Resources', 2, None, '___sec42')]}
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>Data Analysis and Machine Learning: Using Neural networks to solve ODEs and PDEs</h1></center> <!-- document title -->
<p>
<!-- author(s): Kristine Baluka Hein -->
<center>
<b>Kristine Baluka Hein</b>
</center>
<p>
<!-- institution -->
<center><b>Department of Informatics, University of Oslo, Norway</b></center>
<br>
<p>
<center><h4>Nov 11, 2018</h4></center> <!-- date -->
<br>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec0">Differential equations </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.
Having this in mind, we will look closer at whether a neural network manages to solve for a function in an equation.
<p>
A differential equation is an equation where the solution is a function. In the equation, it is given some relations between the function's derivatives subject to some given conditions.
Typically, a differential equation is solved numerically using approximations of Taylor series.
These kind of methods usually depends of choosing step sizes along each dimension that are small enough for the approximations to yield accurate results.
As we will see in the examples, using a neural network manages to outperform some well known methods in selected cases.
A possible way to solve the equation that we will look into, is to formulate a trial solution involving the result from a neural network.
The trial solution should hopefully converge into the true solution.
Be aware though, not all differential equations has an analytical solution.
We will stick with those that has an analytical solution such that we can check how well the network performs.
To make the trial solution converge to the true solution, setting up the cost function and updating the weights and biases within the neural network is crucial for the trial solution to converge.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec1">Description of the equation to solve for </h2>
A differential equation is a equation where the solution is a function.
The equation describes how the derivatives of the function behaves in a given domain along with some conditions.
<p>
Given a differential equation, it is desirable to know how to reformulate it into an equation a neural network can solve.
Having decided on which activation functions each layer should use, along with the number of hidden layers and neurons within each layer,
the changeable parameters of a neural network are the weights and biases for each neuron in every layer in the net.
If a differential equation is reformulated into an equation where minimization of some parameters must be done,
a neural net could possibly solve this equation.
<p>
A trial solution might be tricky to find in general.
Due to the Universal Approximation Theorem, one could hope that outcome of the deep neural net might solve a given differential equation, even though it is used in a simple trial solution.
Let us try this idea on some well-known ordinary differential equations and thereafter try to solve for functions defined by two variables, giving partial differential equations.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec2">Ordinary Differential Equations </h2>
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="___sec3">The trial solution </h2>
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) \)?
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.
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 \( \vec x \) with elements \( x_i \) for \( i = 1,\dots,N \),
the cost function becomes
$$
\begin{equation} \label{cost}
c\left(\vec 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 some 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="___sec4">Minimizing the cost function using gradient descent and automatic differentiation </h2>
To perform the minimization using gradient descent, the gradient of \( c\left(\vec x, P\right) \) is needed.
It might happen so that finding an analytical expression of the gradient of \( c(\vec 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>
In the forthcoming examples presenting possible usages of Autograd and TensorFlow,
it is shown how one could set up a neural network using gradient descent solving a differential
equation.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec5">Example: Exponential decay and setting up the network using Autograd </h2>
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>
In this example, a neural network will be implemented using Autograd in order to perform backpropagation.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec6">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="___sec7">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>
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="___sec8">Reformulating the problem </h2>
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>
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>
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 \( \vec x \) be a vector with elements \( x_i \) and \( c(\vec 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(\vec 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(\vec x, \{P_{\text{hidden} }, P_{\text{output} }\})
$$
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec9">A possible implementation of a neural network using Autograd </h2>
<p>
For simplicity, it is assumed that the input is an array \( \vec 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 \( \vec x \) 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>
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>
The result after weighting the inputs at the \( i \)-th hidden neuron can be written as a vector:
$$
\begin{aligned}
\vec{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} \\
&= \vec{p}_{i, \text{hidden}}^T X
\end{aligned}
$$
<p>
The vector \( \vec{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 \( \vec{z}_{i}^{\text{hidden}} \) for every \( i \)-th neuron within the hidden layer, the vector will be sent to an activation function \( a_i(\vec{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 $\vec{x}_i^{\text{hidden} }$from each \( i \)-th hidden neuron is:
$$
\vec{x}_i^{\text{hidden} } = f\big( \vec{z}_{i}^{\text{hidden}} \big)
$$
<p>
The outputs \( \vec{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>
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}} & \vec{w}_1^{\text{output}}
\end{pmatrix}
\begin{pmatrix}
1 \\
\vec{x}_j^{\text{hidden}}
\end{pmatrix}
\end{aligned}
$$
<p>
Expressing \( z_{1,j}^{\text{output}} \) as a vector gives the following way of weighting the inputs from the hidden layer:
$$
\vec{z}_{1}^{\text{output}} =
\begin{pmatrix}
b_1^{\text{output}} & \vec{w}_1^{\text{output}}
\end{pmatrix}
\begin{pmatrix}
1 & 1 & \dots & 1 \\
\vec{x}_1^{\text{hidden}} & \vec{x}_2^{\text{hidden}} & \dots & \vec{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 \( \vec{z}_{1}^{\text{output}} \) the neural network has finished its feed forward step, and \( \vec{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="___sec10">Backpropagation using Autograd </h2>
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(\vec 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="___sec11">Gradient descent </h2>
The idea of the gradient descent algorithm is to update parameters in direction where the cost function decreases goes to a minimum.
<p>
In general, the update of some parameters \( \vec \omega \) given a cost function defined by some weights \( \vec \omega \), \( c(\vec x, \vec \omega) \), goes as follows:
$$
\vec \omega_{\text{new} } = \vec \omega - \lambda \nabla_{\vec \omega} c(\vec x, \vec \omega)
$$
<p>
for a number of iterations or until $ \big|\big| \vec \omega_{\text{new} } - \vec \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_{\vec \omega} c(\vec x, \vec \omega)$.
The notation \( \nabla_{\vec \omega} \) express the gradient with respect to the elements in \( \vec \omega \).
<p>
In our case, we have to minimize the cost function \( c(\vec 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(\vec x, P) \\
P_{\text{output},\text{new}} &= P_{\text{output}} - \lambda \nabla_{P_{\text{output}}} c(\vec x, P)
\end{aligned}
$$
<p>
In general, one could risk using a cost function having gradients that are cumbersome to derive analytically.
For our case, the cost functions are just the mean squared error.
One could employ an implementation of the back propagation for this case, but we will emphasis
on how one could use automatic differentiation in order to train the network.
<p>
However, it might be useful to know how automatic differentiation can be used, e.g through Autograd, in order to test an implementation.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec12">The network with one input, hidden, and output layer </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"># Autograd will be used for later, so the numpy wrapper for Autograd must be imported</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; font-weight: bold">print</span>(<span style="color: #BA2121">&#39;Initial cost: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&#39;</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; font-weight: bold">print</span>(<span style="color: #BA2121">&#39;Final cost: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&#39;</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">&#39;__main__&#39;</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; font-weight: bold">print</span>(<span style="color: #BA2121">&#39;Max absolute difference: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&#39;</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">&#39;Performance of neural network solving an ODE compared to the analytical solution&#39;</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">&#39;analytical&#39;</span>,<span style="color: #BA2121">&#39;nn&#39;</span>])
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">&#39;x&#39;</span>)
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">&#39;g(x)&#39;</span>)
plt<span style="color: #666666">.</span>show()
</pre></div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec13">The network with one input layer, specified number of hidden layers, and one output layer 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">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; font-weight: bold">print</span>(<span style="color: #BA2121">&#39;Initial cost: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&#39;</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; font-weight: bold">print</span>(<span style="color: #BA2121">&#39;Final cost: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&#39;</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">&#39;__main__&#39;</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">&#39;Performance of a deep neural network solving an ODE compared to the analytical solution&#39;</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">&#39;analytical&#39;</span>,<span style="color: #BA2121">&#39;dnn&#39;</span>])
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">&#39;g(x)&#39;</span>)
plt<span style="color: #666666">.</span>show()
</pre></div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec14">Example: Population growth, comparing Autograd, TensorFlow, and Euler's scheme </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),
a network has been constructed using TensorFlow also.
For comparison, the forward Euler method has been implemented in order to see how the networks performs compared to a numerical scheme.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec15">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="___sec16">The trial solution </h2>
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="___sec17">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&#39;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">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; font-weight: bold">print</span>(<span style="color: #BA2121">&#39;Initial cost: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&#39;</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; font-weight: bold">print</span>(<span style="color: #BA2121">&#39;Final cost: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&#39;</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">&#39;__main__&#39;</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; font-weight: bold">print</span>(<span style="color: #BA2121">&quot;The max absolute difference between the solutions is: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&quot;</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">&#39;Performance of neural network solving an ODE compared to the analytical solution&#39;</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">&#39;analytical&#39;</span>,<span style="color: #BA2121">&#39;nn&#39;</span>])
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">&#39;t&#39;</span>)
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">&#39;g(t)&#39;</span>)
plt<span style="color: #666666">.</span>show()
</pre></div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec18">Using forward Euler to solve the ODE </h2>
<p>
A straight-forward 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">&#39;__main__&#39;</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; font-weight: bold">print</span>(<span style="color: #BA2121">&quot;The max absolute difference between the solutions is: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&quot;</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">&#39;Performance of neural network solving an ODE compared to the analytical solution&#39;</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">&#39;analytical&#39;</span>,<span style="color: #BA2121">&#39;nn&#39;</span>])
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">&#39;t&#39;</span>)
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">&#39;g(t)&#39;</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; font-weight: bold">print</span>(<span style="color: #BA2121">&#39;Max absolute difference between Euler method and analytical: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&#39;</span><span style="color: #666666">%</span>diff1)
<span style="color: #008000; font-weight: bold">print</span>(<span style="color: #BA2121">&#39;Max absolute difference between deep neural network and analytical: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&#39;</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">&#39;euler&#39;</span>,<span style="color: #BA2121">&#39;analytical&#39;</span>,<span style="color: #BA2121">&#39;dnn&#39;</span>])
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">&#39;Time t&#39;</span>)
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">&#39;g(t)&#39;</span>)
plt<span style="color: #666666">.</span>show()
</pre></div>
<p>
Running the program gives
<p>
<!-- code=text typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span>Max absolute difference between Euler method and analytical: 0.011225
Max absolute difference between deep neural network and analytical: 0.00424909
</pre></div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec19">Using TensorFlow to model logistic population growth </h2>
<p>
TensorFlow is a library widely used in the machine learning community.
A neural network can be set up in a flexible manner, where various optimization algorithms are implemented and different types of networks can be used, making it easier to experiment on solving differential equations using neural networks.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec20">The general program flow in TensorFlow </h2>
<p>
Usually, a program in TensorFlow is divided into two parts; the <em>construction phase</em> and the <em>execution phase</em>.
In the construction phase, the computational graph that TensorFlow uses to perform its calculations are set up.
In the execution phase, TensorFlow evaluates any procedure that was defined in the construction phase.
<h2 id="___sec21">Program flow in TensorFlow - Construction phase </h2>
<p>
Here, the architecture for the neural network will be set up, along with the cost function and an optimizer class used during training of the network.
Note that TensorFlow uses a different convention for the weighting done in each neuron in each layer within the network than in the implementation using Autograd.
The matrix-vector multiplication between the input from the previous layer and the weighting at the neuron at current layer in the program using Autograd, is the transpose of the convention used in TensorFlow. But it will not affect that much our construction, as TensorFlow takes care of most of the computations. The only thing we have to be aware of, is how the dimensions are for our inputs.
<h2 id="___sec22">Program flow in TensorFlow - Execution phase </h2>
<p>
The computation graph has been defined, and is ready to be evaluated.
In order to get access to the graph, it has to be initialized and be runned within a Session.
<h2 id="___sec23">The full program modeling logistic population growth using TensorFlow </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">tensorflow</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">tf</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">matplotlib.pyplot</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">plt</span>
<span style="color: #408080; font-style: italic"># Just to reset the graph such that it is possible to rerun this in a</span>
<span style="color: #408080; font-style: italic"># Jupyter cell without resetting the whole kernel.</span>
tf<span style="color: #666666">.</span>reset_default_graph()
<span style="color: #408080; font-style: italic"># Set a seed to ensure getting the same results from every run</span>
tf<span style="color: #666666">.</span>set_random_seed(<span style="color: #666666">4155</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">## The construction phase</span>
<span style="color: #408080; font-style: italic"># Convert the values the trial solution is evaluated at to a tensor.</span>
t_tf <span style="color: #666666">=</span> tf<span style="color: #666666">.</span>convert_to_tensor(t<span style="color: #666666">.</span>reshape(<span style="color: #666666">-1</span>,<span style="color: #666666">1</span>),dtype<span style="color: #666666">=</span>tf<span style="color: #666666">.</span>float64)
zeros <span style="color: #666666">=</span> tf<span style="color: #666666">.</span>reshape(tf<span style="color: #666666">.</span>convert_to_tensor(np<span style="color: #666666">.</span>zeros(t<span style="color: #666666">.</span>shape)),shape<span style="color: #666666">=</span>(<span style="color: #666666">-1</span>,<span style="color: #666666">1</span>))
<span style="color: #408080; font-style: italic"># Define the parameters of the equation</span>
alpha <span style="color: #666666">=</span> tf<span style="color: #666666">.</span>constant(<span style="color: #666666">2.</span>,dtype<span style="color: #666666">=</span>tf<span style="color: #666666">.</span>float64)
A <span style="color: #666666">=</span> tf<span style="color: #666666">.</span>constant(<span style="color: #666666">1.</span>,dtype<span style="color: #666666">=</span>tf<span style="color: #666666">.</span>float64)
g0 <span style="color: #666666">=</span> tf<span style="color: #666666">.</span>constant(<span style="color: #666666">1.2</span>,dtype<span style="color: #666666">=</span>tf<span style="color: #666666">.</span>float64)
num_iter <span style="color: #666666">=</span> <span style="color: #666666">100000</span>
<span style="color: #408080; font-style: italic"># Define the number of neurons at each hidden layer</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_hidden_layers <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(num_hidden_neurons)
<span style="color: #408080; font-style: italic"># Construct the network.</span>
<span style="color: #408080; font-style: italic"># tf.name_scope is used to group each step in the construction,</span>
<span style="color: #408080; font-style: italic"># just for a more organized visualization in TensorBoard</span>
<span style="color: #008000; font-weight: bold">with</span> tf<span style="color: #666666">.</span>name_scope(<span style="color: #BA2121">&#39;dnn&#39;</span>):
<span style="color: #408080; font-style: italic"># Input layer</span>
previous_layer <span style="color: #666666">=</span> t_tf
<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>(num_hidden_layers):
current_layer <span style="color: #666666">=</span> tf<span style="color: #666666">.</span>layers<span style="color: #666666">.</span>dense(previous_layer, num_hidden_neurons[l], name<span style="color: #666666">=</span><span style="color: #BA2121">&#39;hidden</span><span style="color: #BB6688; font-weight: bold">%d</span><span style="color: #BA2121">&#39;</span><span style="color: #666666">%</span>(l<span style="color: #666666">+1</span>), activation<span style="color: #666666">=</span>tf<span style="color: #666666">.</span>nn<span style="color: #666666">.</span>sigmoid)
previous_layer <span style="color: #666666">=</span> current_layer
<span style="color: #408080; font-style: italic"># Output layer</span>
dnn_output <span style="color: #666666">=</span> tf<span style="color: #666666">.</span>layers<span style="color: #666666">.</span>dense(previous_layer, <span style="color: #666666">1</span>, name<span style="color: #666666">=</span><span style="color: #BA2121">&#39;output&#39;</span>)
<span style="color: #408080; font-style: italic"># Define the cost function</span>
<span style="color: #008000; font-weight: bold">with</span> tf<span style="color: #666666">.</span>name_scope(<span style="color: #BA2121">&#39;cost&#39;</span>):
g_trial <span style="color: #666666">=</span> g0 <span style="color: #666666">+</span> t_tf<span style="color: #666666">*</span>dnn_output
d_g_trial <span style="color: #666666">=</span> tf<span style="color: #666666">.</span>gradients(g_trial,t_tf)
func <span style="color: #666666">=</span> alpha<span style="color: #666666">*</span>g_trial<span style="color: #666666">*</span>(A <span style="color: #666666">-</span> g_trial)
cost <span style="color: #666666">=</span> tf<span style="color: #666666">.</span>losses<span style="color: #666666">.</span>mean_squared_error(zeros, d_g_trial[<span style="color: #666666">0</span>] <span style="color: #666666">-</span> func)
<span style="color: #408080; font-style: italic"># Choose the method to minimize the cost function, along with a learning rate</span>
learning_rate <span style="color: #666666">=</span> <span style="color: #666666">1e-2</span>
<span style="color: #008000; font-weight: bold">with</span> tf<span style="color: #666666">.</span>name_scope(<span style="color: #BA2121">&#39;train&#39;</span>):
optimizer <span style="color: #666666">=</span> tf<span style="color: #666666">.</span>train<span style="color: #666666">.</span>GradientDescentOptimizer(learning_rate)
traning_op <span style="color: #666666">=</span> optimizer<span style="color: #666666">.</span>minimize(cost)
<span style="color: #408080; font-style: italic"># Set up a referance to the result from the neural network:</span>
g_dnn_tf <span style="color: #666666">=</span> <span style="color: #008000">None</span>
<span style="color: #408080; font-style: italic"># Define a node that initializes all of the other nodes in the computational graph</span>
<span style="color: #408080; font-style: italic"># used by TensorFlow:</span>
init <span style="color: #666666">=</span> tf<span style="color: #666666">.</span>global_variables_initializer()
<span style="color: #408080; font-style: italic">## Execution phase</span>
<span style="color: #408080; font-style: italic"># Start a session where the graph defined from the construction phase can be evaluated at:</span>
<span style="color: #008000; font-weight: bold">with</span> tf<span style="color: #666666">.</span>Session() <span style="color: #008000; font-weight: bold">as</span> sess:
<span style="color: #408080; font-style: italic"># Initialize the whole graph</span>
init<span style="color: #666666">.</span>run()
<span style="color: #408080; font-style: italic"># Evaluate the initial cost:</span>
<span style="color: #008000; font-weight: bold">print</span>(<span style="color: #BA2121">&#39;Initial cost: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&#39;</span><span style="color: #666666">%</span>cost<span style="color: #666666">.</span>eval())
<span style="color: #408080; font-style: italic"># The training of the network:</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):
sess<span style="color: #666666">.</span>run(traning_op)
<span style="color: #408080; font-style: italic"># If one desires to see how the cost function behaves for each iteration:</span>
<span style="color: #408080; font-style: italic">#if i % 1000 == 0:</span>
<span style="color: #408080; font-style: italic"># print(cost.eval())</span>
<span style="color: #408080; font-style: italic"># Training is done, and we have an approximate solution to the ODE</span>
<span style="color: #008000; font-weight: bold">print</span>(<span style="color: #BA2121">&#39;Final cost: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&#39;</span><span style="color: #666666">%</span>cost<span style="color: #666666">.</span>eval())
<span style="color: #408080; font-style: italic"># Store the result</span>
g_dnn_tf <span style="color: #666666">=</span> g_trial<span style="color: #666666">.</span>eval()
<span style="color: #408080; font-style: italic"># Compare with analytical solution</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">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))
g_analytical <span style="color: #666666">=</span> g_analytic(t)
diff_tf <span style="color: #666666">=</span> g_dnn_tf <span style="color: #666666">-</span> g_analytical<span style="color: #666666">.</span>reshape(<span style="color: #666666">-1</span>,<span style="color: #666666">1</span>)
<span style="color: #008000; font-weight: bold">print</span>(<span style="color: #BA2121">&#39;</span><span style="color: #BB6622; font-weight: bold">\n</span><span style="color: #BA2121">Max absolute difference between the analytical solution and solution from TensorFlow DNN: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&#39;</span><span style="color: #666666">%</span>np<span style="color: #666666">.</span>max(np<span style="color: #666666">.</span>abs(diff_tf)))
<span style="color: #408080; font-style: italic"># Plot the result</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">&#39;Numerical solutions of the ODE&#39;</span>)
plt<span style="color: #666666">.</span>plot(t, g_dnn_tf)
plt<span style="color: #666666">.</span>plot(t, g_analytical)
plt<span style="color: #666666">.</span>legend([<span style="color: #BA2121">&#39;dnn, tensorflow&#39;</span>, <span style="color: #BA2121">&#39;exact&#39;</span>])
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">&#39;Time t&#39;</span>)
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">&#39;g(t)&#39;</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: Solving the one dimensional Poisson equation using Autograd and TensorFlow </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>
There exists many different optimization methods implemented in TensorFlow.
In the examples program using TensorFlow, it could also be of interest to see how
the choice of an optimization method affects our results.
In the <a href="https://www.tensorflow.org/versions/r1.2/api_guides/python/train#Optimizers" target="_blank">TensorFlow documentation about optimizers</a>, a list over available optimization methods are shown.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec25">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="___sec26">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">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; font-weight: bold">print</span>(<span style="color: #BA2121">&#39;Initial cost: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&#39;</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; font-weight: bold">print</span>(<span style="color: #BA2121">&#39;Final cost: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&#39;</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">&#39;__main__&#39;</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; font-weight: bold">print</span>(<span style="color: #BA2121">&quot;The max absolute difference between the solutions is: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&quot;</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">&#39;Performance of neural network solving an ODE compared to the analytical solution&#39;</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">&#39;analytical&#39;</span>,<span style="color: #BA2121">&#39;nn&#39;</span>])
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">&#39;x&#39;</span>)
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">&#39;g(x)&#39;</span>)
plt<span style="color: #666666">.</span>show()
</pre></div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec27">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} \\
A\vec{g} &= \vec{f}
\end{aligned}
$$
<p>
which makes it possible to solve for the vector \( \vec{g} \).
<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">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; font-weight: bold">print</span>(<span style="color: #BA2121">&#39;Initial cost: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&#39;</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; font-weight: bold">print</span>(<span style="color: #BA2121">&#39;Final cost: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&#39;</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">&#39;__main__&#39;</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">&#39;Performance of neural network solving an ODE compared to the analytical solution&#39;</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">&#39;analytical&#39;</span>,<span style="color: #BA2121">&#39;nn&#39;</span>])
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">&#39;x&#39;</span>)
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">&#39;g(x)&#39;</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; font-weight: bold">print</span>(<span style="color: #BA2121">&quot;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">&quot;</span><span style="color: #666666">%</span>max_diff1)
<span style="color: #008000; font-weight: bold">print</span>(<span style="color: #BA2121">&quot;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">&quot;</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">&#39;numerical scheme&#39;</span>,<span style="color: #BA2121">&#39;analytical&#39;</span>,<span style="color: #BA2121">&#39;dnn&#39;</span>])
plt<span style="color: #666666">.</span>show()
</pre></div>
<p>
The program prints out:
<p>
<!-- code=text typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span>The max absolute difference between the analytical solution and DNN Autograd: 0.000464088
The max absolute difference between the analytical solution and numerical scheme: 0.00266858
</pre></div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec28">Using gradient descent in TensorFlow to solve Poisson equation </h2>
The program follows the similar idea as for the logistic population model.
<p>
What has changed, is what the cost function minimizes and the trial solution.
<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">tensorflow</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">tf</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">matplotlib.pyplot</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">plt</span>
<span style="color: #408080; font-style: italic">## Construction phase</span>
<span style="color: #408080; font-style: italic"># Just to reset the graph such that it is possible to rerun this in a</span>
<span style="color: #408080; font-style: italic"># Jupyter cell without resetting the whole kernel.</span>
tf<span style="color: #666666">.</span>reset_default_graph()
tf<span style="color: #666666">.</span>set_random_seed(<span style="color: #666666">4155</span>)
<span style="color: #408080; font-style: italic"># Convert the values the trial solution is evaluated at to a tensor.</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)
x_tf <span style="color: #666666">=</span> tf<span style="color: #666666">.</span>convert_to_tensor(x<span style="color: #666666">.</span>reshape(<span style="color: #666666">-1</span>,<span style="color: #666666">1</span>),dtype<span style="color: #666666">=</span>tf<span style="color: #666666">.</span>float64)
num_iter <span style="color: #666666">=</span> <span style="color: #666666">10000</span>
<span style="color: #408080; font-style: italic"># Define the number of neurons at each hidden layer</span>
num_hidden_neurons <span style="color: #666666">=</span> [<span style="color: #666666">20</span>,<span style="color: #666666">10</span>]
num_hidden_layers <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(num_hidden_neurons)
<span style="color: #408080; font-style: italic"># Construct the network.</span>
<span style="color: #408080; font-style: italic"># tf.name_scope is used to group each step in the construction,</span>
<span style="color: #408080; font-style: italic"># just for a more organized visualization in TensorBoard</span>
<span style="color: #008000; font-weight: bold">with</span> tf<span style="color: #666666">.</span>name_scope(<span style="color: #BA2121">&#39;dnn&#39;</span>):
<span style="color: #408080; font-style: italic"># Input layer</span>
previous_layer <span style="color: #666666">=</span> x_tf
<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>(num_hidden_layers):
current_layer <span style="color: #666666">=</span> tf<span style="color: #666666">.</span>layers<span style="color: #666666">.</span>dense(previous_layer, num_hidden_neurons[l], name<span style="color: #666666">=</span><span style="color: #BA2121">&#39;hidden</span><span style="color: #BB6688; font-weight: bold">%d</span><span style="color: #BA2121">&#39;</span><span style="color: #666666">%</span>(l<span style="color: #666666">+1</span>), activation<span style="color: #666666">=</span>tf<span style="color: #666666">.</span>nn<span style="color: #666666">.</span>sigmoid)
previous_layer <span style="color: #666666">=</span> current_layer
<span style="color: #408080; font-style: italic"># Output layer</span>
dnn_output <span style="color: #666666">=</span> tf<span style="color: #666666">.</span>layers<span style="color: #666666">.</span>dense(previous_layer, <span style="color: #666666">1</span>, name<span style="color: #666666">=</span><span style="color: #BA2121">&#39;output&#39;</span>)
<span style="color: #408080; font-style: italic"># Define the cost function</span>
<span style="color: #008000; font-weight: bold">with</span> tf<span style="color: #666666">.</span>name_scope(<span style="color: #BA2121">&#39;cost&#39;</span>):
g_trial <span style="color: #666666">=</span> x_tf<span style="color: #666666">*</span>(<span style="color: #666666">1-</span>x_tf)<span style="color: #666666">*</span>dnn_output
d_g_trial <span style="color: #666666">=</span> tf<span style="color: #666666">.</span>gradients(g_trial,x_tf)
d2_g_trial <span style="color: #666666">=</span> tf<span style="color: #666666">.</span>gradients(d_g_trial,x_tf)
right_side <span style="color: #666666">=</span> (<span style="color: #666666">3*</span>x_tf <span style="color: #666666">+</span> x_tf<span style="color: #666666">**2</span>)<span style="color: #666666">*</span>tf<span style="color: #666666">.</span>exp(x_tf)
err <span style="color: #666666">=</span> tf<span style="color: #666666">.</span>square( <span style="color: #666666">-</span>d2_g_trial[<span style="color: #666666">0</span>] <span style="color: #666666">-</span> right_side)
cost <span style="color: #666666">=</span> tf<span style="color: #666666">.</span>reduce_sum(err, name <span style="color: #666666">=</span> <span style="color: #BA2121">&#39;cost&#39;</span>)
<span style="color: #408080; font-style: italic"># Choose the method to minimize the cost function, along with a learning rate</span>
learning_rate <span style="color: #666666">=</span> <span style="color: #666666">1e-2</span>
<span style="color: #008000; font-weight: bold">with</span> tf<span style="color: #666666">.</span>name_scope(<span style="color: #BA2121">&#39;train&#39;</span>):
optimizer <span style="color: #666666">=</span> tf<span style="color: #666666">.</span>train<span style="color: #666666">.</span>GradientDescentOptimizer(learning_rate)
traning_op <span style="color: #666666">=</span> optimizer<span style="color: #666666">.</span>minimize(cost)
g_dnn_tf <span style="color: #666666">=</span> <span style="color: #008000">None</span>
<span style="color: #408080; font-style: italic"># Define a node that initializes all of the other nodes in the computational graph</span>
<span style="color: #408080; font-style: italic"># used by TensorFlow:</span>
init <span style="color: #666666">=</span> tf<span style="color: #666666">.</span>global_variables_initializer()
<span style="color: #408080; font-style: italic">## Execution phase</span>
<span style="color: #408080; font-style: italic"># Start a session where the graph defined from the construction phase can be evaluated at:</span>
<span style="color: #008000; font-weight: bold">with</span> tf<span style="color: #666666">.</span>Session() <span style="color: #008000; font-weight: bold">as</span> sess:
<span style="color: #408080; font-style: italic"># Initialize the whole graph</span>
init<span style="color: #666666">.</span>run()
<span style="color: #408080; font-style: italic"># Evaluate the initial cost:</span>
<span style="color: #008000; font-weight: bold">print</span>(<span style="color: #BA2121">&#39;Initial cost: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&#39;</span><span style="color: #666666">%</span>cost<span style="color: #666666">.</span>eval())
<span style="color: #408080; font-style: italic"># The traning of the network:</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):
sess<span style="color: #666666">.</span>run(traning_op)
<span style="color: #408080; font-style: italic"># Training is done, and we have an approximate solution to the ODE</span>
<span style="color: #008000; font-weight: bold">print</span>(<span style="color: #BA2121">&#39;Final cost: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&#39;</span><span style="color: #666666">%</span>cost<span style="color: #666666">.</span>eval())
<span style="color: #408080; font-style: italic"># Store the result</span>
g_dnn_tf <span style="color: #666666">=</span> g_trial<span style="color: #666666">.</span>eval()
writer <span style="color: #666666">=</span> tf<span style="color: #666666">.</span>summary<span style="color: #666666">.</span>FileWriter(<span style="color: #BA2121">&quot;./output&quot;</span>, sess<span style="color: #666666">.</span>graph)
writer<span style="color: #666666">.</span>close()
<span style="color: #408080; font-style: italic"># Evaluate the analytical function to compare with</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)
g_analytical <span style="color: #666666">=</span> g_analytic(x)
diff_tf <span style="color: #666666">=</span> g_dnn_tf <span style="color: #666666">-</span> g_analytical<span style="color: #666666">.</span>reshape(<span style="color: #666666">-1</span>,<span style="color: #666666">1</span>)
<span style="color: #008000; font-weight: bold">print</span>(<span style="color: #BA2121">&#39;</span><span style="color: #BB6622; font-weight: bold">\n</span><span style="color: #BA2121">Max absolute difference between the analytical solution and solution from TensorFlow DNN: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&#39;</span><span style="color: #666666">%</span>np<span style="color: #666666">.</span>max(np<span style="color: #666666">.</span>abs(diff_tf)))
<span style="color: #408080; font-style: italic"># Plot the result</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">&#39;Numerical solutions of the ODE&#39;</span>)
plt<span style="color: #666666">.</span>plot(x, g_dnn_tf)
plt<span style="color: #666666">.</span>plot(x, g_analytical)
plt<span style="color: #666666">.</span>legend([<span style="color: #BA2121">&#39;dnn, tensorflow&#39;</span>,<span style="color: #BA2121">&#39;exact&#39;</span>])
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">&#39;x&#39;</span>)
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">&#39;g(x)&#39;</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">Using a different optimization algorithm implemented in TensorFlow to solve Poisson equation </h2>
<p>
We can see that the results using GradientDescentOptimizer seems to converge towards the analytical solution.
But there exists many other methods for optimization also, see <a href="https://www.tensorflow.org/versions/r1.2/api_guides/python/train#Optimizers" target="_blank">the TensorFlow documentation on Optimizers</a>.
<p>
Adam is an optimization algorithm that changes its learning rates accordingly to the function it tries to minimize for every iteration.
The algorithm is described in <a href="https://arxiv.org/pdf/1412.6980.pdf" target="_blank">this paper</a>.
How much an optimization algorithm has to say for the network to converge, could be interesting to experiment with.
Using the same TensorFlow program as before, the only change to do, is to replace the variable <em>optimizer</em>.
<p>
In the program that uses TensorFlow to solve for the Poisson equation, change the line
<p>
<!-- code=text typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span>optimizer = tf.train.GradientDescentOptimizer(learning_rate)
</pre></div>
<p>
to
<p>
<!-- code=text typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span>optimizer = tf.train.AdamOptimizer(learning_rate)
</pre></div>
<p>
The program using the Adam optimizer with a different initial learning rate yields indeed an interesting result:
<p>
<!-- code=text typeset with pygments style "default" -->
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%"><span></span>Max absolute difference between the analytical solution and solution from TensorFlow DNN: 7.11243e-05
</pre></div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec30">Partial Differential Equations </h2>
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>
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>
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>
If we let \( \vec 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:
$$
\begin{equation*}
c\left(\vec{x}, P\right) = f\left( \left( \vec{x}, \frac{\partial g(\vec x) }{\partial x_1}, \dots , \frac{\partial g(\vec x) }{\partial x_N}, \frac{\partial g(\vec x) }{\partial x_1\partial x_2}, \, \dots \, , \frac{\partial^n g(\vec x) }{\partial x_N^n} \right) \right)^2
\end{equation*}
$$
<p>
If we also have \( M \) different sets of values for \( x_1, \dots, x_N \), that is \( \vec{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( \vec{x}_i, \frac{\partial g(\vec{x}_i) }{\partial x_1}, \dots , \frac{\partial g(\vec{x}_i) }{\partial x_N}, \frac{\partial g(\vec{x}_i) }{\partial x_1\partial x_2}, \, \dots \, , \frac{\partial^n g(\vec{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="___sec31">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="___sec32">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="___sec33">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="___sec34">Setting up the network using Autograd; The trial solution </h2>
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>
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="___sec35">Setting up the network using Autograd; The full program </h2>
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>
Using only 20 neurons in one hidden layer, the program managed to make the trial solution have the maximum absolute error of 0.0075. The execution time, however, was approximately one day and 14 hours on a computer having Intel i7-7560U 2.4 GHz CPU.
<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 in the next example sovling the wave equation, has a much better execution time.
<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">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; font-weight: bold">print</span>(<span style="color: #BA2121">&#39;Initial cost: &#39;</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; font-weight: bold">print</span>(<span style="color: #BA2121">&#39;Final cost: &#39;</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">&#39;__main__&#39;</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; font-weight: bold">print</span>(<span style="color: #BA2121">&#39;Max absolute difference between the analytical solution and the network: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&#39;</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">&#39;3d&#39;</span>)
ax<span style="color: #666666">.</span>set_title(<span style="color: #BA2121">&#39;Solution from the deep neural network w/ </span><span style="color: #BB6688; font-weight: bold">%d</span><span style="color: #BA2121"> layer&#39;</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">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">&#39;Time $t$&#39;</span>)
ax<span style="color: #666666">.</span>set_ylabel(<span style="color: #BA2121">&#39;Position $x$&#39;</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">&#39;3d&#39;</span>)
ax<span style="color: #666666">.</span>set_title(<span style="color: #BA2121">&#39;Analytical solution&#39;</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">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">&#39;Time $t$&#39;</span>)
ax<span style="color: #666666">.</span>set_ylabel(<span style="color: #BA2121">&#39;Position $x$&#39;</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">&#39;3d&#39;</span>)
ax<span style="color: #666666">.</span>set_title(<span style="color: #BA2121">&#39;Difference&#39;</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">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">&#39;Time $t$&#39;</span>)
ax<span style="color: #666666">.</span>set_ylabel(<span style="color: #BA2121">&#39;Position $x$&#39;</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">&quot;Computed solutions at time = </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&quot;</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">&#39;dnn&#39;</span>,<span style="color: #BA2121">&#39;analytical&#39;</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">&quot;Computed solutions at time = </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&quot;</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">&#39;dnn&#39;</span>,<span style="color: #BA2121">&#39;analytical&#39;</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">&quot;Computed solutions at time = </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&quot;</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">&#39;dnn&#39;</span>,<span style="color: #BA2121">&#39;analytical&#39;</span>])
plt<span style="color: #666666">.</span>show()
</pre></div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec36">Example: Solving the wave equation using Autograd and TensorFlow </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="___sec37">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="___sec38">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="___sec39">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="___sec40">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">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; font-weight: bold">print</span>(<span style="color: #BA2121">&#39;Initial cost: &#39;</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; font-weight: bold">print</span>(<span style="color: #BA2121">&#39;Final cost: &#39;</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">&#39;__main__&#39;</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; font-weight: bold">print</span>(<span style="color: #BA2121">&quot;Max difference between analytical and solution from nn: </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&quot;</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">&#39;3d&#39;</span>)
ax<span style="color: #666666">.</span>set_title(<span style="color: #BA2121">&#39;Solution from the deep neural network w/ </span><span style="color: #BB6688; font-weight: bold">%d</span><span style="color: #BA2121"> layer&#39;</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">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">&#39;Time $t$&#39;</span>)
ax<span style="color: #666666">.</span>set_ylabel(<span style="color: #BA2121">&#39;Position $x$&#39;</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">&#39;3d&#39;</span>)
ax<span style="color: #666666">.</span>set_title(<span style="color: #BA2121">&#39;Analytical solution&#39;</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">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">&#39;Time $t$&#39;</span>)
ax<span style="color: #666666">.</span>set_ylabel(<span style="color: #BA2121">&#39;Position $x$&#39;</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">&#39;3d&#39;</span>)
ax<span style="color: #666666">.</span>set_title(<span style="color: #BA2121">&#39;Difference&#39;</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">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">&#39;Time $t$&#39;</span>)
ax<span style="color: #666666">.</span>set_ylabel(<span style="color: #BA2121">&#39;Position $x$&#39;</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">&quot;Computed solutions at time = </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&quot;</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">&#39;dnn&#39;</span>,<span style="color: #BA2121">&#39;analytical&#39;</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">&quot;Computed solutions at time = </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&quot;</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">&#39;dnn&#39;</span>,<span style="color: #BA2121">&#39;analytical&#39;</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">&quot;Computed solutions at time = </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&quot;</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">&#39;dnn&#39;</span>,<span style="color: #BA2121">&#39;analytical&#39;</span>])
plt<span style="color: #666666">.</span>show()
</pre></div>
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec41">Solving the wave equation - the full program using TensorFlow </h2>
As the program using Autograd is fairly slow, one could hope that using TensorFlow
could make a naive implementation faster, and more numerically robust.
<p>
In addition, having TensorFlow at hand, it could be easier to experiment with different
optimization algorithms, and other constructions of the network.
<p>
The following program solves the given wave equation much faster,
<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">tensorflow</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">tf</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">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
Nx <span style="color: #666666">=</span> <span style="color: #666666">10</span>
x_np <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)
Nt <span style="color: #666666">=</span> <span style="color: #666666">10</span>
t_np <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)
X,T <span style="color: #666666">=</span> np<span style="color: #666666">.</span>meshgrid(x_np, t_np)
x <span style="color: #666666">=</span> X<span style="color: #666666">.</span>ravel()
t <span style="color: #666666">=</span> T<span style="color: #666666">.</span>ravel()
<span style="color: #408080; font-style: italic">## The construction phase</span>
zeros <span style="color: #666666">=</span> tf<span style="color: #666666">.</span>reshape(tf<span style="color: #666666">.</span>convert_to_tensor(np<span style="color: #666666">.</span>zeros(x<span style="color: #666666">.</span>shape)),shape<span style="color: #666666">=</span>(<span style="color: #666666">-1</span>,<span style="color: #666666">1</span>))
x <span style="color: #666666">=</span> tf<span style="color: #666666">.</span>reshape(tf<span style="color: #666666">.</span>convert_to_tensor(x),shape<span style="color: #666666">=</span>(<span style="color: #666666">-1</span>,<span style="color: #666666">1</span>))
t <span style="color: #666666">=</span> tf<span style="color: #666666">.</span>reshape(tf<span style="color: #666666">.</span>convert_to_tensor(t),shape<span style="color: #666666">=</span>(<span style="color: #666666">-1</span>,<span style="color: #666666">1</span>))
points <span style="color: #666666">=</span> tf<span style="color: #666666">.</span>concat([x,t],<span style="color: #666666">1</span>)
num_iter <span style="color: #666666">=</span> <span style="color: #666666">100000</span>
num_hidden_neurons <span style="color: #666666">=</span> [<span style="color: #666666">90</span>]
X <span style="color: #666666">=</span> tf<span style="color: #666666">.</span>convert_to_tensor(X)
T <span style="color: #666666">=</span> tf<span style="color: #666666">.</span>convert_to_tensor(T)
<span style="color: #008000; font-weight: bold">with</span> tf<span style="color: #666666">.</span>variable_scope(<span style="color: #BA2121">&#39;dnn&#39;</span>):
num_hidden_layers <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(num_hidden_neurons)
previous_layer <span style="color: #666666">=</span> points
<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>(num_hidden_layers):
current_layer <span style="color: #666666">=</span> tf<span style="color: #666666">.</span>layers<span style="color: #666666">.</span>dense(previous_layer, num_hidden_neurons[l],activation<span style="color: #666666">=</span>tf<span style="color: #666666">.</span>nn<span style="color: #666666">.</span>sigmoid)
previous_layer <span style="color: #666666">=</span> current_layer
dnn_output <span style="color: #666666">=</span> tf<span style="color: #666666">.</span>layers<span style="color: #666666">.</span>dense(previous_layer, <span style="color: #666666">1</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> tf<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>tf<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">with</span> tf<span style="color: #666666">.</span>name_scope(<span style="color: #BA2121">&#39;loss&#39;</span>):
g_trial <span style="color: #666666">=</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: #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>dnn_output
g_trial_d2t <span style="color: #666666">=</span> tf<span style="color: #666666">.</span>gradients(tf<span style="color: #666666">.</span>gradients(g_trial,t),t)
g_trial_d2x <span style="color: #666666">=</span> tf<span style="color: #666666">.</span>gradients(tf<span style="color: #666666">.</span>gradients(g_trial,x),x)
loss <span style="color: #666666">=</span> tf<span style="color: #666666">.</span>losses<span style="color: #666666">.</span>mean_squared_error(zeros, g_trial_d2t[<span style="color: #666666">0</span>] <span style="color: #666666">-</span> g_trial_d2x[<span style="color: #666666">0</span>])
learning_rate <span style="color: #666666">=</span> <span style="color: #666666">0.01</span>
<span style="color: #008000; font-weight: bold">with</span> tf<span style="color: #666666">.</span>name_scope(<span style="color: #BA2121">&#39;train&#39;</span>):
optimizer <span style="color: #666666">=</span> tf<span style="color: #666666">.</span>train<span style="color: #666666">.</span>GradientDescentOptimizer(learning_rate)
traning_op <span style="color: #666666">=</span> optimizer<span style="color: #666666">.</span>minimize(loss)
init <span style="color: #666666">=</span> tf<span style="color: #666666">.</span>global_variables_initializer()
g_analytic <span style="color: #666666">=</span> tf<span style="color: #666666">.</span>sin(np<span style="color: #666666">.</span>pi<span style="color: #666666">*</span>x)<span style="color: #666666">*</span>tf<span style="color: #666666">.</span>cos(np<span style="color: #666666">.</span>pi<span style="color: #666666">*</span>t) <span style="color: #666666">-</span> tf<span style="color: #666666">.</span>sin(np<span style="color: #666666">.</span>pi<span style="color: #666666">*</span>x)<span style="color: #666666">*</span>tf<span style="color: #666666">.</span>sin(np<span style="color: #666666">.</span>pi<span style="color: #666666">*</span>t)
g_dnn <span style="color: #666666">=</span> <span style="color: #008000">None</span>
<span style="color: #408080; font-style: italic">## The execution phase</span>
<span style="color: #008000; font-weight: bold">with</span> tf<span style="color: #666666">.</span>Session() <span style="color: #008000; font-weight: bold">as</span> sess:
init<span style="color: #666666">.</span>run()
<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):
sess<span style="color: #666666">.</span>run(traning_op)
<span style="color: #408080; font-style: italic"># If one desires to see how the cost function behaves during training</span>
<span style="color: #408080; font-style: italic">#if i % 100 == 0:</span>
<span style="color: #408080; font-style: italic"># print(loss.eval())</span>
g_analytic <span style="color: #666666">=</span> g_analytic<span style="color: #666666">.</span>eval()
g_dnn <span style="color: #666666">=</span> g_trial<span style="color: #666666">.</span>eval()
<span style="color: #408080; font-style: italic">## Compare with the analutical solution</span>
diff <span style="color: #666666">=</span> np<span style="color: #666666">.</span>abs(g_analytic <span style="color: #666666">-</span> g_dnn)
<span style="color: #008000; font-weight: bold">print</span>(<span style="color: #BA2121">&#39;Max absolute difference between analytical solution and TensorFlow DNN = &#39;</span>,np<span style="color: #666666">.</span>max(diff))
G_analytic <span style="color: #666666">=</span> g_analytic<span style="color: #666666">.</span>reshape((Nt,Nx))
G_dnn <span style="color: #666666">=</span> g_dnn<span style="color: #666666">.</span>reshape((Nt,Nx))
diff <span style="color: #666666">=</span> np<span style="color: #666666">.</span>abs(G_analytic <span style="color: #666666">-</span> G_dnn)
<span style="color: #408080; font-style: italic"># Plot the results</span>
X,T <span style="color: #666666">=</span> np<span style="color: #666666">.</span>meshgrid(x_np, t_np)
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">&#39;3d&#39;</span>)
ax<span style="color: #666666">.</span>set_title(<span style="color: #BA2121">&#39;Solution from the deep neural network w/ </span><span style="color: #BB6688; font-weight: bold">%d</span><span style="color: #BA2121"> layer&#39;</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(X,T,G_dnn,linewidth<span style="color: #666666">=0</span>,antialiased<span style="color: #666666">=</span><span style="color: #008000">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">&#39;Time $t$&#39;</span>)
ax<span style="color: #666666">.</span>set_ylabel(<span style="color: #BA2121">&#39;Position $x$&#39;</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">&#39;3d&#39;</span>)
ax<span style="color: #666666">.</span>set_title(<span style="color: #BA2121">&#39;Analytical solution&#39;</span>)
s <span style="color: #666666">=</span> ax<span style="color: #666666">.</span>plot_surface(X,T,G_analytic,linewidth<span style="color: #666666">=0</span>,antialiased<span style="color: #666666">=</span><span style="color: #008000">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">&#39;Time $t$&#39;</span>)
ax<span style="color: #666666">.</span>set_ylabel(<span style="color: #BA2121">&#39;Position $x$&#39;</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">&#39;3d&#39;</span>)
ax<span style="color: #666666">.</span>set_title(<span style="color: #BA2121">&#39;Difference&#39;</span>)
s <span style="color: #666666">=</span> ax<span style="color: #666666">.</span>plot_surface(X,T,diff,linewidth<span style="color: #666666">=0</span>,antialiased<span style="color: #666666">=</span><span style="color: #008000">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">&#39;Time $t$&#39;</span>)
ax<span style="color: #666666">.</span>set_ylabel(<span style="color: #BA2121">&#39;Position $x$&#39;</span>);
<span style="color: #408080; font-style: italic">## Take some 3D slices</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_np[indx1]
t2 <span style="color: #666666">=</span> t_np[indx2]
t3 <span style="color: #666666">=</span> t_np[indx3]
<span style="color: #408080; font-style: italic"># Slice the results from the DNN</span>
res1 <span style="color: #666666">=</span> G_dnn[indx1,:]
res2 <span style="color: #666666">=</span> G_dnn[indx2,:]
res3 <span style="color: #666666">=</span> G_dnn[indx3,:]
<span style="color: #408080; font-style: italic"># Slice the analytical results</span>
res_analytical1 <span style="color: #666666">=</span> G_analytic[indx1,:]
res_analytical2 <span style="color: #666666">=</span> G_analytic[indx2,:]
res_analytical3 <span style="color: #666666">=</span> G_analytic[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">&quot;Computed solutions at time = </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&quot;</span><span style="color: #666666">%</span>t1)
plt<span style="color: #666666">.</span>plot(x_np, res1)
plt<span style="color: #666666">.</span>plot(x_np,res_analytical1)
plt<span style="color: #666666">.</span>legend([<span style="color: #BA2121">&#39;dnn&#39;</span>,<span style="color: #BA2121">&#39;analytical&#39;</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">&quot;Computed solutions at time = </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&quot;</span><span style="color: #666666">%</span>t2)
plt<span style="color: #666666">.</span>plot(x_np, res2)
plt<span style="color: #666666">.</span>plot(x_np,res_analytical2)
plt<span style="color: #666666">.</span>legend([<span style="color: #BA2121">&#39;dnn&#39;</span>,<span style="color: #BA2121">&#39;analytical&#39;</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">&quot;Computed solutions at time = </span><span style="color: #BB6688; font-weight: bold">%g</span><span style="color: #BA2121">&quot;</span><span style="color: #666666">%</span>t3)
plt<span style="color: #666666">.</span>plot(x_np, res3)
plt<span style="color: #666666">.</span>plot(x_np,res_analytical3)
plt<span style="color: #666666">.</span>legend([<span style="color: #BA2121">&#39;dnn&#39;</span>,<span style="color: #BA2121">&#39;analytical&#39;</span>])
plt<span style="color: #666666">.</span>show()
</pre></div>
<p>
The program manages to find a solution having max absolute difference to the analytical
at approximately 0.0059, by just using some minutes!
It was found, by some testing, that one hidden layer with 90 neurons actually performed well.
<p>
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
<h2 id="___sec42">Resources </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. Tveitio, R. Winther</a></li>
</ol>
<!-- ------------------- end of main content --------------- -->
</body>
</html>