Skip to content
GitLab
Explore
Sign in
Primary navigation
Search or go to…
Project
V
VarBV-2020
Manage
Activity
Members
Labels
Plan
Issues
Issue boards
Milestones
Wiki
Code
Merge requests
Repository
Branches
Commits
Tags
Repository graph
Compare revisions
Snippets
Build
Pipelines
Jobs
Pipeline schedules
Artifacts
Deploy
Releases
Container registry
Model registry
Operate
Environments
Monitor
Incidents
Service Desk
Analyze
Value stream analytics
Contributor analytics
CI/CD analytics
Repository analytics
Model experiments
Help
Help
Support
GitLab documentation
Compare GitLab plans
GitLab community forum
Contribute to GitLab
Provide feedback
Terms and privacy
Keyboard shortcuts
?
Snippets
Groups
Projects
This is an archived project. Repository and other project resources are read-only.
Show more breadcrumbs
Benjamin Berkels
VarBV-2020
Commits
708b7580
Commit
708b7580
authored
5 years ago
by
Benjamin Berkels
Browse files
Options
Downloads
Patches
Plain Diff
Upload New File
parent
9d6ac53f
Branches
Branches containing commit
No related tags found
No related merge requests found
Changes
1
Show whitespace changes
Inline
Side-by-side
Showing
1 changed file
ex5.ipynb
+326
-0
326 additions, 0 deletions
ex5.ipynb
with
326 additions
and
0 deletions
ex5.ipynb
0 → 100644
+
326
−
0
View file @
708b7580
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## IPython notebook for exercise sheet 5"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Import all Python libraries we will need"
]
},
{
"cell_type": "code",
"metadata": {},
"source": [
"%matplotlib inline\n",
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"from scipy import sparse\n",
"import scipy.sparse.linalg\n",
"from IPython.display import set_matplotlib_formats, display, Math\n",
"set_matplotlib_formats('svg')\n"
],
"outputs": [],
"execution_count": null
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Gradient descent with Armijo rule"
]
},
{
"cell_type": "code",
"metadata": {},
"source": [
"def GradientDescent(x0, E, DE, beta, sigma, maxIter, stopEpsilon, inverseSPMatrix=None):\n",
"\n",
" def ArmijoRule(x, initialTau, beta, sigma, energy, descentDir, gradientAtX, E):\n",
"\n",
" tangentSlope = np.dot(descentDir.ravel(), gradientAtX.ravel())\n",
"\n",
" def ArmijoCondition(tau):\n",
" secantSlope = (E(x + tau * descentDir) - energy)/tau\n",
" cond = (secantSlope / tangentSlope) >= sigma\n",
" return cond\n",
"\n",
" tauMin = 0.000001\n",
" tauMax = 100000\n",
" tau = max(min(initialTau, tauMax), tauMin)\n",
"\n",
" condition = ArmijoCondition(tau)\n",
" if condition:\n",
" while (condition and (tau < tauMax)):\n",
" tau = tau / beta\n",
" condition = ArmijoCondition(tau)\n",
"\n",
" tau = beta * tau\n",
" else:\n",
" while ((not condition) and (tau > tauMin)):\n",
" tau = beta * tau\n",
" condition = ArmijoCondition(tau)\n",
"\n",
" return tau\n",
"\n",
" x = x0\n",
" energyNew = E(x)\n",
" tau = 1\n",
"\n",
" print('Initial energy {:.6f}'.format(energyNew))\n",
" for i in range(maxIter):\n",
" energy = energyNew\n",
" gradient = DE(x)\n",
" descentDir = - gradient\n",
" if (inverseSPMatrix is not None):\n",
" descentDir = inverseSPMatrix * descentDir\n",
"\n",
" tau = ArmijoRule(x, tau, beta, sigma, energy, descentDir, gradient, E)\n",
" x = x + tau * descentDir\n",
" energyNew = E(x)\n",
"\n",
" print('{} steps, tau: {:.6f} energy {:.6f}'.format(i+1, tau, energyNew))\n",
"\n",
" if ((energy - energyNew) < stopEpsilon):\n",
" break\n",
"\n",
" return x\n"
],
"outputs": [],
"execution_count": null
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$J_a[x]=\\sum_{i=1}^n(x_i-f_i)^2+\\lambda\\sum_{i=1}^{n-1}\\frac1{h^2}(x_{i+1}-x_i)^2$$"
]
},
{
"cell_type": "code",
"metadata": {},
"source": [
"def Ja(x, f, h, lambda_):\n",
" energy = np.sum(np.square(x - f)) + lambda_ / h**2 * np.sum(np.square(x[1:]-x[0:-1]))\n",
" return energy\n",
"\n",
"\n",
"def DJa(x, f, h, lambda_):\n",
" grad = 2 * (x - f)\n",
" grad[0:-1] = grad[0:-1] - 2 * lambda_ / h**2 * (x[1:]-x[0:-1])\n",
" grad[1:] = grad[1:] - 2 * lambda_ / h**2 * (x[0:-1] - x[1:])\n",
" return grad\n"
],
"outputs": [],
"execution_count": null
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"$$J_b[x]=\\sum_{i=1}^n(x_i-f_i)^2+\\lambda\\sum_{i=1}^{n-1}\\frac1{h}\\left\\vert x_{i+1}-x_i\\right\\vert_\\epsilon.$$"
]
},
{
"cell_type": "code",
"metadata": {},
"source": [
"def Jb(x, f, h, lambda_, epsilon):\n",
" energy = np.sum(np.square(x - f)) + lambda_ / h * np.sum(np.sqrt(np.square(x[1:] - x[0:-1]) + epsilon**2))\n",
" return energy\n",
"\n",
"\n",
"def DJb(x, f, h, lambda_, epsilon):\n",
" grad = 2 * (x - f)\n",
" grad[0:-1] = grad[0:-1] - lambda_ / h * np.divide(x[1:] - x[0:-1], np.sqrt(np.square(x[1:] - x[0:-1]) + epsilon**2))\n",
" grad[1:] = grad[1:] - lambda_ / h * np.divide(x[0:-1] - x[1:], np.sqrt(np.square(x[0:-1] - x[1:]) + epsilon**2))\n",
" return grad\n"
],
"outputs": [],
"execution_count": null
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Create a noisy input signal"
]
},
{
"cell_type": "code",
"metadata": {},
"source": [
"N = 200\n",
"coords = np.linspace(0, 2*np.pi, N)\n",
"f0 = np.sin(coords)\n",
"np.random.seed(42)\n",
"f = f0 + 0.2 * (np.random.rand(coords.size) - 0.5)\n",
"x0 = f\n",
"plt.plot(coords, f, label='f')\n",
"plt.plot(coords, f0, label='f0')\n",
"plt.legend()\n",
"plt.show()"
],
"outputs": [],
"execution_count": null
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Set parameters"
]
},
{
"cell_type": "code",
"metadata": {},
"source": [
"lambda_ = 0.005\n",
"sigma = 0.5\n",
"beta = 0.5\n",
"h = 1/(N - 1)\n",
"epsilon = .001"
],
"outputs": [],
"execution_count": null
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Minimize $J_a$ using gradient descent."
]
},
{
"cell_type": "code",
"metadata": {},
"source": [
"def Ea(x): return Ja(x, f, h, lambda_)\n",
"def DEa(x): return DJa(x, f, h, lambda_)\n",
"xa = GradientDescent(x0, Ea, DEa, beta, sigma, 1000, 0.001)\n",
"plt.plot(coords, xa, label='xa')\n",
"plt.legend()\n",
"plt.show()"
],
"outputs": [],
"execution_count": null
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Minimize $J_b$ using gradient descent."
]
},
{
"cell_type": "code",
"metadata": {},
"source": [
"def Eb(x): return Jb(x, f, h, lambda_, epsilon)\n",
"def DEb(x): return DJb(x, f, h, lambda_, epsilon)\n",
"xb = GradientDescent(x0, Eb, DEb, beta, sigma, 1000, 0.001)\n",
"plt.plot(coords, xb, label='xb')\n",
"plt.legend()\n",
"plt.show()"
],
"outputs": [],
"execution_count": null
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Minimize $J_a$ the system of linear equations"
]
},
{
"cell_type": "code",
"metadata": {},
"source": [
"L = 1/h * sparse.csr_matrix(sparse.diags([-1, 1], [0, 1], shape=(N, N)))\n",
"L[N-1, N-1] = 0\n",
"identityMatrix = sparse.eye(N)\n",
"A = identityMatrix + lambda_*L.transpose()*L\n",
"# For such a low number of unknowns, computing the inverse is fine.\n",
"invA = scipy.sparse.linalg.inv(sparse.csc_matrix(A))\n",
"xaLE = invA*x0\n",
"plt.plot(coords, xaLE, label='xaLE')\n",
"plt.legend()\n",
"plt.show()"
],
"outputs": [],
"execution_count": null
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Minimize $J_a$ using gradient flow."
]
},
{
"cell_type": "code",
"metadata": {},
"source": [
"# Use a small sigma here to get the optimal tau in this case.\n",
"xaG = GradientDescent(x0, Ea, DEa, beta, 0.1, 1000, 0.001, invA)\n",
"plt.plot(coords, xaG, label='xaG')\n",
"plt.legend()\n",
"plt.show()"
],
"outputs": [],
"execution_count": null
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Plot all results in one figure."
]
},
{
"cell_type": "code",
"metadata": {},
"source": [
"plt.plot(coords, xa, label='xa')\n",
"plt.plot(coords, xaLE, label='xaLE')\n",
"plt.plot(coords, xaG, label='xaG')\n",
"plt.plot(coords, xb, label='xb')\n",
"plt.plot(coords, f, label='f')\n",
"plt.plot(coords, f0, label='f0')\n",
"plt.legend()\n",
"plt.show()\n"
],
"outputs": [],
"execution_count": null
}
],
"metadata": {
"anaconda-cloud": {},
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.1"
}
},
"nbformat": 4,
"nbformat_minor": 1
}
\ No newline at end of file
%% Cell type:markdown id: tags:
## IPython notebook for exercise sheet 5
%% Cell type:markdown id: tags:
### Import all Python libraries we will need
%% Cell type:code id: tags:
```
python
%
matplotlib
inline
import
numpy
as
np
import
matplotlib.pyplot
as
plt
from
scipy
import
sparse
import
scipy.sparse.linalg
from
IPython.display
import
set_matplotlib_formats
,
display
,
Math
set_matplotlib_formats
(
'
svg
'
)
```
%% Cell type:markdown id: tags:
### Gradient descent with Armijo rule
%% Cell type:code id: tags:
```
python
def
GradientDescent
(
x0
,
E
,
DE
,
beta
,
sigma
,
maxIter
,
stopEpsilon
,
inverseSPMatrix
=
None
):
def
ArmijoRule
(
x
,
initialTau
,
beta
,
sigma
,
energy
,
descentDir
,
gradientAtX
,
E
):
tangentSlope
=
np
.
dot
(
descentDir
.
ravel
(),
gradientAtX
.
ravel
())
def
ArmijoCondition
(
tau
):
secantSlope
=
(
E
(
x
+
tau
*
descentDir
)
-
energy
)
/
tau
cond
=
(
secantSlope
/
tangentSlope
)
>=
sigma
return
cond
tauMin
=
0.000001
tauMax
=
100000
tau
=
max
(
min
(
initialTau
,
tauMax
),
tauMin
)
condition
=
ArmijoCondition
(
tau
)
if
condition
:
while
(
condition
and
(
tau
<
tauMax
)):
tau
=
tau
/
beta
condition
=
ArmijoCondition
(
tau
)
tau
=
beta
*
tau
else
:
while
((
not
condition
)
and
(
tau
>
tauMin
)):
tau
=
beta
*
tau
condition
=
ArmijoCondition
(
tau
)
return
tau
x
=
x0
energyNew
=
E
(
x
)
tau
=
1
print
(
'
Initial energy {:.6f}
'
.
format
(
energyNew
))
for
i
in
range
(
maxIter
):
energy
=
energyNew
gradient
=
DE
(
x
)
descentDir
=
-
gradient
if
(
inverseSPMatrix
is
not
None
):
descentDir
=
inverseSPMatrix
*
descentDir
tau
=
ArmijoRule
(
x
,
tau
,
beta
,
sigma
,
energy
,
descentDir
,
gradient
,
E
)
x
=
x
+
tau
*
descentDir
energyNew
=
E
(
x
)
print
(
'
{} steps, tau: {:.6f} energy {:.6f}
'
.
format
(
i
+
1
,
tau
,
energyNew
))
if
((
energy
-
energyNew
)
<
stopEpsilon
):
break
return
x
```
%% Cell type:markdown id: tags:
$$J_a[x]=
\s
um_{i=1}^n(x_i-f_i)^2+
\l
ambda
\s
um_{i=1}^{n-1}
\f
rac1{h^2}(x_{i+1}-x_i)^2$$
%% Cell type:code id: tags:
```
python
def
Ja
(
x
,
f
,
h
,
lambda_
):
energy
=
np
.
sum
(
np
.
square
(
x
-
f
))
+
lambda_
/
h
**
2
*
np
.
sum
(
np
.
square
(
x
[
1
:]
-
x
[
0
:
-
1
]))
return
energy
def
DJa
(
x
,
f
,
h
,
lambda_
):
grad
=
2
*
(
x
-
f
)
grad
[
0
:
-
1
]
=
grad
[
0
:
-
1
]
-
2
*
lambda_
/
h
**
2
*
(
x
[
1
:]
-
x
[
0
:
-
1
])
grad
[
1
:]
=
grad
[
1
:]
-
2
*
lambda_
/
h
**
2
*
(
x
[
0
:
-
1
]
-
x
[
1
:])
return
grad
```
%% Cell type:markdown id: tags:
$$J_b[x]=
\s
um_{i=1}^n(x_i-f_i)^2+
\l
ambda
\s
um_{i=1}^{n-1}
\f
rac1{h}
\l
eft
\v
ert x_{i+1}-x_i
\r
ight
\v
ert_
\e
psilon.$$
%% Cell type:code id: tags:
```
python
def
Jb
(
x
,
f
,
h
,
lambda_
,
epsilon
):
energy
=
np
.
sum
(
np
.
square
(
x
-
f
))
+
lambda_
/
h
*
np
.
sum
(
np
.
sqrt
(
np
.
square
(
x
[
1
:]
-
x
[
0
:
-
1
])
+
epsilon
**
2
))
return
energy
def
DJb
(
x
,
f
,
h
,
lambda_
,
epsilon
):
grad
=
2
*
(
x
-
f
)
grad
[
0
:
-
1
]
=
grad
[
0
:
-
1
]
-
lambda_
/
h
*
np
.
divide
(
x
[
1
:]
-
x
[
0
:
-
1
],
np
.
sqrt
(
np
.
square
(
x
[
1
:]
-
x
[
0
:
-
1
])
+
epsilon
**
2
))
grad
[
1
:]
=
grad
[
1
:]
-
lambda_
/
h
*
np
.
divide
(
x
[
0
:
-
1
]
-
x
[
1
:],
np
.
sqrt
(
np
.
square
(
x
[
0
:
-
1
]
-
x
[
1
:])
+
epsilon
**
2
))
return
grad
```
%% Cell type:markdown id: tags:
### Create a noisy input signal
%% Cell type:code id: tags:
```
python
N
=
200
coords
=
np
.
linspace
(
0
,
2
*
np
.
pi
,
N
)
f0
=
np
.
sin
(
coords
)
np
.
random
.
seed
(
42
)
f
=
f0
+
0.2
*
(
np
.
random
.
rand
(
coords
.
size
)
-
0.5
)
x0
=
f
plt
.
plot
(
coords
,
f
,
label
=
'
f
'
)
plt
.
plot
(
coords
,
f0
,
label
=
'
f0
'
)
plt
.
legend
()
plt
.
show
()
```
%% Cell type:markdown id: tags:
### Set parameters
%% Cell type:code id: tags:
```
python
lambda_
=
0.005
sigma
=
0.5
beta
=
0.5
h
=
1
/
(
N
-
1
)
epsilon
=
.
001
```
%% Cell type:markdown id: tags:
### Minimize $J_a$ using gradient descent.
%% Cell type:code id: tags:
```
python
def
Ea
(
x
):
return
Ja
(
x
,
f
,
h
,
lambda_
)
def
DEa
(
x
):
return
DJa
(
x
,
f
,
h
,
lambda_
)
xa
=
GradientDescent
(
x0
,
Ea
,
DEa
,
beta
,
sigma
,
1000
,
0.001
)
plt
.
plot
(
coords
,
xa
,
label
=
'
xa
'
)
plt
.
legend
()
plt
.
show
()
```
%% Cell type:markdown id: tags:
### Minimize $J_b$ using gradient descent.
%% Cell type:code id: tags:
```
python
def
Eb
(
x
):
return
Jb
(
x
,
f
,
h
,
lambda_
,
epsilon
)
def
DEb
(
x
):
return
DJb
(
x
,
f
,
h
,
lambda_
,
epsilon
)
xb
=
GradientDescent
(
x0
,
Eb
,
DEb
,
beta
,
sigma
,
1000
,
0.001
)
plt
.
plot
(
coords
,
xb
,
label
=
'
xb
'
)
plt
.
legend
()
plt
.
show
()
```
%% Cell type:markdown id: tags:
### Minimize $J_a$ the system of linear equations
%% Cell type:code id: tags:
```
python
L
=
1
/
h
*
sparse
.
csr_matrix
(
sparse
.
diags
([
-
1
,
1
],
[
0
,
1
],
shape
=
(
N
,
N
)))
L
[
N
-
1
,
N
-
1
]
=
0
identityMatrix
=
sparse
.
eye
(
N
)
A
=
identityMatrix
+
lambda_
*
L
.
transpose
()
*
L
# For such a low number of unknowns, computing the inverse is fine.
invA
=
scipy
.
sparse
.
linalg
.
inv
(
sparse
.
csc_matrix
(
A
))
xaLE
=
invA
*
x0
plt
.
plot
(
coords
,
xaLE
,
label
=
'
xaLE
'
)
plt
.
legend
()
plt
.
show
()
```
%% Cell type:markdown id: tags:
### Minimize $J_a$ using gradient flow.
%% Cell type:code id: tags:
```
python
# Use a small sigma here to get the optimal tau in this case.
xaG
=
GradientDescent
(
x0
,
Ea
,
DEa
,
beta
,
0.1
,
1000
,
0.001
,
invA
)
plt
.
plot
(
coords
,
xaG
,
label
=
'
xaG
'
)
plt
.
legend
()
plt
.
show
()
```
%% Cell type:markdown id: tags:
### Plot all results in one figure.
%% Cell type:code id: tags:
```
python
plt
.
plot
(
coords
,
xa
,
label
=
'
xa
'
)
plt
.
plot
(
coords
,
xaLE
,
label
=
'
xaLE
'
)
plt
.
plot
(
coords
,
xaG
,
label
=
'
xaG
'
)
plt
.
plot
(
coords
,
xb
,
label
=
'
xb
'
)
plt
.
plot
(
coords
,
f
,
label
=
'
f
'
)
plt
.
plot
(
coords
,
f0
,
label
=
'
f0
'
)
plt
.
legend
()
plt
.
show
()
```
This diff is collapsed.
Click to expand it.
Preview
0%
Loading
Try again
or
attach a new file
.
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Save comment
Cancel
Please
register
or
sign in
to comment