added dot files

This commit is contained in:
mhjensen
2020-11-22 21:49:09 +01:00
parent 1a7020d3ae
commit ee6fd7d9a0
8 changed files with 1623 additions and 0 deletions
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,255 @@
TITLE: Project 2 on Machine Learning, deadline November 13 (Midnight)
AUTHOR: "Data Analysis and Machine Learning FYS-STK3155/FYS4155":"http://www.uio.no/studier/emner/matnat/fys/FYS3155/index-eng.html" {copyright, 1999-present|CC BY-NC} at Department of Physics, University of Oslo, Norway
DATE: today
===== Classification and Regression, from linear and logistic regression to neural networks =====
The main aim of this project is to study both classification and
regression problems by developing our own feed-forward neural network (FFNN) code. We can reuse the regression algorithms studied
in project 1. We will also include logistic regression for classification
problems and write our own FFNN code for studying
both regression and classification problems. The codes developed in
project 1, including bootstrap and/or cross-validation as well as the
computation of the mean-squared error and/or the $R2$ or the accuracy score (classification problems) functions can
also be utilized in the present analysis.
The data sets that we propose here are (the default sets)
* Regression (fitting a continuous function). In this part you will need to bring back your results from project 1 and compare these with what you get from your Neural Network code to be developed here. The data sets could be
o Either the Franke function or the terrain data from project 1, or data sets your propose.
* Classification. Here you will also need to develop a Logistic regression code that you will use to compare with the Neural Network code. The data set we propose are the so-called "MNIST":"https://en.wikipedia.org/wiki/MNIST_database" data set of images representing hand-written numbers from zero to nine. These are discussed intensively in the lecture notes on neural networks, see for example the slides from "week 41":"https://compphysics.github.io/MachineLearning/doc/pub/week41/html/week41.html"
However, if you would like to study other data sets, feel free to
propose other sets. What we listed here are mere suggestions from our
side. If you opt for another data set, consider using a set which
has been studied in the scientific literature. This makes it easier
for you to compare and analyze your results. Comparing with existing results from the scientific literature is also an essential
element of the scientific discussion.
In particular, when developing your own Neural Network and Logistic Regression codes for classification problems, the so-called Wisconsin Cancer data (which is a binary problem, benign or malignant tumors) may be studied. You can find more information about this at the "Scikit-Learn site":"https://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_breast_cancer.html" or at the "University of California at Irvine":"https://archive.ics.uci.edu/ml/datasets/breast+cancer+wisconsin+(original)".
We will start with a regression problem and we will reuse our codes from project 1 starting with writing our own Stochastic Gradient Descent (SGD) code.
=== Part a): Write your own Stochastic Gradient Descent code, first step ===
In order to get started, we will now replace in our standard ordinary
least squares (OLS) and Ridge regression codes (from project 1) the matrix inversion
algorithm with our own SGD code. You can choose whether you want to
add the momentum SGD optionality or other SGD variants such as RMSprop
or ADAgrad. The lecture notes from "week 40 contain more
details":"https://compphysics.github.io/MachineLearning/doc/pub/week40/html/week40.html"
Perform an analysis of the results for OLS and Ridge regression as
function of the chosen learning rates, the number of mini-batches and
epochs as well as algorithm for scaling the learning rate. You can
also compare your own results with those that can be obtained using
for example _Scikit-Learn_'s various SGD options. Discuss your
results. For Ridge regression you need now to study the results as functions of the hyper-parameter $\lambda$ and
the learning rate $\gamma$. Discuss your results.
You will need your SGD code for the setup of the Neural Network and Logistic Regression codes.
=== Part b): Writing your own Neural Network code ===
Your aim now, and this is the central part of this project, is to
write your own Feed Forward Neural Network code implementing the back
propagation algorithm discussed in the lecture slides from "week 41":"https://compphysics.github.io/MachineLearning/doc/pub/week41/html/week41.html".
We will focus on a regression problem first and study either the
Franke function or terrain data (or both or other data sets) from
project 1. Discuss again your choice of cost function.
Write an FFNN code for regression with a flexible number of hidden
layers and nodes using the Sigmoid function as activation function for
the hidden layers. Initialize the weights using a normal
distribution. How would you initialize the biases? And which
activation function would you select for the final output layer?
Train your network and compare the results with those from your OLS and Ridge Regression codes from project 1.
You should test your results against a similar code using _Scikit-Learn_ (see the examples in the above lecture notes from week 41) or _tensorflow/keras_.
Comment your results and give a critical discussion of the results
obtained with the Linear Regression code and your own Neural Network
code. Compare the results with those from project 1.
Make an analysis of the regularization parameters and the learning rates employed to find the optimal MSE and $R2$ scores.
A useful reference on the back progagation algorithm is "Nielsen's
book":"http://neuralnetworksanddeeplearning.com/". It is an excellent
read.
=== Part c): Testing different activation functions ===
You should now also test different activation functions for the hidden layers. Try out the Sigmoid, the RELU and the Leaky RELU functions and discuss your results. You may also study the way you initialize your weights and biases.
=== Part d): Classification analysis using neural networks ===
With a well-written code it should now be easy to change the
activation function for the output layer.
Here we will change the cost function for our neural network code
developed in parts b) and c) in order to perform a classification analysis.
We will here study the MNIST data set of hand-written numbers as
discussed in the lecture notes from "week
41":"https://compphysics.github.io/MachineLearning/doc/pub/week41/html/week41.html". Use
the _Softmax_ function as activation function. Your code should
however also be able to use a binary activation function as well.
To measure the performance of our classification problem we use the
so-called *accuracy* score. The accuracy is as you would expect just
the number of correctly guessed targets $t_i$ divided by the total
number of targets, that is
!bt
\[
\text{Accuracy} = \frac{\sum_{i=1}^n I(t_i = y_i)}{n} ,
\]
!et
where $I$ is the indicator function, $1$ if $t_i = y_i$ and $0$
otherwise if we have a binary classification problem. Here $t_i$
represents the target and $y_i$ the outputs of your FFNN code and $n$ is simply the number of targets $t_i$.
Discuss your results and give a critical analysis of the various parameters, including hyper-parameters like the learning rates and the regularization parameter $\lambda$ (as you did in Ridge Regression), various activation functions, number of hidden layers and nodes and activation functions.
As stated in the introduction, it can also be useful to study other
datasets. In particular, the so-called Wisconsin Cancer
data (which is a binary problem, benign or malignant tumors) may be
studied. You find more information about this at the "Scikit-Learn
site":"https://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_breast_cancer.html" or at the "University of California
at Irvine":"https://archive.ics.uci.edu/ml/datasets/breast+cancer+wisconsin+(original)".
Again, we strongly recommend that you compare your own neural Network
code for classification and pertinent results against a similar code using _Scikit-Learn_ or _tensorflow/keras_ or _pytorch_.
=== Part e): Write your Logistic Regression code, final step ===
Finally, we want to compare the FFNN code we have developed with
Logistic regression, that is we wish to compare our neural network
classification results with the results we can obtain with another
method.
Define your cost function and the design matrix before you start writing your code.
Write thereafter a Logistic regression code using your SGD algorithm. Study the results as functions of the chosen learning rates.
Add also an $l_2$ regularization parameter $\lambda$. Compare your results with those from your FFNN code as well as those obtained using _Scikit-Learn_'s logistic regression functionality.
The weblink here URL:"https://medium.com/ai-in-plain-english/comparison-between-logistic-regression-and-neural-networks-in-classifying-digits-dc5e85cd93c3"compares logistic regression and FFNN using the MNIST data set. You may find several useful hints and ideas from this article.
=== Part f) Critical evaluation of the various algorithms ===
After all these glorious calculations, you should now summarize the
various algorithms and come with a critical evaluation of their pros
and cons. Which algorithm works best for the regression case and which
is best for the classification case. These codes can also be part of
your final project 3, but now applied to other data sets.
===== Background literature =====
o The text of Michael Nielsen is highly recommended, see "Nielsen's book":"http://neuralnetworksanddeeplearning.com/". It is an excellent read.
o The textbook of "Trevor Hastie, Robert Tibshirani, Jerome H. Friedman, The Elements of Statistical Learning, Springer":"https://www.springer.com/gp/book/9780387848570", chapters 3 and 7 are the most relevant ones for the analysis here.
o "Mehta et al, arXiv 1803.08823":"https://arxiv.org/abs/1803.08823", *A high-bias, low-variance introduction to Machine Learning for physicists*, ArXiv:1803.08823.
===== Introduction to numerical projects =====
Here follows a brief recipe and recommendation on how to write a report for each
project.
* Give a short description of the nature of the problem and the eventual numerical methods you have used.
* Describe the algorithm you have used and/or developed. Here you may find it convenient to use pseudocoding. In many cases you can describe the algorithm in the program itself.
* Include the source code of your program. Comment your program properly.
* If possible, try to find analytic solutions, or known limits in order to test your program when developing the code.
* Include your results either in figure form or in a table. Remember to label your results. All tables and figures should have relevant captions and labels on the axes.
* Try to evaluate the reliabilty and numerical stability/precision of your results. If possible, include a qualitative and/or quantitative discussion of the numerical stability, eventual loss of precision etc.
* Try to give an interpretation of you results in your answers to the problems.
* Critique: if possible include your comments and reflections about the exercise, whether you felt you learnt something, ideas for improvements and other thoughts you've made when solving the exercise. We wish to keep this course at the interactive level and your comments can help us improve it.
* Try to establish a practice where you log your work at the computerlab. You may find such a logbook very handy at later stages in your work, especially when you don't properly remember what a previous test version of your program did. Here you could also record the time spent on solving the exercise, various algorithms you may have tested or other topics which you feel worthy of mentioning.
===== Format for electronic delivery of report and programs =====
The preferred format for the report is a PDF file. You can also use DOC or postscript formats or as an ipython notebook file. As programming language we prefer that you choose between C/C++, Fortran2008 or Python. The following prescription should be followed when preparing the report:
* Use Canvas to hand in your projects, log in at URL:"https://www.uio.no/english/services/it/education/canvas/" with your normal UiO username and password.
* Upload _only_ the report file or the link to your GitHub/GitLab or similar typo of repos! For the source code file(s) you have developed please provide us with your link to your GitHub/GitLab or similar domain. The report file should include all of your discussions and a list of the codes you have developed. Do not include library files which are available at the course homepage, unless you have made specific changes to them.
* In your GitHub/GitLab or similar repository, please include a folder which contains selected results. These can be in the form of output from your code for a selected set of runs and input parameters.
Finally,
we encourage you to collaborate. Optimal working groups consist of
2-3 students. You can then hand in a common report.
===== Software and needed installations =====
If you have Python installed (we recommend Python3) and you feel pretty familiar with installing different packages,
we recommend that you install the following Python packages via _pip_ as
o pip install numpy scipy matplotlib ipython scikit-learn tensorflow sympy pandas pillow
For Python3, replace _pip_ with _pip3_.
See below for a discussion of _tensorflow_ and _scikit-learn_.
For OSX users we recommend also, after having installed Xcode, to install _brew_. Brew allows
for a seamless installation of additional software via for example
o brew install python3
For Linux users, with its variety of distributions like for example the widely popular Ubuntu distribution
you can use _pip_ as well and simply install Python as
o sudo apt-get install python3 (or python for python2.7)
etc etc.
If you don't want to install various Python packages with their dependencies separately, we recommend two widely used distrubutions which set up all relevant dependencies for Python, namely
o "Anaconda":"https://docs.anaconda.com/" Anaconda is an open source distribution of the Python and R programming languages for large-scale data processing, predictive analytics, and scientific computing, that aims to simplify package management and deployment. Package versions are managed by the package management system _conda_
o "Enthought canopy":"https://www.enthought.com/product/canopy/" is a Python distribution for scientific and analytic computing distribution and analysis environment, available for free and under a commercial license.
Popular software packages written in Python for ML are
* "Scikit-learn":"http://scikit-learn.org/stable/",
* "Tensorflow":"https://www.tensorflow.org/",
* "PyTorch":"http://pytorch.org/" and
* "Keras":"https://keras.io/".
These are all freely available at their respective GitHub sites. They
encompass communities of developers in the thousands or more. And the number
of code developers and contributors keeps increasing.
@@ -0,0 +1,278 @@
TITLE: Project 3 on Machine Learning, deadline December 14
AUTHOR: "Data Analysis and Machine Learning FYS-STK3155/FYS4155":"http://www.uio.no/studier/emner/matnat/fys/FYS3155/index-eng.html" {copyright, 1999-present|CC BY-NC} at Department of Physics, University of Oslo, Norway
DATE: today
======= Paths for project 3 =======
===== Defining the data sets to analyze yourself =====
For project 3, you can propose own data sets that relate to your research interests or just use existing data sets from say
o "Kaggle":"https://www.kaggle.com/datasets"
o The "University of California at Irvine (UCI) with its machine learning repository":"http://archive.ics.uci.edu/ml/datasets.html"
The approach to the analysis of these new data sets should follow to a large extent what you did in projects 1 and 2. That is:
o Whether you end up with a regression or a classification problem, you should employ at least two of the methods we have discussed among _linear regression (including Ridge and Lasso)_, _Logistic Regression_, _Neural Networks_, _Convolution Neural Networks_, _Recurrent Neural Networks_, _Support Vector Machines_ and _Decision Trees, Random Forests_, _Bagging and Boosting_. You could for example explore all of the approaches from decision trees, via bagging and voting classifiers, to random forests, boosting and finally XGboost. If you wish to venture into _convolutional neural networks_ or _recurrent neural networks_, or extensions of neural networkds, feel free to do so.
For Boosting, feel also free to write your own codes.
o For project 3, you should feel free to use your own codes from projects 1 and 2, eventually write your own for SVMs and/or Decision trees/random forests/bagging/boosting' or use the available functionality of _Scikit-Learn_, _Tensorflow_, etc.
o The estimates you used and tested in projects 1 and 2 should also be included, that is the $R2$-score, _MSE_, confusion matrix, accuracy score, information gain, ROC and Cumulative gains curves and other, cross-validation and/or bootstrap if these are relevant.
o Similarly, feel free to explore various activations functions in deep learning and various approachs to stochastic gradient descent approaches.
o If possible, you should link the data sets with exisiting research and analyses thereof. Scientific articles which have used Machine Learning algorithms to analyze the data are highly welcome. Perhaps you can improve previous analyses and even publish a new article?
o A critical assessment of the methods with ditto perspectives and recommendations is also something you need to include.
All in all, the report should follow the same pattern as the two previous ones, with abstract, introduction, methods, code, results, conclusions etc..
We propose also an alternative to the above. This is a project on using machine learning methods (neural networks mainly) to the solution of ordinary differential equations and partial differential equations, with a final twist on how to diagonalize a symmetric matrix with neural networks..
This is a field with a large interest recently, spanning from studies of turbulence in fluid mechanics and meteorology to the solution of quantum mechanical systems. As reading background you can use the slides "from week 43":"https://compphysics.github.io/MachineLearning/doc/pub/week43/html/week43.html" and/or the textbook by "Yadav et al":"https://www.springer.com/gp/book/9789401798150".
===== The basic structure of your project =====
Here follows a set up on how to structure your report and analyze the data you have opted for.
=== Part a) ===
The first part deals with structuring and reading the data, much along the same lines as done in projects 1 and 2. Explain how the data are produced and place them in a proper context.
=== Part b) ===
You need to include at least two central algorithms, or as an alternative explore methods from decisions tree to bagging, random forests and boosting. Explain the basics of the methods you have chosen to work with. This would be your theory part.
=== Part c) ===
Then describe your algorithm and its implementation and tests you have performed.
=== Part d) ===
Then presents your results and findings, link with existing literature and more.
=== Part e) ===
Finally, here you should present a critical assessment of the methods you have studied and link your results with the existing literature.
===== Solving partial differential equations with neural networks =====
For this variant of project 3, we will assume that you have some
background in the solution of partial differential equations using
finite difference schemes. We will study the solution of the diffusion
equation in one dimension using a standard explicit scheme and neural
networks to solve the same equations.
For the explicit scheme, you can study for example chapter 10 of the lecture notes in "Computational Physics":"https://github.com/CompPhysics/ComputationalPhysics/blob/master/doc/Lectures/lectures2015.pdf" or alternative sources. For the solution of ordinary and partial differential equations using neural networks, the lectures by "Kristine Baluka Hein":"https://compphysics.github.io/MachineLearning/doc/pub/odenn/html/odenn-bs.html" at this course are highly recommended.
For the machine learning part you can use your own code from project 2 or the functionality of for example _Tensorflow/Keras_..
=== Part a), setting up the problem ===
The physical problem can be that of the temperature gradient in a rod of length $L=1$ at $x=0$ and $x=1$.
We are looking at a one-dimensional
problem
!bt
\begin{equation*}
\frac{\partial^2 u(x,t)}{\partial x^2} =\frac{\partial u(x,t)}{\partial t}, t> 0, x\in [0,L]
\end{equation*}
!et
or
!bt
\begin{equation*}
u_{xx} = u_t,
\end{equation*}
!et
with initial conditions, i.e., the conditions at $t=0$,
!bt
\begin{equation*}
u(x,0)= \sin{(\pi x)} \hspace{0.5cm} 0 < x < L,
\end{equation*}
!et
with $L=1$ the length of the $x$-region of interest. The
boundary conditions are
!bt
\begin{equation*}
u(0,t)= 0 \hspace{0.5cm} t \ge 0,
\end{equation*}
!et
and
!bt
\begin{equation*}
u(L,t)= 0 \hspace{0.5cm} t \ge 0.
\end{equation*}
!et
The function $u(x,t)$ can be the temperature gradient of a rod.
As time increases, the velocity approaches a linear variation with $x$.
We will limit ourselves to the so-called explicit forward Euler algorithm with discretized versions of time given by a forward formula and a centered difference in space resulting in
!bt
\begin{equation*}
u_t\approx \frac{u(x,t+\Delta t)-u(x,t)}{\Delta t}=\frac{u(x_i,t_j+\Delta t)-u(x_i,t_j)}{\Delta t}
\end{equation*}
!et
and
!bt
\begin{equation*}
u_{xx}\approx \frac{u(x+\Delta x,t)-2u(x,t)+u(x-\Delta x,t)}{\Delta x^2},
\end{equation*}
!et
or
!bt
\begin{equation*}
u_{xx}\approx \frac{u(x_i+\Delta x,t_j)-2u(x_i,t_j)+u(x_i-\Delta x,t_j)}{\Delta x^2}.
\end{equation*}
!et
Write down the algorithm and the equations you need to implement.
Find also the analytical solution to the problem.
=== Part b) ===
Implement the explicit scheme algorithm and perform tests of the solution
for $\Delta x=1/10$, $\Delta x=1/100$ using $\Delta t$ as dictated by the stability limit of the explicit scheme. The stability criterion for the explicit scheme requires that $\Delta t/\Delta x^2 \leq 1/2$.
Study the solutions at two time points $t_1$ and $t_2$ where $u(x,t_1)$ is smooth but still significantly curved
and $u(x,t_2)$ is almost linear, close to the stationary state.
=== Part c) Neural networks ===
Study now the lecture notes on solving ODEs and PDEs with neural
network and use either your own code from project 2 or the
functionality of tensorflow/keras to solve the same equation as in
part b). Discuss your results and compare them with the standard
explicit scheme. Include also the analytical solution and compare with
that.
=== Part d) Solving eigenvalue problems ===
Follow the discussion in the work of Yi *et al.* in the article from
"Computers and Mathematics with Applications 47, 1155 (2004)":"https://www.sciencedirect.com/science/article/pii/S0898122104901101", and
use your differential equation solver with neural networks, set up a
simple square, real and symmetric $6\times 6$ matrix and find the
eigenvalues. Compare with the solution from numerical diagonalization with standard eigenvalue solvers from linear algebra.
=== Part e) ===
Finally, present a critical assessment of the methods you have studied and discuss the potential for the solving differential equations and eigenvalue problems with machine learning methods.
===== Introduction to numerical projects =====
Here follows a brief recipe and recommendation on how to write a report for each
project.
* Give a short description of the nature of the problem and the eventual numerical methods you have used.
* Describe the algorithm you have used and/or developed. Here you may find it convenient to use pseudocoding. In many cases you can describe the algorithm in the program itself.
* Include the source code of your program. Comment your program properly.
* If possible, try to find analytic solutions, or known limits in order to test your program when developing the code.
* Include your results either in figure form or in a table. Remember to label your results. All tables and figures should have relevant captions and labels on the axes.
* Try to evaluate the reliabilty and numerical stability/precision of your results. If possible, include a qualitative and/or quantitative discussion of the numerical stability, eventual loss of precision etc.
* Try to give an interpretation of you results in your answers to the problems.
* Critique: if possible include your comments and reflections about the exercise, whether you felt you learnt something, ideas for improvements and other thoughts you've made when solving the exercise. We wish to keep this course at the interactive level and your comments can help us improve it.
* Try to establish a practice where you log your work at the computerlab. You may find such a logbook very handy at later stages in your work, especially when you don't properly remember what a previous test version of your program did. Here you could also record the time spent on solving the exercise, various algorithms you may have tested or other topics which you feel worthy of mentioning.
===== Introduction to numerical projects =====
Here follows a brief recipe and recommendation on how to write a report for each
project.
* Give a short description of the nature of the problem and the eventual numerical methods you have used.
* Describe the algorithm you have used and/or developed. Here you may find it convenient to use pseudocoding. In many cases you can describe the algorithm in the program itself.
* Include the source code of your program. Comment your program properly.
* If possible, try to find analytic solutions, or known limits in order to test your program when developing the code.
* Include your results either in figure form or in a table. Remember to label your results. All tables and figures should have relevant captions and labels on the axes.
* Try to evaluate the reliabilty and numerical stability/precision of your results. If possible, include a qualitative and/or quantitative discussion of the numerical stability, eventual loss of precision etc.
* Try to give an interpretation of you results in your answers to the problems.
* Critique: if possible include your comments and reflections about the exercise, whether you felt you learnt something, ideas for improvements and other thoughts you've made when solving the exercise. We wish to keep this course at the interactive level and your comments can help us improve it.
* Try to establish a practice where you log your work at the computerlab. You may find such a logbook very handy at later stages in your work, especially when you don't properly remember what a previous test version of your program did. Here you could also record the time spent on solving the exercise, various algorithms you may have tested or other topics which you feel worthy of mentioning.
===== Format for electronic delivery of report and programs =====
The preferred format for the report is a PDF file. You can also use DOC or postscript formats or as an ipython notebook file. As programming language we prefer that you choose between C/C++, Fortran2008 or Python. The following prescription should be followed when preparing the report:
* Use Canvas to hand in your projects, log in at URL:"https://www.uio.no/english/services/it/education/canvas/" with your normal UiO username and password.
* Upload _only_ the report file or the link to your GitHub/GitLab or similar typo of repos! For the source code file(s) you have developed please provide us with your link to your GitHub/GitLab or similar domain. The report file should include all of your discussions and a list of the codes you have developed. Do not include library files which are available at the course homepage, unless you have made specific changes to them.
* In your GitHub/GitLab or similar repository, please include a folder which contains selected results. These can be in the form of output from your code for a selected set of runs and input parameters.
Finally,
we encourage you to collaborate. Optimal working groups consist of
2-3 students. You can then hand in a common report.
===== Software and needed installations =====
If you have Python installed (we recommend Python3) and you feel pretty familiar with installing different packages,
we recommend that you install the following Python packages via _pip_ as
o pip install numpy scipy matplotlib ipython scikit-learn tensorflow sympy pandas pillow
For Python3, replace _pip_ with _pip3_.
See below for a discussion of _tensorflow_ and _scikit-learn_.
For OSX users we recommend also, after having installed Xcode, to install _brew_. Brew allows
for a seamless installation of additional software via for example
o brew install python3
For Linux users, with its variety of distributions like for example the widely popular Ubuntu distribution
you can use _pip_ as well and simply install Python as
o sudo apt-get install python3 (or python for python2.7)
etc etc.
If you don't want to install various Python packages with their dependencies separately, we recommend two widely used distrubutions which set up all relevant dependencies for Python, namely
o "Anaconda":"https://docs.anaconda.com/" Anaconda is an open source distribution of the Python and R programming languages for large-scale data processing, predictive analytics, and scientific computing, that aims to simplify package management and deployment. Package versions are managed by the package management system _conda_
o "Enthought canopy":"https://www.enthought.com/product/canopy/" is a Python distribution for scientific and analytic computing distribution and analysis environment, available for free and under a commercial license.
Popular software packages written in Python for ML are
* "Scikit-learn":"http://scikit-learn.org/stable/",
* "Tensorflow":"https://www.tensorflow.org/",
* "PyTorch":"http://pytorch.org/" and
* "Keras":"https://keras.io/".
These are all freely available at their respective GitHub sites. They
encompass communities of developers in the thousands or more. And the number
of code developers and contributors keeps increasing.
+3
View File
@@ -0,0 +1,3 @@
#!/bin/sh
doconce clean
rm -rf *.pdf *.tex ipynb*.tar.gz *.html ._*.html *~ reveal.js Trash README.txt
+87
View File
@@ -0,0 +1,87 @@
#!/bin/sh
set -x
function system {
"$@"
if [ $? -ne 0 ]; then
echo "make.sh: unsuccessful command $@"
echo "abort!"
exit 1
fi
}
if [ $# -eq 0 ]; then
echo 'bash make.sh slides1|slides2'
exit 1
fi
name=$1
rm -f *.tar.gz
opt="--encoding=utf-8"
opt=
rm -f *.aux
# Plain HTML documents
html=${name}
system doconce format html $name --pygments_html_style=default --html_style=bloodish --html_links_in_new_window --html_output=$html $opt
system doconce split_html $html.html --method=space10
# Bootstrap style
html=${name}-bs
system doconce format html $name --html_style=bootstrap --pygments_html_style=default --html_admon=bootstrap_panel --html_output=$html $opt
system doconce split_html $html.html --method=split --pagination --nav_button=bottom
# IPython notebook
system doconce format ipynb $name $opt
# Ordinary plain LaTeX document
system doconce format pdflatex $name --print_latex_style=trac --latex_admon=paragraph $opt
system doconce ptex2tex $name envir=verbatim
# Add special packages
doconce subst "% Add user's preamble" "\g<1>\n\\usepackage{simplewick}" $name.tex
doconce replace 'section{' 'section*{' $name.tex
pdflatex -shell-escape $name
pdflatex -shell-escape $name
mv -f $name.pdf ${name}.pdf
cp $name.tex ${name}.tex
# Publish
dest=../../../../Projects/2020
if [ ! -d $dest/$name ]; then
mkdir $dest/$name
mkdir $dest/$name/pdf
mkdir $dest/$name/html
mkdir $dest/$name/ipynb
fi
cp ${name}*.tex $dest/$name/pdf
cp ${name}*.pdf $dest/$name/pdf
cp -r ${name}*.html ._${name}*.html $dest/$name/html
# Figures: cannot just copy link, need to physically copy the files
if [ -d fig-${name} ]; then
if [ ! -d $dest/$name/html/fig-$name ]; then
mkdir $dest/$name/html/fig-$name
fi
cp -r fig-${name}/* $dest/$name/html/fig-$name
fi
cp ${name}.ipynb $dest/$name/ipynb
ipynb_tarfile=ipynb-${name}-src.tar.gz
if [ ! -f ${ipynb_tarfile} ]; then
cat > README.txt <<EOF
This IPython notebook ${name}.ipynb does not require any additional
programs.
EOF
tar czf ${ipynb_tarfile} README.txt
fi
cp ${ipynb_tarfile} $dest/$name/ipynb
+7
View File
@@ -0,0 +1,7 @@
from sklearn.datasets import load_iris
from sklearn import tree
X, y = load_iris(return_X_y=True)
tree_clf = tree.DecisionTreeClassifier()
tree_clf = clf.fit(X, y)
# and then plot the tree
tree.plot_tree(tree_clf)
+993
View File
@@ -0,0 +1,993 @@
TITLE: Week 48: Support Vector Machines and Summary of course
AUTHOR: Morten Hjorth-Jensen {copyright, 1999-present|CC BY-NC} at Department of Physics, University of Oslo & Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
DATE: today
!split
===== Overview of week 48 =====
* _Thursday_: Support Vector Machines, Kernels, Classification and Regression
* _Friday_: Summary of course with perspectives for future studies
Geron's chapter 5. Chapter 12 (sections 12.1-12.3 are the most relevant ones) of Hastie et al contains also a good discussion.
!split
===== Thursday =====
We finalize our discussion on Support Vector Machines with an emphasis on kernel transformations and applications to regression. The following "video attempts at giving an overview on this part":"https://www.youtube.com/watch?v=Toet3EiSFcM&ab_channel=StatQuestwithJoshStarmer". See also the "follow-up video":"https://www.youtube.com/watch?v=Qc5IyLW_hns&ab_channel=StatQuestwithJoshStarmer".
!split
===== Friday =====
Friday's lecture is split in two parts. It starts with a summary of
what we have done this semester and continues with perspectives for future studies and
modern research projects in machine learning.
!split
===== Support Vector Machines, overarching aims =====
As discussed last week,
a Support Vector Machine (SVM) is a very powerful and versatile
Machine Learning method, capable of performing linear or nonlinear
classification, regression, and even outlier detection. It is one of
the most popular models in Machine Learning, and anyone interested in
Machine Learning should have it in their toolbox. SVMs are
particularly well suited for classification of complex but small-sized or
medium-sized datasets.
The case with two well-separated classes only can be understood in an
intuitive way in terms of lines in a two-dimensional space separating
the two classes.
The basic mathematics behind the SVM is however less familiar to most of us.
It relies on the definition of hyperplanes and the
definition of a _margin_ which separates classes (in case of
classification problems) of variables. It is also used for regression
problems. I recommend you take a look at the lectures from last week on the binary classification problem.
!split
===== Kernels and non-linearity =====
The cases we studied last week were all characterized by two classes
with a close to linear separability. The classifiers we have described
so far find linear boundaries in our input feature space. It is
possible to make our procedure more flexible by exploring the feature
space using other basis expansions such as higher-order polynomials,
wavelets, splines etc.
If our feature space is not easy to separate, as shown in the figure
here, we can achieve a better separation by introducing more complex
basis functions. The ideal would be, as shown in the next figure, to, via a specific transformation to
obtain a separation between the classes which is almost linear.
The change of basis, from $x\rightarrow z=\phi(x)$ leads to the same type of equations to be solved, except that
we need to introduce for example a polynomial transformation to a two-dimensional training set.
!bc pycod
import numpy as np
import os
np.random.seed(42)
# To plot pretty figures
import matplotlib
import matplotlib.pyplot as plt
plt.rcParams['axes.labelsize'] = 14
plt.rcParams['xtick.labelsize'] = 12
plt.rcParams['ytick.labelsize'] = 12
from sklearn.svm import SVC
from sklearn import datasets
X1D = np.linspace(-4, 4, 9).reshape(-1, 1)
X2D = np.c_[X1D, X1D**2]
y = np.array([0, 0, 1, 1, 1, 1, 1, 0, 0])
plt.figure(figsize=(11, 4))
plt.subplot(121)
plt.grid(True, which='both')
plt.axhline(y=0, color='k')
plt.plot(X1D[:, 0][y==0], np.zeros(4), "bs")
plt.plot(X1D[:, 0][y==1], np.zeros(5), "g^")
plt.gca().get_yaxis().set_ticks([])
plt.xlabel(r"$x_1$", fontsize=20)
plt.axis([-4.5, 4.5, -0.2, 0.2])
plt.subplot(122)
plt.grid(True, which='both')
plt.axhline(y=0, color='k')
plt.axvline(x=0, color='k')
plt.plot(X2D[:, 0][y==0], X2D[:, 1][y==0], "bs")
plt.plot(X2D[:, 0][y==1], X2D[:, 1][y==1], "g^")
plt.xlabel(r"$x_1$", fontsize=20)
plt.ylabel(r"$x_2$", fontsize=20, rotation=0)
plt.gca().get_yaxis().set_ticks([0, 4, 8, 12, 16])
plt.plot([-4.5, 4.5], [6.5, 6.5], "r--", linewidth=3)
plt.axis([-4.5, 4.5, -1, 17])
plt.subplots_adjust(right=1)
plt.show()
!ec
!split
===== The equations =====
Suppose we define a polynomial transformation of degree two only (we continue to live in a plane with $x_i$ and $y_i$ as variables)
!bt
\[
z = \phi(x_i) =\left(x_i^2, y_i^2, \sqrt{2}x_iy_i\right).
\]
!et
With our new basis, the equations we solved earlier are basically the same, that is we have now (without the slack option for simplicity)
!bt
\[
{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\bm{z}_i^T\bm{z}_j,
\]
!et
subject to the constraints $\lambda_i\geq 0$, $\sum_i\lambda_iy_i=0$, and for the support vectors
!bt
\[
y_i(\bm{w}^T\bm{z}_i+b)= 1 \hspace{0.1cm}\forall i,
\]
!et
from which we also find $b$.
To compute $\bm{z}_i^T\bm{z}_j$ we define the kernel $K(\bm{x}_i,\bm{x}_j)$ as
!bt
\[
K(\bm{x}_i,\bm{x}_j)=\bm{z}_i^T\bm{z}_j= \phi(\bm{x}_i)^T\phi(\bm{x}_j).
\]
!et
For the above example, the kernel reads
!bt
\[
K(\bm{x}_i,\bm{x}_j)=[x_i^2, y_i^2, \sqrt{2}x_iy_i]^T\begin{bmatrix} x_j^2 \\ y_j^2 \\ \sqrt{2}x_jy_j \end{bmatrix}=x_i^2x_j^2+2x_ix_jy_iy_j+y_i^2y_j^2.
\]
!et
We note that this is nothing but the dot product of the two original
vectors $(\bm{x}_i^T\bm{x}_j)^2$. Instead of thus computing the
product in the Lagrangian of $\bm{z}_i^T\bm{z}_j$ we simply compute
the dot product $(\bm{x}_i^T\bm{x}_j)^2$.
This leads to the so-called
kernel trick and the result leads to the same as if we went through
the trouble of performing the transformation
$\phi(\bm{x}_i)^T\phi(\bm{x}_j)$ during the SVM calculations.
!split
===== The problem to solve =====
Using our definition of the kernel We can rewrite again the Lagrangian
!bt
\[
{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\bm{x}_i^T\bm{z}_j,
\]
!et
subject to the constraints $\lambda_i\geq 0$, $\sum_i\lambda_iy_i=0$ in terms of a convex optimization problem
!bt
\[
\frac{1}{2} \bm{\lambda}^T\begin{bmatrix} y_1y_1K(\bm{x}_1,\bm{x}_1) & y_1y_2K(\bm{x}_1,\bm{x}_2) & \dots & \dots & y_1y_nK(\bm{x}_1,\bm{x}_n) \\
y_2y_1K(\bm{x}_2,\bm{x}_1) & y_2y_2(\bm{x}_2,\bm{x}_2) & \dots & \dots & y_1y_nK(\bm{x}_2,\bm{x}_n) \\
\dots & \dots & \dots & \dots & \dots \\
\dots & \dots & \dots & \dots & \dots \\
y_ny_1K(\bm{x}_n,\bm{x}_1) & y_ny_2K(\bm{x}_n\bm{x}_2) & \dots & \dots & y_ny_nK(\bm{x}_n,\bm{x}_n) \\
\end{bmatrix}\bm{\lambda}-\mathbb{1}\bm{\lambda},
\]
!et
subject to $\bm{y}^T\bm{\lambda}=0$. Here we defined the vectors $\bm{\lambda} =[\lambda_1,\lambda_2,\dots,\lambda_n]$ and
$\bm{y}=[y_1,y_2,\dots,y_n]$.
If we add the slack constants this leads to the additional constraint $0\leq \lambda_i \leq C$.
We can rewrite this (see the solutions below) in terms of a convex optimization problem of the type
!bt
\begin{align*}
&\mathrm{min}_{\lambda}\hspace{0.2cm} \frac{1}{2}\bm{\lambda}^T\bm{P}\bm{\lambda}+\bm{q}^T\bm{\lambda},\\ \nonumber
&\mathrm{subject\hspace{0.1cm}to} \hspace{0.2cm} \bm{G}\bm{\lambda} \preceq \bm{h} \hspace{0.2cm} \wedge \bm{A}\bm{\lambda}=f.
\end{align*}
!et
Below we discuss how to solve these equations. Here we note that the matrix $\bm{P}$ has matrix elements $p_{ij}=y_iy_jK(\bm{x}_i,\bm{x}_j)$.
Given a kernel $K$ and the targets $y_i$ this matrix is easy to set up. The constraint $\bm{y}^T\bm{\lambda}=0$ leads to $f=0$ and $\bm{A}=\bm{y}$. How to set up the matrix $\bm{G}$ is discussed later. Here note that the inequalities $0\leq \lambda_i \leq C$ can be split up into
$0\leq \lambda_i$ and $\lambda_i \leq C$. These two inequalities define then the matrix $\bm{G}$ and the vector $\bm{h}$.
!split
===== Different kernels and Mercer's theorem =====
There are several popular kernels being used. These are
o Linear: $K(\bm{x},\bm{y})=\bm{x}^T\bm{y}$,
o Polynomial: $K(\bm{x},\bm{y})=(\bm{x}^T\bm{y}+\gamma)^d$,
o Gaussian Radial Basis Function: $K(\bm{x},\bm{y})=\exp{\left(-\gamma\vert\vert\bm{x}-\bm{y}\vert\vert^2\right)}$,
o Tanh: $K(\bm{x},\bm{y})=\tanh{(\bm{x}^T\bm{y}+\gamma)}$,
and many other ones.
An important theorem for us is "Mercer's
theorem":"https://en.wikipedia.org/wiki/Mercer%27s_theorem". The
theorem states that if a kernel function $K$ is symmetric, continuous
and leads to a positive semi-definite matrix $\bm{P}$ then there
exists a function $\phi$ that maps $\bm{x}_i$ and $\bm{x}_j$ into
another space (possibly with much higher dimensions) such that
!bt
\[
K(\bm{x}_i,\bm{x}_j)=\phi(\bm{x}_i)^T\phi(\bm{x}_j).
\]
!et
So you can use $K$ as a kernel since you know $\phi$ exists, even if
you dont know what $\phi$ is.
Note that some frequently used kernels (such as the Sigmoid kernel)
dont respect all of Mercers conditions, yet they generally work well
in practice.
!split
===== The moons example =====
!bc pycod
from __future__ import division, print_function, unicode_literals
import numpy as np
np.random.seed(42)
import matplotlib
import matplotlib.pyplot as plt
plt.rcParams['axes.labelsize'] = 14
plt.rcParams['xtick.labelsize'] = 12
plt.rcParams['ytick.labelsize'] = 12
from sklearn.svm import SVC
from sklearn import datasets
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import LinearSVC
from sklearn.datasets import make_moons
X, y = make_moons(n_samples=100, noise=0.15, random_state=42)
def plot_dataset(X, y, axes):
plt.plot(X[:, 0][y==0], X[:, 1][y==0], "bs")
plt.plot(X[:, 0][y==1], X[:, 1][y==1], "g^")
plt.axis(axes)
plt.grid(True, which='both')
plt.xlabel(r"$x_1$", fontsize=20)
plt.ylabel(r"$x_2$", fontsize=20, rotation=0)
plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])
plt.show()
from sklearn.datasets import make_moons
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import PolynomialFeatures
polynomial_svm_clf = Pipeline([
("poly_features", PolynomialFeatures(degree=3)),
("scaler", StandardScaler()),
("svm_clf", LinearSVC(C=10, loss="hinge", random_state=42))
])
polynomial_svm_clf.fit(X, y)
def plot_predictions(clf, axes):
x0s = np.linspace(axes[0], axes[1], 100)
x1s = np.linspace(axes[2], axes[3], 100)
x0, x1 = np.meshgrid(x0s, x1s)
X = np.c_[x0.ravel(), x1.ravel()]
y_pred = clf.predict(X).reshape(x0.shape)
y_decision = clf.decision_function(X).reshape(x0.shape)
plt.contourf(x0, x1, y_pred, cmap=plt.cm.brg, alpha=0.2)
plt.contourf(x0, x1, y_decision, cmap=plt.cm.brg, alpha=0.1)
plot_predictions(polynomial_svm_clf, [-1.5, 2.5, -1, 1.5])
plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])
plt.show()
from sklearn.svm import SVC
poly_kernel_svm_clf = Pipeline([
("scaler", StandardScaler()),
("svm_clf", SVC(kernel="poly", degree=3, coef0=1, C=5))
])
poly_kernel_svm_clf.fit(X, y)
poly100_kernel_svm_clf = Pipeline([
("scaler", StandardScaler()),
("svm_clf", SVC(kernel="poly", degree=10, coef0=100, C=5))
])
poly100_kernel_svm_clf.fit(X, y)
plt.figure(figsize=(11, 4))
plt.subplot(121)
plot_predictions(poly_kernel_svm_clf, [-1.5, 2.5, -1, 1.5])
plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])
plt.title(r"$d=3, r=1, C=5$", fontsize=18)
plt.subplot(122)
plot_predictions(poly100_kernel_svm_clf, [-1.5, 2.5, -1, 1.5])
plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])
plt.title(r"$d=10, r=100, C=5$", fontsize=18)
plt.show()
def gaussian_rbf(x, landmark, gamma):
return np.exp(-gamma * np.linalg.norm(x - landmark, axis=1)**2)
gamma = 0.3
x1s = np.linspace(-4.5, 4.5, 200).reshape(-1, 1)
x2s = gaussian_rbf(x1s, -2, gamma)
x3s = gaussian_rbf(x1s, 1, gamma)
XK = np.c_[gaussian_rbf(X1D, -2, gamma), gaussian_rbf(X1D, 1, gamma)]
yk = np.array([0, 0, 1, 1, 1, 1, 1, 0, 0])
plt.figure(figsize=(11, 4))
plt.subplot(121)
plt.grid(True, which='both')
plt.axhline(y=0, color='k')
plt.scatter(x=[-2, 1], y=[0, 0], s=150, alpha=0.5, c="red")
plt.plot(X1D[:, 0][yk==0], np.zeros(4), "bs")
plt.plot(X1D[:, 0][yk==1], np.zeros(5), "g^")
plt.plot(x1s, x2s, "g--")
plt.plot(x1s, x3s, "b:")
plt.gca().get_yaxis().set_ticks([0, 0.25, 0.5, 0.75, 1])
plt.xlabel(r"$x_1$", fontsize=20)
plt.ylabel(r"Similarity", fontsize=14)
plt.annotate(r'$\mathbf{x}$',
xy=(X1D[3, 0], 0),
xytext=(-0.5, 0.20),
ha="center",
arrowprops=dict(facecolor='black', shrink=0.1),
fontsize=18,
)
plt.text(-2, 0.9, "$x_2$", ha="center", fontsize=20)
plt.text(1, 0.9, "$x_3$", ha="center", fontsize=20)
plt.axis([-4.5, 4.5, -0.1, 1.1])
plt.subplot(122)
plt.grid(True, which='both')
plt.axhline(y=0, color='k')
plt.axvline(x=0, color='k')
plt.plot(XK[:, 0][yk==0], XK[:, 1][yk==0], "bs")
plt.plot(XK[:, 0][yk==1], XK[:, 1][yk==1], "g^")
plt.xlabel(r"$x_2$", fontsize=20)
plt.ylabel(r"$x_3$ ", fontsize=20, rotation=0)
plt.annotate(r'$\phi\left(\mathbf{x}\right)$',
xy=(XK[3, 0], XK[3, 1]),
xytext=(0.65, 0.50),
ha="center",
arrowprops=dict(facecolor='black', shrink=0.1),
fontsize=18,
)
plt.plot([-0.1, 1.1], [0.57, -0.1], "r--", linewidth=3)
plt.axis([-0.1, 1.1, -0.1, 1.1])
plt.subplots_adjust(right=1)
plt.show()
x1_example = X1D[3, 0]
for landmark in (-2, 1):
k = gaussian_rbf(np.array([[x1_example]]), np.array([[landmark]]), gamma)
print("Phi({}, {}) = {}".format(x1_example, landmark, k))
rbf_kernel_svm_clf = Pipeline([
("scaler", StandardScaler()),
("svm_clf", SVC(kernel="rbf", gamma=5, C=0.001))
])
rbf_kernel_svm_clf.fit(X, y)
from sklearn.svm import SVC
gamma1, gamma2 = 0.1, 5
C1, C2 = 0.001, 1000
hyperparams = (gamma1, C1), (gamma1, C2), (gamma2, C1), (gamma2, C2)
svm_clfs = []
for gamma, C in hyperparams:
rbf_kernel_svm_clf = Pipeline([
("scaler", StandardScaler()),
("svm_clf", SVC(kernel="rbf", gamma=gamma, C=C))
])
rbf_kernel_svm_clf.fit(X, y)
svm_clfs.append(rbf_kernel_svm_clf)
plt.figure(figsize=(11, 7))
for i, svm_clf in enumerate(svm_clfs):
plt.subplot(221 + i)
plot_predictions(svm_clf, [-1.5, 2.5, -1, 1.5])
plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])
gamma, C = hyperparams[i]
plt.title(r"$\gamma = {}, C = {}$".format(gamma, C), fontsize=16)
plt.show()
!ec
!split
===== Mathematical optimization of convex functions =====
A mathematical (quadratic) optimization problem, or just optimization problem, has the form
!bt
\begin{align*}
&\mathrm{min}_{\lambda}\hspace{0.2cm} \frac{1}{2}\bm{\lambda}^T\bm{P}\bm{\lambda}+\bm{q}^T\bm{\lambda},\\ \nonumber
&\mathrm{subject\hspace{0.1cm}to} \hspace{0.2cm} \bm{G}\bm{\lambda} \preceq \bm{h} \wedge \bm{A}\bm{\lambda}=f.
\end{align*}
!et
subject to some constraints for say a selected set $i=1,2,\dots, n$.
In our case we are optimizing with respect to the Lagrangian multipliers $\lambda_i$, and the
vector $\bm{\lambda}=[\lambda_1, \lambda_2,\dots, \lambda_n]$ is the optimization variable we are dealing with.
In our case we are particularly interested in a class of optimization problems called convex optmization problems.
In our discussion on gradient descent methods we discussed at length the definition of a convex function.
Convex optimization problems play a central role in applied mathematics and we recommend strongly "Boyd and Vandenberghe's text on the topics":"http://web.stanford.edu/~boyd/cvxbook/".
!split
===== How do we solve these problems? =====
If we use Python as programming language and wish to venture beyond
_scikit-learn_, _tensorflow_ and similar software which makes our
lives so much easier, we need to dive into the wonderful world of
quadratic programming. We can, if we wish, solve the minimization
problem using say standard gradient methods or conjugate gradient
methods. However, these methods tend to exhibit a rather slow
converge. So, welcome to the promised land of quadratic programming.
The functions we need are contained in the quadratic programming package _CVXOPT_ and we need to import it together with _numpy_ as
!bc pycod
import numpy
import cvxopt
!ec
This will make our life much easier. You don't need t write your own optimizer.
!split
===== A simple example =====
We remind ourselves about the general problem we want to solve
!bt
\begin{align*}
&\mathrm{min}_{x}\hspace{0.2cm} \frac{1}{2}\bm{x}^T\bm{P}\bm{x}+\bm{q}^T\bm{x},\\ \nonumber
&\mathrm{subject\hspace{0.1cm} to} \hspace{0.2cm} \bm{G}\bm{x} \preceq \bm{h} \wedge \bm{A}\bm{x}=f.
\end{align*}
!et
Let us show how to perform the optmization using a simple case. Assume we want to optimize the following problem
!bt
\begin{align*}
&\mathrm{min}_{x}\hspace{0.2cm} \frac{1}{2}x^2+5x+3y \\ \nonumber
&\mathrm{subject to} \\ \nonumber
&x, y \geq 0 \\ \nonumber
&x+3y \geq 15 \\ \nonumber
&2x+5y \leq 100 \\ \nonumber
&3x+4y \leq 80. \\ \nonumber
\end{align*}
!et
The minimization problem can be rewritten in terms of vectors and matrices as (with $x$ and $y$ being the unknowns)
!bt
\[
\frac{1}{2}\begin{bmatrix} x\\ y \end{bmatrix}^T \begin{bmatrix} 1 & 0\\ 0 & 0 \end{bmatrix} \begin{bmatrix} x \\ y \end{bmatrix} + \begin{bmatrix}3\\ 4 \end{bmatrix}^T \begin{bmatrix}x \\ y \end{bmatrix}.
\]
!et
Similarly, we can now set up the inequalities (we need to change $\geq$ to $\leq$ by multiplying with $-1$ on bot sides) as the following matrix-vector equation
!bt
\[
\begin{bmatrix} -1 & 0 \\ 0 & -1 \\ -1 & -3 \\ 2 & 5 \\ 3 & 4\end{bmatrix}\begin{bmatrix} x \\ y\end{bmatrix} \preceq \begin{bmatrix}0 \\ 0\\ -15 \\ 100 \\ 80\end{bmatrix}.
\]
!et
We have collapsed all the inequalities into a single matrix $\bm{G}$. We see also that our matrix
!bt
\[
\bm{P} =\begin{bmatrix} 1 & 0\\ 0 & 0 \end{bmatrix}
\]
!et
is clearly positive semi-definite (all eigenvalues larger or equal zero).
Finally, the vector $\bm{h}$ is defined as
!bt
\[
\bm{h} = \begin{bmatrix}0 \\ 0\\ -15 \\ 100 \\ 80\end{bmatrix}.
\]
!et
Since we don't have any equalities the matrix $\bm{A}$ is set to zero
The following code solves the equations for us
!bc pycod
# Import the necessary packages
import numpy
from cvxopt import matrix
from cvxopt import solvers
P = matrix(numpy.diag([1,0]), tc=d)
q = matrix(numpy.array([3,4]), tc=d)
G = matrix(numpy.array([[-1,0],[0,-1],[-1,-3],[2,5],[3,4]]), tc=d)
h = matrix(numpy.array([0,0,-15,100,80]), tc=d)
# Construct the QP, invoke solver
sol = solvers.qp(P,q,G,h)
# Extract optimal value and solution
sol[x]
sol[primal objective]
!ec
!split
===== Back to the more realistic cases =====
We are now ready to return to our setup of the optmization problem for a more realistic case. Introducing the _slack_ parameter $C$ we have
!bt
\[
\frac{1}{2} \bm{\lambda}^T\begin{bmatrix} y_1y_1K(\bm{x}_1,\bm{x}_1) & y_1y_2K(\bm{x}_1,\bm{x}_2) & \dots & \dots & y_1y_nK(\bm{x}_1,\bm{x}_n) \\
y_2y_1K(\bm{x}_2,\bm{x}_1) & y_2y_2K(\bm{x}_2,\bm{x}_2) & \dots & \dots & y_1y_nK(\bm{x}_2,\bm{x}_n) \\
\dots & \dots & \dots & \dots & \dots \\
\dots & \dots & \dots & \dots & \dots \\
y_ny_1K(\bm{x}_n,\bm{x}_1) & y_ny_2K(\bm{x}_n\bm{x}_2) & \dots & \dots & y_ny_nK(\bm{x}_n,\bm{x}_n) \\
\end{bmatrix}\bm{\lambda}-\mathbb{I}\bm{\lambda},
\]
!et
subject to $\bm{y}^T\bm{\lambda}=0$. Here we defined the vectors $\bm{\lambda} =[\lambda_1,\lambda_2,\dots,\lambda_n]$ and
$\bm{y}=[y_1,y_2,\dots,y_n]$.
With the slack constants this leads to the additional constraint $0\leq \lambda_i \leq C$.
!split
===== Summary of course =====
!split
===== What? Me worry? No final exam in this course! =====
FIGURE: [figures/exam1.jpeg, width=500 frac=0.6]
!split
===== Topics we have covered this year =====
The course has two central parts
o Statistical analysis and optimization of data
o Machine learning
!split
===== Statistical analysis and optimization of data =====
The following topics be covered
o Basic concepts, expectation values, variance, covariance, correlation functions and errors;
o Simpler models, binomial distribution, the Poisson distribution, simple and multivariate normal distributions;
o Central elements from linear algebra
o Gradient methods for data optimization
o Estimation of errors using cross-validation, bootstrapping and jackknife methods;
o Practical optimization using Singular-value decomposition and least squares for parameterizing data.
o Principal Component Analysis.
!split
===== Machine learning =====
The following topics will be covered
o Linear methods for regression and classification:
o Ordinary Least Squares
o Ridge regression
o Lasso regression
o Logistic regression
o Neural networks and deep learning:
o Feed Forward Neural Networks
o Convolutional Neural Networks
o Recurrent Neural Networks
o Decisions trees and ensemble methods:
o Decision trees
o Bagging and voting
o Random forests
o Boosting and gradient boosting
o Support vector machines
o Binary classification and multiclass classification
o Kernel methods
o Regression
!split
===== Learning outcomes and overarching aims of this course =====
The course introduces a variety of central algorithms and methods
essential for studies of data analysis and machine learning. The
course is project based and through the various projects, normally
three, you will be exposed to fundamental research problems
in these fields, with the aim to reproduce state of the art scientific
results. The students will learn to develop and structure large codes
for studying these systems, get acquainted with computing facilities
and learn to handle large scientific projects. A good scientific and
ethical conduct is emphasized throughout the course.
* Understand linear methods for regression and classification;
* Learn about neural network;
* Learn about baggin, boosting and trees
* Support vector machines
* Learn about basic data analysis;
* Be capable of extending the acquired knowledge to other systems and cases;
* Have an understanding of central algorithms used in data analysis and machine learning;
* Work on numerical projects to illustrate the theory. The projects play a central role and you are expected to know modern programming languages like Python or C++.
!split
===== Perspective on Machine Learning =====
o Rapidly emerging application area
o Experiment AND theory are evolving in many many fields. Still many low-hanging fruits.
o Requires education/retraining for more widespread adoption
o A lot of “word-of-mouth” development methods
Huge amounts of data sets require automation, classical analysis tools often inadequate.
High energy physics hit this wall in the 90s.
In 2009 single top quark production was determined via "Boosted decision trees, Bayesian
Neural Networks, etc.":"https://arxiv.org/pdf/0903.0850.pdf"
!split
===== Machine Learning Research =====
Where to find recent results:
o Conference proceedings, arXiv and blog posts!
o _NIPS_: "Neural Information Processing Systems":"https://papers.nips.cc"
o _ICLR_: "International Conference on Learning Representations":"https://openreview.net/group?id=ICLR.cc/2018/Conference#accepted-oral-papers"
o _ICML_: International Conference on Machine Learning
o "Journal of Machine Learning Research":"http://www.jmlr.org/papers/v19/"
!split
===== Starting your Machine Learning Project =====
o Identify problem type: classification, generation, regression
o Consider your data carefully
o Choose a simple model that fits 1. and 2.
o Consider your data carefully again… data representation
o Based on results, feedback loop to earliest possible point
!split
===== Choose a Model and Algorithm =====
o Supervised?
o Start with the simplest model that fits your problem
o Start with minimal processing of data
!split
===== Preparing Your Data =====
o Shuffle your data
o Mean center your data
* Why?
o Normalize the variance
* Why?
o _Whitening_
* Decorrelates data
* Can be hit or miss
o When to do train/test split?
!split
===== Which Activation and Weights to Choose in Neural Networks =====
o RELU? ELU?
o Sigmoid or Tanh?
o Set all weights to 0?
* Terrible idea
o Set all weights to random values?
* Small random values
!split
===== Optimization Methods and Hyperparameters =====
o Stochastic gradient descent
o Stochastic gradient descent + momentum
o State-of-the-art approaches:
* RMSProp
* Adam
Which regularization and hyperparameters? $L_1$ or $L_2$, soft classifiers, depths of trees and many other. Need to explore a large set of hyperparameters and regularization methods.
!split
===== Resampling =====
When do we resample?
o Bootstrap
o Cross-validation
o Jackknife and many other
!split
===== Other courses on Data science and Machine Learning at UiO =====
The link here URL:"https://www.mn.uio.no/english/research/about/centre-focus/innovation/data-science/studies/" gives an excellent overview of courses on Machine learning at UiO.
o "STK2100 Machine learning and statistical methods for prediction and classification":"http://www.uio.no/studier/emner/matnat/math/STK2100/index-eng.html".
o "IN3050/IN4050 Introduction to Artificial Intelligence and Machine Learning":"https://www.uio.no/studier/emner/matnat/ifi/IN3050/index-eng.html". Introductory course in machine learning and AI with an algorithmic approach.
o "STK-INF3000/4000 Selected Topics in Data Science":"http://www.uio.no/studier/emner/matnat/math/STK-INF3000/index-eng.html". The course provides insight into selected contemporary relevant topics within Data Science.
o "IN4080 Natural Language Processing":"https://www.uio.no/studier/emner/matnat/ifi/IN4080/index.html". Probabilistic and machine learning techniques applied to natural language processing.
o "STK-IN4300 Statistical learning methods in Data Science":"https://www.uio.no/studier/emner/matnat/math/STK-IN4300/index-eng.html". An advanced introduction to statistical and machine learning. For students with a good mathematics and statistics background.
o "IN-STK5000 Adaptive Methods for Data-Based Decision Making":"https://www.uio.no/studier/emner/matnat/ifi/IN-STK5000/index-eng.html". Methods for adaptive collection and processing of data based on machine learning techniques.
o "IN5400/INF5860 Machine Learning for Image Analysis":"https://www.uio.no/studier/emner/matnat/ifi/IN5400/". An introduction to deep learning with particular emphasis on applications within Image analysis, but useful for other application areas too.
o "TEK5040 Dyp læring for autonome systemer":"https://www.uio.no/studier/emner/matnat/its/TEK5040/". The course addresses advanced algorithms and architectures for deep learning with neural networks. The course provides an introduction to how deep-learning techniques can be used in the construction of key parts of advanced autonomous systems that exist in physical environments and cyber environments.
!split
===== Additional courses of interest =====
o "STK4051 Computational Statistics":"https://www.uio.no/studier/emner/matnat/math/STK4051/index-eng.html"
o "STK4021 Applied Bayesian Analysis and Numerical Methods":"https://www.uio.no/studier/emner/matnat/math/STK4021/index-eng.html"
!split
===== What's the future like? =====
Based on multi-layer nonlinear neural networks, deep learning can
learn directly from raw data, automatically extract and abstract
features from layer to layer, and then achieve the goal of regression,
classification, or ranking. Deep learning has made breakthroughs in
computer vision, speech processing and natural language, and reached
or even surpassed human level. The success of deep learning is mainly
due to the three factors: big data, big model, and big computing.
In the past few decades, many different architectures of deep neural
networks have been proposed, such as
o Convolutional neural networks, which are mostly used in image and video data processing, and have also been applied to sequential data such as text processing;
o Recurrent neural networks, which can process sequential data of variable length and have been widely used in natural language understanding and speech processing;
o Encoder-decoder framework, which is mostly used for image or sequence generation, such as machine translation, text summarization, and image captioning.
!split
===== Bayesian Machine Learning =====
This is an important topic if we aim at extracting a probability
distribution. This gives us also a confidence interval and error
estimates.
Bayesian machine learning allows us to encode our prior beliefs about
what those models should look like, independent of what the data tells
us. This is especially useful when we dont have a ton of data to
confidently learn our model.
!split
===== Reinforcement Learning =====
Reinforcement learning is a sub-area of machine learning. It studies
how agents take actions based on trial and error, so as to maximize
some notion of cumulative reward in a dynamic system or
environment. Due to its generality, the problem has also been studied
in many other disciplines, such as game theory, control theory,
operations research, information theory, multi-agent systems, swarm
intelligence, statistics, and genetic algorithms.
In March 2016, AlphaGo, a computer program that plays the board game
Go, beat Lee Sedol in a five-game match. This was the first time a
computer Go program had beaten a 9-dan (highest rank) professional
without handicaps. AlphaGo is based on deep convolutional neural
networks and reinforcement learning. AlphaGos victory was a major
milestone in artificial intelligence and it has also made
reinforcement learning a hot research area in the field of machine
learning.
!split
===== Transfer learning =====
The goal of transfer learning is to transfer the model or knowledge
obtained from a source task to the target task, in order to resolve
the issues of insufficient training data in the target task. The
rationality of doing so lies in that usually the source and target
tasks have inter-correlations, and therefore either the features,
samples, or models in the source task might provide useful information
for us to better solve the target task. Transfer learning is a hot
research topic in recent years, with many problems still waiting to be
solved in this space.
!split
===== Adversarial learning =====
The conventional deep generative model has a potential problem: the
model tends to generate extreme instances to maximize the
probabilistic likelihood, which will hurt its performance. Adversarial
learning utilizes the adversarial behaviors (e.g., generating
adversarial instances or training an adversarial model) to enhance the
robustness of the model and improve the quality of the generated
data. In recent years, one of the most promising unsupervised learning
technologies, generative adversarial networks (GAN), has already been
successfully applied to image, speech, and text.
!split
===== Dual learning =====
Dual learning is a new learning paradigm, the basic idea of which is
to use the primal-dual structure between machine learning tasks to
obtain effective feedback/regularization, and guide and strengthen the
learning process, thus reducing the requirement of large-scale labeled
data for deep learning. The idea of dual learning has been applied to
many problems in machine learning, including machine translation,
image style conversion, question answering and generation, image
classification and generation, text classification and generation,
image-to-text, and text-to-image.
!split
===== Distributed machine learning =====
Distributed computation will speed up machine learning algorithms,
significantly improve their efficiency, and thus enlarge their
application. When distributed meets machine learning, more than just
implementing the machine learning algorithms in parallel is required.
!split
===== Meta learning =====
Meta learning is an emerging research direction in machine
learning. Roughly speaking, meta learning concerns learning how to
learn, and focuses on the understanding and adaptation of the learning
itself, instead of just completing a specific learning task. That is,
a meta learner needs to be able to evaluate its own learning methods
and adjust its own learning methods according to specific learning
tasks.
!split
===== The Challenges Facing Machine Learning =====
While there has been much progress in machine learning, there are also challenges.
For example, the mainstream machine learning technologies are
black-box approaches, making us concerned about their potential
risks. To tackle this challenge, we may want to make machine learning
more explainable and controllable. As another example, the
computational complexity of machine learning algorithms is usually
very high and we may want to invent lightweight algorithms or
implementations. Furthermore, in many domains such as physics,
chemistry, biology, and social sciences, people usually seek elegantly
simple equations (e.g., the Schrödinger equation) to uncover the
underlying laws behind various phenomena. In the field of machine
learning, can we reveal simple laws instead of designing more complex
models for data fitting? Although there are many challenges, we are
still very optimistic about the future of machine learning. As we look
forward to the future, here are what we think the research hotspots in
the next ten years will be.
!split
===== Explainable machine learning =====
Machine learning, especially deep learning, evolves rapidly. The
ability gap between machine and human on many complex cognitive tasks
becomes narrower and narrower. However, we are still in the very early
stage in terms of explaining why those effective models work and how
they work.
What is missing: the gap between correlation and causation Most
machine learning techniques, especially the statistical ones, depend
highly on data correlation to make predictions and analyses. In
contrast, rational humans tend to reply on clear and trustworthy
causality relations obtained via logical reasoning on real and clear
facts. It is one of the core goals of explainable machine learning to
transition from solving problems by data correlation to solving
problems by logical reasoning.
!split
===== Quantum machine learning =====
Quantum machine learning is an emerging interdisciplinary research
area at the intersection of quantum computing and machine learning.
Quantum computers use effects such as quantum coherence and quantum
entanglement to process information, which is fundamentally different
from classical computers. Quantum algorithms have surpassed the best
classical algorithms in several problems (e.g., searching for an
unsorted database, inverting a sparse matrix), which we call quantum
acceleration.
When quantum computing meets machine learning, it can be a mutually
beneficial and reinforcing process, as it allows us to take advantage
of quantum computing to improve the performance of classical machine
learning algorithms. In addition, we can also use the machine learning
algorithms (on classic computers) to analyze and improve quantum
computing systems.
!split
===== Quantum machine learning algorithms based on linear algebra =====
Many quantum machine learning algorithms are based on variants of
quantum algorithms for solving linear equations, which can efficiently
solve N-variable linear equations with complexity of O(log2 N) under
certain conditions. The quantum matrix inversion algorithm can
accelerate many machine learning methods, such as least square linear
regression, least square version of support vector machine, Gaussian
process, and more. The training of these algorithms can be simplified
to solve linear equations. The key bottleneck of this type of quantum
machine learning algorithms is data input—that is, how to initialize
the quantum system with the entire data set. Although efficient
data-input algorithms exist for certain situations, how to efficiently
input data into a quantum system is as yet unknown for most cases.
!split
===== Quantum reinforcement learning =====
In quantum reinforcement learning, a quantum agent interacts with the
classical environment to obtain rewards from the environment, so as to
adjust and improve its behavioral strategies. In some cases, it
achieves quantum acceleration by the quantum processing capabilities
of the agent or the possibility of exploring the environment through
quantum superposition. Such algorithms have been proposed in
superconducting circuits and systems of trapped ions.
!split
===== Quantum deep learning =====
Dedicated quantum information processors, such as quantum annealers
and programmable photonic circuits, are well suited for building deep
quantum networks. The simplest deep quantum network is the Boltzmann
machine. The classical Boltzmann machine consists of bits with tunable
interactions and is trained by adjusting the interaction of these bits
so that the distribution of its expression conforms to the statistics
of the data. To quantize the Boltzmann machine, the neural network can
simply be represented as a set of interacting quantum spins that
correspond to an adjustable Ising model. Then, by initializing the
input neurons in the Boltzmann machine to a fixed state and allowing
the system to heat up, we can read out the output qubits to get the
result.
!split
===== Social machine learning =====
Machine learning aims to imitate how humans
learn. While we have developed successful machine learning algorithms,
until now we have ignored one important fact: humans are social. Each
of us is one part of the total society and it is difficult for us to
live, learn, and improve ourselves, alone and isolated. Therefore, we
should design machines with social properties. Can we let machines
evolve by imitating human society so as to achieve more effective,
intelligent, interpretable “social machine learning”?
And much more.
!split
===== The last words? =====
Early computer scientist Alan Kay said, _The best way to predict the
future is to create it_. Therefore, all machine learning
practitioners, whether scholars or engineers, professors or students,
need to work together to advance these important research
topics. Together, we will not just predict the future, but create it.
!split
===== Best wishes to you all and thanks so much for your heroic efforts this semester =====
FIGURE: [figures/Nebbdyr2.png, width=500 frac=0.6]