diff --git a/README.md b/README.md index 458ee77cd..c02ab72a6 100644 --- a/README.md +++ b/README.md @@ -383,9 +383,11 @@ Recommended prereading: Chapters 1-2 (linear algebra) and chapter 3 (statistics) - Hastie et al sections 9.1 and 9.2. Geron's text chapter 6 (Decision trees) and chapter 8 on PCA and Clustering ### Week 45 November 8-12 -- Lab Wednesday: Work on project 2, project 3 available Friday 12th. Deadline project 2 is November 15. +- Lab Wednesday: Work on project 2, project 3 available Friday 12th. Deadline project 2 is November 20. - Lecture Thursday: Decision Trees and Ensemble methods, Bagging and Voting + - Video of Lecture at https://www.uio.no/studier/emner/matnat/fys/FYS-STK3155/h21/forelesningsvideoer/LectureNovember11.mp4?vrtx=view-as-webpage - Lecture Friday: Ensemble Methods, Random Forests, Boosting and gradient boosting + - Video of Lecture at https://www.uio.no/studier/emner/matnat/fys/FYS-STK3155/h21/forelesningsvideoer/LectureNovember12.mp4?vrtx=view-as-webpage - Reading recommendations: - See lecture notes for week 45 at https://compphysics.github.io/MachineLearning/doc/web/course.html. - Decision Trees: Geron's chapter 6 covers decision trees while ensemble models, voting and bagging are discussed in chapter 7. @@ -394,11 +396,12 @@ Recommended prereading: Chapters 1-2 (linear algebra) and chapter 3 (statistics) ### Week 46 November 15-19 - Lab Wednesday: Work on project 3 -- Lecture Thursday: Ensemble Methods, Random Forests, Boosting and gradient boosting -- Lecture Friday: Support Vector machines +- Lecture Thursday: Support Vector machines. Summary Ensemble Methods, Random Forests, Boosting and gradient boosting +- Lecture Friday: Workshop on project 3 - Reading recommendations: - See lecture notes for week 46 at https://compphysics.github.io/MachineLearning/doc/web/course.html. - Hastie et al chapter 12 + - Bishop chapter 7.1 and 7.2 ### Week 47 November 22-26 - Lab Wednesday: Work on project 3 diff --git a/doc/HandWrittenNotes/2021/NotesNovember12.pdf b/doc/HandWrittenNotes/2021/NotesNovember12.pdf new file mode 100644 index 000000000..f18c4e16d Binary files /dev/null and b/doc/HandWrittenNotes/2021/NotesNovember12.pdf differ diff --git a/doc/LectureNotes/schedule.md b/doc/LectureNotes/schedule.md index 9333732d7..2c066d3aa 100644 --- a/doc/LectureNotes/schedule.md +++ b/doc/LectureNotes/schedule.md @@ -154,7 +154,9 @@ For the reading assignments we use the following abbreviations: ### Week 45 November 8-12 - Lab Wednesday: Work on project 2, project 3 available. Deadline project 2 is November 15. - Lecture Thursday: Ensemble methods, bagging and random forests + - Video of Lecture at https://www.uio.no/studier/emner/matnat/fys/FYS-STK3155/h21/forelesningsvideoer/LectureNovember11.mp4?vrtx=view-as-webpage - Lecture Friday: Boosting and gradient boosting + - Video of Lecture at https://www.uio.no/studier/emner/matnat/fys/FYS-STK3155/h21/forelesningsvideoer/LectureNovember12.mp4?vrtx=view-as-webpage - Reading recommendations: - See lecture notes for week 45 at https://compphysics.github.io/MachineLearning/doc/web/course.html. - Hastie et al chapter 10 diff --git a/doc/Projects/2020/Project3/html/._Project3-bs000.html b/doc/Projects/2020/Project3/html/._Project3-bs000.html new file mode 100644 index 000000000..47e28dced --- /dev/null +++ b/doc/Projects/2020/Project3/html/._Project3-bs000.html @@ -0,0 +1,440 @@ + + + + + + + +Project 3 on Machine Learning, deadline December 17, 2021 + + + + + + + + + + + + + + + + + + + + +
+

 

 

 

+ + +
+
+

Project 3 on Machine Learning, deadline December 17, 2021

+
+ + +
+Data Analysis and Machine Learning FYS-STK3155/FYS4155 +
+ +
+Department of Physics, University of Oslo, Norway +
+
+
+

Nov 13, 2021

+
+
+ + +
+

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

+
    +
  1. Kaggle
  2. +
  3. The University of California at Irvine (UCI) with its machine learning repository.
  4. +
+

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:

+
    +
  1. 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.
  2. +
+

For Boosting, feel also free to write your own codes.

+ +
    +
  1. 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.
  2. +
  3. 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.
  4. +
  5. Similarly, feel free to explore various activations functions in deep learning and various approachs to stochastic gradient descent approaches.
  6. +
  7. 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?
  8. +
  9. A critical assessment of the methods with ditto perspectives and recommendations is also something you need to include.
  10. +
+

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 and/or the textbook by Yadav et al.

+

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 or alternative sources. For the solution of ordinary and partial differential equations using neural networks, the lectures by Kristine Baluka Hein 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 +

+ +$$ +\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*} +$$ + +

or

+ +$$ +\begin{equation*} +u_{xx} = u_t, +\end{equation*} +$$ + +

with initial conditions, i.e., the conditions at \( t=0 \),

+$$ +\begin{equation*} +u(x,0)= \sin{(\pi x)} \hspace{0.5cm} 0 < x < L, +\end{equation*} +$$ + +

with \( L=1 \) the length of the \( x \)-region of interest. The +boundary conditions are +

+ +$$ +\begin{equation*} +u(0,t)= 0 \hspace{0.5cm} t \ge 0, +\end{equation*} +$$ + +

and

+ +$$ +\begin{equation*} +u(L,t)= 0 \hspace{0.5cm} t \ge 0. +\end{equation*} +$$ + +

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

+$$ +\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*} +$$ + +

and

+ +$$ +\begin{equation*} +u_{xx}\approx \frac{u(x+\Delta x,t)-2u(x,t)+u(x-\Delta x,t)}{\Delta x^2}, +\end{equation*} +$$ + +

or

+ +$$ +\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*} +$$ + +

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), 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. +

+ + +

Introduction to numerical projects

+ +

Here follows a brief recipe and recommendation on how to write a report for each +project. +

+ + +

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:

+ + +

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 +

+
    +
  1. pip install numpy scipy matplotlib ipython scikit-learn tensorflow sympy pandas pillow
  2. +
+

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 +

+
    +
  1. brew install python3
  2. +
+

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 +

+
    +
  1. sudo apt-get install python3 (or python for python2.7)
  2. +
+

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

+
    +
  1. Anaconda 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
  2. +
  3. Enthought canopy is a Python distribution for scientific and analytic computing distribution and analysis environment, available for free and under a commercial license.
  4. +
+

Popular software packages written in Python for ML are

+ + +

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. +

+ +

+ +

+ +
+ + + + +
+ © 1999-2021, "Data Analysis and Machine Learning FYS-STK3155/FYS4155":"http://www.uio.no/studier/emner/matnat/fys/FYS3155/index-eng.html". Released under CC Attribution-NonCommercial 4.0 license +
+ + + diff --git a/doc/Projects/2020/Project3/html/Project3-bs.html b/doc/Projects/2020/Project3/html/Project3-bs.html index 85eb0aa16..47e28dced 100644 --- a/doc/Projects/2020/Project3/html/Project3-bs.html +++ b/doc/Projects/2020/Project3/html/Project3-bs.html @@ -1,31 +1,28 @@ - + - - -Project 3 on Machine Learning, deadline December 16 - + +Project 3 on Machine Learning, deadline December 17, 2021 + - - - @@ -87,8 +100,6 @@ MathJax.Hub.Config({ - - -
-

 

 

 

- - - -
-

Project 3 on Machine Learning, deadline December 16

+
+

Project 3 on Machine Learning, deadline December 17, 2021

+
-

-

Data Analysis and Machine Learning FYS-STK3155/FYS4155
- -

+

+Department of Physics, University of Oslo, Norway +
+
+
+

Nov 13, 2021

+
+
+ -
Department of Physics, University of Oslo, Norway
-
-

-

Dec 11, 2020

-
-

+

Paths for project 3

+

Defining the data sets to analyze yourself

-

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 - +

For project 3, you can propose own data sets that relate to your research interests or just use existing data sets from say

  1. Kaggle
  2. The University of California at Irvine (UCI) with its machine learning repository.
- -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: - +

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:

  1. 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. +

For Boosting, feel also free to write your own codes.

  1. 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.
  2. @@ -188,66 +186,47 @@ For Boosting, feel also free to write your own codes.
  3. 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?
  4. 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..

-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..

-

-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 and/or the textbook by Yadav et al.

+

The basic structure of your project

-

-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 and/or the textbook by Yadav et al. +

Here follows a set up on how to structure your report and analyze the data you have opted for.

+

Part a)

-

The basic structure of your project

+

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)

-

-Here follows a set up on how to structure your report and analyze the data you have opted for. +

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)

-

Part a)

+

Then describe your algorithm and its implementation and tests you have performed.

+

Part d)

-

-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. +

Then presents your results and findings, link with existing literature and more.

+

Part e)

-

Part b)

+

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

-

-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 +

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 or alternative sources. For the solution of ordinary and partial differential equations using neural networks, the lectures by Kristine Baluka Hein at this course are highly recommended. +

For the explicit scheme, you can study for example chapter 10 of the lecture notes in Computational Physics or alternative sources. For the solution of ordinary and partial differential equations using neural networks, the lectures by Kristine Baluka Hein 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.. +

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

-

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 \). +

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 +

$$ \begin{equation*} @@ -255,7 +234,7 @@ $$ \end{equation*} $$ -or +

or

$$ \begin{equation*} @@ -263,15 +242,16 @@ u_{xx} = u_t, \end{equation*} $$ -with initial conditions, i.e., the conditions at \( t=0 \), +

with initial conditions, i.e., the conditions at \( t=0 \),

$$ \begin{equation*} u(x,0)= \sin{(\pi x)} \hspace{0.5cm} 0 < x < L, \end{equation*} $$ -with \( L=1 \) the length of the \( x \)-region of interest. The +

with \( L=1 \) the length of the \( x \)-region of interest. The boundary conditions are +

$$ \begin{equation*} @@ -279,7 +259,7 @@ u(0,t)= 0 \hspace{0.5cm} t \ge 0, \end{equation*} $$ -and +

and

$$ \begin{equation*} @@ -287,18 +267,18 @@ u(L,t)= 0 \hspace{0.5cm} t \ge 0. \end{equation*} $$ -The function \( u(x,t) \) can be the temperature gradient of a rod. -As time increases, the velocity approaches a linear variation with \( x \). +

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 +

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

$$ \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*} $$ -and +

and

$$ \begin{equation*} @@ -306,7 +286,7 @@ u_{xx}\approx \frac{u(x+\Delta x,t)-2u(x,t)+u(x-\Delta x,t)}{\Delta x^2}, \end{equation*} $$ -or +

or

$$ \begin{equation*} @@ -314,49 +294,43 @@ u_{xx}\approx \frac{u(x_i+\Delta x,t_j)-2u(x_i,t_j)+u(x_i-\Delta x,t_j)}{\Delta \end{equation*} $$ -

-Write down the algorithm and the equations you need to implement. -Find also the analytical solution to the problem. +

Write down the algorithm and the equations you need to implement. +Find also the analytical solution to the problem. +

+

Part b)

-

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 \). +

-

-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 +

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

-

Part c) Neural networks

- -

-Study now the lecture notes on solving ODEs and PDEs with neural +

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

-

Part d) Solving eigenvalue problems

- -

-Follow the discussion in the work of Yi et al. in the article from +

Follow the discussion in the work of Yi et al. in the article from Computers and Mathematics with Applications 47, 1155 (2004), 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)

-

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

-

-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 +

Here follows a brief recipe and recommendation on how to write a report for each project. +

+

Introduction to numerical projects

-

Introduction to numerical projects

- -

-Here follows a brief recipe and recommendation on how to write a report for each +

Here follows a brief recipe and recommendation on how to write a report for each project. +

+

Format for electronic delivery of report and programs

-

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: +

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:

- -Finally, +

Finally, we encourage you to collaborate. Optimal working groups consist of -2-3 students. You can then hand in a common report. +2-3 students. You can then hand in a common report. +

+

Software and needed installations

-

Software and needed installations

- -

-If you have Python installed (we recommend Python3) and you feel pretty familiar with installing different packages, +

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 - +

  1. pip install numpy scipy matplotlib ipython scikit-learn tensorflow sympy pandas pillow
+

For Python3, replace pip with pip3.

-For Python3, replace pip with pip3. +

See below for a discussion of tensorflow and scikit-learn.

-

-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 OSX users we recommend also, after having installed Xcode, to install brew. Brew allows for a seamless installation of additional software via for example - +

  1. brew install python3
- -For Linux users, with its variety of distributions like for example the widely popular Ubuntu distribution +

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 - +

  1. sudo apt-get install python3 (or python for python2.7)
+

etc etc.

-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 - +

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

  1. Anaconda 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
  2. Enthought 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 +

Popular software packages written in Python for ML are

- -These are all freely available at their respective GitHub sites. They +

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. - -

+

@@ -464,25 +423,18 @@ of code developers and contributors keeps increasing.

  • 1
  • -
    - - -
    - © 1999-2020, "Data Analysis and Machine Learning FYS-STK3155/FYS4155":"http://www.uio.no/studier/emner/matnat/fys/FYS3155/index-eng.html". Released under CC Attribution-NonCommercial 4.0 license + © 1999-2021, "Data Analysis and Machine Learning FYS-STK3155/FYS4155":"http://www.uio.no/studier/emner/matnat/fys/FYS3155/index-eng.html". Released under CC Attribution-NonCommercial 4.0 license
    - - - diff --git a/doc/Projects/2020/Project3/html/Project3.html b/doc/Projects/2020/Project3/html/Project3.html index 02711eb55..de797d882 100644 --- a/doc/Projects/2020/Project3/html/Project3.html +++ b/doc/Projects/2020/Project3/html/Project3.html @@ -1,72 +1,164 @@ - + - - -Project 3 on Machine Learning, deadline December 16 - - + +Project 3 on Machine Learning, deadline December 17, 2021 - - @@ -86,49 +178,37 @@ MathJax.Hub.Config({ - - +
    +

    Project 3 on Machine Learning, deadline December 17, 2021

    +
    - - -

    Project 3 on Machine Learning, deadline December 16

    - -

    -

    Data Analysis and Machine Learning FYS-STK3155/FYS4155
    - -

    - -

    Department of Physics, University of Oslo, Norway
    +
    +Department of Physics, University of Oslo, Norway +

    -

    -

    Dec 11, 2020

    +
    +

    Nov 13, 2021

    +

    +

    Paths for project 3

    +

    Defining the data sets to analyze yourself

    -

    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 - +

    For project 3, you can propose own data sets that relate to your research interests or just use existing data sets from say

    1. Kaggle
    2. The University of California at Irvine (UCI) with its machine learning repository.
    - -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: - +

    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:

    1. 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. +

    For Boosting, feel also free to write your own codes.

    1. 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.
    2. @@ -137,66 +217,47 @@ For Boosting, feel also free to write your own codes.
    3. 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?
    4. 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..

    -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..

    -

    -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 and/or the textbook by Yadav et al.

    +

    The basic structure of your project

    -

    -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 and/or the textbook by Yadav et al. +

    Here follows a set up on how to structure your report and analyze the data you have opted for.

    +

    Part a)

    -

    The basic structure of your project

    +

    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)

    -

    -Here follows a set up on how to structure your report and analyze the data you have opted for. +

    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)

    -

    Part a)

    +

    Then describe your algorithm and its implementation and tests you have performed.

    +

    Part d)

    -

    -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. +

    Then presents your results and findings, link with existing literature and more.

    +

    Part e)

    -

    Part b)

    +

    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

    -

    -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 +

    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 or alternative sources. For the solution of ordinary and partial differential equations using neural networks, the lectures by Kristine Baluka Hein at this course are highly recommended. +

    For the explicit scheme, you can study for example chapter 10 of the lecture notes in Computational Physics or alternative sources. For the solution of ordinary and partial differential equations using neural networks, the lectures by Kristine Baluka Hein 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.. +

    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

    -

    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 \). +

    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 +

    $$ \begin{equation*} @@ -204,7 +265,7 @@ $$ \end{equation*} $$ -or +

    or

    $$ \begin{equation*} @@ -212,15 +273,16 @@ u_{xx} = u_t, \end{equation*} $$ -with initial conditions, i.e., the conditions at \( t=0 \), +

    with initial conditions, i.e., the conditions at \( t=0 \),

    $$ \begin{equation*} u(x,0)= \sin{(\pi x)} \hspace{0.5cm} 0 < x < L, \end{equation*} $$ -with \( L=1 \) the length of the \( x \)-region of interest. The +

    with \( L=1 \) the length of the \( x \)-region of interest. The boundary conditions are +

    $$ \begin{equation*} @@ -228,7 +290,7 @@ u(0,t)= 0 \hspace{0.5cm} t \ge 0, \end{equation*} $$ -and +

    and

    $$ \begin{equation*} @@ -236,18 +298,18 @@ u(L,t)= 0 \hspace{0.5cm} t \ge 0. \end{equation*} $$ -The function \( u(x,t) \) can be the temperature gradient of a rod. -As time increases, the velocity approaches a linear variation with \( x \). +

    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 +

    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

    $$ \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*} $$ -and +

    and

    $$ \begin{equation*} @@ -255,7 +317,7 @@ u_{xx}\approx \frac{u(x+\Delta x,t)-2u(x,t)+u(x-\Delta x,t)}{\Delta x^2}, \end{equation*} $$ -or +

    or

    $$ \begin{equation*} @@ -263,49 +325,43 @@ u_{xx}\approx \frac{u(x_i+\Delta x,t_j)-2u(x_i,t_j)+u(x_i-\Delta x,t_j)}{\Delta \end{equation*} $$ -

    -Write down the algorithm and the equations you need to implement. -Find also the analytical solution to the problem. +

    Write down the algorithm and the equations you need to implement. +Find also the analytical solution to the problem. +

    +

    Part b)

    -

    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 \). +

    -

    -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 +

    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

    -

    Part c) Neural networks

    - -

    -Study now the lecture notes on solving ODEs and PDEs with neural +

    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

    -

    Part d) Solving eigenvalue problems

    - -

    -Follow the discussion in the work of Yi et al. in the article from +

    Follow the discussion in the work of Yi et al. in the article from Computers and Mathematics with Applications 47, 1155 (2004), 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)

    -

    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

    -

    -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 +

    Here follows a brief recipe and recommendation on how to write a report for each project. +

    +

    Introduction to numerical projects

    -

    Introduction to numerical projects

    - -

    -Here follows a brief recipe and recommendation on how to write a report for each +

    Here follows a brief recipe and recommendation on how to write a report for each project. +

    +

    Format for electronic delivery of report and programs

    -

    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: +

    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:

    - -Finally, +

    Finally, we encourage you to collaborate. Optimal working groups consist of -2-3 students. You can then hand in a common report. +2-3 students. You can then hand in a common report. +

    +

    Software and needed installations

    -

    Software and needed installations

    - -

    -If you have Python installed (we recommend Python3) and you feel pretty familiar with installing different packages, +

    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 - +

    1. pip install numpy scipy matplotlib ipython scikit-learn tensorflow sympy pandas pillow
    +

    For Python3, replace pip with pip3.

    -For Python3, replace pip with pip3. +

    See below for a discussion of tensorflow and scikit-learn.

    -

    -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 OSX users we recommend also, after having installed Xcode, to install brew. Brew allows for a seamless installation of additional software via for example - +

    1. brew install python3
    - -For Linux users, with its variety of distributions like for example the widely popular Ubuntu distribution +

    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 - +

    1. sudo apt-get install python3 (or python for python2.7)
    +

    etc etc.

    -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 - +

    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

    1. Anaconda 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
    2. Enthought 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 +

    Popular software packages written in Python for ML are

    - -These are all freely available at their respective GitHub sites. They +

    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. - -

    +

    - -
    - © 1999-2020, "Data Analysis and Machine Learning FYS-STK3155/FYS4155":"http://www.uio.no/studier/emner/matnat/fys/FYS3155/index-eng.html". Released under CC Attribution-NonCommercial 4.0 license + © 1999-2021, "Data Analysis and Machine Learning FYS-STK3155/FYS4155":"http://www.uio.no/studier/emner/matnat/fys/FYS3155/index-eng.html". Released under CC Attribution-NonCommercial 4.0 license
    - - - diff --git a/doc/Projects/2020/Project3/ipynb/Project3.ipynb b/doc/Projects/2020/Project3/ipynb/Project3.ipynb index a84d561d2..87b64320c 100644 --- a/doc/Projects/2020/Project3/ipynb/Project3.ipynb +++ b/doc/Projects/2020/Project3/ipynb/Project3.ipynb @@ -2,23 +2,48 @@ "cells": [ { "cell_type": "markdown", - "metadata": {}, + "id": "4eefd1b6", + "metadata": { + "editable": true + }, "source": [ - "\n", - "# Project 3 on Machine Learning, deadline December 16\n", - "\n", - " \n", + "\n", + "" + ] + }, + { + "cell_type": "markdown", + "id": "60bedd95", + "metadata": { + "editable": true + }, + "source": [ + "# Project 3 on Machine Learning, deadline December 17, 2021\n", "**[Data Analysis and Machine Learning FYS-STK3155/FYS4155](http://www.uio.no/studier/emner/matnat/fys/FYS3155/index-eng.html)**, Department of Physics, University of Oslo, Norway\n", "\n", - "Date: **Dec 11, 2020**\n", - "\n", - "Copyright 1999-2020, [Data Analysis and Machine Learning FYS-STK3155/FYS4155](http://www.uio.no/studier/emner/matnat/fys/FYS3155/index-eng.html). Released under CC Attribution-NonCommercial 4.0 license\n", - "\n", - "\n", - "\n", - "\n", - "# Paths for project 3\n", + "Date: **Nov 13, 2021**\n", "\n", + "Copyright 1999-2021, [Data Analysis and Machine Learning FYS-STK3155/FYS4155](http://www.uio.no/studier/emner/matnat/fys/FYS3155/index-eng.html). Released under CC Attribution-NonCommercial 4.0 license" + ] + }, + { + "cell_type": "markdown", + "id": "4c0f2617", + "metadata": { + "editable": true + }, + "source": [ + "# Paths for project 3" + ] + }, + { + "cell_type": "markdown", + "id": "6d6a33a8", + "metadata": { + "editable": true + }, + "source": [ "## Defining the data sets to analyze yourself\n", "\n", "For project 3, you can propose own data sets that relate to your research interests or just use existing data sets from say\n", @@ -45,33 +70,88 @@ "\n", "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.. \n", "\n", - "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).\n", - "\n", + "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)." + ] + }, + { + "cell_type": "markdown", + "id": "93851dd6", + "metadata": { + "editable": true + }, + "source": [ "## The basic structure of your project\n", "\n", - "Here follows a set up on how to structure your report and analyze the data you have opted for.\n", - "\n", + "Here follows a set up on how to structure your report and analyze the data you have opted for." + ] + }, + { + "cell_type": "markdown", + "id": "d43e8960", + "metadata": { + "editable": true + }, + "source": [ "### Part a)\n", "\n", - "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.\n", - "\n", + "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." + ] + }, + { + "cell_type": "markdown", + "id": "e8204f03", + "metadata": { + "editable": true + }, + "source": [ "### Part b)\n", "\n", - "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.\n", - "\n", - "\n", + "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." + ] + }, + { + "cell_type": "markdown", + "id": "dbc59b86", + "metadata": { + "editable": true + }, + "source": [ "### Part c)\n", "\n", - "Then describe your algorithm and its implementation and tests you have performed.\n", - "\n", + "Then describe your algorithm and its implementation and tests you have performed." + ] + }, + { + "cell_type": "markdown", + "id": "dcff5b58", + "metadata": { + "editable": true + }, + "source": [ "### Part d)\n", "\n", - "Then presents your results and findings, link with existing literature and more.\n", - "\n", + "Then presents your results and findings, link with existing literature and more." + ] + }, + { + "cell_type": "markdown", + "id": "70e05a5c", + "metadata": { + "editable": true + }, + "source": [ "### Part e)\n", "\n", - "Finally, here you should present a critical assessment of the methods you have studied and link your results with the existing literature. \n", - "\n", + "Finally, here you should present a critical assessment of the methods you have studied and link your results with the existing literature." + ] + }, + { + "cell_type": "markdown", + "id": "7899934c", + "metadata": { + "editable": true + }, + "source": [ "## Solving partial differential equations with neural networks\n", "\n", "For this variant of project 3, we will assume that you have some\n", @@ -82,8 +162,16 @@ "\n", "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.\n", "\n", - "For the machine learning part you can use your own code from project 2 or the functionality of for example **Tensorflow/Keras**.. \n", - "\n", + "For the machine learning part you can use your own code from project 2 or the functionality of for example **Tensorflow/Keras**.." + ] + }, + { + "cell_type": "markdown", + "id": "054d1255", + "metadata": { + "editable": true + }, + "source": [ "### Part a), setting up the problem\n", "\n", "The physical problem can be that of the temperature gradient in a rod of length $L=1$ at $x=0$ and $x=1$.\n", @@ -93,7 +181,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "f0a14045", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\frac{\\partial^2 u(x,t)}{\\partial x^2} =\\frac{\\partial u(x,t)}{\\partial t}, t> 0, x\\in [0,L]\n", @@ -102,14 +193,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "c115bb19", + "metadata": { + "editable": true + }, "source": [ "or" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "6f297b9e", + "metadata": { + "editable": true + }, "source": [ "$$\n", "u_{xx} = u_t,\n", @@ -118,14 +215,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "b7eecb41", + "metadata": { + "editable": true + }, "source": [ "with initial conditions, i.e., the conditions at $t=0$," ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "b7ae63ad", + "metadata": { + "editable": true + }, "source": [ "$$\n", "u(x,0)= \\sin{(\\pi x)} \\hspace{0.5cm} 0 < x < L,\n", @@ -134,7 +237,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "1536c36b", + "metadata": { + "editable": true + }, "source": [ "with $L=1$ the length of the $x$-region of interest. The \n", "boundary conditions are" @@ -142,7 +248,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "a4b5e85c", + "metadata": { + "editable": true + }, "source": [ "$$\n", "u(0,t)= 0 \\hspace{0.5cm} t \\ge 0,\n", @@ -151,14 +260,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "017a9c0e", + "metadata": { + "editable": true + }, "source": [ "and" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "47b0930b", + "metadata": { + "editable": true + }, "source": [ "$$\n", "u(L,t)= 0 \\hspace{0.5cm} t \\ge 0.\n", @@ -167,7 +282,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "5d12978d", + "metadata": { + "editable": true + }, "source": [ "The function $u(x,t)$ can be the temperature gradient of a rod.\n", "As time increases, the velocity approaches a linear variation with $x$. \n", @@ -177,7 +295,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "99a443e1", + "metadata": { + "editable": true + }, "source": [ "$$\n", "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}\n", @@ -186,14 +307,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "efb9d4ad", + "metadata": { + "editable": true + }, "source": [ "and" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "e4701f46", + "metadata": { + "editable": true + }, "source": [ "$$\n", "u_{xx}\\approx \\frac{u(x+\\Delta x,t)-2u(x,t)+u(x-\\Delta x,t)}{\\Delta x^2},\n", @@ -202,14 +329,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "7a568111", + "metadata": { + "editable": true + }, "source": [ "or" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "4ae11074", + "metadata": { + "editable": true + }, "source": [ "$$\n", "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}.\n", @@ -218,20 +351,38 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "3b111fdd", + "metadata": { + "editable": true + }, "source": [ "Write down the algorithm and the equations you need to implement.\n", - "Find also the analytical solution to the problem. \n", - "\n", + "Find also the analytical solution to the problem." + ] + }, + { + "cell_type": "markdown", + "id": "b107a067", + "metadata": { + "editable": true + }, + "source": [ "### Part b)\n", "\n", "Implement the explicit scheme algorithm and perform tests of the solution \n", "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$. \n", "\n", "Study the solutions at two time points $t_1$ and $t_2$ where $u(x,t_1)$ is smooth but still significantly curved\n", - "and $u(x,t_2)$ is almost linear, close to the stationary state.\n", - "\n", - "\n", + "and $u(x,t_2)$ is almost linear, close to the stationary state." + ] + }, + { + "cell_type": "markdown", + "id": "7e62077c", + "metadata": { + "editable": true + }, + "source": [ "### Part c) Neural networks\n", "\n", "Study now the lecture notes on solving ODEs and PDEs with neural\n", @@ -239,22 +390,44 @@ "functionality of tensorflow/keras to solve the same equation as in\n", "part b). Discuss your results and compare them with the standard\n", "explicit scheme. Include also the analytical solution and compare with\n", - "that.\n", - "\n", - "\n", + "that." + ] + }, + { + "cell_type": "markdown", + "id": "2176774a", + "metadata": { + "editable": true + }, + "source": [ "### Part d) Solving eigenvalue problems\n", "\n", "Follow the discussion in the work of Yi *et al.* in the article from\n", "[Computers and Mathematics with Applications 47, 1155 (2004)](https://www.sciencedirect.com/science/article/pii/S0898122104901101), and\n", "use your differential equation solver with neural networks, set up a\n", "simple square, real and symmetric $6\\times 6$ matrix and find the\n", - "eigenvalues. Compare with the solution from numerical diagonalization with standard eigenvalue solvers from linear algebra.\n", - "\n", + "eigenvalues. Compare with the solution from numerical diagonalization with standard eigenvalue solvers from linear algebra." + ] + }, + { + "cell_type": "markdown", + "id": "9b623633", + "metadata": { + "editable": true + }, + "source": [ "### Part e)\n", "\n", - "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. \n", - "\n", - "\n", + "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." + ] + }, + { + "cell_type": "markdown", + "id": "30a12295", + "metadata": { + "editable": true + }, + "source": [ "## Introduction to numerical projects\n", "\n", "Here follows a brief recipe and recommendation on how to write a report for each\n", @@ -276,8 +449,16 @@ "\n", " * 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.\n", "\n", - " * 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.\n", - "\n", + " * 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." + ] + }, + { + "cell_type": "markdown", + "id": "46f47751", + "metadata": { + "editable": true + }, + "source": [ "## Introduction to numerical projects\n", "\n", "Here follows a brief recipe and recommendation on how to write a report for each\n", @@ -299,8 +480,16 @@ "\n", " * 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.\n", "\n", - " * 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.\n", - "\n", + " * 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." + ] + }, + { + "cell_type": "markdown", + "id": "e0329054", + "metadata": { + "editable": true + }, + "source": [ "## Format for electronic delivery of report and programs\n", "\n", "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:\n", @@ -313,10 +502,16 @@ "\n", "Finally, \n", "we encourage you to collaborate. Optimal working groups consist of \n", - "2-3 students. You can then hand in a common report. \n", - "\n", - "\n", - "\n", + "2-3 students. You can then hand in a common report." + ] + }, + { + "cell_type": "markdown", + "id": "e3f10246", + "metadata": { + "editable": true + }, + "source": [ "## Software and needed installations\n", "\n", "If you have Python installed (we recommend Python3) and you feel pretty familiar with installing different packages, \n", @@ -360,5 +555,5 @@ ], "metadata": {}, "nbformat": 4, - "nbformat_minor": 4 + "nbformat_minor": 5 } diff --git a/doc/Projects/2020/Project3/ipynb/ipynb-Project3-src.tar.gz b/doc/Projects/2020/Project3/ipynb/ipynb-Project3-src.tar.gz index 9e8559144..cc3e00964 100644 Binary files a/doc/Projects/2020/Project3/ipynb/ipynb-Project3-src.tar.gz and b/doc/Projects/2020/Project3/ipynb/ipynb-Project3-src.tar.gz differ diff --git a/doc/Projects/2020/Project3/pdf/Project3.p.tex b/doc/Projects/2020/Project3/pdf/Project3.p.tex index 6a1f7637e..044cbbf02 100644 --- a/doc/Projects/2020/Project3/pdf/Project3.p.tex +++ b/doc/Projects/2020/Project3/pdf/Project3.p.tex @@ -1,12 +1,12 @@ %% %% Automatically generated file from DocOnce source -%% (https://github.com/hplgit/doconce/) -%% +%% (https://github.com/doconce/doconce/) +%% doconce format latex Project3.do.txt --print_latex_style=trac --latex_admon=paragraph %% % #ifdef PTEX2TEX_EXPLANATION %% %% The file follows the ptex2tex extended LaTeX format, see -%% ptex2tex: http://code.google.com/p/ptex2tex/ +%% ptex2tex: https://code.google.com/p/ptex2tex/ %% %% Run %% ptex2tex myfile @@ -14,7 +14,7 @@ %% doconce ptex2tex myfile %% %% to turn myfile.p.tex into an ordinary LaTeX file myfile.tex. -%% (The ptex2tex program: http://code.google.com/p/ptex2tex) +%% (The ptex2tex program: https://code.google.com/p/ptex2tex) %% Many preprocess options can be added to ptex2tex or doconce ptex2tex %% %% ptex2tex -DMINTED myfile @@ -79,14 +79,14 @@ final, % draft: marks overfull hboxes, figures with paths % Ensure copyright on titlepage (article style) and chapter pages (book style) \fancypagestyle{plain}{ \fancyhf{} - \fancyfoot[C]{{\footnotesize \copyright\ 1999-2020, "Data Analysis and Machine Learning FYS-STK3155/FYS4155":"http://www.uio.no/studier/emner/matnat/fys/FYS3155/index-eng.html". Released under CC Attribution-NonCommercial 4.0 license}} + \fancyfoot[C]{{\footnotesize \copyright\ 1999-2021, "Data Analysis and Machine Learning FYS-STK3155/FYS4155":"http://www.uio.no/studier/emner/matnat/fys/FYS3155/index-eng.html". Released under CC Attribution-NonCommercial 4.0 license}} % \renewcommand{\footrulewidth}{0mm} \renewcommand{\headrulewidth}{0mm} } % Ensure copyright on titlepages with \thispagestyle{empty} \fancypagestyle{empty}{ \fancyhf{} - \fancyfoot[C]{{\footnotesize \copyright\ 1999-2020, "Data Analysis and Machine Learning FYS-STK3155/FYS4155":"http://www.uio.no/studier/emner/matnat/fys/FYS3155/index-eng.html". Released under CC Attribution-NonCommercial 4.0 license}} + \fancyfoot[C]{{\footnotesize \copyright\ 1999-2021, "Data Analysis and Machine Learning FYS-STK3155/FYS4155":"http://www.uio.no/studier/emner/matnat/fys/FYS3155/index-eng.html". Released under CC Attribution-NonCommercial 4.0 license}} \renewcommand{\footrulewidth}{0mm} \renewcommand{\headrulewidth}{0mm} } @@ -129,7 +129,7 @@ final, % draft: marks overfull hboxes, figures with paths \begin{center} {\LARGE\bf \begin{spacing}{1.25} -Project 3 on Machine Learning, deadline December 16 +Project 3 on Machine Learning, deadline December 17, 2021 \end{spacing} } \end{center} @@ -149,7 +149,7 @@ Project 3 on Machine Learning, deadline December 16 % --- begin date --- \begin{center} -Dec 11, 2020 +Nov 13, 2021 \end{center} % --- end date --- @@ -205,7 +205,6 @@ The first part deals with structuring and reading the data, much along the same \paragraph{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. - \paragraph{Part c).} Then describe your algorithm and its implementation and tests you have performed. @@ -283,7 +282,6 @@ for $\Delta x=1/10$, $\Delta x=1/100$ using $\Delta t$ as dictated by the stabi 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. - \paragraph{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 @@ -292,7 +290,6 @@ part b). Discuss your results and compare them with the standard explicit scheme. Include also the analytical solution and compare with that. - \paragraph{Part d) Solving eigenvalue problems.} Follow the discussion in the work of Yi \emph{et al.} in the article from \href{{https://www.sciencedirect.com/science/article/pii/S0898122104901101}}{Computers and Mathematics with Applications 47, 1155 (2004)}, and @@ -303,7 +300,6 @@ eigenvalues. Compare with the solution from numerical diagonalization with stand \paragraph{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. - \subsection{Introduction to numerical projects} Here follows a brief recipe and recommendation on how to write a report for each @@ -373,8 +369,6 @@ Finally, we encourage you to collaborate. Optimal working groups consist of 2-3 students. You can then hand in a common report. - - \subsection{Software and needed installations} If you have Python installed (we recommend Python3) and you feel pretty familiar with installing different packages, @@ -430,9 +424,6 @@ encompass communities of developers in the thousands or more. And the number of code developers and contributors keeps increasing. - - - % ------------------- end of main content --------------- % #ifdef PREAMBLE diff --git a/doc/Projects/2020/Project3/pdf/Project3.pdf b/doc/Projects/2020/Project3/pdf/Project3.pdf index 54358200b..4353dafc0 100644 Binary files a/doc/Projects/2020/Project3/pdf/Project3.pdf and b/doc/Projects/2020/Project3/pdf/Project3.pdf differ diff --git a/doc/Projects/2020/Project3/pdf/Project3.tex b/doc/Projects/2020/Project3/pdf/Project3.tex index 7bb5aa7fa..599d6f39f 100644 --- a/doc/Projects/2020/Project3/pdf/Project3.tex +++ b/doc/Projects/2020/Project3/pdf/Project3.tex @@ -1,7 +1,7 @@ %% %% Automatically generated file from DocOnce source -%% (https://github.com/hplgit/doconce/) -%% +%% (https://github.com/doconce/doconce/) +%% doconce format latex Project3.do.txt --print_latex_style=trac --latex_admon=paragraph %% @@ -54,14 +54,14 @@ final, % draft: marks overfull hboxes, figures with paths % Ensure copyright on titlepage (article style) and chapter pages (book style) \fancypagestyle{plain}{ \fancyhf{} - \fancyfoot[C]{{\footnotesize \copyright\ 1999-2020, "Data Analysis and Machine Learning FYS-STK3155/FYS4155":"http://www.uio.no/studier/emner/matnat/fys/FYS3155/index-eng.html". Released under CC Attribution-NonCommercial 4.0 license}} + \fancyfoot[C]{{\footnotesize \copyright\ 1999-2021, "Data Analysis and Machine Learning FYS-STK3155/FYS4155":"http://www.uio.no/studier/emner/matnat/fys/FYS3155/index-eng.html". Released under CC Attribution-NonCommercial 4.0 license}} % \renewcommand{\footrulewidth}{0mm} \renewcommand{\headrulewidth}{0mm} } % Ensure copyright on titlepages with \thispagestyle{empty} \fancypagestyle{empty}{ \fancyhf{} - \fancyfoot[C]{{\footnotesize \copyright\ 1999-2020, "Data Analysis and Machine Learning FYS-STK3155/FYS4155":"http://www.uio.no/studier/emner/matnat/fys/FYS3155/index-eng.html". Released under CC Attribution-NonCommercial 4.0 license}} + \fancyfoot[C]{{\footnotesize \copyright\ 1999-2021, "Data Analysis and Machine Learning FYS-STK3155/FYS4155":"http://www.uio.no/studier/emner/matnat/fys/FYS3155/index-eng.html". Released under CC Attribution-NonCommercial 4.0 license}} \renewcommand{\footrulewidth}{0mm} \renewcommand{\headrulewidth}{0mm} } @@ -103,7 +103,7 @@ final, % draft: marks overfull hboxes, figures with paths \begin{center} {\LARGE\bf \begin{spacing}{1.25} -Project 3 on Machine Learning, deadline December 16 +Project 3 on Machine Learning, deadline December 17, 2021 \end{spacing} } \end{center} @@ -123,7 +123,7 @@ Project 3 on Machine Learning, deadline December 16 % --- begin date --- \begin{center} -Dec 11, 2020 +Nov 13, 2021 \end{center} % --- end date --- @@ -179,7 +179,6 @@ The first part deals with structuring and reading the data, much along the same \paragraph{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. - \paragraph{Part c).} Then describe your algorithm and its implementation and tests you have performed. @@ -257,7 +256,6 @@ for $\Delta x=1/10$, $\Delta x=1/100$ using $\Delta t$ as dictated by the stabi 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. - \paragraph{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 @@ -266,7 +264,6 @@ part b). Discuss your results and compare them with the standard explicit scheme. Include also the analytical solution and compare with that. - \paragraph{Part d) Solving eigenvalue problems.} Follow the discussion in the work of Yi \emph{et al.} in the article from \href{{https://www.sciencedirect.com/science/article/pii/S0898122104901101}}{Computers and Mathematics with Applications 47, 1155 (2004)}, and @@ -277,7 +274,6 @@ eigenvalues. Compare with the solution from numerical diagonalization with stand \paragraph{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. - \subsection*{Introduction to numerical projects} Here follows a brief recipe and recommendation on how to write a report for each @@ -347,8 +343,6 @@ Finally, we encourage you to collaborate. Optimal working groups consist of 2-3 students. You can then hand in a common report. - - \subsection*{Software and needed installations} If you have Python installed (we recommend Python3) and you feel pretty familiar with installing different packages, @@ -404,9 +398,6 @@ encompass communities of developers in the thousands or more. And the number of code developers and contributors keeps increasing. - - - % ------------------- end of main content --------------- \end{document} diff --git a/doc/Projects/2021/Project3/html/._Project3-bs000.html b/doc/Projects/2021/Project3/html/._Project3-bs000.html new file mode 100644 index 000000000..dccf24e20 --- /dev/null +++ b/doc/Projects/2021/Project3/html/._Project3-bs000.html @@ -0,0 +1,457 @@ + + + + + + + +Project 3 on Machine Learning, deadline December 17, 2021 + + + + + + + + + + + + + + + + + + + + +
    +

     

     

     

    + + +
    +
    +

    Project 3 on Machine Learning, deadline December 17, 2021

    +
    + + +
    +Data Analysis and Machine Learning FYS-STK3155/FYS4155 +
    + +
    +Department of Physics, University of Oslo, Norway +
    +
    +
    +

    Nov 14, 2021

    +
    +
    + + +
    +

    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

    +
      +
    1. Kaggle
    2. +
    3. The University of California at Irvine (UCI) with its machine learning repository.
    4. +
    5. Or other sources.
    6. +
    +

    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:

    +
      +
    1. 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, Adversarial 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. You can also study unsupervised methods, although we in this course have mainly paid attendtion to supervised learning. The methods we have explored as Principal Component Analysis and k-means Clustering.
    2. +
    +

    For Boosting, feel also free to write your own codes.

    + +
      +
    1. 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.
    2. +
    3. 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.
    4. +
    5. Similarly, feel free to explore various activations functions in deep learning and various approachs to stochastic gradient descent approaches.
    6. +
    7. 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?
    8. +
    9. A critical assessment of the methods with ditto perspectives and recommendations is also something you need to include.
    10. +
    +

    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 and/or the textbook by Yadav et al.

    + +

    Note: Project 3 has an additional exercise which can give you an additional score of 30 (thirty) points. These are added to the total score from all projects. See below for the additional exercise.

    +

    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 or alternative sources. For the solution of ordinary and partial differential equations using neural networks, the lectures by Kristine Baluka Hein 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 +

    + +$$ +\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*} +$$ + +

    or

    + +$$ +\begin{equation*} +u_{xx} = u_t, +\end{equation*} +$$ + +

    with initial conditions, i.e., the conditions at \( t=0 \),

    +$$ +\begin{equation*} +u(x,0)= \sin{(\pi x)} \hspace{0.5cm} 0 < x < L, +\end{equation*} +$$ + +

    with \( L=1 \) the length of the \( x \)-region of interest. The +boundary conditions are +

    + +$$ +\begin{equation*} +u(0,t)= 0 \hspace{0.5cm} t \ge 0, +\end{equation*} +$$ + +

    and

    + +$$ +\begin{equation*} +u(L,t)= 0 \hspace{0.5cm} t \ge 0. +\end{equation*} +$$ + +

    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

    +$$ +\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*} +$$ + +

    and

    + +$$ +\begin{equation*} +u_{xx}\approx \frac{u(x+\Delta x,t)-2u(x,t)+u(x-\Delta x,t)}{\Delta x^2}, +\end{equation*} +$$ + +

    or

    + +$$ +\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*} +$$ + +

    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), 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.

    +

    Additonal (optional) exercise, adding 30 more points to final score

    + +

    This exercise can be done independently of the other tasks. Here you +can also choose the data set you want to use. Furthermore, you can use +your codes from projects 1 and 2 as well as the codes here or simply use +libraries like Scikit-Learn, Tensorflow or similar. +

    + +

    Your task is to perform an analysis of the bias-variance tradeoff +using at least three of the main sets of algorithms we have discussed in this +course. We will limit ourselves to a regression problem (fitting). However, feel free to venture into a classification problem. +

    + +

    You +are free to choose between bootstrap for resampling (recommended) or +cross-validation in order to get the best possible estimates. The +methods you could study are Linear Regression (OLS, Ridge and Lasso), +deep learning (feed forward neural networks and/or recurrent neural +networks), Ensemble methods (decision trees, bagging, random forests +and boosting) and support vector machines. +

    + +

    Study the bias-variance tradeoff for at least three of these sets of +algorithms for a data set of your choice as function of the complexity +of your model. Comment and discuss the results. Discuss the pros and +cons of the various methods. Are there some methods which provide both +low variance and low bias? +

    + +

    Hint: when you use different methods, pay attention to how you represent (and understand) the complexity of the model. For example, when using decision trees you may represent the complexity of your model by the depth of the tree.

    +

    Introduction to numerical projects

    + +

    Here follows a brief recipe and recommendation on how to write a report for each +project. +

    + + +

    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:

    + + +

    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 +

    +
      +
    1. pip install numpy scipy matplotlib ipython scikit-learn tensorflow sympy pandas pillow
    2. +
    +

    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 +

    +
      +
    1. brew install python3
    2. +
    +

    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 +

    +
      +
    1. sudo apt-get install python3 (or python for python2.7)
    2. +
    +

    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

    +
      +
    1. Anaconda 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
    2. +
    3. Enthought canopy is a Python distribution for scientific and analytic computing distribution and analysis environment, available for free and under a commercial license.
    4. +
    +

    Popular software packages written in Python for ML are

    + + +

    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. +

    + +

    + +

    + +
    + + + + +
    + © 1999-2021, "Data Analysis and Machine Learning FYS-STK3155/FYS4155":"http://www.uio.no/studier/emner/matnat/fys/FYS3155/index-eng.html". Released under CC Attribution-NonCommercial 4.0 license +
    + + + diff --git a/doc/Projects/2021/Project3/html/Project3-bs.html b/doc/Projects/2021/Project3/html/Project3-bs.html new file mode 100644 index 000000000..dccf24e20 --- /dev/null +++ b/doc/Projects/2021/Project3/html/Project3-bs.html @@ -0,0 +1,457 @@ + + + + + + + +Project 3 on Machine Learning, deadline December 17, 2021 + + + + + + + + + + + + + + + + + + + + +
    +

     

     

     

    + + +
    +
    +

    Project 3 on Machine Learning, deadline December 17, 2021

    +
    + + +
    +Data Analysis and Machine Learning FYS-STK3155/FYS4155 +
    + +
    +Department of Physics, University of Oslo, Norway +
    +
    +
    +

    Nov 14, 2021

    +
    +
    + + +
    +

    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

    +
      +
    1. Kaggle
    2. +
    3. The University of California at Irvine (UCI) with its machine learning repository.
    4. +
    5. Or other sources.
    6. +
    +

    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:

    +
      +
    1. 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, Adversarial 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. You can also study unsupervised methods, although we in this course have mainly paid attendtion to supervised learning. The methods we have explored as Principal Component Analysis and k-means Clustering.
    2. +
    +

    For Boosting, feel also free to write your own codes.

    + +
      +
    1. 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.
    2. +
    3. 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.
    4. +
    5. Similarly, feel free to explore various activations functions in deep learning and various approachs to stochastic gradient descent approaches.
    6. +
    7. 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?
    8. +
    9. A critical assessment of the methods with ditto perspectives and recommendations is also something you need to include.
    10. +
    +

    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 and/or the textbook by Yadav et al.

    + +

    Note: Project 3 has an additional exercise which can give you an additional score of 30 (thirty) points. These are added to the total score from all projects. See below for the additional exercise.

    +

    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 or alternative sources. For the solution of ordinary and partial differential equations using neural networks, the lectures by Kristine Baluka Hein 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 +

    + +$$ +\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*} +$$ + +

    or

    + +$$ +\begin{equation*} +u_{xx} = u_t, +\end{equation*} +$$ + +

    with initial conditions, i.e., the conditions at \( t=0 \),

    +$$ +\begin{equation*} +u(x,0)= \sin{(\pi x)} \hspace{0.5cm} 0 < x < L, +\end{equation*} +$$ + +

    with \( L=1 \) the length of the \( x \)-region of interest. The +boundary conditions are +

    + +$$ +\begin{equation*} +u(0,t)= 0 \hspace{0.5cm} t \ge 0, +\end{equation*} +$$ + +

    and

    + +$$ +\begin{equation*} +u(L,t)= 0 \hspace{0.5cm} t \ge 0. +\end{equation*} +$$ + +

    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

    +$$ +\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*} +$$ + +

    and

    + +$$ +\begin{equation*} +u_{xx}\approx \frac{u(x+\Delta x,t)-2u(x,t)+u(x-\Delta x,t)}{\Delta x^2}, +\end{equation*} +$$ + +

    or

    + +$$ +\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*} +$$ + +

    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), 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.

    +

    Additonal (optional) exercise, adding 30 more points to final score

    + +

    This exercise can be done independently of the other tasks. Here you +can also choose the data set you want to use. Furthermore, you can use +your codes from projects 1 and 2 as well as the codes here or simply use +libraries like Scikit-Learn, Tensorflow or similar. +

    + +

    Your task is to perform an analysis of the bias-variance tradeoff +using at least three of the main sets of algorithms we have discussed in this +course. We will limit ourselves to a regression problem (fitting). However, feel free to venture into a classification problem. +

    + +

    You +are free to choose between bootstrap for resampling (recommended) or +cross-validation in order to get the best possible estimates. The +methods you could study are Linear Regression (OLS, Ridge and Lasso), +deep learning (feed forward neural networks and/or recurrent neural +networks), Ensemble methods (decision trees, bagging, random forests +and boosting) and support vector machines. +

    + +

    Study the bias-variance tradeoff for at least three of these sets of +algorithms for a data set of your choice as function of the complexity +of your model. Comment and discuss the results. Discuss the pros and +cons of the various methods. Are there some methods which provide both +low variance and low bias? +

    + +

    Hint: when you use different methods, pay attention to how you represent (and understand) the complexity of the model. For example, when using decision trees you may represent the complexity of your model by the depth of the tree.

    +

    Introduction to numerical projects

    + +

    Here follows a brief recipe and recommendation on how to write a report for each +project. +

    + + +

    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:

    + + +

    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 +

    +
      +
    1. pip install numpy scipy matplotlib ipython scikit-learn tensorflow sympy pandas pillow
    2. +
    +

    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 +

    +
      +
    1. brew install python3
    2. +
    +

    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 +

    +
      +
    1. sudo apt-get install python3 (or python for python2.7)
    2. +
    +

    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

    +
      +
    1. Anaconda 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
    2. +
    3. Enthought canopy is a Python distribution for scientific and analytic computing distribution and analysis environment, available for free and under a commercial license.
    4. +
    +

    Popular software packages written in Python for ML are

    + + +

    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. +

    + +

    + +

    + +
    + + + + +
    + © 1999-2021, "Data Analysis and Machine Learning FYS-STK3155/FYS4155":"http://www.uio.no/studier/emner/matnat/fys/FYS3155/index-eng.html". Released under CC Attribution-NonCommercial 4.0 license +
    + + + diff --git a/doc/Projects/2021/Project3/html/Project3.html b/doc/Projects/2021/Project3/html/Project3.html new file mode 100644 index 000000000..5fe0f289b --- /dev/null +++ b/doc/Projects/2021/Project3/html/Project3.html @@ -0,0 +1,474 @@ + + + + + + + +Project 3 on Machine Learning, deadline December 17, 2021 + + + + + + + + + + + + + + +
    +

    Project 3 on Machine Learning, deadline December 17, 2021

    +
    + + +
    +Data Analysis and Machine Learning FYS-STK3155/FYS4155 +
    + +
    +Department of Physics, University of Oslo, Norway +
    +
    +
    +

    Nov 14, 2021

    +
    +
    +

    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

    +
      +
    1. Kaggle
    2. +
    3. The University of California at Irvine (UCI) with its machine learning repository.
    4. +
    5. Or other sources.
    6. +
    +

    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:

    +
      +
    1. 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, Adversarial 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. You can also study unsupervised methods, although we in this course have mainly paid attendtion to supervised learning. The methods we have explored as Principal Component Analysis and k-means Clustering.
    2. +
    +

    For Boosting, feel also free to write your own codes.

    + +
      +
    1. 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.
    2. +
    3. 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.
    4. +
    5. Similarly, feel free to explore various activations functions in deep learning and various approachs to stochastic gradient descent approaches.
    6. +
    7. 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?
    8. +
    9. A critical assessment of the methods with ditto perspectives and recommendations is also something you need to include.
    10. +
    +

    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 and/or the textbook by Yadav et al.

    + +

    Note: Project 3 has an additional exercise which can give you an additional score of 30 (thirty) points. These are added to the total score from all projects. See below for the additional exercise.

    +

    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 or alternative sources. For the solution of ordinary and partial differential equations using neural networks, the lectures by Kristine Baluka Hein 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 +

    + +$$ +\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*} +$$ + +

    or

    + +$$ +\begin{equation*} +u_{xx} = u_t, +\end{equation*} +$$ + +

    with initial conditions, i.e., the conditions at \( t=0 \),

    +$$ +\begin{equation*} +u(x,0)= \sin{(\pi x)} \hspace{0.5cm} 0 < x < L, +\end{equation*} +$$ + +

    with \( L=1 \) the length of the \( x \)-region of interest. The +boundary conditions are +

    + +$$ +\begin{equation*} +u(0,t)= 0 \hspace{0.5cm} t \ge 0, +\end{equation*} +$$ + +

    and

    + +$$ +\begin{equation*} +u(L,t)= 0 \hspace{0.5cm} t \ge 0. +\end{equation*} +$$ + +

    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

    +$$ +\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*} +$$ + +

    and

    + +$$ +\begin{equation*} +u_{xx}\approx \frac{u(x+\Delta x,t)-2u(x,t)+u(x-\Delta x,t)}{\Delta x^2}, +\end{equation*} +$$ + +

    or

    + +$$ +\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*} +$$ + +

    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), 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.

    +

    Additonal (optional) exercise, adding 30 more points to final score

    + +

    This exercise can be done independently of the other tasks. Here you +can also choose the data set you want to use. Furthermore, you can use +your codes from projects 1 and 2 as well as the codes here or simply use +libraries like Scikit-Learn, Tensorflow or similar. +

    + +

    Your task is to perform an analysis of the bias-variance tradeoff +using at least three of the main sets of algorithms we have discussed in this +course. We will limit ourselves to a regression problem (fitting). However, feel free to venture into a classification problem. +

    + +

    You +are free to choose between bootstrap for resampling (recommended) or +cross-validation in order to get the best possible estimates. The +methods you could study are Linear Regression (OLS, Ridge and Lasso), +deep learning (feed forward neural networks and/or recurrent neural +networks), Ensemble methods (decision trees, bagging, random forests +and boosting) and support vector machines. +

    + +

    Study the bias-variance tradeoff for at least three of these sets of +algorithms for a data set of your choice as function of the complexity +of your model. Comment and discuss the results. Discuss the pros and +cons of the various methods. Are there some methods which provide both +low variance and low bias? +

    + +

    Hint: when you use different methods, pay attention to how you represent (and understand) the complexity of the model. For example, when using decision trees you may represent the complexity of your model by the depth of the tree.

    +

    Introduction to numerical projects

    + +

    Here follows a brief recipe and recommendation on how to write a report for each +project. +

    + + +

    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:

    + + +

    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 +

    +
      +
    1. pip install numpy scipy matplotlib ipython scikit-learn tensorflow sympy pandas pillow
    2. +
    +

    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 +

    +
      +
    1. brew install python3
    2. +
    +

    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 +

    +
      +
    1. sudo apt-get install python3 (or python for python2.7)
    2. +
    +

    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

    +
      +
    1. Anaconda 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
    2. +
    3. Enthought canopy is a Python distribution for scientific and analytic computing distribution and analysis environment, available for free and under a commercial license.
    4. +
    +

    Popular software packages written in Python for ML are

    + + +

    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. +

    + + +
    + © 1999-2021, "Data Analysis and Machine Learning FYS-STK3155/FYS4155":"http://www.uio.no/studier/emner/matnat/fys/FYS3155/index-eng.html". Released under CC Attribution-NonCommercial 4.0 license +
    + + + diff --git a/doc/Projects/2021/Project3/ipynb/Project3.ipynb b/doc/Projects/2021/Project3/ipynb/Project3.ipynb new file mode 100644 index 000000000..3fb613d09 --- /dev/null +++ b/doc/Projects/2021/Project3/ipynb/Project3.ipynb @@ -0,0 +1,567 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "e6c08da8", + "metadata": { + "editable": true + }, + "source": [ + "\n", + "" + ] + }, + { + "cell_type": "markdown", + "id": "0309e266", + "metadata": { + "editable": true + }, + "source": [ + "# Project 3 on Machine Learning, deadline December 17, 2021\n", + "**[Data Analysis and Machine Learning FYS-STK3155/FYS4155](http://www.uio.no/studier/emner/matnat/fys/FYS3155/index-eng.html)**, Department of Physics, University of Oslo, Norway\n", + "\n", + "Date: **Nov 14, 2021**\n", + "\n", + "Copyright 1999-2021, [Data Analysis and Machine Learning FYS-STK3155/FYS4155](http://www.uio.no/studier/emner/matnat/fys/FYS3155/index-eng.html). Released under CC Attribution-NonCommercial 4.0 license" + ] + }, + { + "cell_type": "markdown", + "id": "cedebbe4", + "metadata": { + "editable": true + }, + "source": [ + "# Paths for project 3" + ] + }, + { + "cell_type": "markdown", + "id": "9038e49a", + "metadata": { + "editable": true + }, + "source": [ + "## Defining the data sets to analyze yourself\n", + "\n", + "For project 3, you can propose own data sets that relate to your research interests or just use existing data sets from say\n", + "1. [Kaggle](https://www.kaggle.com/datasets) \n", + "\n", + "2. The [University of California at Irvine (UCI) with its machine learning repository](https://archive.ics.uci.edu/ml/index.php).\n", + "\n", + "3. Or other sources.\n", + "\n", + "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:\n", + "1. 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**, **Adversarial 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. You can also study unsupervised methods, although we in this course have mainly paid attendtion to supervised learning. The methods we have explored as **Principal Component Analysis** and **k-means Clustering**.\n", + "\n", + "For Boosting, feel also free to write your own codes.\n", + "\n", + "1. 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. \n", + "\n", + "2. 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.\n", + "\n", + "3. Similarly, feel free to explore various activations functions in deep learning and various approachs to stochastic gradient descent approaches.\n", + "\n", + "4. 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? \n", + "\n", + "5. A critical assessment of the methods with ditto perspectives and recommendations is also something you need to include.\n", + "\n", + "All in all, the report should follow the same pattern as the two previous ones, with abstract, introduction, methods, code, results, conclusions etc..\n", + "\n", + "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.\n", + "\n", + "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/week42/html/week42.html) and/or the textbook by [Yadav et al](https://www.springer.com/gp/book/9789401798150).\n", + "\n", + "**Note**: Project 3 has an additional exercise which can give you an additional score of 30 (thirty) points. These are added to the total score from all projects. See below for the additional exercise." + ] + }, + { + "cell_type": "markdown", + "id": "89190c80", + "metadata": { + "editable": true + }, + "source": [ + "## The basic structure of your project\n", + "\n", + "Here follows a set up on how to structure your report and analyze the data you have opted for." + ] + }, + { + "cell_type": "markdown", + "id": "b2944795", + "metadata": { + "editable": true + }, + "source": [ + "### Part a)\n", + "\n", + "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." + ] + }, + { + "cell_type": "markdown", + "id": "5d7f5f66", + "metadata": { + "editable": true + }, + "source": [ + "### Part b)\n", + "\n", + "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." + ] + }, + { + "cell_type": "markdown", + "id": "55083a27", + "metadata": { + "editable": true + }, + "source": [ + "### Part c)\n", + "\n", + "Then describe your algorithm and its implementation and tests you have performed." + ] + }, + { + "cell_type": "markdown", + "id": "26bb3996", + "metadata": { + "editable": true + }, + "source": [ + "### Part d)\n", + "\n", + "Then presents your results and findings, link with existing literature and more." + ] + }, + { + "cell_type": "markdown", + "id": "99cbbdf4", + "metadata": { + "editable": true + }, + "source": [ + "### Part e)\n", + "\n", + "Finally, here you should present a critical assessment of the methods you have studied and link your results with the existing literature." + ] + }, + { + "cell_type": "markdown", + "id": "1cf8305f", + "metadata": { + "editable": true + }, + "source": [ + "## Solving partial differential equations with neural networks\n", + "\n", + "For this variant of project 3, we will assume that you have some\n", + "background in the solution of partial differential equations using\n", + "finite difference schemes. We will study the solution of the diffusion\n", + "equation in one dimension using a standard explicit scheme and neural\n", + "networks to solve the same equations.\n", + "\n", + "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.\n", + "\n", + "For the machine learning part you can use your own code from project 2 or the functionality of for example **Tensorflow/Keras**.." + ] + }, + { + "cell_type": "markdown", + "id": "c76618e8", + "metadata": { + "editable": true + }, + "source": [ + "### Part a), setting up the problem\n", + "\n", + "The physical problem can be that of the temperature gradient in a rod of length $L=1$ at $x=0$ and $x=1$.\n", + "We are looking at a one-dimensional\n", + "problem" + ] + }, + { + "cell_type": "markdown", + "id": "ac2c5732", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "\\frac{\\partial^2 u(x,t)}{\\partial x^2} =\\frac{\\partial u(x,t)}{\\partial t}, t> 0, x\\in [0,L]\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "ead9d520", + "metadata": { + "editable": true + }, + "source": [ + "or" + ] + }, + { + "cell_type": "markdown", + "id": "8db95bf3", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "u_{xx} = u_t,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "2f93712e", + "metadata": { + "editable": true + }, + "source": [ + "with initial conditions, i.e., the conditions at $t=0$," + ] + }, + { + "cell_type": "markdown", + "id": "62a0980a", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "u(x,0)= \\sin{(\\pi x)} \\hspace{0.5cm} 0 < x < L,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "28f54a78", + "metadata": { + "editable": true + }, + "source": [ + "with $L=1$ the length of the $x$-region of interest. The \n", + "boundary conditions are" + ] + }, + { + "cell_type": "markdown", + "id": "e0068e8b", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "u(0,t)= 0 \\hspace{0.5cm} t \\ge 0,\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "f9ae2916", + "metadata": { + "editable": true + }, + "source": [ + "and" + ] + }, + { + "cell_type": "markdown", + "id": "88e71606", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "u(L,t)= 0 \\hspace{0.5cm} t \\ge 0.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "69bc12e7", + "metadata": { + "editable": true + }, + "source": [ + "The function $u(x,t)$ can be the temperature gradient of a rod.\n", + "As time increases, the velocity approaches a linear variation with $x$. \n", + "\n", + "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" + ] + }, + { + "cell_type": "markdown", + "id": "fa2123d5", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "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}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "27474b17", + "metadata": { + "editable": true + }, + "source": [ + "and" + ] + }, + { + "cell_type": "markdown", + "id": "1c4da408", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "u_{xx}\\approx \\frac{u(x+\\Delta x,t)-2u(x,t)+u(x-\\Delta x,t)}{\\Delta x^2},\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "06021617", + "metadata": { + "editable": true + }, + "source": [ + "or" + ] + }, + { + "cell_type": "markdown", + "id": "b845d906", + "metadata": { + "editable": true + }, + "source": [ + "$$\n", + "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}.\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "id": "6c3956bc", + "metadata": { + "editable": true + }, + "source": [ + "Write down the algorithm and the equations you need to implement.\n", + "Find also the analytical solution to the problem." + ] + }, + { + "cell_type": "markdown", + "id": "15d51aa1", + "metadata": { + "editable": true + }, + "source": [ + "### Part b)\n", + "\n", + "Implement the explicit scheme algorithm and perform tests of the solution \n", + "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$. \n", + "\n", + "Study the solutions at two time points $t_1$ and $t_2$ where $u(x,t_1)$ is smooth but still significantly curved\n", + "and $u(x,t_2)$ is almost linear, close to the stationary state." + ] + }, + { + "cell_type": "markdown", + "id": "356b0ce1", + "metadata": { + "editable": true + }, + "source": [ + "### Part c) Neural networks\n", + "\n", + "Study now the lecture notes on solving ODEs and PDEs with neural\n", + "network and use either your own code from project 2 or the\n", + "functionality of tensorflow/keras to solve the same equation as in\n", + "part b). Discuss your results and compare them with the standard\n", + "explicit scheme. Include also the analytical solution and compare with\n", + "that." + ] + }, + { + "cell_type": "markdown", + "id": "5254f0ec", + "metadata": { + "editable": true + }, + "source": [ + "### Part d) Solving eigenvalue problems\n", + "\n", + "Follow the discussion in the work of Yi *et al.* in the article from\n", + "[Computers and Mathematics with Applications 47, 1155 (2004)](https://www.sciencedirect.com/science/article/pii/S0898122104901101), and\n", + "use your differential equation solver with neural networks, set up a\n", + "simple square, real and symmetric $6\\times 6$ matrix and find the\n", + "eigenvalues. Compare with the solution from numerical diagonalization with standard eigenvalue solvers from linear algebra." + ] + }, + { + "cell_type": "markdown", + "id": "fb586020", + "metadata": { + "editable": true + }, + "source": [ + "### Part e)\n", + "\n", + "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." + ] + }, + { + "cell_type": "markdown", + "id": "8f43137a", + "metadata": { + "editable": true + }, + "source": [ + "## Additonal (optional) exercise, adding 30 more points to final score\n", + "\n", + "This exercise can be done independently of the other tasks. Here you\n", + "can also choose the data set you want to use. Furthermore, you can use\n", + "your codes from projects 1 and 2 as well as the codes here or simply use\n", + "libraries like **Scikit-Learn**, **Tensorflow** or similar.\n", + "\n", + "Your task is to perform an analysis of the bias-variance tradeoff\n", + "using at least three of the main sets of algorithms we have discussed in this\n", + "course. We will limit ourselves to a regression problem (fitting). However, feel free to venture into a classification problem.\n", + "\n", + "You\n", + "are free to choose between bootstrap for resampling (recommended) or\n", + "cross-validation in order to get the best possible estimates. The\n", + "methods you could study are Linear Regression (OLS, Ridge and Lasso),\n", + "deep learning (feed forward neural networks and/or recurrent neural\n", + "networks), Ensemble methods (decision trees, bagging, random forests\n", + "and boosting) and support vector machines.\n", + "\n", + "Study the bias-variance tradeoff for at least three of these sets of\n", + "algorithms for a data set of your choice as function of the complexity\n", + "of your model. Comment and discuss the results. Discuss the pros and\n", + "cons of the various methods. Are there some methods which provide both\n", + "low variance and low bias?\n", + "\n", + "**Hint**: when you use different methods, pay attention to how you represent (and understand) the complexity of the model. For example, when using decision trees you may represent the complexity of your model by the depth of the tree." + ] + }, + { + "cell_type": "markdown", + "id": "5efcf1de", + "metadata": { + "editable": true + }, + "source": [ + "## Introduction to numerical projects\n", + "\n", + "Here follows a brief recipe and recommendation on how to write a report for each\n", + "project.\n", + "\n", + " * Give a short description of the nature of the problem and the eventual numerical methods you have used.\n", + "\n", + " * 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.\n", + "\n", + " * Include the source code of your program. Comment your program properly.\n", + "\n", + " * If possible, try to find analytic solutions, or known limits in order to test your program when developing the code.\n", + "\n", + " * 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.\n", + "\n", + " * 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.\n", + "\n", + " * Try to give an interpretation of you results in your answers to the problems.\n", + "\n", + " * 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.\n", + "\n", + " * 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." + ] + }, + { + "cell_type": "markdown", + "id": "e53cd89a", + "metadata": { + "editable": true + }, + "source": [ + "## Format for electronic delivery of report and programs\n", + "\n", + "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:\n", + "\n", + " * Use Canvas to hand in your projects, log in at with your normal UiO username and password.\n", + "\n", + " * 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.\n", + "\n", + " * 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.\n", + "\n", + "Finally, \n", + "we encourage you to collaborate. Optimal working groups consist of \n", + "2-3 students. You can then hand in a common report." + ] + }, + { + "cell_type": "markdown", + "id": "f1b49648", + "metadata": { + "editable": true + }, + "source": [ + "## Software and needed installations\n", + "\n", + "If you have Python installed (we recommend Python3) and you feel pretty familiar with installing different packages, \n", + "we recommend that you install the following Python packages via **pip** as\n", + "1. pip install numpy scipy matplotlib ipython scikit-learn tensorflow sympy pandas pillow\n", + "\n", + "For Python3, replace **pip** with **pip3**.\n", + "\n", + "See below for a discussion of **tensorflow** and **scikit-learn**. \n", + "\n", + "For OSX users we recommend also, after having installed Xcode, to install **brew**. Brew allows \n", + "for a seamless installation of additional software via for example\n", + "1. brew install python3\n", + "\n", + "For Linux users, with its variety of distributions like for example the widely popular Ubuntu distribution\n", + "you can use **pip** as well and simply install Python as \n", + "1. sudo apt-get install python3 (or python for python2.7)\n", + "\n", + "etc etc. \n", + "\n", + "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\n", + "1. [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**\n", + "\n", + "2. [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.\n", + "\n", + "Popular software packages written in Python for ML are\n", + "\n", + "* [Scikit-learn](http://scikit-learn.org/stable/), \n", + "\n", + "* [Tensorflow](https://www.tensorflow.org/),\n", + "\n", + "* [PyTorch](http://pytorch.org/) and \n", + "\n", + "* [Keras](https://keras.io/).\n", + "\n", + "These are all freely available at their respective GitHub sites. They \n", + "encompass communities of developers in the thousands or more. And the number\n", + "of code developers and contributors keeps increasing." + ] + } + ], + "metadata": {}, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/doc/Projects/2021/Project3/ipynb/ipynb-Project3-src.tar.gz b/doc/Projects/2021/Project3/ipynb/ipynb-Project3-src.tar.gz new file mode 100644 index 000000000..c9332ae71 Binary files /dev/null and b/doc/Projects/2021/Project3/ipynb/ipynb-Project3-src.tar.gz differ diff --git a/doc/Projects/2021/Project3/pdf/Project3.p.tex b/doc/Projects/2021/Project3/pdf/Project3.p.tex new file mode 100644 index 000000000..03a195fde --- /dev/null +++ b/doc/Projects/2021/Project3/pdf/Project3.p.tex @@ -0,0 +1,437 @@ +%% +%% Automatically generated file from DocOnce source +%% (https://github.com/doconce/doconce/) +%% doconce format latex Project3.do.txt --print_latex_style=trac --latex_admon=paragraph +%% +% #ifdef PTEX2TEX_EXPLANATION +%% +%% The file follows the ptex2tex extended LaTeX format, see +%% ptex2tex: https://code.google.com/p/ptex2tex/ +%% +%% Run +%% ptex2tex myfile +%% or +%% doconce ptex2tex myfile +%% +%% to turn myfile.p.tex into an ordinary LaTeX file myfile.tex. +%% (The ptex2tex program: https://code.google.com/p/ptex2tex) +%% Many preprocess options can be added to ptex2tex or doconce ptex2tex +%% +%% ptex2tex -DMINTED myfile +%% doconce ptex2tex myfile envir=minted +%% +%% ptex2tex will typeset code environments according to a global or local +%% .ptex2tex.cfg configure file. doconce ptex2tex will typeset code +%% according to options on the command line (just type doconce ptex2tex to +%% see examples). If doconce ptex2tex has envir=minted, it enables the +%% minted style without needing -DMINTED. +% #endif + +% #define PREAMBLE + +% #ifdef PREAMBLE +%-------------------- begin preamble ---------------------- + +\documentclass[% +oneside, % oneside: electronic viewing, twoside: printing +final, % draft: marks overfull hboxes, figures with paths +10pt]{article} + +\listfiles % print all files needed to compile this document + +\usepackage{relsize,makeidx,color,setspace,amsmath,amsfonts,amssymb} +\usepackage[table]{xcolor} +\usepackage{bm,ltablex,microtype} + +\usepackage[pdftex]{graphicx} + +\usepackage[T1]{fontenc} +%\usepackage[latin1]{inputenc} +\usepackage{ucs} +\usepackage[utf8x]{inputenc} + +\usepackage{lmodern} % Latin Modern fonts derived from Computer Modern + +% Hyperlinks in PDF: +\definecolor{linkcolor}{rgb}{0,0,0.4} +\usepackage{hyperref} +\hypersetup{ + breaklinks=true, + colorlinks=true, + linkcolor=linkcolor, + urlcolor=linkcolor, + citecolor=black, + filecolor=black, + %filecolor=blue, + pdfmenubar=true, + pdftoolbar=true, + bookmarksdepth=3 % Uncomment (and tweak) for PDF bookmarks with more levels than the TOC + } +%\hyperbaseurl{} % hyperlinks are relative to this root + +\setcounter{tocdepth}{2} % levels in table of contents + +% --- fancyhdr package for fancy headers --- +\usepackage{fancyhdr} +\fancyhf{} % sets both header and footer to nothing +\renewcommand{\headrulewidth}{0pt} +\fancyfoot[LE,RO]{\thepage} +% Ensure copyright on titlepage (article style) and chapter pages (book style) +\fancypagestyle{plain}{ + \fancyhf{} + \fancyfoot[C]{{\footnotesize \copyright\ 1999-2021, "Data Analysis and Machine Learning FYS-STK3155/FYS4155":"http://www.uio.no/studier/emner/matnat/fys/FYS3155/index-eng.html". Released under CC Attribution-NonCommercial 4.0 license}} +% \renewcommand{\footrulewidth}{0mm} + \renewcommand{\headrulewidth}{0mm} +} +% Ensure copyright on titlepages with \thispagestyle{empty} +\fancypagestyle{empty}{ + \fancyhf{} + \fancyfoot[C]{{\footnotesize \copyright\ 1999-2021, "Data Analysis and Machine Learning FYS-STK3155/FYS4155":"http://www.uio.no/studier/emner/matnat/fys/FYS3155/index-eng.html". Released under CC Attribution-NonCommercial 4.0 license}} + \renewcommand{\footrulewidth}{0mm} + \renewcommand{\headrulewidth}{0mm} +} + +\pagestyle{fancy} + + +% prevent orhpans and widows +\clubpenalty = 10000 +\widowpenalty = 10000 + +% --- end of standard preamble for documents --- + + +% insert custom LaTeX commands... + +\raggedbottom +\makeindex +\usepackage[totoc]{idxlayout} % for index in the toc +\usepackage[nottoc]{tocbibind} % for references/bibliography in the toc + +%-------------------- end preamble ---------------------- + +\begin{document} + +% matching end for #ifdef PREAMBLE +% #endif + +\newcommand{\exercisesection}[1]{\subsection*{#1}} + + +% ------------------- main content ---------------------- + + + +% ----------------- title ------------------------- + +\thispagestyle{empty} + +\begin{center} +{\LARGE\bf +\begin{spacing}{1.25} +Project 3 on Machine Learning, deadline December 17, 2021 +\end{spacing} +} +\end{center} + +% ----------------- author(s) ------------------------- + +\begin{center} +{\bf \href{{http://www.uio.no/studier/emner/matnat/fys/FYS3155/index-eng.html}}{Data Analysis and Machine Learning FYS-STK3155/FYS4155}} +\end{center} + + \begin{center} +% List of all institutions: +\centerline{{\small Department of Physics, University of Oslo, Norway}} +\end{center} + +% ----------------- end author(s) ------------------------- + +% --- begin date --- +\begin{center} +Nov 14, 2021 +\end{center} +% --- end date --- + +\vspace{1cm} + + +\section{Paths for project 3} + +\subsection{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 +\begin{enumerate} +\item \href{{https://www.kaggle.com/datasets}}{Kaggle} + +\item The \href{{https://archive.ics.uci.edu/ml/index.php}}{University of California at Irvine (UCI) with its machine learning repository}. + +\item Or other sources. +\end{enumerate} + +\noindent +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: +\begin{enumerate} +\item Whether you end up with a regression or a classification problem, you should employ at least two of the methods we have discussed among \textbf{linear regression (including Ridge and Lasso)}, \textbf{Logistic Regression}, \textbf{Neural Networks}, \textbf{Convolution Neural Networks}, \textbf{Recurrent Neural Networks}, \textbf{Adversarial Neural Networks}, \textbf{Support Vector Machines} and \textbf{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 \textbf{convolutional neural networks} or \textbf{recurrent neural networks}, or extensions of neural networkds, feel free to do so. You can also study unsupervised methods, although we in this course have mainly paid attendtion to supervised learning. The methods we have explored as \textbf{Principal Component Analysis} and \textbf{k-means Clustering}. +\end{enumerate} + +\noindent +For Boosting, feel also free to write your own codes. + +\begin{enumerate} +\item 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 \textbf{Scikit-Learn}, \textbf{Tensorflow}, etc. + +\item The estimates you used and tested in projects 1 and 2 should also be included, that is the $R2$-score, \textbf{MSE}, confusion matrix, accuracy score, information gain, ROC and Cumulative gains curves and other, cross-validation and/or bootstrap if these are relevant. + +\item Similarly, feel free to explore various activations functions in deep learning and various approachs to stochastic gradient descent approaches. + +\item 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? + +\item A critical assessment of the methods with ditto perspectives and recommendations is also something you need to include. +\end{enumerate} + +\noindent +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 \href{{https://compphysics.github.io/MachineLearning/doc/pub/week42/html/week42.html}}{from week 43} and/or the textbook by \href{{https://www.springer.com/gp/book/9789401798150}}{Yadav et al}. + +\textbf{Note}: Project 3 has an additional exercise which can give you an additional score of 30 (thirty) points. These are added to the total score from all projects. See below for the additional exercise. + +\subsection{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. + +\paragraph{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. + +\paragraph{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. + +\paragraph{Part c).} +Then describe your algorithm and its implementation and tests you have performed. + +\paragraph{Part d).} +Then presents your results and findings, link with existing literature and more. + +\paragraph{Part e).} +Finally, here you should present a critical assessment of the methods you have studied and link your results with the existing literature. + +\subsection{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 \href{{https://github.com/CompPhysics/ComputationalPhysics/blob/master/doc/Lectures/lectures2015.pdf}}{Computational Physics} or alternative sources. For the solution of ordinary and partial differential equations using neural networks, the lectures by \href{{https://compphysics.github.io/MachineLearning/doc/pub/odenn/html/odenn-bs.html}}{Kristine Baluka Hein} 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 \textbf{Tensorflow/Keras}.. + +\paragraph{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 + +\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*} +or + +\begin{equation*} +u_{xx} = u_t, +\end{equation*} +with initial conditions, i.e., the conditions at $t=0$, +\begin{equation*} +u(x,0)= \sin{(\pi x)} \hspace{0.5cm} 0 < x < L, +\end{equation*} +with $L=1$ the length of the $x$-region of interest. The +boundary conditions are + +\begin{equation*} +u(0,t)= 0 \hspace{0.5cm} t \ge 0, +\end{equation*} +and + +\begin{equation*} +u(L,t)= 0 \hspace{0.5cm} t \ge 0. +\end{equation*} +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 +\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*} +and + +\begin{equation*} +u_{xx}\approx \frac{u(x+\Delta x,t)-2u(x,t)+u(x-\Delta x,t)}{\Delta x^2}, +\end{equation*} +or + +\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*} + +Write down the algorithm and the equations you need to implement. +Find also the analytical solution to the problem. + +\paragraph{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. + +\paragraph{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. + +\paragraph{Part d) Solving eigenvalue problems.} +Follow the discussion in the work of Yi \emph{et al.} in the article from +\href{{https://www.sciencedirect.com/science/article/pii/S0898122104901101}}{Computers and Mathematics with Applications 47, 1155 (2004)}, 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. + +\paragraph{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. + +\subsection{Additonal (optional) exercise, adding 30 more points to final score} + +This exercise can be done independently of the other tasks. Here you +can also choose the data set you want to use. Furthermore, you can use +your codes from projects 1 and 2 as well as the codes here or simply use +libraries like \textbf{Scikit-Learn}, \textbf{Tensorflow} or similar. + +Your task is to perform an analysis of the bias-variance tradeoff +using at least three of the main sets of algorithms we have discussed in this +course. We will limit ourselves to a regression problem (fitting). However, feel free to venture into a classification problem. + +You +are free to choose between bootstrap for resampling (recommended) or +cross-validation in order to get the best possible estimates. The +methods you could study are Linear Regression (OLS, Ridge and Lasso), +deep learning (feed forward neural networks and/or recurrent neural +networks), Ensemble methods (decision trees, bagging, random forests +and boosting) and support vector machines. + +Study the bias-variance tradeoff for at least three of these sets of +algorithms for a data set of your choice as function of the complexity +of your model. Comment and discuss the results. Discuss the pros and +cons of the various methods. Are there some methods which provide both +low variance and low bias? + +\textbf{Hint}: when you use different methods, pay attention to how you represent (and understand) the complexity of the model. For example, when using decision trees you may represent the complexity of your model by the depth of the tree. + +\subsection{Introduction to numerical projects} + +Here follows a brief recipe and recommendation on how to write a report for each +project. + +\begin{itemize} + \item Give a short description of the nature of the problem and the eventual numerical methods you have used. + + \item 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. + + \item Include the source code of your program. Comment your program properly. + + \item If possible, try to find analytic solutions, or known limits in order to test your program when developing the code. + + \item 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. + + \item 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. + + \item Try to give an interpretation of you results in your answers to the problems. + + \item 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. + + \item 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. +\end{itemize} + +\noindent +\subsection{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: + +\begin{itemize} + \item Use Canvas to hand in your projects, log in at \href{{https://www.uio.no/english/services/it/education/canvas/}}{\nolinkurl{https://www.uio.no/english/services/it/education/canvas/}} with your normal UiO username and password. + + \item Upload \textbf{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. + + \item 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. +\end{itemize} + +\noindent +Finally, +we encourage you to collaborate. Optimal working groups consist of +2-3 students. You can then hand in a common report. + +\subsection{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 \textbf{pip} as +\begin{enumerate} +\item pip install numpy scipy matplotlib ipython scikit-learn tensorflow sympy pandas pillow +\end{enumerate} + +\noindent +For Python3, replace \textbf{pip} with \textbf{pip3}. + +See below for a discussion of \textbf{tensorflow} and \textbf{scikit-learn}. + +For OSX users we recommend also, after having installed Xcode, to install \textbf{brew}. Brew allows +for a seamless installation of additional software via for example +\begin{enumerate} +\item brew install python3 +\end{enumerate} + +\noindent +For Linux users, with its variety of distributions like for example the widely popular Ubuntu distribution +you can use \textbf{pip} as well and simply install Python as +\begin{enumerate} +\item sudo apt-get install python3 (or python for python2.7) +\end{enumerate} + +\noindent +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 +\begin{enumerate} +\item \href{{https://docs.anaconda.com/}}{Anaconda} 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 \textbf{conda} + +\item \href{{https://www.enthought.com/product/canopy/}}{Enthought canopy} is a Python distribution for scientific and analytic computing distribution and analysis environment, available for free and under a commercial license. +\end{enumerate} + +\noindent +Popular software packages written in Python for ML are + +\begin{itemize} +\item \href{{http://scikit-learn.org/stable/}}{Scikit-learn}, + +\item \href{{https://www.tensorflow.org/}}{Tensorflow}, + +\item \href{{http://pytorch.org/}}{PyTorch} and + +\item \href{{https://keras.io/}}{Keras}. +\end{itemize} + +\noindent +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. + + +% ------------------- end of main content --------------- + +% #ifdef PREAMBLE +\end{document} +% #endif + diff --git a/doc/Projects/2021/Project3/pdf/Project3.pdf b/doc/Projects/2021/Project3/pdf/Project3.pdf new file mode 100644 index 000000000..11b9f8821 Binary files /dev/null and b/doc/Projects/2021/Project3/pdf/Project3.pdf differ diff --git a/doc/Projects/2021/Project3/pdf/Project3.tex b/doc/Projects/2021/Project3/pdf/Project3.tex new file mode 100644 index 000000000..c436aa4e3 --- /dev/null +++ b/doc/Projects/2021/Project3/pdf/Project3.tex @@ -0,0 +1,409 @@ +%% +%% Automatically generated file from DocOnce source +%% (https://github.com/doconce/doconce/) +%% doconce format latex Project3.do.txt --print_latex_style=trac --latex_admon=paragraph +%% + + +%-------------------- begin preamble ---------------------- + +\documentclass[% +oneside, % oneside: electronic viewing, twoside: printing +final, % draft: marks overfull hboxes, figures with paths +10pt]{article} + +\listfiles % print all files needed to compile this document + +\usepackage{relsize,makeidx,color,setspace,amsmath,amsfonts,amssymb} +\usepackage[table]{xcolor} +\usepackage{bm,ltablex,microtype} + +\usepackage[pdftex]{graphicx} + +\usepackage[T1]{fontenc} +%\usepackage[latin1]{inputenc} +\usepackage{ucs} +\usepackage[utf8x]{inputenc} + +\usepackage{lmodern} % Latin Modern fonts derived from Computer Modern + +% Hyperlinks in PDF: +\definecolor{linkcolor}{rgb}{0,0,0.4} +\usepackage{hyperref} +\hypersetup{ + breaklinks=true, + colorlinks=true, + linkcolor=linkcolor, + urlcolor=linkcolor, + citecolor=black, + filecolor=black, + %filecolor=blue, + pdfmenubar=true, + pdftoolbar=true, + bookmarksdepth=3 % Uncomment (and tweak) for PDF bookmarks with more levels than the TOC + } +%\hyperbaseurl{} % hyperlinks are relative to this root + +\setcounter{tocdepth}{2} % levels in table of contents + +% --- fancyhdr package for fancy headers --- +\usepackage{fancyhdr} +\fancyhf{} % sets both header and footer to nothing +\renewcommand{\headrulewidth}{0pt} +\fancyfoot[LE,RO]{\thepage} +% Ensure copyright on titlepage (article style) and chapter pages (book style) +\fancypagestyle{plain}{ + \fancyhf{} + \fancyfoot[C]{{\footnotesize \copyright\ 1999-2021, "Data Analysis and Machine Learning FYS-STK3155/FYS4155":"http://www.uio.no/studier/emner/matnat/fys/FYS3155/index-eng.html". Released under CC Attribution-NonCommercial 4.0 license}} +% \renewcommand{\footrulewidth}{0mm} + \renewcommand{\headrulewidth}{0mm} +} +% Ensure copyright on titlepages with \thispagestyle{empty} +\fancypagestyle{empty}{ + \fancyhf{} + \fancyfoot[C]{{\footnotesize \copyright\ 1999-2021, "Data Analysis and Machine Learning FYS-STK3155/FYS4155":"http://www.uio.no/studier/emner/matnat/fys/FYS3155/index-eng.html". Released under CC Attribution-NonCommercial 4.0 license}} + \renewcommand{\footrulewidth}{0mm} + \renewcommand{\headrulewidth}{0mm} +} + +\pagestyle{fancy} + + +% prevent orhpans and widows +\clubpenalty = 10000 +\widowpenalty = 10000 + +% --- end of standard preamble for documents --- + + +% insert custom LaTeX commands... + +\raggedbottom +\makeindex +\usepackage[totoc]{idxlayout} % for index in the toc +\usepackage[nottoc]{tocbibind} % for references/bibliography in the toc + +%-------------------- end preamble ---------------------- + +\begin{document} + +% matching end for #ifdef PREAMBLE + +\newcommand{\exercisesection}[1]{\subsection*{#1}} + + +% ------------------- main content ---------------------- + + + +% ----------------- title ------------------------- + +\thispagestyle{empty} + +\begin{center} +{\LARGE\bf +\begin{spacing}{1.25} +Project 3 on Machine Learning, deadline December 17, 2021 +\end{spacing} +} +\end{center} + +% ----------------- author(s) ------------------------- + +\begin{center} +{\bf \href{{http://www.uio.no/studier/emner/matnat/fys/FYS3155/index-eng.html}}{Data Analysis and Machine Learning FYS-STK3155/FYS4155}} +\end{center} + + \begin{center} +% List of all institutions: +\centerline{{\small Department of Physics, University of Oslo, Norway}} +\end{center} + +% ----------------- end author(s) ------------------------- + +% --- begin date --- +\begin{center} +Nov 14, 2021 +\end{center} +% --- end date --- + +\vspace{1cm} + + +\section*{Paths for project 3} + +\subsection*{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 +\begin{enumerate} +\item \href{{https://www.kaggle.com/datasets}}{Kaggle} + +\item The \href{{https://archive.ics.uci.edu/ml/index.php}}{University of California at Irvine (UCI) with its machine learning repository}. + +\item Or other sources. +\end{enumerate} + +\noindent +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: +\begin{enumerate} +\item Whether you end up with a regression or a classification problem, you should employ at least two of the methods we have discussed among \textbf{linear regression (including Ridge and Lasso)}, \textbf{Logistic Regression}, \textbf{Neural Networks}, \textbf{Convolution Neural Networks}, \textbf{Recurrent Neural Networks}, \textbf{Adversarial Neural Networks}, \textbf{Support Vector Machines} and \textbf{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 \textbf{convolutional neural networks} or \textbf{recurrent neural networks}, or extensions of neural networkds, feel free to do so. You can also study unsupervised methods, although we in this course have mainly paid attendtion to supervised learning. The methods we have explored as \textbf{Principal Component Analysis} and \textbf{k-means Clustering}. +\end{enumerate} + +\noindent +For Boosting, feel also free to write your own codes. + +\begin{enumerate} +\item 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 \textbf{Scikit-Learn}, \textbf{Tensorflow}, etc. + +\item The estimates you used and tested in projects 1 and 2 should also be included, that is the $R2$-score, \textbf{MSE}, confusion matrix, accuracy score, information gain, ROC and Cumulative gains curves and other, cross-validation and/or bootstrap if these are relevant. + +\item Similarly, feel free to explore various activations functions in deep learning and various approachs to stochastic gradient descent approaches. + +\item 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? + +\item A critical assessment of the methods with ditto perspectives and recommendations is also something you need to include. +\end{enumerate} + +\noindent +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 \href{{https://compphysics.github.io/MachineLearning/doc/pub/week42/html/week42.html}}{from week 43} and/or the textbook by \href{{https://www.springer.com/gp/book/9789401798150}}{Yadav et al}. + +\textbf{Note}: Project 3 has an additional exercise which can give you an additional score of 30 (thirty) points. These are added to the total score from all projects. See below for the additional exercise. + +\subsection*{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. + +\paragraph{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. + +\paragraph{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. + +\paragraph{Part c).} +Then describe your algorithm and its implementation and tests you have performed. + +\paragraph{Part d).} +Then presents your results and findings, link with existing literature and more. + +\paragraph{Part e).} +Finally, here you should present a critical assessment of the methods you have studied and link your results with the existing literature. + +\subsection*{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 \href{{https://github.com/CompPhysics/ComputationalPhysics/blob/master/doc/Lectures/lectures2015.pdf}}{Computational Physics} or alternative sources. For the solution of ordinary and partial differential equations using neural networks, the lectures by \href{{https://compphysics.github.io/MachineLearning/doc/pub/odenn/html/odenn-bs.html}}{Kristine Baluka Hein} 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 \textbf{Tensorflow/Keras}.. + +\paragraph{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 + +\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*} +or + +\begin{equation*} +u_{xx} = u_t, +\end{equation*} +with initial conditions, i.e., the conditions at $t=0$, +\begin{equation*} +u(x,0)= \sin{(\pi x)} \hspace{0.5cm} 0 < x < L, +\end{equation*} +with $L=1$ the length of the $x$-region of interest. The +boundary conditions are + +\begin{equation*} +u(0,t)= 0 \hspace{0.5cm} t \ge 0, +\end{equation*} +and + +\begin{equation*} +u(L,t)= 0 \hspace{0.5cm} t \ge 0. +\end{equation*} +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 +\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*} +and + +\begin{equation*} +u_{xx}\approx \frac{u(x+\Delta x,t)-2u(x,t)+u(x-\Delta x,t)}{\Delta x^2}, +\end{equation*} +or + +\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*} + +Write down the algorithm and the equations you need to implement. +Find also the analytical solution to the problem. + +\paragraph{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. + +\paragraph{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. + +\paragraph{Part d) Solving eigenvalue problems.} +Follow the discussion in the work of Yi \emph{et al.} in the article from +\href{{https://www.sciencedirect.com/science/article/pii/S0898122104901101}}{Computers and Mathematics with Applications 47, 1155 (2004)}, 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. + +\paragraph{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. + +\subsection*{Additonal (optional) exercise, adding 30 more points to final score} + +This exercise can be done independently of the other tasks. Here you +can also choose the data set you want to use. Furthermore, you can use +your codes from projects 1 and 2 as well as the codes here or simply use +libraries like \textbf{Scikit-Learn}, \textbf{Tensorflow} or similar. + +Your task is to perform an analysis of the bias-variance tradeoff +using at least three of the main sets of algorithms we have discussed in this +course. We will limit ourselves to a regression problem (fitting). However, feel free to venture into a classification problem. + +You +are free to choose between bootstrap for resampling (recommended) or +cross-validation in order to get the best possible estimates. The +methods you could study are Linear Regression (OLS, Ridge and Lasso), +deep learning (feed forward neural networks and/or recurrent neural +networks), Ensemble methods (decision trees, bagging, random forests +and boosting) and support vector machines. + +Study the bias-variance tradeoff for at least three of these sets of +algorithms for a data set of your choice as function of the complexity +of your model. Comment and discuss the results. Discuss the pros and +cons of the various methods. Are there some methods which provide both +low variance and low bias? + +\textbf{Hint}: when you use different methods, pay attention to how you represent (and understand) the complexity of the model. For example, when using decision trees you may represent the complexity of your model by the depth of the tree. + +\subsection*{Introduction to numerical projects} + +Here follows a brief recipe and recommendation on how to write a report for each +project. + +\begin{itemize} + \item Give a short description of the nature of the problem and the eventual numerical methods you have used. + + \item 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. + + \item Include the source code of your program. Comment your program properly. + + \item If possible, try to find analytic solutions, or known limits in order to test your program when developing the code. + + \item 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. + + \item 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. + + \item Try to give an interpretation of you results in your answers to the problems. + + \item 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. + + \item 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. +\end{itemize} + +\noindent +\subsection*{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: + +\begin{itemize} + \item Use Canvas to hand in your projects, log in at \href{{https://www.uio.no/english/services/it/education/canvas/}}{\nolinkurl{https://www.uio.no/english/services/it/education/canvas/}} with your normal UiO username and password. + + \item Upload \textbf{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. + + \item 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. +\end{itemize} + +\noindent +Finally, +we encourage you to collaborate. Optimal working groups consist of +2-3 students. You can then hand in a common report. + +\subsection*{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 \textbf{pip} as +\begin{enumerate} +\item pip install numpy scipy matplotlib ipython scikit-learn tensorflow sympy pandas pillow +\end{enumerate} + +\noindent +For Python3, replace \textbf{pip} with \textbf{pip3}. + +See below for a discussion of \textbf{tensorflow} and \textbf{scikit-learn}. + +For OSX users we recommend also, after having installed Xcode, to install \textbf{brew}. Brew allows +for a seamless installation of additional software via for example +\begin{enumerate} +\item brew install python3 +\end{enumerate} + +\noindent +For Linux users, with its variety of distributions like for example the widely popular Ubuntu distribution +you can use \textbf{pip} as well and simply install Python as +\begin{enumerate} +\item sudo apt-get install python3 (or python for python2.7) +\end{enumerate} + +\noindent +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 +\begin{enumerate} +\item \href{{https://docs.anaconda.com/}}{Anaconda} 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 \textbf{conda} + +\item \href{{https://www.enthought.com/product/canopy/}}{Enthought canopy} is a Python distribution for scientific and analytic computing distribution and analysis environment, available for free and under a commercial license. +\end{enumerate} + +\noindent +Popular software packages written in Python for ML are + +\begin{itemize} +\item \href{{http://scikit-learn.org/stable/}}{Scikit-learn}, + +\item \href{{https://www.tensorflow.org/}}{Tensorflow}, + +\item \href{{http://pytorch.org/}}{PyTorch} and + +\item \href{{https://keras.io/}}{Keras}. +\end{itemize} + +\noindent +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. + + +% ------------------- end of main content --------------- + +\end{document} + diff --git a/doc/pub/week34/html/._week34-bs000.html b/doc/pub/week34/html/._week34-bs000.html index 743aee240..6c35019c1 100644 --- a/doc/pub/week34/html/._week34-bs000.html +++ b/doc/pub/week34/html/._week34-bs000.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 34: Introduction to the course, Logistics and Practicalities - + - - - -
    -

     

     

     

    - - - -
    -

    Week 34: Introduction to the course, Logistics and Practicalities

    +
    +

    Week 34: Introduction to the course, Logistics and Practicalities

    +
    -

    -

    Morten Hjorth-Jensen [1, 2]
    - -

    +

    +[1] Department of Physics, University of Oslo +
    +
    +[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University +
    +
    +
    +

    Nov 13, 2021

    +
    +
    -
    [1] Department of Physics, University of Oslo
    -
    [2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
    -
    -

    -

    Oct 12, 2021

    -
    -

    Read »

    @@ -412,25 +400,18 @@ MathJax.Hub.Config({
  • »
  • -
    - - -
    © 1999-2021, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
    - - - diff --git a/doc/pub/week34/html/._week34-bs001.html b/doc/pub/week34/html/._week34-bs001.html index 43fdb5828..efd6035d5 100644 --- a/doc/pub/week34/html/._week34-bs001.html +++ b/doc/pub/week34/html/._week34-bs001.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 34: Introduction to the course, Logistics and Practicalities - + - - -
    -
    -

     

     

     

    - -

    Overview of first week

    -

    -

    - +

    • Wednesday August 25: Introduction to software and repetition of Python Programming
    • Thursday August 26: First lecture: Presentation of the course, aims and content
    • @@ -383,7 +369,6 @@ MathJax.Hub.Config({
    -

      @@ -404,25 +389,18 @@ MathJax.Hub.Config({
    • »
    -
    - - -
    - - - diff --git a/doc/pub/week34/html/._week34-bs002.html b/doc/pub/week34/html/._week34-bs002.html index 6000b6d5c..0b781483c 100644 --- a/doc/pub/week34/html/._week34-bs002.html +++ b/doc/pub/week34/html/._week34-bs002.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 34: Introduction to the course, Logistics and Practicalities - + - - -
    -
    -

     

     

     

    - -

    Reading Recommendations

    -

    -

    -For the reading assignments we use the following abbreviations: - + +

    For the reading assignments we use the following abbreviations:

    • GBC: Goodfellow, Bengio, and Courville, Deep Learning
    • CMB: Christopher M. Bishop, Pattern Recognition and Machine Learning
    • HTF: Hastie, Tibshirani, and Friedman, The Elements of Statistical Learning
    • AG: Aurelien Geron, Hands‑On Machine Learning with Scikit‑Learn and TensorFlow
    - -Reading recommendations this week: Refresh linear algebra, GBC chapters 1 and 2. CMB sections 1.1 and 3.1. HTF chapters 2 and 3. Install scikit-learn. See lecture notes for week 34 at https://compphysics.github.io/MachineLearning/doc/web/course.html +

    Reading recommendations this week: Refresh linear algebra, GBC chapters 1 and 2. CMB sections 1.1 and 3.1. HTF chapters 2 and 3. Install scikit-learn. See lecture notes for week 34 at https://compphysics.github.io/MachineLearning/doc/web/course.html

    -

    -
    - - -
    - - - diff --git a/doc/pub/week34/html/._week34-bs003.html b/doc/pub/week34/html/._week34-bs003.html index 2ec093d3b..8175eb6be 100644 --- a/doc/pub/week34/html/._week34-bs003.html +++ b/doc/pub/week34/html/._week34-bs003.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 34: Introduction to the course, Logistics and Practicalities - + - - - -
    -

     

     

     

    - -

    Thursday August 26

    -

    -The lectures will be recorded and updated videos will be posted after the lectures. +

    The lectures will be recorded and updated videos will be posted after the lectures.

    -

    -"Video of Lecture August 26, 2021":"https://www.uio.no/studier/emner/matnat/fys/FYS-STK4155/h21/forelesningsvideoer/LectureThursdayAugust26.mp4?vrtx=view-as-webpage +

    "Video of Lecture August 26, 2021":"https://www.uio.no/studier/emner/matnat/fys/FYS-STK4155/h21/forelesningsvideoer/LectureThursdayAugust26.mp4?vrtx=view-as-webpage

    -

    -Zoom link for lectures: https://msu.zoom.us/j/93311529525?pwd=a1VXSzY4aTFWVy9Rb05mNDJTZ09lZz09 +

    Zoom link for lectures: https://msu.zoom.us/j/93311529525?pwd=a1VXSzY4aTFWVy9Rb05mNDJTZ09lZz09

    +

    Video of Lecture from Fall Semester 2020.

    -Video of Lecture from Fall Semester 2020. - -

    -
    - - -
    - - - diff --git a/doc/pub/week34/html/._week34-bs004.html b/doc/pub/week34/html/._week34-bs004.html index 51c8ce86b..1461a98a2 100644 --- a/doc/pub/week34/html/._week34-bs004.html +++ b/doc/pub/week34/html/._week34-bs004.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 34: Introduction to the course, Logistics and Practicalities - + - - - -
    -

     

     

     

    - -

    Lectures and ComputerLab

    -

    -

    - +

    • Lectures: Thursday (12.15pm-2pm and Friday (12.15pm-2pm).
    • Weekly reading assignments and videos needed to solve projects and exercises.
    • @@ -384,7 +370,6 @@ MathJax.Hub.Config({
    -

      @@ -408,25 +393,18 @@ MathJax.Hub.Config({
    • »
    -
    - - -
    - - - diff --git a/doc/pub/week34/html/._week34-bs005.html b/doc/pub/week34/html/._week34-bs005.html index 7ddfd8d99..61272e1e0 100644 --- a/doc/pub/week34/html/._week34-bs005.html +++ b/doc/pub/week34/html/._week34-bs005.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 34: Introduction to the course, Logistics and Practicalities - + - - -
    -
    -

     

     

     

    - -

    Announcement

    -

    -NORA AI competetion: See the link here https://www.nora.ai/Competition/image-segmentation.html +

    NORA AI competetion: See the link here https://www.nora.ai/Competition/image-segmentation.html

    -

    -
    - - -
    - - - diff --git a/doc/pub/week34/html/._week34-bs006.html b/doc/pub/week34/html/._week34-bs006.html index ba15ac7bc..5ddc25613 100644 --- a/doc/pub/week34/html/._week34-bs006.html +++ b/doc/pub/week34/html/._week34-bs006.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 34: Introduction to the course, Logistics and Practicalities - + - - - -
    -

     

     

     

    - -

    Communication channels

    -

    -
    - - -
    - - - diff --git a/doc/pub/week34/html/._week34-bs007.html b/doc/pub/week34/html/._week34-bs007.html index 54b32c5ca..06097d02c 100644 --- a/doc/pub/week34/html/._week34-bs007.html +++ b/doc/pub/week34/html/._week34-bs007.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 34: Introduction to the course, Logistics and Practicalities - + - - - -
    -

     

     

     

    - -

    Course Format

    -

    -

    - +

    • Three compulsory projects. Electronic reports only using Canvas to hand in projects and git as version control software and GitHub for repository (or GitLab) of all your material.
    • Evaluation and grading: The three projects are graded and each counts 1/3 of the final mark. No final written or oral exam. -
      1. For the last project each group/participant submits a proposal or works with suggested (by us) proposals for the project.
      2. If possible, we would like to organize the last project as a workshop where each group makes a poster and presents this to all other participants of the course
      3. Poster session where all participants can study and discuss the other proposals.
      4. Based on feedback etc, each group finalizes the report and submits for grading.
      -
    • Python is the default programming language, but feel free to use C/C++ and/or Fortran or other programming languages. All source codes discussed during the lectures can be found at the webpage and github address of the course.
    -

    -
    - - -
    - - - diff --git a/doc/pub/week34/html/._week34-bs008.html b/doc/pub/week34/html/._week34-bs008.html index 056781ad4..b8618eb6f 100644 --- a/doc/pub/week34/html/._week34-bs008.html +++ b/doc/pub/week34/html/._week34-bs008.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 34: Introduction to the course, Logistics and Practicalities - + - - - -
    -

     

     

     

    - -

    Teachers

    -

    -

    + -

    Teachers : -

    • Morten Hjorth-Jensen, morten.hjorth-jensen@fys.uio.no
    • -
      • Phone: +47-48257387
      • Office: Department of Physics, University of Oslo, Eastern wing, room FØ470
      • Office hours: Anytime! Individual or group office hours can be arranged either in person or via zoom. Feel free to send an email for planning.
      -
    • Øyvind Sigmundson Schøyen, oyvinssc@student.matnat.uio.no
    • -
      • Office: Department of Physics, University of Oslo, Eastern wing, room FØ452
      -
    • Stian Dysthe Bilek stian.bilek@fys.uio.no
    • -
      • Office: Department of Physics, University of Oslo, Eastern wing, room FØ450
      -
    • Linus Ekstrøm, linueks@gmail.com, linus.ekstrom@fys.uio.no
    • Nicholas Karlsen, nicholaskarlsen1102@gmail.com, nicholas.karlsen@fys.uio.no
    • Bendik Steinsvåg Dalen, b.s.dalen@fys.uio.no
    • @@ -405,7 +384,6 @@ MathJax.Hub.Config({
    -

      @@ -433,25 +411,18 @@ MathJax.Hub.Config({
    • »
    -
    - - -
    - - - diff --git a/doc/pub/week34/html/._week34-bs009.html b/doc/pub/week34/html/._week34-bs009.html index de2868328..2cbbba9e2 100644 --- a/doc/pub/week34/html/._week34-bs009.html +++ b/doc/pub/week34/html/._week34-bs009.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 34: Introduction to the course, Logistics and Practicalities - + - - -
    -
    -

     

     

     

    - -

    Deadlines for projects (tentative)

    -

    -

    +

    1. Project 1: October 11 (available September 10) graded with feedback)
    2. -
    3. Project 2: November 15 (available October 12, graded with feedback)
    4. -
    5. Project 3: December 13 (available November 8, graded with feedback)
    6. +
    7. Project 2: November 20 (available October 12, graded with feedback)
    8. +
    9. Project 3: December 17 (available November 13, graded with feedback)
    - -Projects are handed in using Canvas. We use Github as repository for codes, benchmark calculations etc. Comments and feedback on projects only via Canvas. - -

    +

    Projects are handed in using Canvas. We use Github as repository for codes, benchmark calculations etc. Comments and feedback on projects only via Canvas.

    -

    -
    - - -
    - - - diff --git a/doc/pub/week34/html/._week34-bs010.html b/doc/pub/week34/html/._week34-bs010.html index a998fc406..5a9b808e9 100644 --- a/doc/pub/week34/html/._week34-bs010.html +++ b/doc/pub/week34/html/._week34-bs010.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 34: Introduction to the course, Logistics and Practicalities - + - - - -
    -

     

     

     

    - -
    1. The lecture notes are collected as a jupyter-book at https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/intro.html.
    - -In addition to the lecture notes, we recommend the books of Bishop and Goodfellow et al. We will follow these texts closely and the weekly reading assignments refer to these two texts. The text by Hastie et al is also widely used in the Machine Learning community. Finally, we also recommend the hands-on text by Geron, see below. +

    In addition to the lecture notes, we recommend the books of Bishop and Goodfellow et al. We will follow these texts closely and the weekly reading assignments refer to these two texts. The text by Hastie et al is also widely used in the Machine Learning community. Finally, we also recommend the hands-on text by Geron, see below.

    1. Christopher M. Bishop, Pattern Recognition and Machine Learning, Springer, https://www.springer.com/gp/book/9780387310732.
    2. Ian Goodfellow, Yoshua Bengio, and Aaron Courville. The different chapters are available for free at https://www.deeplearningbook.org/. Chapters 2-14 are highly recommended. The lectures follow to a larg extent this text. The weekly plans will include reading suggestions from these two textbooks.
    - -Additional textbooks: +

    Additional textbooks:

    1. Trevor Hastie, Robert Tibshirani, Jerome H. Friedman, The Elements of Statistical Learning, Springer, https://www.springer.com/gp/book/9780387848570. This is a well-known text and serves as additional literature.
    2. Aurelien Geron, Hands‑On Machine Learning with Scikit‑Learn and TensorFlow, O'Reilly, https://www.oreilly.com/library/view/hands-on-machine-learning/9781492032632/. This text is very useful since it contains many code examples and hands-on applications of all algorithms discussed in this course.
    -

    -
    - - -
    - - - diff --git a/doc/pub/week34/html/._week34-bs011.html b/doc/pub/week34/html/._week34-bs011.html index 1729fd337..2d034cd1e 100644 --- a/doc/pub/week34/html/._week34-bs011.html +++ b/doc/pub/week34/html/._week34-bs011.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 34: Introduction to the course, Logistics and Practicalities - + - - - -
    -

     

     

     

    - -

    Prerequisites

    -

    -Basic knowledge in programming and mathematics, with an emphasis on +

    Basic knowledge in programming and mathematics, with an emphasis on linear algebra. Knowledge of Python or/and C++ as programming languages is strongly recommended and experience with Jupiter notebook is recommended. Required courses are the equivalents to the University @@ -377,8 +364,8 @@ of the corresponding computing and programming courses INF1000/INF1110 or MAT-INF1100/MAT-INF1100L/BIOS1100/KJM-INF1100. Most universities offer nowadays a basic programming course (often compulsory) where Python is the recurring programming language. +

    -

    -
    - - -
    - - - diff --git a/doc/pub/week34/html/._week34-bs012.html b/doc/pub/week34/html/._week34-bs012.html index de101ca39..a298b76d1 100644 --- a/doc/pub/week34/html/._week34-bs012.html +++ b/doc/pub/week34/html/._week34-bs012.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 34: Introduction to the course, Logistics and Practicalities - + - - - -
    -

     

     

     

    - -

    Learning outcomes

    -

    -

    + -

    -This course aims at giving you insights and knowledge about many of +

    This course aims at giving you insights and knowledge about many of the central algorithms used in Data Analysis and Machine Learning. The course is project based and through various numerical projects, normally three, you will be exposed to fundamental research problems @@ -386,6 +372,7 @@ Learning is applied to, get acquainted with computing facilities and learn to handle large scientific projects. A good scientific and ethical conduct is emphasized throughout the course. More specifically, after this course you will +

    • Learn about basic data analysis, statistical analysis, Bayesian statistics, Monte Carlo sampling, data optimization and machine learning;
    • @@ -403,7 +390,6 @@ specifically, after this course you will
    -

      @@ -433,25 +419,18 @@ specifically, after this course you will
    • »
    -
    - - -
    - - - diff --git a/doc/pub/week34/html/._week34-bs013.html b/doc/pub/week34/html/._week34-bs013.html index 8a599a544..6313d674f 100644 --- a/doc/pub/week34/html/._week34-bs013.html +++ b/doc/pub/week34/html/._week34-bs013.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 34: Introduction to the course, Logistics and Practicalities - + - - -
    -
    -

     

     

     

    - -

    Topics covered in this course: Statistical analysis and optimization of data

    -

    -The course has two central parts +

    The course has two central parts

    1. Statistical analysis and optimization of data
    2. Machine learning
    +

    These topics will be scattered thorughout the course and may not necessarily be taught separately. Rather, we will often take an approach (during the lectures and project/exercise sessions) where say elements from statistical data analysis are mixed with specific Machine Learning algorithms

    -These topics will be scattered thorughout the course and may not necessarily be taught separately. Rather, we will often take an approach (during the lectures and project/exercise sessions) where say elements from statistical data analysis are mixed with specific Machine Learning algorithms - -

    -

    - -

    -We plan to cover the following topics: + +

    We plan to cover the following topics:

    • Basic concepts, expectation values, variance, covariance, correlation functions and errors;
    • Simpler models, binomial distribution, the Poisson distribution, simple and multivariate normal distributions;
    • @@ -398,7 +381,6 @@ We plan to cover the following topics:
    -

      @@ -428,25 +410,18 @@ We plan to cover the following topics:
    • »
    -
    - - -
    - - - diff --git a/doc/pub/week34/html/._week34-bs014.html b/doc/pub/week34/html/._week34-bs014.html index 19af70aae..7e9caf178 100644 --- a/doc/pub/week34/html/._week34-bs014.html +++ b/doc/pub/week34/html/._week34-bs014.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 34: Introduction to the course, Logistics and Practicalities - + - - -
    -
    -

     

     

     

    - -

    Topics covered in this course: Machine Learning

    -

    -

    -The following topics will be covered - + +

    The following topics will be covered

    • Linear Regression and Logistic Regression;
    • Neural networks and deep learning, including convolutional and recurrent neural networks
    • @@ -382,15 +368,11 @@ The following topics will be covered
    • Boltzmann Machines
    • Unsupervised learning Dimensionality reduction, from PCA to clustering
    - -Hands-on demonstrations, exercises and projects aim at deepening your understanding of these topics. - -

    +

    Hands-on demonstrations, exercises and projects aim at deepening your understanding of these topics.

    -

    -
    - - -
    - - - diff --git a/doc/pub/week34/html/._week34-bs015.html b/doc/pub/week34/html/._week34-bs015.html index 3969f450f..8e96e427b 100644 --- a/doc/pub/week34/html/._week34-bs015.html +++ b/doc/pub/week34/html/._week34-bs015.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 34: Introduction to the course, Logistics and Practicalities - + - - - -
    -

     

     

     

    - - -

    -

    - +

    -

      @@ -410,25 +395,18 @@ MathJax.Hub.Config({
    • »
    -
    - - -
    - - - diff --git a/doc/pub/week34/html/._week34-bs016.html b/doc/pub/week34/html/._week34-bs016.html index b58c3db49..1be4e5258 100644 --- a/doc/pub/week34/html/._week34-bs016.html +++ b/doc/pub/week34/html/._week34-bs016.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 34: Introduction to the course, Logistics and Practicalities - + - - -
    -
    -

     

     

     

    - -

    Other courses on Data science and Machine Learning at UiO

    -

    -The link here 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. +

    The link here 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.

    1. STK2100 Machine learning and statistical methods for prediction and classification.
    2. @@ -383,7 +370,6 @@ The link here STK4051 Computational Statistics
    3. STK4021 Applied Bayesian Analysis and Numerical Methods
    -

    -
    - - -
    - - - diff --git a/doc/pub/week34/html/._week34-bs017.html b/doc/pub/week34/html/._week34-bs017.html index 667a4b4e7..85017794f 100644 --- a/doc/pub/week34/html/._week34-bs017.html +++ b/doc/pub/week34/html/._week34-bs017.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 34: Introduction to the course, Logistics and Practicalities - + - - - -
    -

     

     

     

    - -

    Introduction

    -

    -Our emphasis throughout this series of lectures +

    Our emphasis throughout this series of lectures is on understanding the mathematical aspects of -different algorithms used in the fields of data analysis and machine learning. +different algorithms used in the fields of data analysis and machine learning. +

    -

    -However, where possible we will emphasize the +

    However, where possible we will emphasize the importance of using available software. We start thus with a hands-on and top-down approach to machine learning. The aim is thus to start with relevant data or data we have produced @@ -387,24 +374,24 @@ the data and predictions. We move thereafter to more interesting cases such as data from say experiments (below we will look at experimental nuclear binding energies as an example). These are examples where we can easily set up the data and then use machine learning algorithms included in for example -Scikit-Learn. +Scikit-Learn. +

    -

    -These examples will serve us the purpose of getting +

    These examples will serve us the purpose of getting started. Furthermore, they allow us to catch more than two birds with a stone. They will allow us to bring in some programming specific topics and tools as well as showing the power of various Python -libraries for machine learning and statistical data analysis. +libraries for machine learning and statistical data analysis. +

    -

    -Here, we will mainly focus on two +

    Here, we will mainly focus on two specific Python packages for Machine Learning, Scikit-Learn and Tensorflow (see below for links etc). Moreover, the examples we introduce will serve as inputs to many of our discussions later, as well as allowing you to set up models and produce your own data and get started with programming. +

    -

    -
    - - -
    - - - diff --git a/doc/pub/week34/html/._week34-bs018.html b/doc/pub/week34/html/._week34-bs018.html index f9551796b..ebd53f0fe 100644 --- a/doc/pub/week34/html/._week34-bs018.html +++ b/doc/pub/week34/html/._week34-bs018.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 34: Introduction to the course, Logistics and Practicalities - + - - - -
    -

     

     

     

    - -

    What is Machine Learning?

    -

    -Statistics, data science and machine learning form important fields of +

    Statistics, data science and machine learning form important fields of research in modern science. They describe how to learn and make predictions from data, as well as allowing us to extract important correlations about physical process and the underlying laws of motion in large data sets. The latter, big data sets, appear frequently in essentially all disciplines, from the traditional Science, Technology, Mathematics and Engineering fields to Life Science, Law, education -research, the Humanities and the Social Sciences. +research, the Humanities and the Social Sciences. +

    -

    -It has become more +

    It has become more and more common to see research projects on big data in for example the Social Sciences where extracting patterns from complicated survey data is one of many research directions. Having a solid grasp of data @@ -393,17 +380,17 @@ in the private or the public sector. This author has had several students or met students who have been hired recently based on their skills and competences in scientific computing and data science, often with marginal knowledge of machine learning. +

    -

    -Machine learning is a subfield of computer science, and is closely +

    Machine learning is a subfield of computer science, and is closely related to computational statistics. It evolved from the study of pattern recognition in artificial intelligence (AI) research, and has made contributions to AI tasks like computer vision, natural language processing and speech recognition. Many of the methods we will study are also -strongly rooted in basic mathematics and physics research. +strongly rooted in basic mathematics and physics research. +

    -

    -Ideally, machine learning represents the science of giving computers +

    Ideally, machine learning represents the science of giving computers the ability to learn without being explicitly programmed. The idea is that there exist generic algorithms which can be used to find patterns in a broad class of data sets without having to write code @@ -411,10 +398,10 @@ specifically for each problem. The algorithm will build its own logic based on the data. You should however always keep in mind that machines and algorithms are to a large extent developed by humans. The insights and knowledge we have about a specific system, play a central -role when we develop a specific machine learning algorithm. +role when we develop a specific machine learning algorithm. +

    -

    -Machine learning is an extremely rich field, in spite of its young +

    Machine learning is an extremely rich field, in spite of its young age. The increases we have seen during the last three decades in computational capabilities have been followed by developments of methods and techniques for analyzing and handling large date sets, @@ -434,8 +421,8 @@ solid command of linear algebra, multivariate theory, probability theory, statistical data analysis, understanding errors and Monte Carlo methods are central elements in a proper understanding of many of algorithms and methods we will discuss. +

    -

    -
    - - -
    - - - diff --git a/doc/pub/week34/html/._week34-bs019.html b/doc/pub/week34/html/._week34-bs019.html index 396cf0f11..19187ff53 100644 --- a/doc/pub/week34/html/._week34-bs019.html +++ b/doc/pub/week34/html/._week34-bs019.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 34: Introduction to the course, Logistics and Practicalities - + - - - -
    -

     

     

     

    - -

    Types of Machine Learning

    -

    -The approaches to machine learning are many, but are often split into +

    The approaches to machine learning are many, but are often split into two main categories. In supervised learning we know the answer to a problem, and let the computer deduce the logic behind it. On the other hand, unsupervised learning is a method for finding patterns and @@ -377,17 +364,17 @@ Some authours also operate with a third category, namely reinforcement learning. This is a paradigm of learning inspired by behavioral psychology, where learning is achieved by trial-and-error, solely from rewards and punishment. +

    -

    -Another way to categorize machine learning tasks is to consider the +

    Another way to categorize machine learning tasks is to consider the desired output of a system. Some of the most common tasks are: +

    -

    -
    - - -
    - - - diff --git a/doc/pub/week34/html/._week34-bs020.html b/doc/pub/week34/html/._week34-bs020.html index c5eb1da2a..f04c01518 100644 --- a/doc/pub/week34/html/._week34-bs020.html +++ b/doc/pub/week34/html/._week34-bs020.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 34: Introduction to the course, Logistics and Practicalities - + - - - -
    -

     

     

     

    - -

    Essential elements of ML

    -

    -The methods we cover have three main topics in common, irrespective of +

    The methods we cover have three main topics in common, irrespective of whether we deal with supervised or unsupervised learning. +

    - - -

    -
    - - -
    - - - diff --git a/doc/pub/week34/html/._week34-bs021.html b/doc/pub/week34/html/._week34-bs021.html index fd7a96690..657a546a2 100644 --- a/doc/pub/week34/html/._week34-bs021.html +++ b/doc/pub/week34/html/._week34-bs021.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 34: Introduction to the course, Logistics and Practicalities - + - - - -
    -

     

     

     

    - -

    An optimization/minimization problem

    -

    -At the heart of basically all Machine Learning algorithms we will encounter so-called minimization or optimization algorithms. A large family of such methods are so-called gradient methods. +

    At the heart of basically all Machine Learning algorithms we will encounter so-called minimization or optimization algorithms. A large family of such methods are so-called gradient methods.

    -

    -
    - - -
    - - - diff --git a/doc/pub/week34/html/._week34-bs022.html b/doc/pub/week34/html/._week34-bs022.html index d494a2bd5..142c167a8 100644 --- a/doc/pub/week34/html/._week34-bs022.html +++ b/doc/pub/week34/html/._week34-bs022.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 34: Introduction to the course, Logistics and Practicalities - + - - - -
    -

     

     

     

    - -

    A Frequentist approach to data analysis

    -

    -When you hear phrases like predictions and estimations and +

    When you hear phrases like predictions and estimations and correlations and causations, what do you think of? May be you think of the difference between classifying new data points and generating new data points. @@ -376,9 +363,9 @@ Or perhaps you consider that correlations represent some kind of symmetric state if \( A \) is correlated with \( B \), then \( B \) is correlated with \( A \). Causation on the other hand is directional, that is if \( A \) causes \( B \), \( B \) does not necessarily cause \( A \). +

    -

    -These concepts are in some sense the difference between machine +

    These concepts are in some sense the difference between machine learning and statistics. In machine learning and prediction based tasks, we are often interested in developing algorithms that are capable of learning patterns from given data in an automated fashion, @@ -387,15 +374,15 @@ assessments of newly given data. In many cases, our primary concern is the quality of the predictions or assessments, and we are less concerned about the underlying patterns that were learned in order to make these predictions. +

    -

    -In machine learning we normally use a so-called frequentist approach, +

    In machine learning we normally use a so-called frequentist approach, where the aim is to make predictions and find correlations. We focus less on for example extracting a probability distribution function (PDF). The PDF can be used in turn to make estimations and find causations such as given \( A \) what is the likelihood of finding \( B \). +

    -

    -
    - - -
    - - - diff --git a/doc/pub/week34/html/._week34-bs023.html b/doc/pub/week34/html/._week34-bs023.html index 222050c89..f6bcf30f7 100644 --- a/doc/pub/week34/html/._week34-bs023.html +++ b/doc/pub/week34/html/._week34-bs023.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 34: Introduction to the course, Logistics and Practicalities - + - - - -
    -

     

     

     

    - -

    What is a good model?

    -

    -In science and engineering we often end up in situations where we want to infer (or learn) a +

    In science and engineering we often end up in situations where we want to infer (or learn) a quantitative model \( M \) for a given set of sample points \( \boldsymbol{X} \in [x_1, x_2,\dots x_N] \). +

    -

    -As we will see repeatedely in these lectures, we could try to fit these data points to a model given by a +

    As we will see repeatedely in these lectures, we could try to fit these data points to a model given by a straight line, or if we wish to be more sophisticated to a more complex function. +

    -

    -The reason for inferring such a model is that it +

    The reason for inferring such a model is that it serves many useful purposes. On the one hand, the model can reveal information encoded in the data or underlying mechanisms from which the data were generated. For instance, we could discover important corelations that relate interesting physics interpretations. +

    -

    -In addition, it can simplify the representation of the given data set and help +

    In addition, it can simplify the representation of the given data set and help us in making predictions about future data samples. +

    -

    -A first important consideration to keep in mind is that inferring the correct model +

    A first important consideration to keep in mind is that inferring the correct model for a given data set is an elusive, if not impossible, task. The fundamental difficulty is that if we are not specific about what we mean by a correct model, there could easily be many different models that fit the given data set equally well. +

    -

    -
    - - -
    - - - diff --git a/doc/pub/week34/html/._week34-bs024.html b/doc/pub/week34/html/._week34-bs024.html index ef90cd140..745e53e90 100644 --- a/doc/pub/week34/html/._week34-bs024.html +++ b/doc/pub/week34/html/._week34-bs024.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 34: Introduction to the course, Logistics and Practicalities - + - - - -
    -

     

     

     

    - -

    What is a good model? Can we define it?

    -

    -The central question is this: what leads us to say that a model is correct or +

    The central question is this: what leads us to say that a model is correct or optimal for a given data set? To make the model inference problem well posed, i.e., to guarantee that there is a unique optimal model for the given data, we need to impose additional assumptions or restrictions on the class of models considered. To @@ -381,17 +368,16 @@ with the simplest possible class of models that is just necessary to describe th or solve the problem at hand. More precisely, the model class should be rich enough to contain at least one model that can fit the data to a desired accuracy and yet be restricted enough that it is relatively simple to find the best model for the given data. +

    -

    -Thus, the most popular strategy is to start from the +

    Thus, the most popular strategy is to start from the simplest class of models and increase the complexity of the models only when the simpler models become inadequate. For instance, if we work with a regression problem to fit a set of sample points, one may first try the simplest class of models, namely linear models, followed obviously by more complex models. +

    -

    -How to evaluate which model fits best the data is something we will come back to over and over again in these sets of lectures. +

    How to evaluate which model fits best the data is something we will come back to over and over again in these sets of lectures.

    -

      @@ -421,25 +407,18 @@ How to evaluate which model fits best the data is something we will come back to
    • »
    -
    - - -
    - - - diff --git a/doc/pub/week34/html/._week34-bs025.html b/doc/pub/week34/html/._week34-bs025.html index 741df9dbe..7d93894f6 100644 --- a/doc/pub/week34/html/._week34-bs025.html +++ b/doc/pub/week34/html/._week34-bs025.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 34: Introduction to the course, Logistics and Practicalities - + - - - -
    -

     

     

     

    - -

    Software and needed installations

    -

    -We will make extensive use of Python as programming language and its +

    We will make extensive use of Python as programming language and its myriad of available libraries. You will find Jupyter notebooks invaluable in your work. You can run R codes in the Jupyter/IPython notebooks, with the immediate benefit of visualizing your data. You can also use compiled languages like C++, Rust, Julia, Fortran etc if you prefer. The focus in these lectures will be on Python. +

    -

    -If you have Python installed (we strongly recommend Python3) and you feel +

    If you have Python installed (we strongly recommend Python3) and you feel pretty familiar with installing different packages, we recommend that you install the following Python packages via pip as +

    1. pip install numpy scipy matplotlib ipython scikit-learn mglearn sympy pandas pillow
    +

    For Python3, replace pip with pip3.

    -For Python3, replace pip with pip3. - -

    -For OSX users we recommend, after having installed Xcode, to +

    For OSX users we recommend, after having installed Xcode, to install brew. Brew allows for a seamless installation of additional software via for example +

    1. brew install python3
    - -For Linux users, with its variety of distributions like for example the widely popular Ubuntu distribution, +

    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 +

    1. sudo apt-get install python3 (or python for pyhton2.7)
    +

    etc etc.

    -etc etc. - -

      @@ -435,25 +420,18 @@ etc etc.
    • »
    -
    - - -
    - - - diff --git a/doc/pub/week34/html/._week34-bs026.html b/doc/pub/week34/html/._week34-bs026.html index bcd75fb81..405515819 100644 --- a/doc/pub/week34/html/._week34-bs026.html +++ b/doc/pub/week34/html/._week34-bs026.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 34: Introduction to the course, Logistics and Practicalities - + - - - -
    -

     

     

     

    - -

    Python installers

    -

    -If you don't want to perform these operations separately and venture +

    If you don't want to perform these operations separately and venture into the hassle of exploring how to set up dependencies and paths, we recommend two widely used distrubutions which set up all relevant dependencies for Python, namely +

    - -which is an open source +

    which 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. +

    - -is a Python +

    is a Python distribution for scientific and analytic computing distribution and analysis environment, available for free and under a commercial license. +

    -

    -Furthermore, Google's Colab is a free Jupyter notebook environment that requires +

    Furthermore, Google's Colab is a free Jupyter notebook environment that requires no setup and runs entirely in the cloud. Try it out! +

    -

      @@ -426,25 +413,18 @@ no setup and runs entirely in the cloud. Try it out!
    • »
    -
    - - -
    - - - diff --git a/doc/pub/week34/html/._week34-bs027.html b/doc/pub/week34/html/._week34-bs027.html index d89241da8..7154383d6 100644 --- a/doc/pub/week34/html/._week34-bs027.html +++ b/doc/pub/week34/html/._week34-bs027.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 34: Introduction to the course, Logistics and Practicalities - + - - - -
    -

     

     

     

    - -

    Useful Python libraries

    -Here we list several useful Python libraries we strongly recommend (if you use anaconda many of these are already there) +

    Here we list several useful Python libraries we strongly recommend (if you use anaconda many of these are already there)

    • NumPy is a highly popular library for large, multi-dimensional arrays and matrices, along with a large collection of high-level mathematical functions to operate on these arrays
    • @@ -381,7 +369,6 @@ Here we list several useful Python libraries we strongly recommend (if you use a
    • Keras is a high-level neural networks API, written in Python and capable of running on top of TensorFlow, CNTK, or Theano
    • And many more such as pytorch, Theano etc
    -

      @@ -411,25 +398,18 @@ Here we list several useful Python libraries we strongly recommend (if you use a
    • »
    -
    - - -
    - - - diff --git a/doc/pub/week34/html/._week34-bs028.html b/doc/pub/week34/html/._week34-bs028.html index f061e80db..cba01d955 100644 --- a/doc/pub/week34/html/._week34-bs028.html +++ b/doc/pub/week34/html/._week34-bs028.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 34: Introduction to the course, Logistics and Practicalities - + - - - -
    -

     

     

     

    - -

    Installing R, C++, cython or Julia

    -

    -You will also find it convenient to utilize R. We will mainly +

    You will also find it convenient to utilize R. We will mainly use Python during our lectures and in various projects and exercises. Those of you already familiar with R should feel free to continue using R, keeping @@ -378,12 +365,12 @@ notebook allows you to run R codes interactively in your browser. The software library R is really tailored for statistical data analysis and allows for an easy usage of the tools and algorithms we will discuss in these lectures. +

    -

    -To install R with Jupyter notebook +

    To install R with Jupyter notebook follow the link here +

    -

      @@ -413,25 +400,18 @@ To install R with Jupyter notebook
    • »
    -
    - - -
    - - - diff --git a/doc/pub/week34/html/._week34-bs029.html b/doc/pub/week34/html/._week34-bs029.html index a0a21c458..7bc0becfd 100644 --- a/doc/pub/week34/html/._week34-bs029.html +++ b/doc/pub/week34/html/._week34-bs029.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 34: Introduction to the course, Logistics and Practicalities - + - - - -
    -

     

     

     

    - -

    Installing R, C++, cython, Numba etc

    -

    -For the C++ aficionados, Jupyter/IPython notebook allows you also to +

    For the C++ aficionados, Jupyter/IPython notebook allows you also to install C++ and run codes written in this language interactively in the browser. Since we will emphasize writing many of the algorithms yourself, you can thus opt for either Python or C++ (or Fortran or other compiled languages) as programming languages. +

    -

    -To add more entropy, cython can also be used when running your +

    To add more entropy, cython can also be used when running your notebooks. It means that Python with the jupyter notebook setup allows you to integrate widely popular softwares and tools for scientific computing. Similarly, the @@ -384,22 +371,39 @@ capabilities with minimal rewrites of your codes. With its versatility, including symbolic operations, Python offers a unique computational environment. Your jupyter notebook can easily be converted into a nicely rendered PDF file or a Latex file for -further processing. For example, convert to latex as +further processing. For example, convert to latex as +

    -

    - -

    pycod jupyter nbconvert filename.ipynb --to latex 
    -
    -

    -And to add more versatility, the Python package SymPy is a Python library for symbolic mathematics. It aims to become a full-featured computer algebra system (CAS) and is entirely written in Python. + +

    +
    +
    +
    +
    +
    pycod jupyter nbconvert filename.ipynb --to latex 
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    -

    -Finally, if you wish to use the light mark-up language +

    And to add more versatility, the Python package SymPy is a Python library for symbolic mathematics. It aims to become a full-featured computer algebra system (CAS) and is entirely written in Python.

    + +

    Finally, if you wish to use the light mark-up language doconce you can convert a standard ascii text file into various HTML formats, ipython notebooks, latex files, pdf files etc with minimal edits. These lectures were generated using doconce. +

    -

      @@ -429,25 +433,18 @@ formats, ipython notebooks, latex files, pdf files etc with minimal edits. These
    • »
    -
    - - -
    - - - diff --git a/doc/pub/week34/html/._week34-bs030.html b/doc/pub/week34/html/._week34-bs030.html index ced6ad896..71571162a 100644 --- a/doc/pub/week34/html/._week34-bs030.html +++ b/doc/pub/week34/html/._week34-bs030.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 34: Introduction to the course, Logistics and Practicalities - + - - - -
    -

     

     

     

    - -

    Numpy examples and Important Matrix and vector handling packages

    -

    -There are several central software libraries for linear algebra and eigenvalue problems. Several of the more +

    There are several central software libraries for linear algebra and eigenvalue problems. Several of the more popular ones have been wrapped into ofter software packages like those from the widely used text Numerical Recipes. The original source codes in many of the available packages are often taken from the widely used software package LAPACK, which follows two other popular packages developed in the 1970s, namely EISPACK and LINPACK. We describe them shortly here. +

    • LINPACK: package for linear equations and least square problems.
    • LAPACK:package for solving symmetric, unsymmetric and generalized eigenvalue problems. From LAPACK's website http://www.netlib.org it is possible to download for free all source codes from this library. Both C/C++ and Fortran versions are available.
    • BLAS (I, II and III): (Basic Linear Algebra Subprograms) are routines that provide standard building blocks for performing basic vector and matrix operations. Blas I is vector operations, II vector-matrix operations and III matrix-matrix operations. Highly parallelized and efficient codes, all available for download from http://www.netlib.org.
    -

      @@ -408,25 +395,18 @@ developed in the 1970s, namely EISPACK and LINPACK. We describe them shortly he
    • »
    -
    - - -
    - - - diff --git a/doc/pub/week34/html/._week34-bs031.html b/doc/pub/week34/html/._week34-bs031.html index cb513eadb..51dfd6fb5 100644 --- a/doc/pub/week34/html/._week34-bs031.html +++ b/doc/pub/week34/html/._week34-bs031.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 34: Introduction to the course, Logistics and Practicalities - + - - - -
    -

     

     

     

    - -

    Basic Matrix Features

    -

    -

    + $$ \mathbf{A} = \begin{bmatrix} a_{11} & a_{12} & a_{13} & a_{14} \\ @@ -386,18 +373,16 @@ $$ \end{bmatrix} $$ -

    -The inverse of a matrix is defined by +

    The inverse of a matrix is defined by

    $$ \mathbf{A}^{-1} \cdot \mathbf{A} = I $$ -

    - +
    @@ -411,12 +396,10 @@ $$
    Relations Name matrix elements
    -

    -

      @@ -446,25 +429,18 @@ $$
    • »
    -
    - - -
    - - - diff --git a/doc/pub/week34/html/._week34-bs032.html b/doc/pub/week34/html/._week34-bs032.html index f00965c04..e565e738a 100644 --- a/doc/pub/week34/html/._week34-bs032.html +++ b/doc/pub/week34/html/._week34-bs032.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 34: Introduction to the course, Logistics and Practicalities - + - - - -
    -

     

     

     

    - -

    Some famous Matrices

      @@ -378,7 +366,6 @@ MathJax.Hub.Config({
    • Upper banded with bandwidth \( p \): \( a_{ij}=0 \) for \( i < j+p \)
    • Banded, block upper triangular, block lower triangular....
    -

      @@ -408,25 +395,18 @@ MathJax.Hub.Config({
    • »
    -
    - - -
    - - - diff --git a/doc/pub/week34/html/._week34-bs033.html b/doc/pub/week34/html/._week34-bs033.html index cd42cfe65..a72e0ae5e 100644 --- a/doc/pub/week34/html/._week34-bs033.html +++ b/doc/pub/week34/html/._week34-bs033.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 34: Introduction to the course, Logistics and Practicalities - + - - - -
    -

     

     

     

    - -

    More Basic Matrix Features

    -

    -

    -For an \( N\times N \) matrix \( \mathbf{A} \) the following properties are all equivalent + +

    For an \( N\times N \) matrix \( \mathbf{A} \) the following properties are all equivalent

    • If the inverse of \( \mathbf{A} \) exists, \( \mathbf{A} \) is nonsingular.
    • @@ -385,7 +372,6 @@ For an \( N\times N \) matrix \( \mathbf{A} \) the following properties are all
    -

      @@ -415,25 +401,18 @@ For an \( N\times N \) matrix \( \mathbf{A} \) the following properties are all
    • »
    -
    - - -
    - - - diff --git a/doc/pub/week34/html/._week34-bs034.html b/doc/pub/week34/html/._week34-bs034.html index 8c7e2149e..6f4ed5e73 100644 --- a/doc/pub/week34/html/._week34-bs034.html +++ b/doc/pub/week34/html/._week34-bs034.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 34: Introduction to the course, Logistics and Practicalities - + - - -
    -
    -

     

     

     

    - -

    Numpy and arrays

    -Numpy provides an easy way to handle arrays in Python. The standard way to import this library is as +

    Numpy provides an easy way to handle arrays in Python. The standard way to import this library is as

    -

    -

    import numpy as np
    -
    -

    -Here follows a simple example where we set up an array of ten elements, all determined by random numbers drawn according to the normal distribution, -

    +

    +
    +
    +
    +
    +
    import numpy as np
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    Here follows a simple example where we set up an array of ten elements, all determined by random numbers drawn according to the normal distribution,

    -
    n = 10
    +
    +
    +
    +
    +
    +
    n = 10
     x = np.random.normal(size=n)
     print(x)
    -
    -

    -We defined a vector \( x \) with \( n=10 \) elements with its values given by the Normal distribution \( N(0,1) \). +

    +
    +
    + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    We defined a vector \( x \) with \( n=10 \) elements with its values given by the Normal distribution \( N(0,1) \). Another alternative is to declare a vector as follows -

    +

    -
    import numpy as np
    +
    +
    +
    +
    +
    +
    import numpy as np
     x = np.array([1, 2, 3])
     print(x)
    -
    -

    -Here we have defined a vector with three elements, with \( x_0=1 \), \( x_1=2 \) and \( x_2=3 \). Note that both Python and C++ +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    Here we have defined a vector with three elements, with \( x_0=1 \), \( x_1=2 \) and \( x_2=3 \). Note that both Python and C++ start numbering array elements from \( 0 \) and on. This means that a vector with \( n \) elements has a sequence of entities \( x_0, x_1, x_2, \dots, x_{n-1} \). We could also let (recommended) Numpy to compute the logarithms of a specific array as -

    +

    -
    import numpy as np
    +
    +
    +
    +
    +
    +
    import numpy as np
     x = np.log(np.array([4, 7, 8]))
     print(x)
    -
    -

    -In the last example we used Numpy's unary function \( np.log \). This function is +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    In the last example we used Numpy's unary function \( np.log \). This function is highly tuned to compute array elements since the code is vectorized and does not require looping. We normaly recommend that you use the Numpy intrinsic functions instead of the corresponding log function from Python's math module. The looping is done explicitely by the np.log function. The alternative, and slower way to compute the logarithms of a vector would be to write +

    -

    -

    import numpy as np
    +
    +
    +
    +
    +
    +
    import numpy as np
     from math import log
     x = np.array([4, 7, 8])
     for i in range(0, len(x)):
         x[i] = log(x[i])
     print(x)
    -
    -

    -We note that our code is much longer already and we need to import the log function from the math module. +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    We note that our code is much longer already and we need to import the log function from the math module. The attentive reader will also notice that the output is \( [1, 1, 2] \). Python interprets automagically our numbers as integers (like the automatic keyword in C++). To change this we could define our array elements to be double precision numbers as -

    +

    -
    import numpy as np
    +
    +
    +
    +
    +
    +
    import numpy as np
     x = np.log(np.array([4, 7, 8], dtype = np.float64))
     print(x)
    -
    -

    -or simply write them as double precision numbers (Python uses 64 bits as default for floating point type variables), that is -

    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    or simply write them as double precision numbers (Python uses 64 bits as default for floating point type variables), that is

    -
    import numpy as np
    +
    +
    +
    +
    +
    +
    import numpy as np
     x = np.log(np.array([4.0, 7.0, 8.0]))
     print(x)
    -
    -

    -To check the number of bytes (remember that one byte contains eight bits for double precision variables), you can use simple use the itemsize functionality (the array \( x \) is actually an object which inherits the functionalities defined in Numpy) as -

    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    To check the number of bytes (remember that one byte contains eight bits for double precision variables), you can use simple use the itemsize functionality (the array \( x \) is actually an object which inherits the functionalities defined in Numpy) as

    -
    import numpy as np
    +
    +
    +
    +
    +
    +
    import numpy as np
     x = np.log(np.array([4.0, 7.0, 8.0]))
     print(x.itemsize)
    -
    -

    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    - - - -
    - - - diff --git a/doc/pub/week34/html/._week34-bs035.html b/doc/pub/week34/html/._week34-bs035.html index 190e60cef..904bd965d 100644 --- a/doc/pub/week34/html/._week34-bs035.html +++ b/doc/pub/week34/html/._week34-bs035.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 34: Introduction to the course, Logistics and Practicalities - + - - - -
    -

     

     

     

    - -

    Matrices in Python

    -

    -Having defined vectors, we are now ready to try out matrices. We can +

    Having defined vectors, we are now ready to try out matrices. We can define a \( 3 \times 3 \) real matrix \( \boldsymbol{A} \) as (recall that we user lowercase letters for vectors and uppercase letters for matrices) +

    -

    -

    import numpy as np
    +
    +
    +
    +
    +
    +
    import numpy as np
     A = np.log(np.array([ [4.0, 7.0, 8.0], [3.0, 10.0, 11.0], [4.0, 5.0, 7.0] ]))
     print(A)
    -
    -

    -If we use the shape function we would get \( (3, 3) \) as output, that is verifying that our matrix is a \( 3\times 3 \) matrix. We can slice the matrix and print for example the first column (Python organized matrix elements in a row-major order, see below) as -

    +

    +
    +
    + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    If we use the shape function we would get \( (3, 3) \) as output, that is verifying that our matrix is a \( 3\times 3 \) matrix. We can slice the matrix and print for example the first column (Python organized matrix elements in a row-major order, see below) as

    -
    import numpy as np
    +
    +
    +
    +
    +
    +
    import numpy as np
     A = np.log(np.array([ [4.0, 7.0, 8.0], [3.0, 10.0, 11.0], [4.0, 5.0, 7.0] ]))
     # print the first column, row-major order and elements start with 0
     print(A[:,0]) 
    -
    -

    -We can continue this was by printing out other columns or rows. The example here prints out the second column -

    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    We can continue this was by printing out other columns or rows. The example here prints out the second column

    -
    import numpy as np
    +
    +
    +
    +
    +
    +
    import numpy as np
     A = np.log(np.array([ [4.0, 7.0, 8.0], [3.0, 10.0, 11.0], [4.0, 5.0, 7.0] ]))
     # print the first column, row-major order and elements start with 0
     print(A[1,:]) 
    -
    -

    -Numpy contains many other functionalities that allow us to slice, subdivide etc etc arrays. We strongly recommend that you look up the Numpy website for more details. Useful functions when defining a matrix are the np.zeros function which declares a matrix of a given dimension and sets all elements to zero -

    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    Numpy contains many other functionalities that allow us to slice, subdivide etc etc arrays. We strongly recommend that you look up the Numpy website for more details. Useful functions when defining a matrix are the np.zeros function which declares a matrix of a given dimension and sets all elements to zero

    -
    import numpy as np
    +
    +
    +
    +
    +
    +
    import numpy as np
     n = 10
     # define a matrix of dimension 10 x 10 and set all elements to zero
     A = np.zeros( (n, n) )
     print(A) 
    -
    -

    -or initializing all elements to -

    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    or initializing all elements to

    -
    import numpy as np
    +
    +
    +
    +
    +
    +
    import numpy as np
     n = 10
     # define a matrix of dimension 10 x 10 and set all elements to one
     A = np.ones( (n, n) )
     print(A) 
    -
    -

    -or as unitarily distributed random numbers (see the material on random number generators in the statistics part) -

    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    or as unitarily distributed random numbers (see the material on random number generators in the statistics part)

    -
    import numpy as np
    +
    +
    +
    +
    +
    +
    import numpy as np
     n = 10
     # define a matrix of dimension 10 x 10 and set all elements to random numbers with x \in [0, 1]
     A = np.random.rand(n, n)
     print(A) 
    -
    -

    -As we will see throughout these lectures, there are several extremely useful functionalities in Numpy. +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    As we will see throughout these lectures, there are several extremely useful functionalities in Numpy. As an example, consider the discussion of the covariance matrix. Suppose we have defined three vectors \( \boldsymbol{x}, \boldsymbol{y}, \boldsymbol{z} \) with \( n \) elements each. The covariance matrix is defined as +

    $$ \boldsymbol{\Sigma} = \begin{bmatrix} \sigma_{xx} & \sigma_{xy} & \sigma_{xz} \\ \sigma_{yx} & \sigma_{yy} & \sigma_{yz} \\ @@ -443,13 +534,14 @@ $$ \end{bmatrix}, $$ -where for example +

    where for example

    $$ \sigma_{xy} =\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})(y_i- \overline{y}). $$ -The Numpy function np.cov calculates the covariance elements using the factor \( 1/(n-1) \) instead of \( 1/n \) since it assumes we do not have the exact mean values. +

    The Numpy function np.cov calculates the covariance elements using the factor \( 1/(n-1) \) instead of \( 1/n \) since it assumes we do not have the exact mean values. The following simple function uses the np.vstack function which takes each vector of dimension \( 1\times n \) and produces a \( 3\times n \) matrix \( \boldsymbol{W} \) +

    $$ \boldsymbol{W} = \begin{bmatrix} x_0 & x_1 & x_2 & \dots & x_{n-2} & x_{n-1} \\ y_0 & y_1 & y_2 & \dots & y_{n-2} & y_{n-1} \\ @@ -457,17 +549,21 @@ $$ \end{bmatrix}, $$ -

    -which in turn is converted into into the \( 3\times 3 \) covariance matrix +

    which in turn is converted into into the \( 3\times 3 \) covariance matrix \( \boldsymbol{\Sigma} \) via the Numpy function np.cov(). We note that we can also calculate the mean value of each set of samples \( \boldsymbol{x} \) etc using the Numpy function np.mean(x). We can also extract the eigenvalues of the covariance matrix through the np.linalg.eig() function. +

    -

    -

    # Importing various packages
    +
    +
    +
    +
    +
    +
    # Importing various packages
     import numpy as np
     
     n = 100
    @@ -482,11 +578,26 @@ Sigma = np.print(Sigma)
     Eigvals, Eigvecs = np.linalg.eig(Sigma)
     print(Eigvals)
    -
    -

    - +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    -
    import numpy as np
    +
    +
    +
    +
    +
    +
    import numpy as np
     import matplotlib.pyplot as plt
     from scipy import sparse
     eye = np.eye(4)
    @@ -497,8 +608,22 @@ x = np.l
     y = np.sin(x)
     plt.plot(x,y,marker='x')
     plt.show()
    -
    -

    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    - - - -
    - - - diff --git a/doc/pub/week34/html/._week34-bs036.html b/doc/pub/week34/html/._week34-bs036.html index d8797b3ed..a5e61ece4 100644 --- a/doc/pub/week34/html/._week34-bs036.html +++ b/doc/pub/week34/html/._week34-bs036.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 34: Introduction to the course, Logistics and Practicalities - + - - - -
    -

     

     

     

    - -

    Meet the Pandas

    -

    -



    +

    +
    +

    +
    +

    -

    -Another useful Python package is +

    Another useful Python package is pandas, which is an open source library providing high-performance, easy-to-use data structures and data analysis tools for Python. pandas stands for panel data, a term borrowed from econometrics and is an efficient library for data analysis with an emphasis on tabular data. pandas has two major classes, the DataFrame class with two-dimensional data objects and tabular data organized in columns and the class Series with a focus on one-dimensional data objects. Both classes allow you to index data easily as we will see in the examples below. -pandas allows you also to perform mathematical operations on the data, spanning from simple reshapings of vectors and matrices to statistical operations. +pandas allows you also to perform mathematical operations on the data, spanning from simple reshapings of vectors and matrices to statistical operations. +

    -

    -The following simple example shows how we can, in an easy way make tables of our data. Here we define a data set which includes names, place of birth and date of birth, and displays the data in an easy to read way. We will see repeated use of pandas, in particular in connection with classification of data. +

    The following simple example shows how we can, in an easy way make tables of our data. Here we define a data set which includes names, place of birth and date of birth, and displays the data in an easy to read way. We will see repeated use of pandas, in particular in connection with classification of data.

    -

    -

    import pandas as pd
    +
    +
    +
    +
    +
    +
    import pandas as pd
     from IPython.display import display
     data = {'First Name': ["Frodo", "Bilbo", "Aragorn II", "Samwise"],
             'Last Name': ["Baggins", "Baggins","Elessar","Gamgee"],
    @@ -393,45 +387,115 @@ data = {'Fi
             }
     data_pandas = pd.DataFrame(data)
     display(data_pandas)
    -
    -

    -In the above we have imported pandas with the shorthand pd, the latter has become the standard way we import pandas. We make then a list of various variables +

    +
    +
    + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    In the above we have imported pandas with the shorthand pd, the latter has become the standard way we import pandas. We make then a list of various variables and reorganize the aboves lists into a DataFrame and then print out a neat table with specific column labels as Name, place of birth and date of birth. Displaying these results, we see that the indices are given by the default numbers from zero to three. pandas is extremely flexible and we can easily change the above indices by defining a new type of indexing as -

    +

    -
    data_pandas = pd.DataFrame(data,index=['Frodo','Bilbo','Aragorn','Sam'])
    +
    +
    +
    +
    +
    +
    data_pandas = pd.DataFrame(data,index=['Frodo','Bilbo','Aragorn','Sam'])
     display(data_pandas)
    -
    -

    -Thereafter we display the content of the row which begins with the index Aragorn -

    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    Thereafter we display the content of the row which begins with the index Aragorn

    -
    display(data_pandas.loc['Aragorn'])
    -
    -

    -We can easily append data to this, for example -

    +

    +
    +
    +
    +
    +
    display(data_pandas.loc['Aragorn'])
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    We can easily append data to this, for example

    -
    new_hobbit = {'First Name': ["Peregrin"],
    +
    +
    +
    +
    +
    +
    new_hobbit = {'First Name': ["Peregrin"],
                   'Last Name': ["Took"],
                   'Place of birth': ["Shire"],
                   'Date of Birth T.A.': [2990]
                   }
     data_pandas=data_pandas.append(pd.DataFrame(new_hobbit, index=['Pippin']))
     display(data_pandas)
    -
    -

    -Here are other examples where we use the DataFrame functionality to handle arrays, now with more interesting features for us, namely numbers. We set up a matrix +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    Here are other examples where we use the DataFrame functionality to handle arrays, now with more interesting features for us, namely numbers. We set up a matrix of dimensionality \( 10\times 5 \) and compute the mean value and standard deviation of each column. Similarly, we can perform mathematial operations like squaring the matrix elements and many other operations. -

    +

    -
    import numpy as np
    +
    +
    +
    +
    +
    +
    import numpy as np
     import pandas as pd
     from IPython.display import display
     np.random.seed(100)
    @@ -444,13 +508,30 @@ display(df)
     print(df.mean())
     print(df.std())
     display(df**2)
    -
    -

    -Thereafter we can select specific columns only and plot final results -

    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    Thereafter we can select specific columns only and plot final results

    -
    df.columns = ['First', 'Second', 'Third', 'Fourth', 'Fifth']
    +
    +
    +
    +
    +
    +
    df.columns = ['First', 'Second', 'Third', 'Fourth', 'Fifth']
     df.index = np.arange(10)
     
     display(df)
    @@ -468,29 +549,58 @@ plt.show()
     
     df.plot.bar(figsize=(10,6), rot=15)
     plt.show()
    -
    -

    -We can produce a \( 4\times 4 \) matrix -

    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    We can produce a \( 4\times 4 \) matrix

    -
    b = np.arange(16).reshape((4,4))
    +
    +
    +
    +
    +
    +
    b = np.arange(16).reshape((4,4))
     print(b)
     df1 = pd.DataFrame(b)
     print(df1)
    -
    -

    -and many other operations. +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + -

    -The Series class is another important class included in +

    and many other operations.

    + +

    The Series class is another important class included in pandas. You can view it as a specialization of DataFrame but where we have just a single column of data. It shares many of the same features as _DataFrame. As with DataFrame, most operations are vectorized, achieving thereby a high performance when dealing with computations of arrays, in particular labeled arrays. As we will see below it leads also to a very concice code close to the mathematical operations we may be interested in. -For multidimensional arrays, we recommend strongly xarray. xarray has much of the same flexibility as pandas, but allows for the extension to higher dimensions than two. We will see examples later of the usage of both pandas and xarray. +For multidimensional arrays, we recommend strongly xarray. xarray has much of the same flexibility as pandas, but allows for the extension to higher dimensions than two. We will see examples later of the usage of both pandas and xarray. +

    -

    - - - -
    - - - diff --git a/doc/pub/week34/html/._week34-bs037.html b/doc/pub/week34/html/._week34-bs037.html index 637028baf..f26a487d1 100644 --- a/doc/pub/week34/html/._week34-bs037.html +++ b/doc/pub/week34/html/._week34-bs037.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 34: Introduction to the course, Logistics and Practicalities - + - - - -
    -

     

     

     

    - -

    Friday August 27

    -

    -"Video of Lecture August 27, 2021":"https://www.uio.no/studier/emner/matnat/fys/FYS-STK4155/h21/forelesningsvideoer/LectureThursdayAugust27.mp4?vrtx=view-as-webpage +

    "Video of Lecture August 27, 2021":"https://www.uio.no/studier/emner/matnat/fys/FYS-STK4155/h21/forelesningsvideoer/LectureThursdayAugust27.mp4?vrtx=view-as-webpage

    -

    -Video of Lecture from fall 2020 and Handwritten notes +

    Video of Lecture from fall 2020 and Handwritten notes

    -

      @@ -403,25 +388,18 @@ MathJax.Hub.Config({
    • »
    -
    - - -
    - - - diff --git a/doc/pub/week34/html/._week34-bs038.html b/doc/pub/week34/html/._week34-bs038.html index e3e6109ac..9fe805d82 100644 --- a/doc/pub/week34/html/._week34-bs038.html +++ b/doc/pub/week34/html/._week34-bs038.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 34: Introduction to the course, Logistics and Practicalities - + - - - -
    -

     

     

     

    - +

    Simple linear regression model using scikit-learn

    -

    Simple linear regression model using scikit-learn

    +

    We start with perhaps our simplest possible example, using Scikit-Learn to perform linear regression analysis on a data set produced by us.

    -

    -We start with perhaps our simplest possible example, using Scikit-Learn to perform linear regression analysis on a data set produced by us. - -

    -What follows is a simple Python code where we have defined a function +

    What follows is a simple Python code where we have defined a function \( y \) in terms of the variable \( x \). Both are defined as vectors with \( 100 \) entries. The numbers in the vector \( \boldsymbol{x} \) are given by random numbers generated with a uniform distribution with entries @@ -379,9 +365,9 @@ by random numbers generated with a uniform distribution with entries later). These values are then used to define a function \( y(x) \) (tabulated again as a vector) with a linear dependence on \( x \) plus a random noise added via the normal distribution. +

    -

    -The Numpy functions are imported used the import numpy as np +

    The Numpy functions are imported used the import numpy as np statement and the random number generator for the uniform distribution is called using the function np.random.rand(), where we specificy that we want \( 100 \) random variables. Using Numpy we define @@ -390,13 +376,13 @@ our case. With the Numpy function randn() we can compute random numbers with the normal distribution (mean value \( \mu \) equal to zero and variance \( \sigma^2 \) set to one) and produce the values of \( y \) assuming a linear dependence as function of \( x \) +

    $$ y = 2x+N(0,1), $$ -

    -where \( N(0,1) \) represents random numbers generated by the normal +

    where \( N(0,1) \) represents random numbers generated by the normal distribution. From Scikit-Learn we import then the LinearRegression functionality and make a prediction \( \tilde{y} = \alpha + \beta x \) using the function fit(x,y). We call the set of @@ -404,22 +390,26 @@ data \( (\boldsymbol{x},\boldsymbol{y}) \) for our training data. The Python pac scikit-learn has also a functionality which extracts the above fitting parameters \( \alpha \) and \( \beta \) (see below). Later we will distinguish between training data and test data. +

    -

    -For plotting we use the Python package +

    For plotting we use the Python package matplotlib which produces publication quality figures. Feel free to explore the extensive gallery of examples. In this example we plot our original values of \( x \) and \( y \) as well as the prediction ypredict (\( \tilde{y} \)), which attempts at fitting our data with a straight line. +

    -

    -The Python code follows here. -

    +

    The Python code follows here.

    -
    # Importing various packages
    +
    +
    +
    +
    +
    +
    # Importing various packages
     import numpy as np
     import matplotlib.pyplot as plt
     from sklearn.linear_model import LinearRegression
    @@ -438,9 +428,22 @@ plt.xlabel(r
     plt.ylabel(r'$y$')
     plt.title(r'Simple Linear Regression')
     plt.show()
    -
    -

    -This example serves several aims. It allows us to demonstrate several +

    +
    +
    + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    This example serves several aims. It allows us to demonstrate several aspects of data analysis and later machine learning algorithms. The immediate visualization shows that our linear fit is not impressive. It goes through the data points, but there are many @@ -448,38 +451,38 @@ outliers which are not reproduced by our linear regression. We could now play around with this small program and change for example the factor in front of \( x \) and the normal distribution. Try to change the function \( y \) to +

    $$ y = 10x+0.01 \times N(0,1), $$ -

    -where \( x \) is defined as before. Does the fit look better? Indeed, by +

    where \( x \) is defined as before. Does the fit look better? Indeed, by reducing the role of the noise given by the normal distribution we see immediately that our linear prediction seemingly reproduces better the training set. However, this testing 'by the eye' is obviouly not satisfactory in the long run. Here we have only defined the training data and our model, and have not discussed a more rigorous approach to the cost function. +

    -

    -We need more rigorous criteria in defining whether we have succeeded or +

    We need more rigorous criteria in defining whether we have succeeded or not in modeling our training data. You will be surprised to see that many scientists seldomly venture beyond this 'by the eye' approach. A standard approach for the cost function is the so-called \( \chi^2 \) function (a variant of the mean-squared error (MSE)) +

    $$ \chi^2 = \frac{1}{n} \sum_{i=0}^{n-1}\frac{(y_i-\tilde{y}_i)^2}{\sigma_i^2}, $$ -

    -where \( \sigma_i^2 \) is the variance (to be defined later) of the entry +

    where \( \sigma_i^2 \) is the variance (to be defined later) of the entry \( y_i \). We may not know the explicit value of \( \sigma_i^2 \), it serves however the aim of scaling the equations and make the cost function -dimensionless. +dimensionless. +

    -

    -Minimizing the cost function is a central aspect of +

    Minimizing the cost function is a central aspect of our discussions to come. Finding its minima as function of the model parameters (\( \alpha \) and \( \beta \) in our case) will be a recurring theme in these series of lectures. Essentially all machine learning @@ -492,30 +495,34 @@ employed are various variants of gradient methods. These will be discussed in more detail later. Again, you'll be surprised to hear that many practitioners minimize the above function ''by the eye', popularly dubbed as 'chi by the eye'. That is, change a parameter and see (visually and numerically) that -the \( \chi^2 \) function becomes smaller. +the \( \chi^2 \) function becomes smaller. +

    -

    -There are many ways to define the cost function. A simpler approach is to look at the relative difference between the training data and the predicted data, that is we define +

    There are many ways to define the cost function. A simpler approach is to look at the relative difference between the training data and the predicted data, that is we define the relative error (why would we prefer the MSE instead of the relative error?) as +

    $$ \epsilon_{\mathrm{relative}}= \frac{\vert \boldsymbol{y} -\boldsymbol{\tilde{y}}\vert}{\vert \boldsymbol{y}\vert}. $$ -

    -The squared cost function results in an arithmetic mean-unbiased +

    The squared cost function results in an arithmetic mean-unbiased estimator, and the absolute-value cost function results in a median-unbiased estimator (in the one-dimensional case, and a geometric median-unbiased estimator for the multi-dimensional case). The squared cost function has the disadvantage that it has the tendency to be dominated by outliers. +

    -

    -We can modify easily the above Python code and plot the relative error instead -

    +

    We can modify easily the above Python code and plot the relative error instead

    -
    import numpy as np
    +
    +
    +
    +
    +
    +
    import numpy as np
     import matplotlib.pyplot as plt
     from sklearn.linear_model import LinearRegression
     
    @@ -531,26 +538,44 @@ plt.xlabel(r
     plt.ylabel(r'$\epsilon_{\mathrm{relative}}$')
     plt.title(r'Relative error')
     plt.show()
    -
    -

    -Depending on the parameter in front of the normal distribution, we may +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    Depending on the parameter in front of the normal distribution, we may have a small or larger relative error. Try to play around with different training data sets and study (graphically) the value of the relative error. +

    -

    -As mentioned above, Scikit-Learn has an impressive functionality. +

    As mentioned above, Scikit-Learn has an impressive functionality. We can for example extract the values of \( \alpha \) and \( \beta \) and their error estimates, or the variance and standard deviation and many -other properties from the statistical data analysis. +other properties from the statistical data analysis. +

    -

    -Here we show an +

    Here we show an example of the functionality of Scikit-Learn. -

    +

    -
    import numpy as np 
    +
    +
    +
    +
    +
    +
    import numpy as np 
     import matplotlib.pyplot as plt 
     from sklearn.linear_model import LinearRegression 
     from sklearn.metrics import mean_squared_error, r2_score, mean_squared_log_error, mean_absolute_error
    @@ -577,84 +602,101 @@ plt.xlabel(r
     plt.ylabel(r'$y$')
     plt.title(r'Linear Regression fit ')
     plt.show()
    -
    -

    -The function coef gives us the parameter \( \beta \) of our fit while intercept yields +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    The function coef gives us the parameter \( \beta \) of our fit while intercept yields \( \alpha \). Depending on the constant in front of the normal distribution, we get values near or far from \( \alpha =2 \) and \( \beta =5 \). Try to play around with different parameters in front of the normal distribution. The function meansquarederror gives us the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error or loss defined as +

    $$ MSE(\boldsymbol{y},\boldsymbol{\tilde{y}}) = \frac{1}{n} \sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, $$ -

    -The smaller the value, the better the fit. Ideally we would like to +

    The smaller the value, the better the fit. Ideally we would like to have an MSE equal zero. The attentive reader has probably recognized this function as being similar to the \( \chi^2 \) function defined above. +

    -

    -The r2score function computes \( R^2 \), the coefficient of +

    The r2score function computes \( R^2 \), the coefficient of determination. It provides a measure of how well future samples are likely to be predicted by the model. Best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse). A constant model that always predicts the expected value of \( \boldsymbol{y} \), disregarding the input features, would get a \( R^2 \) score of \( 0.0 \). +

    -

    -If \( \tilde{\boldsymbol{y}}_i \) is the predicted value of the \( i-th \) sample and \( y_i \) is the corresponding true value, then the score \( R^2 \) is defined as +

    If \( \tilde{\boldsymbol{y}}_i \) is the predicted value of the \( i-th \) sample and \( y_i \) is the corresponding true value, then the score \( R^2 \) is defined as

    $$ R^2(\boldsymbol{y}, \tilde{\boldsymbol{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2}, $$ -where we have defined the mean value of \( \boldsymbol{y} \) as +

    where we have defined the mean value of \( \boldsymbol{y} \) as

    $$ \bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. $$ -Another quantity taht we will meet again in our discussions of regression analysis is +

    Another quantity taht we will meet again in our discussions of regression analysis is the mean absolute error (MAE), a risk metric corresponding to the expected value of the absolute error loss or what we call the \( l1 \)-norm loss. In our discussion above we presented the relative error. The MAE is defined as follows +

    $$ \text{MAE}(\boldsymbol{y}, \boldsymbol{\tilde{y}}) = \frac{1}{n} \sum_{i=0}^{n-1} \left| y_i - \tilde{y}_i \right|. $$ -We present the +

    We present the squared logarithmic (quadratic) error +

    $$ \text{MSLE}(\boldsymbol{y}, \boldsymbol{\tilde{y}}) = \frac{1}{n} \sum_{i=0}^{n - 1} (\log_e (1 + y_i) - \log_e (1 + \tilde{y}_i) )^2, $$ -

    -where \( \log_e (x) \) stands for the natural logarithm of \( x \). This error +

    where \( \log_e (x) \) stands for the natural logarithm of \( x \). This error estimate is best to use when targets having exponential growth, such as population counts, average sales of a commodity over a span of -years etc. +years etc. +

    -

    -Finally, another cost function is the Huber cost function used in robust regression. +

    Finally, another cost function is the Huber cost function used in robust regression.

    -

    -The rationale behind this possible cost function is its reduced +

    The rationale behind this possible cost function is its reduced sensitivity to outliers in the data set. In our discussions on dimensionality reduction and normalization of data we will meet other ways of dealing with outliers. +

    -

    -The Huber cost function is defined as +

    The Huber cost function is defined as

    $$ H_{\delta}(\boldsymbol{a})=\left\{\begin{array}{cc}\frac{1}{2} \boldsymbol{a}^{2}& \text{for }|\boldsymbol{a}|\leq \delta\\ \delta (|\boldsymbol{a}|-\frac{1}{2}\delta ),&\text{otherwise}.\end{array}\right. $$ -Here \( \boldsymbol{a}=\boldsymbol{y} - \boldsymbol{\tilde{y}} \). +

    Here \( \boldsymbol{a}=\boldsymbol{y} - \boldsymbol{\tilde{y}} \).

    -

    -We will discuss in more detail these and other functions in the +

    We will discuss in more detail these and other functions in the various lectures. We conclude this part with another example. Instead of a linear \( x \)-dependence we study now a cubic polynomial and use the polynomial regression analysis tools of scikit-learn. +

    -

    -

    import matplotlib.pyplot as plt
    +
    +
    +
    +
    +
    +
    import matplotlib.pyplot as plt
     import numpy as np
     import random
     from sklearn.linear_model import Ridge
    @@ -684,74 +726,85 @@ plt.show()
         return abs(np.sum(err))/len(err)
     
     print (error(y))
    -
    - +
    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    +

    To our real data: nuclear binding energies. Brief reminder on masses and binding energies

    -

    -Let us now dive into nuclear physics and remind ourselves briefly about some basic features about binding +

    Let us now dive into nuclear physics and remind ourselves briefly about some basic features about binding energies. A basic quantity which can be measured for the ground states of nuclei is the atomic mass \( M(N, Z) \) of the neutral atom with -atomic mass number \( A \) and charge \( Z \). The number of neutrons is \( N \). There are indeed several sophisticated experiments worldwide which allow us to measure this quantity to high precision (parts per million even). +atomic mass number \( A \) and charge \( Z \). The number of neutrons is \( N \). There are indeed several sophisticated experiments worldwide which allow us to measure this quantity to high precision (parts per million even). +

    -

    -Atomic masses are usually tabulated in terms of the mass excess defined by +

    Atomic masses are usually tabulated in terms of the mass excess defined by

    $$ \Delta M(N, Z) = M(N, Z) - uA, $$ -where \( u \) is the Atomic Mass Unit +

    where \( u \) is the Atomic Mass Unit

    $$ u = M(^{12}\mathrm{C})/12 = 931.4940954(57) \hspace{0.1cm} \mathrm{MeV}/c^2. $$ -The nucleon masses are +

    The nucleon masses are

    $$ m_p = 1.00727646693(9)u, $$ -and +

    and

    $$ m_n = 939.56536(8)\hspace{0.1cm} \mathrm{MeV}/c^2 = 1.0086649156(6)u. $$ -

    -In the 2016 mass evaluation of by W.J.Huang, G.Audi, M.Wang, F.G.Kondev, S.Naimi and X.Xu +

    In the 2016 mass evaluation of by W.J.Huang, G.Audi, M.Wang, F.G.Kondev, S.Naimi and X.Xu there are data on masses and decays of 3437 nuclei. +

    -

    -The nuclear binding energy is defined as the energy required to break +

    The nuclear binding energy is defined as the energy required to break up a given nucleus into its constituent parts of \( N \) neutrons and \( Z \) protons. In terms of the atomic masses \( M(N, Z) \) the binding energy is defined by +

    $$ BE(N, Z) = ZM_H c^2 + Nm_n c^2 - M(N, Z)c^2 , $$ -where \( M_H \) is the mass of the hydrogen atom and \( m_n \) is the mass of the neutron. +

    where \( M_H \) is the mass of the hydrogen atom and \( m_n \) is the mass of the neutron. In terms of the mass excess the binding energy is given by +

    $$ BE(N, Z) = Z\Delta_H c^2 + N\Delta_n c^2 -\Delta(N, Z)c^2 , $$ -where \( \Delta_H c^2 = 7.2890 \) MeV and \( \Delta_n c^2 = 8.0713 \) MeV. +

    where \( \Delta_H c^2 = 7.2890 \) MeV and \( \Delta_n c^2 = 8.0713 \) MeV.

    -

    -A popular and physically intuitive model which can be used to parametrize +

    A popular and physically intuitive model which can be used to parametrize the experimental binding energies as function of \( A \), is the so-called liquid drop model. The ansatz is based on the following expression +

    $$ BE(N,Z) = a_1A-a_2A^{2/3}-a_3\frac{Z^2}{A^{1/3}}-a_4\frac{(N-Z)^2}{A}, $$ -

    -where \( A \) stands for the number of nucleons and the $a_i$s are parameters which are determined by a fit -to the experimental data. +

    where \( A \) stands for the number of nucleons and the $a_i$s are parameters which are determined by a fit +to the experimental data. +

    -

    -To arrive at the above expression we have assumed that we can make the following assumptions: +

    To arrive at the above expression we have assumed that we can make the following assumptions:

    - -We could also add a so-called pairing term, which is a correction term that +

    We could also add a so-called pairing term, which is a correction term that arises from the tendency of proton pairs and neutron pairs to -occur. An even number of particles is more stable than an odd number. - +occur. An even number of particles is more stable than an odd number. +

    Organizing our data

    -

    -Let us start with reading and organizing our data. +

    Let us start with reading and organizing our data. We start with the compilation of masses and binding energies from 2016. After having downloaded this file to our own computer, we are now ready to read the file and start structuring our data. +

    -

    -We start with preparing folders for storing our calculations and the data file over masses and binding energies. We import also various modules that we will find useful in order to present various Machine Learning methods. Here we focus mainly on the functionality of scikit-learn. -

    +

    We start with preparing folders for storing our calculations and the data file over masses and binding energies. We import also various modules that we will find useful in order to present various Machine Learning methods. Here we focus mainly on the functionality of scikit-learn.

    -
    # Common imports
    +
    +
    +
    +
    +
    +
    # Common imports
     import numpy as np
     import pandas as pd
     import matplotlib.pyplot as plt
    @@ -809,13 +864,30 @@ DATA_ID = "
         plt.savefig(image_path(fig_id) + ".png", format='png')
     
     infile = open(data_path("MassEval2016.dat"),'r')
    -
    -

    -Before we proceed, we define also a function for making our plots. You can obviously avoid this and simply set up various matplotlib commands every time you need them. You may however find it convenient to collect all such commands in one function and simply call this function. -

    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    Before we proceed, we define also a function for making our plots. You can obviously avoid this and simply set up various matplotlib commands every time you need them. You may however find it convenient to collect all such commands in one function and simply call this function.

    -
    from pylab import plt, mpl
    +
    +
    +
    +
    +
    +
    from pylab import plt, mpl
     plt.style.use('seaborn')
     mpl.rcParams['font.family'] = 'serif'
     
    @@ -826,20 +898,37 @@ mpl.rcParams[&#
             plt.xlabel(axlabels[0])
             plt.ylabel(axlabels[1])
         plt.legend(loc=0)
    -
    -

    -Our next step is to read the data on experimental binding energies and +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    Our next step is to read the data on experimental binding energies and reorganize them as functions of the mass number \( A \), the number of protons \( Z \) and neutrons \( N \) using pandas. Before we do this it is always useful (unless you have a binary file or other types of compressed data) to actually open the file and simply take a look at it! +

    -

    -In particular, the program that outputs the final nuclear masses is written in Fortran with a specific format. It means that we need to figure out the format and which columns contain the data we are interested in. Pandas comes with a function that reads formatted output. After having admired the file, we are now ready to start massaging it with pandas. The file begins with some basic format information. -

    +

    In particular, the program that outputs the final nuclear masses is written in Fortran with a specific format. It means that we need to figure out the format and which columns contain the data we are interested in. Pandas comes with a function that reads formatted output. After having admired the file, we are now ready to start massaging it with pandas. The file begins with some basic format information.

    -
    """                                                                                                                         
    +
    +
    +
    +
    +
    +
    """                                                                                                                         
     This is taken from the data file of the mass 2016 evaluation.                                                               
     All files are 3436 lines long with 124 character per line.                                                                  
            Headers are 39 lines long.                                                                                           
    @@ -849,17 +938,35 @@ In particular, the program that outputs the final nuclear masses is written in F
        widths=(1,3,5,5,5,1,3,4,1,13,11,11,9,1,2,11,9,1,3,1,12,11,1),                                                            
        Pandas has also a variable header, with length 39 in this case.                                                          
     """
    -
    -

    -The data we are interested in are in columns 2, 3, 4 and 11, giving us +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    The data we are interested in are in columns 2, 3, 4 and 11, giving us the number of neutrons, protons, mass numbers and binding energies, respectively. We add also for the sake of completeness the element name. The data are in fixed-width formatted lines and we will covert them into the pandas DataFrame structure. +

    -

    -

    # Read the experimental data with Pandas
    +
    +
    +
    +
    +
    +
    # Read the experimental data with Pandas
     Masses = pd.read_fwf(infile, usecols=(2,3,4,6,11),
                   names=('N', 'Z', 'A', 'Element', 'Ebinding'),
                   widths=(1,3,5,5,5,1,3,4,1,13,11,11,9,1,2,11,9,1,3,1,12,11,1),
    @@ -877,58 +984,129 @@ Masses['Ebinding'] = Masses.groupby('A')
     # Find the rows of the grouped DataFrame with the maximum binding energy.
     Masses = Masses.apply(lambda t: t[t.Ebinding==t.Ebinding.max()])
    -
    -

    -We have now read in the data, grouped them according to the variables we are interested in. +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    We have now read in the data, grouped them according to the variables we are interested in. We see how easy it is to reorganize the data using pandas. If we were to do these operations in C/C++ or Fortran, we would have had to write various functions/subroutines which perform the above reorganizations for us. Having reorganized the data, we can now start to make some simple fits using both the functionalities in numpy and -Scikit-Learn afterwards. +Scikit-Learn afterwards. +

    -

    -Now we define five variables which contain +

    Now we define five variables which contain the number of nucleons \( A \), the number of protons \( Z \) and the number of neutrons \( N \), the element name and finally the energies themselves. -

    +

    -
    A = Masses['A']
    +
    +
    +
    +
    +
    +
    A = Masses['A']
     Z = Masses['Z']
     N = Masses['N']
     Element = Masses['Element']
     Energies = Masses['Ebinding']
     print(Masses)
    -
    -

    -The next step, and we will define this mathematically later, is to set up the so-called design matrix. We will throughout call this matrix \( \boldsymbol{X} \). +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    The next step, and we will define this mathematically later, is to set up the so-called design matrix. We will throughout call this matrix \( \boldsymbol{X} \). It has dimensionality \( p\times n \), where \( n \) is the number of data points and \( p \) are the so-called predictors. In our case here they are given by the number of polynomials in \( A \) we wish to include in the fit. -

    +

    -
    # Now we set up the design matrix X
    +
    +
    +
    +
    +
    +
    # Now we set up the design matrix X
     X = np.zeros((len(A),5))
     X[:,0] = 1
     X[:,1] = A
     X[:,2] = A**(2.0/3.0)
     X[:,3] = A**(-1.0/3.0)
     X[:,4] = A**(-1.0)
    -
    -

    -With scikitlearn we are now ready to use linear regression and fit our data. -

    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    With scikitlearn we are now ready to use linear regression and fit our data.

    -
    clf = skl.LinearRegression().fit(X, Energies)
    +
    +
    +
    +
    +
    +
    clf = skl.LinearRegression().fit(X, Energies)
     fity = clf.predict(X)
    -
    -

    -Pretty simple! +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    Pretty simple! Now we can print measures of how our fit is doing, the coefficients from the fits and plot the final fit together with our data. -

    +

    -
    # The mean squared error                               
    +
    +
    +
    +
    +
    +
    # The mean squared error                               
     print("Mean squared error: %.2f" % mean_squared_error(Energies, fity))
     # Explained variance score: 1 is perfect prediction                                 
     print('Variance score: %.2f' % r2_score(Energies, fity))
    @@ -948,17 +1126,32 @@ ax.plot(Masses[
     ax.legend()
     save_fig("Masses2016")
     plt.show()
    -
    - +
    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    +

    Seeing the wood for the trees

    -

    -As a teaser, let us now see how we can do this with decision trees using scikit-learn. Later we will switch to so-called random forests! +

    As a teaser, let us now see how we can do this with decision trees using scikit-learn. Later we will switch to so-called random forests!

    -

    -

    #Decision Tree Regression
    +
    +
    +
    +
    +
    +
    #Decision Tree Regression
     from sklearn.tree import DecisionTreeRegressor
     regr_1=DecisionTreeRegressor(max_depth=5)
     regr_2=DecisionTreeRegressor(max_depth=7)
    @@ -987,16 +1180,32 @@ save_fig("Masses2016Trees")
     plt.show()
     print(Masses)
     print(np.mean( (Energies-y_1)**2))
    -
    - +
    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    +

    And what about using neural networks?

    - -The seaborn package allows us to visualize data in an efficient way. Note that we use scikit-learn's multi-layer perceptron (or feed forward neural network) +

    The seaborn package allows us to visualize data in an efficient way. Note that we use scikit-learn's multi-layer perceptron (or feed forward neural network) functionality. -

    +

    -
    from sklearn.neural_network import MLPRegressor
    +
    +
    +
    +
    +
    +
    from sklearn.neural_network import MLPRegressor
     from sklearn.metrics import accuracy_score
     import seaborn as sns
     
    @@ -1025,23 +1234,34 @@ ax.set_title(&q
     ax.set_ylabel("$\eta$")
     ax.set_xlabel("$\lambda$")
     plt.show()
    -
    - +
    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    +

    A first summary

    -

    -The aim behind these introductory words was to present to you various +

    The aim behind these introductory words was to present to you various Python libraries and their functionalities, in particular libraries like numpy, pandas, xarray and matplotlib and other that make our life much easier -in handling various data sets and visualizing data. +in handling various data sets and visualizing data. +

    -

    -Furthermore, +

    Furthermore, Scikit-Learn allows us with few lines of code to implement popular Machine Learning algorithms for supervised learning. Later we will meet Tensorflow, a powerful library for deep learning. Now it is time to dive more into the details of various methods. We will start with linear regression and try to take a deeper look at what it entails. +

    -

    - - - -
    - - - diff --git a/doc/pub/week34/html/._week34-bs039.html b/doc/pub/week34/html/._week34-bs039.html index 38629b795..bfbed2761 100644 --- a/doc/pub/week34/html/._week34-bs039.html +++ b/doc/pub/week34/html/._week34-bs039.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 34: Introduction to the course, Logistics and Practicalities - + - - - -
    -

     

     

     

    - -

    Why Linear Regression (aka Ordinary Least Squares and family)

    -

    -Fitting a continuous function with linear parameterization in terms of the parameters \( \boldsymbol{\beta} \). - +

    Fitting a continuous function with linear parameterization in terms of the parameters \( \boldsymbol{\beta} \).

    • Method of choice for fitting a continuous function!
    • Gives an excellent introduction to central Machine Learning features with understandable pedagogical links to other methods like Neural Networks, Support Vector Machines etc
    • @@ -381,11 +367,10 @@ Fitting a continuous function with linear parameterization in terms of the param
    • Allows for easy hands-on understanding of gradient descent methods
    • and many more features
    - -For more discussions of Ridge and Lasso regression, Wessel van Wieringen's article is highly recommended. +

    For more discussions of Ridge and Lasso regression, Wessel van Wieringen's article is highly recommended. Similarly, Mehta et al's article is also recommended. +

    -

    -
    - - -
    - - - diff --git a/doc/pub/week34/html/._week34-bs040.html b/doc/pub/week34/html/._week34-bs040.html index f219f314b..aa803551e 100644 --- a/doc/pub/week34/html/._week34-bs040.html +++ b/doc/pub/week34/html/._week34-bs040.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 34: Introduction to the course, Logistics and Practicalities - + - - - -
    -

     

     

     

    - -

    Regression analysis, overarching aims

    -

    + -

    -Regression modeling deals with the description of the sampling distribution of a given random variable \( y \) and how it varies as function of another variable or a set of such variables \( \boldsymbol{x} =[x_0, x_1,\dots, x_{n-1}]^T \). -The first variable is called the dependent, the outcome or the response variable while the set of variables \( \boldsymbol{x} \) is called the independent variable, or the predictor variable or the explanatory variable. - -

    -A regression model aims at finding a likelihood function \( p(\boldsymbol{y}\vert \boldsymbol{x}) \), that is the conditional distribution for \( \boldsymbol{y} \) with a given \( \boldsymbol{x} \). The estimation of \( p(\boldsymbol{y}\vert \boldsymbol{x}) \) is made using a data set with +

    Regression modeling deals with the description of the sampling distribution of a given random variable \( y \) and how it varies as function of another variable or a set of such variables \( \boldsymbol{x} =[x_0, x_1,\dots, x_{n-1}]^T \). +The first variable is called the dependent, the outcome or the response variable while the set of variables \( \boldsymbol{x} \) is called the independent variable, or the predictor variable or the explanatory variable. +

    +

    A regression model aims at finding a likelihood function \( p(\boldsymbol{y}\vert \boldsymbol{x}) \), that is the conditional distribution for \( \boldsymbol{y} \) with a given \( \boldsymbol{x} \). The estimation of \( p(\boldsymbol{y}\vert \boldsymbol{x}) \) is made using a data set with

    • \( n \) cases \( i = 0, 1, 2, \dots, n-1 \)
    • Response (target, dependent or outcome) variable \( y_i \) with \( i = 0, 1, 2, \dots, n-1 \)
    • \( p \) so-called explanatory (independent or predictor) variables \( \boldsymbol{x}_i=[x_{i0}, x_{i1}, \dots, x_{ip-1}] \) with \( i = 0, 1, 2, \dots, n-1 \) and explanatory variables running from \( 0 \) to \( p-1 \). See below for more explicit examples.
    - - The goal of the regression analysis is to extract/exploit relationship between \( \boldsymbol{y} \) and \( \boldsymbol{x} \) in or to infer causal dependencies, approximations to the likelihood functions, functional relationships and to make predictions, making fits and many other things. +

    The goal of the regression analysis is to extract/exploit relationship between \( \boldsymbol{y} \) and \( \boldsymbol{x} \) in or to infer causal dependencies, approximations to the likelihood functions, functional relationships and to make predictions, making fits and many other things.

    -

      @@ -418,25 +402,18 @@ A regression model aims at finding a likelihood function \( p(\boldsymbol{y}\ver
    • »
    -
    - - -
    - - - diff --git a/doc/pub/week34/html/._week34-bs041.html b/doc/pub/week34/html/._week34-bs041.html index c32d013fd..dac785e3f 100644 --- a/doc/pub/week34/html/._week34-bs041.html +++ b/doc/pub/week34/html/._week34-bs041.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 34: Introduction to the course, Logistics and Practicalities - + - - - -
    -

     

     

     

    - -

    Regression analysis, overarching aims II

    -

    + -

    -Consider an experiment in which \( p \) characteristics of \( n \) samples are +

    Consider an experiment in which \( p \) characteristics of \( n \) samples are measured. The data from this experiment, for various explanatory variables \( p \) are normally represented by a matrix \( \mathbf{X} \). +

    -

    -The matrix \( \mathbf{X} \) is called the design +

    The matrix \( \mathbf{X} \) is called the design matrix. Additional information of the samples is available in the form of \( \boldsymbol{y} \) (also as above). The variable \( \boldsymbol{y} \) is generally referred to as the response variable. The aim of @@ -386,17 +373,14 @@ f(\mathbf{X}_{i,\ast}) \). When no prior knowledge on the form of \( f(\cdot) \) is available, it is common to assume a linear relationship between \( \boldsymbol{X} \) and \( \boldsymbol{y} \). This assumption gives rise to the linear regression model where \( \boldsymbol{\beta} = [\beta_0, \ldots, -\beta_{p-1}]^{T} \) are the regression parameters. +\beta_{p-1}]^{T} \) are the regression parameters. +

    -

    -Linear regression gives us a set of analytical equations for the parameters \( \beta_j \). - -

    +

    Linear regression gives us a set of analytical equations for the parameters \( \beta_j \).

    -

      @@ -426,25 +410,18 @@ Linear regression gives us a set of analytical equations for the parameters \( \
    • »
    -
    - - -
    - - - diff --git a/doc/pub/week34/html/._week34-bs042.html b/doc/pub/week34/html/._week34-bs042.html index 9b8aa7edf..bdfea39d0 100644 --- a/doc/pub/week34/html/._week34-bs042.html +++ b/doc/pub/week34/html/._week34-bs042.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 34: Introduction to the course, Logistics and Practicalities - + - - - -
    -

     

     

     

    - -

    Examples

    -

    -In order to understand the relation among the predictors \( p \), the set of data \( n \) and the target (outcome, output etc) \( \boldsymbol{y} \), -consider the model we discussed for describing nuclear binding energies. + +

    In order to understand the relation among the predictors \( p \), the set of data \( n \) and the target (outcome, output etc) \( \boldsymbol{y} \), +consider the model we discussed for describing nuclear binding energies. +

    -

    -There we assumed that we could parametrize the data using a polynomial approximation based on the liquid drop model. +

    There we assumed that we could parametrize the data using a polynomial approximation based on the liquid drop model. Assuming +

    $$ BE(A) = a_0+a_1A+a_2A^{2/3}+a_3A^{-1/3}+a_4A^{-1}, $$ -we have five predictors, that is the intercept, the \( A \) dependent term, the \( A^{2/3} \) term and the \( A^{-1/3} \) and \( A^{-1} \) terms. +

    we have five predictors, that is the intercept, the \( A \) dependent term, the \( A^{2/3} \) term and the \( A^{-1/3} \) and \( A^{-1} \) terms. This gives \( p=0,1,2,3,4 \). Furthermore we have \( n \) entries for each predictor. It means that our design matrix is a \( p\times n \) matrix \( \boldsymbol{X} \). +

    -

    -Here the predictors are based on a model we have made. A popular data set which is widely encountered in ML applications is the -so-called credit card default data from Taiwan. The data set contains data on \( n=30000 \) credit card holders with predictors like gender, marital status, age, profession, education, etc. In total there are \( 24 \) such predictors or attributes leading to a design matrix of dimensionality \( 24 \times 30000 \). This is however a classification problem and we will come back to it when we discuss Logistic Regression. - -

    +

    Here the predictors are based on a model we have made. A popular data set which is widely encountered in ML applications is the +so-called credit card default data from Taiwan. The data set contains data on \( n=30000 \) credit card holders with predictors like gender, marital status, age, profession, education, etc. In total there are \( 24 \) such predictors or attributes leading to a design matrix of dimensionality \( 24 \times 30000 \). This is however a classification problem and we will come back to it when we discuss Logistic Regression. +

    -

      @@ -422,25 +409,18 @@ so-called »
    -
    - - -
    - - - diff --git a/doc/pub/week34/html/._week34-bs043.html b/doc/pub/week34/html/._week34-bs043.html index 2e89cbcaf..b5347c89b 100644 --- a/doc/pub/week34/html/._week34-bs043.html +++ b/doc/pub/week34/html/._week34-bs043.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 34: Introduction to the course, Logistics and Practicalities - + - - - -
    -

     

     

     

    - -

    General linear models

    -

    -Before we proceed let us study a case from linear algebra where we aim at fitting a set of data \( \boldsymbol{y}=[y_0,y_1,\dots,y_{n-1}] \). We could think of these data as a result of an experiment or a complicated numerical experiment. These data are functions of a series of variables \( \boldsymbol{x}=[x_0,x_1,\dots,x_{n-1}] \), that is \( y_i = y(x_i) \) with \( i=0,1,2,\dots,n-1 \). The variables \( x_i \) could represent physical quantities like time, temperature, position etc. We assume that \( y(x) \) is a smooth function. + +

    Before we proceed let us study a case from linear algebra where we aim at fitting a set of data \( \boldsymbol{y}=[y_0,y_1,\dots,y_{n-1}] \). We could think of these data as a result of an experiment or a complicated numerical experiment. These data are functions of a series of variables \( \boldsymbol{x}=[x_0,x_1,\dots,x_{n-1}] \), that is \( y_i = y(x_i) \) with \( i=0,1,2,\dots,n-1 \). The variables \( x_i \) could represent physical quantities like time, temperature, position etc. We assume that \( y(x) \) is a smooth function.

    -

    -Since obtaining these data points may not be trivial, we want to use these data to fit a function which can allow us to make predictions for values of \( y \) which are not in the present set. The perhaps simplest approach is to assume we can parametrize our function in terms of a polynomial of degree \( n-1 \) with \( n \) points, that is +

    Since obtaining these data points may not be trivial, we want to use these data to fit a function which can allow us to make predictions for values of \( y \) which are not in the present set. The perhaps simplest approach is to assume we can parametrize our function in terms of a polynomial of degree \( n-1 \) with \( n \) points, that is

    $$ y=y(x) \rightarrow y(x_i)=\tilde{y}_i+\epsilon_i=\sum_{j=0}^{n-1} \beta_j x_i^j+\epsilon_i, $$ -where \( \epsilon_i \) is the error in our approximation. - -

    +

    where \( \epsilon_i \) is the error in our approximation.

    -

      @@ -414,25 +398,18 @@ where \( \epsilon_i \) is the error in our approximation.
    • »
    -
    - - -
    - - - diff --git a/doc/pub/week34/html/._week34-bs044.html b/doc/pub/week34/html/._week34-bs044.html index 6fd784d16..f42350a19 100644 --- a/doc/pub/week34/html/._week34-bs044.html +++ b/doc/pub/week34/html/._week34-bs044.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 34: Introduction to the course, Logistics and Practicalities - + - - - -
    -

     

     

     

    - -

    Rewriting the fitting procedure as a linear algebra problem

    -

    -For every set of values \( y_i,x_i \) we have thus the corresponding set of equations + +

    For every set of values \( y_i,x_i \) we have thus the corresponding set of equations

    $$ \begin{align*} y_0&=\beta_0+\beta_1x_0^1+\beta_2x_0^2+\dots+\beta_{n-1}x_0^{n-1}+\epsilon_0\\ @@ -383,7 +371,6 @@ $$
    -

      @@ -413,25 +400,18 @@ $$
    • »
    -
    - - -
    - - - diff --git a/doc/pub/week34/html/._week34-bs045.html b/doc/pub/week34/html/._week34-bs045.html index a59a14d5c..f1458b329 100644 --- a/doc/pub/week34/html/._week34-bs045.html +++ b/doc/pub/week34/html/._week34-bs045.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 34: Introduction to the course, Logistics and Practicalities - + - - -
    -
    -

     

     

     

    - -

    Rewriting the fitting procedure as a linear algebra problem, more details

    -

    -Defining the vectors + +

    Defining the vectors

    $$ \boldsymbol{y} = [y_0,y_1, y_2,\dots, y_{n-1}]^T, $$ -and +

    and

    $$ \boldsymbol{\beta} = [\beta_0,\beta_1, \beta_2,\dots, \beta_{n-1}]^T, $$ -and +

    and

    $$ \boldsymbol{\epsilon} = [\epsilon_0,\epsilon_1, \epsilon_2,\dots, \epsilon_{n-1}]^T, $$ -and the design matrix +

    and the design matrix

    $$ \boldsymbol{X}= \begin{bmatrix} @@ -396,17 +384,16 @@ $$ \end{bmatrix} $$ -we can rewrite our equations as +

    we can rewrite our equations as

    $$ \boldsymbol{y} = \boldsymbol{X}\boldsymbol{\beta}+\boldsymbol{\epsilon}. $$ -The above design matrix is called a Vandermonde matrix. +

    The above design matrix is called a Vandermonde matrix.

    -

      @@ -436,25 +423,18 @@ The above design matrix is called a »
    -
    - - -
    - - - diff --git a/doc/pub/week34/html/._week34-bs046.html b/doc/pub/week34/html/._week34-bs046.html index 5b7e7f34e..554cc0651 100644 --- a/doc/pub/week34/html/._week34-bs046.html +++ b/doc/pub/week34/html/._week34-bs046.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 34: Introduction to the course, Logistics and Practicalities - + - - - -
    -

     

     

     

    - -

    Generalizing the fitting procedure as a linear algebra problem

    -

    + -

    -We are obviously not limited to the above polynomial expansions. We +

    We are obviously not limited to the above polynomial expansions. We could replace the various powers of \( x \) with elements of Fourier series or instead of \( x_i^j \) we could have \( \cos{(j x_i)} \) or \( \sin{(j x_i)} \), or time series or other orthogonal functions. For every set of values \( y_i,x_i \) we can then generalize the equations to +

    $$ \begin{align*} @@ -389,13 +377,12 @@ y_{n-1}&=\beta_0x_{n-1,0}+\beta_1x_{n-1,2}+\beta_2x_{n-1,2}+\dots+\beta_{n-1}x_{ \end{align*} $$ -

    + Note that we have \( p=n \) here. The matrix is symmetric. This is generally not the case!

    -

      @@ -425,25 +412,18 @@ $$
    • »
    -
    - - -
    - - - diff --git a/doc/pub/week34/html/._week34-bs047.html b/doc/pub/week34/html/._week34-bs047.html index 716a17993..01c7d0179 100644 --- a/doc/pub/week34/html/._week34-bs047.html +++ b/doc/pub/week34/html/._week34-bs047.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 34: Introduction to the course, Logistics and Practicalities - + - - - -
    -

     

     

     

    - -

    Generalizing the fitting procedure as a linear algebra problem

    -

    -We redefine in turn the matrix \( \boldsymbol{X} \) as + +

    We redefine in turn the matrix \( \boldsymbol{X} \) as

    $$ \boldsymbol{X}= \begin{bmatrix} @@ -381,17 +369,16 @@ x_{n-1,0}& x_{n-1,1} &x_{n-1,2}& \dots & \dots &x_{n-1,n-1}\\ \end{bmatrix} $$ -and without loss of generality we rewrite again our equations as +

    and without loss of generality we rewrite again our equations as

    $$ \boldsymbol{y} = \boldsymbol{X}\boldsymbol{\beta}+\boldsymbol{\epsilon}. $$ -The left-hand side of this equation is kwown. Our error vector \( \boldsymbol{\epsilon} \) and the parameter vector \( \boldsymbol{\beta} \) are our unknow quantities. How can we obtain the optimal set of \( \beta_i \) values? +

    The left-hand side of this equation is kwown. Our error vector \( \boldsymbol{\epsilon} \) and the parameter vector \( \boldsymbol{\beta} \) are our unknow quantities. How can we obtain the optimal set of \( \beta_i \) values?

    -

      @@ -421,25 +408,18 @@ The left-hand side of this equation is kwown. Our error vector \( \boldsymbol{\e
    • »
    -
    - - -
    - - - diff --git a/doc/pub/week34/html/._week34-bs048.html b/doc/pub/week34/html/._week34-bs048.html index 85b77e0e5..81f4e8937 100644 --- a/doc/pub/week34/html/._week34-bs048.html +++ b/doc/pub/week34/html/._week34-bs048.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 34: Introduction to the course, Logistics and Practicalities - + - - - -
    -

     

     

     

    - -

    Optimizing our parameters

    -

    -We have defined the matrix \( \boldsymbol{X} \) via the equations + +

    We have defined the matrix \( \boldsymbol{X} \) via the equations

    $$ \begin{align*} y_0&=\beta_0x_{00}+\beta_1x_{01}+\beta_2x_{02}+\dots+\beta_{n-1}x_{0n-1}+\epsilon_0\\ @@ -382,17 +370,14 @@ y_{n-1}&=\beta_0x_{n-1,0}+\beta_1x_{n-1,2}+\beta_2x_{n-1,2}+\dots+\beta_{n-1}x_{ \end{align*} $$ -

    -As we noted above, we stayed with a system with the design matrix +

    As we noted above, we stayed with a system with the design matrix \( \boldsymbol{X}\in {\mathbb{R}}^{n\times n} \), that is we have \( p=n \). For reasons to come later (algorithmic arguments) we will hereafter define our matrix as \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \), with the predictors refering to the column numbers and the entries \( n \) being the row elements. - -

    +

    -

      @@ -422,25 +407,18 @@ our matrix as \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \), with the predict
    • »
    -
    - - -
    - - - diff --git a/doc/pub/week34/html/._week34-bs049.html b/doc/pub/week34/html/._week34-bs049.html index ee0cb5cc3..a2853801d 100644 --- a/doc/pub/week34/html/._week34-bs049.html +++ b/doc/pub/week34/html/._week34-bs049.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 34: Introduction to the course, Logistics and Practicalities - + - - - -
    -

     

     

     

    - -

    Our model for the nuclear binding energies

    -

    -In our introductory notes we looked at the so-called liquid drop model. Let us remind ourselves about what we did by looking at the code. +

    In our introductory notes we looked at the so-called liquid drop model. Let us remind ourselves about what we did by looking at the code.

    -

    -We restate the parts of the code we are most interested in. -

    +

    We restate the parts of the code we are most interested in.

    -
    # Common imports
    +
    +
    +
    +
    +
    +
    # Common imports
     import numpy as np
     import pandas as pd
     import matplotlib.pyplot as plt
    @@ -444,16 +434,28 @@ DesignMatrix = pd.index = A
     DesignMatrix.columns = ['1', 'A', 'A^(2/3)', 'A^(-1/3)', '1/A']
     display(DesignMatrix)
    -
    -

    -With \( \boldsymbol{\beta}\in {\mathbb{R}}^{p\times 1} \), it means that we will hereafter write our equations for the approximation as +

    +
    +
    + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    With \( \boldsymbol{\beta}\in {\mathbb{R}}^{p\times 1} \), it means that we will hereafter write our equations for the approximation as

    $$ \boldsymbol{\tilde{y}}= \boldsymbol{X}\boldsymbol{\beta}, $$ -throughout these lectures. +

    throughout these lectures.

    -

      @@ -483,25 +485,18 @@ throughout these lectures.
    • »
    - - - -
    - - - diff --git a/doc/pub/week34/html/._week34-bs050.html b/doc/pub/week34/html/._week34-bs050.html index ea8a5eaa4..c928b64f4 100644 --- a/doc/pub/week34/html/._week34-bs050.html +++ b/doc/pub/week34/html/._week34-bs050.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 34: Introduction to the course, Logistics and Practicalities - + - - - -
    -

     

     

     

    - -

    Optimizing our parameters, more details

    -

    -With the above we use the design matrix to define the approximation \( \boldsymbol{\tilde{y}} \) via the unknown quantity \( \boldsymbol{\beta} \) as + +

    With the above we use the design matrix to define the approximation \( \boldsymbol{\tilde{y}} \) via the unknown quantity \( \boldsymbol{\beta} \) as

    $$ \boldsymbol{\tilde{y}}= \boldsymbol{X}\boldsymbol{\beta}, $$ -and in order to find the optimal parameters \( \beta_i \) instead of solving the above linear algebra problem, we define a function which gives a measure of the spread between the values \( y_i \) (which represent hopefully the exact values) and the parameterized values \( \tilde{y}_i \), namely +

    and in order to find the optimal parameters \( \beta_i \) instead of solving the above linear algebra problem, we define a function which gives a measure of the spread between the values \( y_i \) (which represent hopefully the exact values) and the parameterized values \( \tilde{y}_i \), namely

    $$ C(\boldsymbol{\beta})=\frac{1}{n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{\tilde{y}}\right)^T\left(\boldsymbol{y}-\boldsymbol{\tilde{y}}\right)\right\}, $$ -or using the matrix \( \boldsymbol{X} \) and in a more compact matrix-vector notation as +

    or using the matrix \( \boldsymbol{X} \) and in a more compact matrix-vector notation as

    $$ C(\boldsymbol{\beta})=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)^T\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)\right\}. $$ -This function is one possible way to define the so-called cost function. +

    This function is one possible way to define the so-called cost function.

    -

    -It is also common to define +

    It is also common to define the function \( C \) as +

    $$ C(\boldsymbol{\beta})=\frac{1}{2n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2, $$ -since when taking the first derivative with respect to the unknown parameters \( \beta \), the factor of \( 2 \) cancels out. +

    since when taking the first derivative with respect to the unknown parameters \( \beta \), the factor of \( 2 \) cancels out.

    -

      @@ -429,25 +416,18 @@ since when taking the first derivative with respect to the unknown parameters \(
    • »
    -
    - - -
    - - - diff --git a/doc/pub/week34/html/._week34-bs051.html b/doc/pub/week34/html/._week34-bs051.html index df9fedcd3..c63a221ca 100644 --- a/doc/pub/week34/html/._week34-bs051.html +++ b/doc/pub/week34/html/._week34-bs051.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 34: Introduction to the course, Logistics and Practicalities - + - - - -
    -

     

     

     

    - -

    Interpretations and optimizing our parameters

    -

    + -

    -The function +

    The function

    $$ C(\boldsymbol{\beta})=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)^T\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)\right\}, $$ -can be linked to the variance of the quantity \( y_i \) if we interpret the latter as the mean value. +

    can be linked to the variance of the quantity \( y_i \) if we interpret the latter as the mean value. When linking (see the discussion below) with the maximum likelihood approach below, we will indeed interpret \( y_i \) as a mean value +

    $$ y_{i}=\langle y_i \rangle = \beta_0x_{i,0}+\beta_1x_{i,1}+\beta_2x_{i,2}+\dots+\beta_{n-1}x_{i,n-1}+\epsilon_i, $$ -

    -where \( \langle y_i \rangle \) is the mean value. Keep in mind also that +

    where \( \langle y_i \rangle \) is the mean value. Keep in mind also that till now we have treated \( y_i \) as the exact value. Normally, the response (dependent or outcome) variable \( y_i \) the outcome of a numerical experiment or another type of experiment and is thus only an @@ -391,35 +378,32 @@ approximation to the true value. It is then always accompanied by an error estimate, often limited to a statistical error estimate given by the standard deviation discussed earlier. In the discussion here we will treat \( y_i \) as our exact value for the response variable. +

    -

    -In order to find the parameters \( \beta_i \) we will then minimize the spread of \( C(\boldsymbol{\beta}) \), that is we are going to solve the problem +

    In order to find the parameters \( \beta_i \) we will then minimize the spread of \( C(\boldsymbol{\beta}) \), that is we are going to solve the problem

    $$ {\displaystyle \min_{\boldsymbol{\beta}\in {\mathbb{R}}^{p}}}\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)^T\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)\right\}. $$ -In practical terms it means we will require +

    In practical terms it means we will require

    $$ \frac{\partial C(\boldsymbol{\beta})}{\partial \beta_j} = \frac{\partial }{\partial \beta_j}\left[ \frac{1}{n}\sum_{i=0}^{n-1}\left(y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}\right)^2\right]=0, $$ -which results in +

    which results in

    $$ \frac{\partial C(\boldsymbol{\beta})}{\partial \beta_j} = -\frac{2}{n}\left[ \sum_{i=0}^{n-1}x_{ij}\left(y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}\right)\right]=0, $$ -or in a matrix-vector form as +

    or in a matrix-vector form as

    $$ \frac{\partial C(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}} = 0 = \boldsymbol{X}^T\left( \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right). $$ - -

    -

      @@ -449,25 +433,18 @@ $$
    • »
    -
    - - -
    - - - diff --git a/doc/pub/week34/html/._week34-bs052.html b/doc/pub/week34/html/._week34-bs052.html index 9a2307409..ba5fc44ff 100644 --- a/doc/pub/week34/html/._week34-bs052.html +++ b/doc/pub/week34/html/._week34-bs052.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 34: Introduction to the course, Logistics and Practicalities - + - - - -
    -

     

     

     

    - -

    Interpretations and optimizing our parameters

    -

    -We can rewrite + +

    We can rewrite

    $$ \frac{\partial C(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}} = 0 = \boldsymbol{X}^T\left( \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right), $$ -as +

    as

    $$ \boldsymbol{X}^T\boldsymbol{y} = \boldsymbol{X}^T\boldsymbol{X}\boldsymbol{\beta}, $$ -and if the matrix \( \boldsymbol{X}^T\boldsymbol{X} \) is invertible we have the solution +

    and if the matrix \( \boldsymbol{X}^T\boldsymbol{X} \) is invertible we have the solution

    $$ \boldsymbol{\beta} =\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}. $$ -

    -We note also that since our design matrix is defined as \( \boldsymbol{X}\in +

    We note also that since our design matrix is defined as \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \), the product \( \boldsymbol{X}^T\boldsymbol{X} \in {\mathbb{R}}^{p\times p} \). In the above case we have that \( p \ll n \), in our case \( p=5 \) meaning that we end up with inverting a small @@ -394,21 +381,20 @@ matrices to invert. The methods discussed here and for many other supervised learning algorithms like classification with logistic regression or support vector machines, exhibit dimensionalities which allow for the usage of direct linear algebra methods such as LU decomposition or Singular Value Decomposition (SVD) for finding the inverse of the matrix -\( \boldsymbol{X}^T\boldsymbol{X} \). +\( \boldsymbol{X}^T\boldsymbol{X} \). +

    -

    -

    -Small question: Do you think the example we have at hand here (the nuclear binding energies) can lead to problems in inverting the matrix \( \boldsymbol{X}^T\boldsymbol{X} \)? What kind of problems can we expect? + +

    Small question: Do you think the example we have at hand here (the nuclear binding energies) can lead to problems in inverting the matrix \( \boldsymbol{X}^T\boldsymbol{X} \)? What kind of problems can we expect?

    -

      @@ -438,25 +424,18 @@ allow for the usage of direct linear algebra methods such as LU decomposi
    • »
    -
    - - -
    - - - diff --git a/doc/pub/week34/html/._week34-bs053.html b/doc/pub/week34/html/._week34-bs053.html index a2df0c125..50e57ea0e 100644 --- a/doc/pub/week34/html/._week34-bs053.html +++ b/doc/pub/week34/html/._week34-bs053.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 34: Introduction to the course, Logistics and Practicalities - + - - - -
    -

     

     

     

    - -

    Some useful matrix and vector expressions

    -

    -The following matrix and vector relation will be useful here and for the rest of the course. Vectors are always written as boldfaced lower case letters and +

    The following matrix and vector relation will be useful here and for the rest of the course. Vectors are always written as boldfaced lower case letters and matrices as upper case boldfaced letters. +

    $$ \frac{\partial (\boldsymbol{b}^T\boldsymbol{a})}{\partial \boldsymbol{a}} = \boldsymbol{b}, @@ -416,25 +404,18 @@ $$
  • »
  • -
    - - -
    - - - diff --git a/doc/pub/week34/html/._week34-bs054.html b/doc/pub/week34/html/._week34-bs054.html index 01d9fd676..2742315b5 100644 --- a/doc/pub/week34/html/._week34-bs054.html +++ b/doc/pub/week34/html/._week34-bs054.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 34: Introduction to the course, Logistics and Practicalities - + - - - -
    -

     

     

     

    - -

    Interpretations and optimizing our parameters

    -

    -The residuals \( \boldsymbol{\epsilon} \) are in turn given by + +

    The residuals \( \boldsymbol{\epsilon} \) are in turn given by

    $$ \boldsymbol{\epsilon} = \boldsymbol{y}-\boldsymbol{\tilde{y}} = \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}, $$ -and with +

    and with

    $$ \boldsymbol{X}^T\left( \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)= 0, $$ -we have +

    we have

    $$ \boldsymbol{X}^T\boldsymbol{\epsilon}=\boldsymbol{X}^T\left( \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)= 0, $$ -meaning that the solution for \( \boldsymbol{\beta} \) is the one which minimizes the residuals. Later we will link this with the maximum likelihood approach. - -

    +

    meaning that the solution for \( \boldsymbol{\beta} \) is the one which minimizes the residuals. Later we will link this with the maximum likelihood approach.

    -

    -Let us now return to our nuclear binding energies and simply code the above equations. +

    Let us now return to our nuclear binding energies and simply code the above equations.

    -

      @@ -424,25 +408,18 @@ Let us now return to our nuclear binding energies and simply code the above equa
    • »
    -
    - - -
    - - - diff --git a/doc/pub/week34/html/._week34-bs055.html b/doc/pub/week34/html/._week34-bs055.html index c2cbb0de2..2e2e7e49f 100644 --- a/doc/pub/week34/html/._week34-bs055.html +++ b/doc/pub/week34/html/._week34-bs055.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 34: Introduction to the course, Logistics and Practicalities - + - - - -
    -

     

     

     

    - -

    Own code for Ordinary Least Squares

    -

    -It is rather straightforward to implement the matrix inversion and obtain the parameters \( \boldsymbol{\beta} \). After having defined the matrix \( \boldsymbol{X} \) we simply need to +

    It is rather straightforward to implement the matrix inversion and obtain the parameters \( \boldsymbol{\beta} \). After having defined the matrix \( \boldsymbol{X} \) we simply need to write -

    +

    -
    # matrix inversion to find beta
    +
    +
    +
    +
    +
    +
    # matrix inversion to find beta
     beta = np.linalg.inv(X.T.dot(X)).dot(X.T).dot(Energies)
     # and then make the prediction
     ytilde = X @ beta
    -
    -

    -Alternatively, you can use the least squares functionality in Numpy as -

    +

    +
    +
    + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    Alternatively, you can use the least squares functionality in Numpy as

    -
    fit = np.linalg.lstsq(X, Energies, rcond =None)[0]
    +
    +
    +
    +
    +
    +
    fit = np.linalg.lstsq(X, Energies, rcond =None)[0]
     ytildenp = np.dot(fit,X.T)
    -
    -

    -And finally we plot our fit with and compare with data -

    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    And finally we plot our fit with and compare with data

    -
    Masses['Eapprox']  = ytilde
    +
    +
    +
    +
    +
    +
    Masses['Eapprox']  = ytilde
     # Generate a plot comparing the experimental with the fitted values values.
     fig, ax = plt.subplots()
     ax.set_xlabel(r'$A = N + Z$')
    @@ -403,8 +429,22 @@ ax.plot(Masses[
     ax.legend()
     save_fig("Masses2016OLS")
     plt.show()
    -
    -

    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

      @@ -434,25 +474,18 @@ plt.show()
    • »
    - - - -
    - - - diff --git a/doc/pub/week34/html/._week34-bs056.html b/doc/pub/week34/html/._week34-bs056.html index 22aefbc89..ba562cbd3 100644 --- a/doc/pub/week34/html/._week34-bs056.html +++ b/doc/pub/week34/html/._week34-bs056.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 34: Introduction to the course, Logistics and Practicalities - + - - - -
    -

     

     

     

    - -

    Adding error analysis and training set up

    -

    -We can easily test our fit by computing the \( R2 \) score that we discussed in connection with the functionality of Scikit-Learn in the introductory slides. +

    We can easily test our fit by computing the \( R2 \) score that we discussed in connection with the functionality of Scikit-Learn in the introductory slides. Since we are not using Scikit-Learn here we can define our own \( R2 \) function as -

    +

    -
    def R2(y_data, y_model):
    +
    +
    +
    +
    +
    +
    def R2(y_data, y_model):
         return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)
    -
    -

    -and we would be using it as -

    +

    +
    +
    + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    and we would be using it as

    -
    print(R2(Energies,ytilde))
    -
    -

    -We can easily add our MSE score as -

    +

    +
    +
    +
    +
    +
    print(R2(Energies,ytilde))
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    We can easily add our MSE score as

    -
    def MSE(y_data,y_model):
    +
    +
    +
    +
    +
    +
    def MSE(y_data,y_model):
         n = np.size(y_model)
         return np.sum((y_data-y_model)**2)/n
     
     print(MSE(Energies,ytilde))
    -
    -

    -and finally the relative error as -

    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    and finally the relative error as

    -
    def RelativeError(y_data,y_model):
    +
    +
    +
    +
    +
    +
    def RelativeError(y_data,y_model):
         return abs((y_data-y_model)/y_data)
     print(RelativeError(Energies, ytilde))
    -
    -

    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

      @@ -433,25 +490,18 @@ and finally the relative error as
    • »
    - - - -
    - - - diff --git a/doc/pub/week34/html/._week34-bs057.html b/doc/pub/week34/html/._week34-bs057.html index f1c4d9a28..090db4663 100644 --- a/doc/pub/week34/html/._week34-bs057.html +++ b/doc/pub/week34/html/._week34-bs057.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 34: Introduction to the course, Logistics and Practicalities - + - - - -
    -

     

     

     

    - -

    The \( \chi^2 \) function

    -

    + -

    -Normally, the response (dependent or outcome) variable \( y_i \) is the +

    Normally, the response (dependent or outcome) variable \( y_i \) is the outcome of a numerical experiment or another type of experiment and is thus only an approximation to the true value. It is then always accompanied by an error estimate, often limited to a statistical error estimate given by the standard deviation discussed earlier. In the discussion here we will treat \( y_i \) as our exact value for the response variable. +

    -

    -Introducing the standard deviation \( \sigma_i \) for each measurement +

    Introducing the standard deviation \( \sigma_i \) for each measurement \( y_i \), we define now the \( \chi^2 \) function (omitting the \( 1/n \) term) as +

    $$ \chi^2(\boldsymbol{\beta})=\frac{1}{n}\sum_{i=0}^{n-1}\frac{\left(y_i-\tilde{y}_i\right)^2}{\sigma_i^2}=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{\tilde{y}}\right)^T\frac{1}{\boldsymbol{\Sigma^2}}\left(\boldsymbol{y}-\boldsymbol{\tilde{y}}\right)\right\}, $$ -where the matrix \( \boldsymbol{\Sigma} \) is a diagonal matrix with \( \sigma_i \) as matrix elements. - -

    +

    where the matrix \( \boldsymbol{\Sigma} \) is a diagonal matrix with \( \sigma_i \) as matrix elements.

    -

      @@ -423,25 +408,18 @@ where the matrix \( \boldsymbol{\Sigma} \) is a diagonal matrix with \( \sigma_i
    • »
    -
    - - -
    - - - diff --git a/doc/pub/week34/html/._week34-bs058.html b/doc/pub/week34/html/._week34-bs058.html index 687481d4c..4905d159c 100644 --- a/doc/pub/week34/html/._week34-bs058.html +++ b/doc/pub/week34/html/._week34-bs058.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 34: Introduction to the course, Logistics and Practicalities - + - - - -
    -

     

     

     

    - -

    The \( \chi^2 \) function

    -

    + -

    -In order to find the parameters \( \beta_i \) we will then minimize the spread of \( \chi^2(\boldsymbol{\beta}) \) by requiring +

    In order to find the parameters \( \beta_i \) we will then minimize the spread of \( \chi^2(\boldsymbol{\beta}) \) by requiring

    $$ \frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \beta_j} = \frac{\partial }{\partial \beta_j}\left[ \frac{1}{n}\sum_{i=0}^{n-1}\left(\frac{y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}}{\sigma_i}\right)^2\right]=0, $$ -which results in +

    which results in

    $$ \frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \beta_j} = -\frac{2}{n}\left[ \sum_{i=0}^{n-1}\frac{x_{ij}}{\sigma_i}\left(\frac{y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}}{\sigma_i}\right)\right]=0, $$ -or in a matrix-vector form as +

    or in a matrix-vector form as

    $$ \frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}} = 0 = \boldsymbol{A}^T\left( \boldsymbol{b}-\boldsymbol{A}\boldsymbol{\beta}\right). $$ -where we have defined the matrix \( \boldsymbol{A} =\boldsymbol{X}/\boldsymbol{\Sigma} \) with matrix elements \( a_{ij} = x_{ij}/\sigma_i \) and the vector \( \boldsymbol{b} \) with elements \( b_i = y_i/\sigma_i \). +

    where we have defined the matrix \( \boldsymbol{A} =\boldsymbol{X}/\boldsymbol{\Sigma} \) with matrix elements \( a_{ij} = x_{ij}/\sigma_i \) and the vector \( \boldsymbol{b} \) with elements \( b_i = y_i/\sigma_i \).

    -

      @@ -418,25 +404,18 @@ where we have defined the matrix \( \boldsymbol{A} =\boldsymbol{X}/\boldsymbol{\
    • »
    -
    - - -
    - - - diff --git a/doc/pub/week34/html/._week34-bs059.html b/doc/pub/week34/html/._week34-bs059.html index 2d27878b7..ea546ff3f 100644 --- a/doc/pub/week34/html/._week34-bs059.html +++ b/doc/pub/week34/html/._week34-bs059.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 34: Introduction to the course, Logistics and Practicalities - + - - - -
    -

     

     

     

    - -

    The \( \chi^2 \) function

    -

    + -

    -We can rewrite +

    We can rewrite

    $$ \frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}} = 0 = \boldsymbol{A}^T\left( \boldsymbol{b}-\boldsymbol{A}\boldsymbol{\beta}\right), $$ -as +

    as

    $$ \boldsymbol{A}^T\boldsymbol{b} = \boldsymbol{A}^T\boldsymbol{A}\boldsymbol{\beta}, $$ -and if the matrix \( \boldsymbol{A}^T\boldsymbol{A} \) is invertible we have the solution +

    and if the matrix \( \boldsymbol{A}^T\boldsymbol{A} \) is invertible we have the solution

    $$ \boldsymbol{\beta} =\left(\boldsymbol{A}^T\boldsymbol{A}\right)^{-1}\boldsymbol{A}^T\boldsymbol{b}. $$ @@ -389,7 +376,6 @@ $$
    -

      @@ -415,25 +401,18 @@ $$
    • »
    -
    - - -
    - - - diff --git a/doc/pub/week34/html/._week34-bs060.html b/doc/pub/week34/html/._week34-bs060.html index 89ed92a16..cf8f8636e 100644 --- a/doc/pub/week34/html/._week34-bs060.html +++ b/doc/pub/week34/html/._week34-bs060.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 34: Introduction to the course, Logistics and Practicalities - + - - -
    -
    -

     

     

     

    - -

    The \( \chi^2 \) function

    -

    + -

    -If we then introduce the matrix +

    If we then introduce the matrix

    $$ \boldsymbol{H} = \left(\boldsymbol{A}^T\boldsymbol{A}\right)^{-1}, $$ -we have then the following expression for the parameters \( \beta_j \) (the matrix elements of \( \boldsymbol{H} \) are \( h_{ij} \)) +

    we have then the following expression for the parameters \( \beta_j \) (the matrix elements of \( \boldsymbol{H} \) are \( h_{ij} \))

    $$ \beta_j = \sum_{k=0}^{p-1}h_{jk}\sum_{i=0}^{n-1}\frac{y_i}{\sigma_i}\frac{x_{ik}}{\sigma_i} = \sum_{k=0}^{p-1}h_{jk}\sum_{i=0}^{n-1}b_ia_{ik} $$ -We state without proof the expression for the uncertainty in the parameters \( \beta_j \) as (we leave this as an exercise) +

    We state without proof the expression for the uncertainty in the parameters \( \beta_j \) as (we leave this as an exercise)

    $$ \sigma^2(\beta_j) = \sum_{i=0}^{n-1}\sigma_i^2\left( \frac{\partial \beta_j}{\partial y_i}\right)^2, $$ -resulting in +

    resulting in

    $$ \sigma^2(\beta_j) = \left(\sum_{k=0}^{p-1}h_{jk}\sum_{i=0}^{n-1}a_{ik}\right)\left(\sum_{l=0}^{p-1}h_{jl}\sum_{m=0}^{n-1}a_{ml}\right) = h_{jj}! $$ @@ -394,7 +381,6 @@ $$
    -

      @@ -419,25 +405,18 @@ $$
    • »
    -
    - - -
    - - - diff --git a/doc/pub/week34/html/._week34-bs061.html b/doc/pub/week34/html/._week34-bs061.html index a441e73aa..977c28b8e 100644 --- a/doc/pub/week34/html/._week34-bs061.html +++ b/doc/pub/week34/html/._week34-bs061.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 34: Introduction to the course, Logistics and Practicalities - + - - -
    -
    -

     

     

     

    - -

    The \( \chi^2 \) function

    -

    -The first step here is to approximate the function \( y \) with a first-order polynomial, that is we write + +

    The first step here is to approximate the function \( y \) with a first-order polynomial, that is we write

    $$ y=y(x) \rightarrow y(x_i) \approx \beta_0+\beta_1 x_i. $$ -By computing the derivatives of \( \chi^2 \) with respect to \( \beta_0 \) and \( \beta_1 \) show that these are given by +

    By computing the derivatives of \( \chi^2 \) with respect to \( \beta_0 \) and \( \beta_1 \) show that these are given by

    $$ \frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \beta_0} = -2\left[ \frac{1}{n}\sum_{i=0}^{n-1}\left(\frac{y_i-\beta_0-\beta_1x_{i}}{\sigma_i^2}\right)\right]=0, $$ -and +

    and

    $$ \frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \beta_1} = -\frac{2}{n}\left[ \sum_{i=0}^{n-1}x_i\left(\frac{y_i-\beta_0-\beta_1x_{i}}{\sigma_i^2}\right)\right]=0. $$ @@ -387,7 +375,6 @@ $$
    -

      @@ -411,25 +398,18 @@ $$
    • »
    -
    - - -
    - - - diff --git a/doc/pub/week34/html/._week34-bs062.html b/doc/pub/week34/html/._week34-bs062.html index 59eb611c3..ed6ff4c81 100644 --- a/doc/pub/week34/html/._week34-bs062.html +++ b/doc/pub/week34/html/._week34-bs062.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 34: Introduction to the course, Logistics and Practicalities - + - - -
    -
    -

     

     

     

    - -

    The \( \chi^2 \) function

    -

    + -

    -For a linear fit (a first-order polynomial) we don't need to invert a matrix!! +

    For a linear fit (a first-order polynomial) we don't need to invert a matrix!! Defining +

    $$ \gamma = \sum_{i=0}^{n-1}\frac{1}{\sigma_i^2}, $$ @@ -397,8 +385,7 @@ $$ \gamma_{xy} = \sum_{i=0}^{n-1}\frac{y_ix_{i}}{\sigma_i^2}, $$ -

    -we obtain +

    we obtain

    $$ \beta_0 = \frac{\gamma_{xx}\gamma_y-\gamma_x\gamma_y}{\gamma\gamma_{xx}-\gamma_x^2}, @@ -409,18 +396,15 @@ $$ \beta_1 = \frac{\gamma_{xy}\gamma-\gamma_x\gamma_y}{\gamma\gamma_{xx}-\gamma_x^2}. $$ -

    -This approach (different linear and non-linear regression) suffers +

    This approach (different linear and non-linear regression) suffers often from both being underdetermined and overdetermined in the unknown coefficients \( \beta_i \). A better approach is to use the Singular Value Decomposition (SVD) method discussed next week. - -

    +

    -

      @@ -443,25 +427,18 @@ Singular Value Decomposition (SVD) method discussed next week.
    • »
    -
    - - -
    - - - diff --git a/doc/pub/week34/html/._week34-bs063.html b/doc/pub/week34/html/._week34-bs063.html index 68d6518e8..b9fa86611 100644 --- a/doc/pub/week34/html/._week34-bs063.html +++ b/doc/pub/week34/html/._week34-bs063.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 34: Introduction to the course, Logistics and Practicalities - + - - - -
    -

     

     

     

    - -

    Fitting an Equation of State for Dense Nuclear Matter

    -

    -Before we continue, let us introduce yet another example. We are going to fit the +

    Before we continue, let us introduce yet another example. We are going to fit the nuclear equation of state using results from many-body calculations. The equation of state we have made available here, as function of density, has been derived using modern nucleon-nucleon potentials with the addition of three-body forces. This time the file is presented as a standard csv file. +

    -

    -The beginning of the Python code here is similar to what you have seen +

    The beginning of the Python code here is similar to what you have seen before, with the same initializations and declarations. We use also pandas again, rather extensively in order to organize our data. +

    -

    -The difference now is that we use Scikit-Learn's regression tools +

    The difference now is that we use Scikit-Learn's regression tools instead of our own matrix inversion implementation. Furthermore, we sneak in Ridge regression (to be discussed below) which includes a hyperparameter \( \lambda \), also to be explained below. +

    -

      @@ -409,25 +396,18 @@ hyperparameter \( \lambda \), also to be explained below.
    • »
    -
    - - -
    - - - diff --git a/doc/pub/week34/html/._week34-bs064.html b/doc/pub/week34/html/._week34-bs064.html index 5e17d02d8..fe2f6ba81 100644 --- a/doc/pub/week34/html/._week34-bs064.html +++ b/doc/pub/week34/html/._week34-bs064.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 34: Introduction to the course, Logistics and Practicalities - + - - - -
    -

     

     

     

    - -

    The code

    -

    -

    # Common imports
    +
    +
    +
    +
    +
    +
    # Common imports
     import os
     import numpy as np
     import pandas as pd
    @@ -455,17 +447,30 @@ ax.plot(EoS[
     ax.legend()
     save_fig("EoSfitting")
     plt.show()
    -
    -

    -The above simple polynomial in density \( \rho \) gives an excellent fit -to the data. +

    +
    +
    + + +
    +
    +
    +
    +
    +
    +
    +
    + -

    -We note also that there is a small deviation between the +

    The above simple polynomial in density \( \rho \) gives an excellent fit +to the data. +

    + +

    We note also that there is a small deviation between the standard OLS and the Ridge regression at higher densities. We discuss this in more detail below. +

    -

      @@ -486,25 +491,18 @@ below.
    • »
    - - - -
    - - - diff --git a/doc/pub/week34/html/._week34-bs065.html b/doc/pub/week34/html/._week34-bs065.html index 1d03cd0e8..15c5fd644 100644 --- a/doc/pub/week34/html/._week34-bs065.html +++ b/doc/pub/week34/html/._week34-bs065.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 34: Introduction to the course, Logistics and Practicalities - + - - - -
    -

     

     

     

    - -

    Splitting our Data in Training and Test data

    -

    -It is normal in essentially all Machine Learning studies to split the +

    It is normal in essentially all Machine Learning studies to split the data in a training set and a test set (sometimes also an additional validation set). Scikit-Learn has an own function for this. There is no explicit recipe for how much data should be included as training @@ -378,11 +365,16 @@ postpone a discussion of this splitting to the end of these notes and our discussion of the so-called bias-variance tradeoff. Here we limit ourselves to repeat the above equation of state fitting example but now splitting the data into a training set and a test set. +

    -

    -

    import os
    +
    +
    +
    +
    +
    +
    import os
     import numpy as np
     import pandas as pd
     import matplotlib.pyplot as plt
    @@ -446,8 +438,22 @@ ypredict = X_test print(R2(y_test,ypredict))
     print("Test MSE")
     print(MSE(y_test,ypredict))
    -
    -

    +

    +
    +
    + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

      @@ -467,25 +473,18 @@ ypredict = X_test »
    - - - -
    - - - diff --git a/doc/pub/week34/html/._week34-bs066.html b/doc/pub/week34/html/._week34-bs066.html index 931375977..3c0ddfddc 100644 --- a/doc/pub/week34/html/._week34-bs066.html +++ b/doc/pub/week34/html/._week34-bs066.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 34: Introduction to the course, Logistics and Practicalities - + - - - -
    -

     

     

     

    - -

    Exercises for week 35

    -Here are three possible exercises for week 35 and the lab sessions of Wednesday September 1. +

    Here are three possible exercises for week 35 and the lab sessions of Wednesday September 1.

    -

    -

    Exercise 1: Setting up various Python environments

    -

    -The first exercise here is of a mere technical art. We want you to have - +

    The first exercise here is of a mere technical art. We want you to have

    • git as a version control software and to establish a user account on a provider like GitHub. Other providers like GitLab etc are equally fine. You can also use the University of Oslo GitHub facilities.
    • Install various Python packages
    - -We will make extensive use of Python as programming language and its +

    We will make extensive use of Python as programming language and its myriad of available libraries. You will find IPython/Jupyter notebooks invaluable in your work. You can run R codes in the Jupyter/IPython notebooks, with the immediate benefit of visualizing your data. You can also use compiled languages like C++, Rust, Fortran etc if you prefer. The focus in these lectures will be on Python. +

    -

    -If you have Python installed (we recommend Python3) and you feel +

    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 +

    1. pip install numpy scipy matplotlib ipython scikit-learn sympy pandas pillow
    - -For Tensorflow, we recommend following the instructions in the text of +

    For Tensorflow, we recommend following the instructions in the text of Aurelien Geron, Hands‑On Machine Learning with Scikit‑Learn and TensorFlow, O'Reilly +

    -

    -We will come back to tensorflow later. +

    We will come back to tensorflow later.

    -

    -For Python3, replace pip with pip3. +

    For Python3, replace pip with pip3.

    -

    -For OSX users we recommend, after having installed Xcode, to +

    For OSX users we recommend, after having installed Xcode, to install brew. Brew allows for a seamless installation of additional software via for example +

    1. brew install python3
    - -For Linux users, with its variety of distributions like for example the widely popular Ubuntu distribution, +

    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 +

    1. sudo apt-get install python3 (or python for Python2.7)
    - -If you don't want to perform these operations separately and venture +

    If you don't want to perform these operations separately and venture into the hassle of exploring how to set up dependencies and paths, we recommend two widely used distrubutions which set up all relevant dependencies for Python, namely +

    - -which is an open source +

    which 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. +

    - -is a Python +

    is a Python distribution for scientific and analytic computing distribution and analysis environment, available for free and under a commercial license. +

    -

    -We recommend using Anaconda if you are not too familiar with setting paths in a terminal environment. +

    We recommend using Anaconda if you are not too familiar with setting paths in a terminal environment.

    -

    -

    -

    Exercise 2: making your own data and exploring scikit-learn

    -

    -We will generate our own dataset for a function \( y(x) \) where \( x \in [0,1] \) and defined by random numbers computed with the uniform distribution. The function \( y \) is a quadratic polynomial in \( x \) with added stochastic noise according to the normal distribution \( \cal {N}(0,1) \). +

    We will generate our own dataset for a function \( y(x) \) where \( x \in [0,1] \) and defined by random numbers computed with the uniform distribution. The function \( y \) is a quadratic polynomial in \( x \) with added stochastic noise according to the normal distribution \( \cal {N}(0,1) \). The following simple Python instructions define our \( x \) and \( y \) values (with 100 data points). -

    +

    -
    x = np.random.rand(100,1)
    +
    +
    +
    +
    +
    +
    x = np.random.rand(100,1)
     y = 2.0+5*x*x+0.1*np.random.randn(100,1)
    -
    +
    +
    +
    + + +
    +
    +
    +
    +
    +
    +
    +
    + + +
    1. Write your own code (following the examples under the regression notes) for computing the parametrization of the data set fitting a second-order polynomial.
    2. Use thereafter scikit-learn (see again the examples in the regression slides) and compare with your own code.
    3. Using scikit-learn, compute also the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error defined as
    - $$ MSE(\boldsymbol{y},\boldsymbol{\tilde{y}}) = \frac{1}{n} \sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, $$ -and the \( R^2 \) score function. +

    and the \( R^2 \) score function. If \( \tilde{\boldsymbol{y}}_i \) is the predicted value of the \( i-th \) sample and \( y_i \) is the corresponding true value, then the score \( R^2 \) is defined as +

    $$ R^2(\boldsymbol{y}, \tilde{\boldsymbol{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2}, $$ -where we have defined the mean value of \( \boldsymbol{y} \) as +

    where we have defined the mean value of \( \boldsymbol{y} \) as

    $$ \bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. $$ -You can use the functionality included in scikit-learn. If you feel for it, you can use your own program and define functions which compute the above two functions. +

    You can use the functionality included in scikit-learn. If you feel for it, you can use your own program and define functions which compute the above two functions. Discuss the meaning of these results. Try also to vary the coefficient in front of the added stochastic noise term and discuss the quality of the fits. +

    -

    - +

    +

    Solution. +

    -

    -The code here is an example of where we define our own design matrix and fit parameters \( \beta \). -

    +

    The code here is an example of where we define our own design matrix and fit parameters \( \beta \).

    -
    import os
    +
    +
    +
    +
    +
    +
    import os
     import numpy as np
     import pandas as pd
     import matplotlib.pyplot as plt
    @@ -548,31 +551,40 @@ ypredict = X_test print(R2(y_test,ypredict))
     print("Test MSE")
     print(MSE(y_test,ypredict))
    -
    -

    +

    +
    +
    +
    + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    -

    -

    -

    -

    Exercise 3: Normalizing our data

    -

    -A much used approach before starting to train the data is to preprocess our +

    A much used approach before starting to train the data is to preprocess our data. Normally the data may need a rescaling and/or may be sensitive to extreme values. Scaling the data renders our inputs much more suitable for the algorithms we want to employ. +

    -

    -Scikit-Learn has several functions which allow us to rescale the +

    Scikit-Learn has several functions which allow us to rescale the data, normally resulting in much better results in terms of various accuracy scores. The StandardScaler function in Scikit-Learn ensures that for each feature/predictor we study the mean value is @@ -581,18 +593,18 @@ matrix). This scaling has the drawback that it does not ensure that we have a particular maximum or minimum in our data set. Another function included in Scikit-Learn is the MinMaxScaler which ensures that all features are exactly between \( 0 \) and \( 1 \). The +

    -

    -The Normalizer scales each data +

    The Normalizer scales each data point such that the feature vector has a euclidean length of one. In other words, it projects a data point on the circle (or sphere in the case of higher dimensions) with a radius of 1. This means every data point is scaled by a different number (by the inverse of it’s length). This normalization is often used when only the direction (or angle) of the data matters, not the length of the feature vector. +

    -

    -The RobustScaler works similarly to the StandardScaler in that it +

    The RobustScaler works similarly to the StandardScaler in that it ensures statistical properties for each feature that guarantee that they are on the same scale. However, the RobustScaler uses the median and quartiles, instead of mean and variance. This makes the @@ -600,65 +612,127 @@ RobustScaler ignore data points that are very different from the rest (like measurement errors). These odd data points are also called outliers, and might often lead to trouble for other scaling techniques. +

    -

    -It also common to split the data in a training set and a testing set. A typical split is to use \( 80\% \) of the data for training and the rest +

    It also common to split the data in a training set and a testing set. A typical split is to use \( 80\% \) of the data for training and the rest for testing. This can be done as follows with our design matrix \( \boldsymbol{X} \) and data \( \boldsymbol{y} \) (remember to import scikit-learn) -

    +

    -
    # split in training and test data
    +
    +
    +
    +
    +
    +
    # split in training and test data
     X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.2)
    -
    -

    -Then we can use the standard scaler to scale our data as -

    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    Then we can use the standard scaler to scale our data as

    -
    scaler = StandardScaler()
    +
    +
    +
    +
    +
    +
    scaler = StandardScaler()
     scaler.fit(X_train)
     X_train_scaled = scaler.transform(X_train)
     X_test_scaled = scaler.transform(X_test)
    -
    -

    -In this exercise we want you to to compute the MSE for the training +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    In this exercise we want you to to compute the MSE for the training data and the test data as function of the complexity of a polynomial, -that is the degree of a given polynomial. We want you also to compute the \( R2 \) score as function of the complexity of the model for both training data and test data. You should also run the calculation with and without scaling. +that is the degree of a given polynomial. We want you also to compute the \( R2 \) score as function of the complexity of the model for both training data and test data. You should also run the calculation with and without scaling. +

    -

    -One of +

    One of the aims is to reproduce Figure 2.11 of Hastie et al. +

    -

    -Our data is defined by \( x\in [-3,3] \) with a total of for example \( 100 \) data points. -

    +

    Our data is defined by \( x\in [-3,3] \) with a total of for example \( 100 \) data points.

    -
    np.random.seed()
    +
    +
    +
    +
    +
    +
    np.random.seed()
     n = 100
     maxdegree = 14
     # Make data set.
     x = np.linspace(-3, 3, n).reshape(-1, 1)
     y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
    -
    -

    -where \( y \) is the function we want to fit with a given polynomial. +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + +

    where \( y \) is the function we want to fit with a given polynomial.

    + +

    a) Write a first code which sets up a design matrix \( X \) defined by a fifth-order polynomial. Scale your data and split it in training and test data. +

    + + +

    b) Perform an ordinary least squares and compute the means squared error and the \( R2 \) factor for the training data and the test data, with and without scaling. +

    + + +

    c) Add now a model which allows you to make polynomials up to degree \( 15 \). Perform a standard OLS fitting of the training data and compute the MSE and \( R2 \) for the training and test data and plot both test and training data MSE and \( R2 \) as functions of the polynomial degree. Compare what you see with Figure 2.11 of Hastie et al. Comment your results. For which polynomial degree do you find an optimal MSE (smallest value)? +

    + + -

    -

      @@ -676,25 +750,18 @@ Add now a model which allows you to make polynomials up to degree \( 15 \). Per
    • 67
    - - - -
    - - - diff --git a/doc/pub/week34/html/week34-bs.html b/doc/pub/week34/html/week34-bs.html index 743aee240..6c35019c1 100644 --- a/doc/pub/week34/html/week34-bs.html +++ b/doc/pub/week34/html/week34-bs.html @@ -1,6 +1,7 @@ @@ -8,24 +9,20 @@ Automatically generated HTML file from DocOnce source - Week 34: Introduction to the course, Logistics and Practicalities - + - - - -
    -

     

     

     

    - - - -
    -

    Week 34: Introduction to the course, Logistics and Practicalities

    +
    +

    Week 34: Introduction to the course, Logistics and Practicalities

    +
    -

    -

    Morten Hjorth-Jensen [1, 2]
    - -

    +

    +[1] Department of Physics, University of Oslo +
    +
    +[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University +
    +
    +
    +

    Nov 13, 2021

    +
    +
    -
    [1] Department of Physics, University of Oslo
    -
    [2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
    -
    -

    -

    Oct 12, 2021

    -
    -

    Read »

    @@ -412,25 +400,18 @@ MathJax.Hub.Config({
  • »
  • -
    - - -
    © 1999-2021, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
    - - - diff --git a/doc/pub/week34/html/week34-reveal.html b/doc/pub/week34/html/week34-reveal.html index 8b78adb7a..a4a4913c9 100644 --- a/doc/pub/week34/html/week34-reveal.html +++ b/doc/pub/week34/html/week34-reveal.html @@ -1,18 +1,17 @@ + - + + - Week 34: Introduction to the course, Logistics and Practicalities - - - - - - @@ -55,36 +54,81 @@ document.getElementsByTagName( 'head' )[0].appendChild( link ); - - - +
    +

    Week 34: Introduction to the course, Logistics and Practicalities

    +
    - - -

    Week 34: Introduction to the course, Logistics and Practicalities

    - -

    -

    Morten Hjorth-Jensen [1, 2]
    - -

    +

    +[1] Department of Physics, University of Oslo +
    +
    +[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University +
    +
    +
    +

    Nov 13, 2021

    +
    +
    -
    [1] Department of Physics, University of Oslo
    -
    [2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
    -
    -

    -

    Oct 12, 2021

    -
    -











    -

    Overview of first week

    -

    -

    • Wednesday August 25: Introduction to software and repetition of Python Programming
    • Thursday August 26: First lecture: Presentation of the course, aims and content
    • @@ -322,59 +318,44 @@ MathJax.Hub.Config({
    -











    -

    Reading Recommendations

    -

    -For the reading assignments we use the following abbreviations: - +

    For the reading assignments we use the following abbreviations:

    • GBC: Goodfellow, Bengio, and Courville, Deep Learning
    • CMB: Christopher M. Bishop, Pattern Recognition and Machine Learning
    • HTF: Hastie, Tibshirani, and Friedman, The Elements of Statistical Learning
    • AG: Aurelien Geron, Hands‑On Machine Learning with Scikit‑Learn and TensorFlow
    - -Reading recommendations this week: Refresh linear algebra, GBC chapters 1 and 2. CMB sections 1.1 and 3.1. HTF chapters 2 and 3. Install scikit-learn. See lecture notes for week 34 at https://compphysics.github.io/MachineLearning/doc/web/course.html +

    Reading recommendations this week: Refresh linear algebra, GBC chapters 1 and 2. CMB sections 1.1 and 3.1. HTF chapters 2 and 3. Install scikit-learn. See lecture notes for week 34 at https://compphysics.github.io/MachineLearning/doc/web/course.html

    -











    -

    Thursday August 26

    -

    -The lectures will be recorded and updated videos will be posted after the lectures. +

    The lectures will be recorded and updated videos will be posted after the lectures.

    -

    -"Video of Lecture August 26, 2021":"https://www.uio.no/studier/emner/matnat/fys/FYS-STK4155/h21/forelesningsvideoer/LectureThursdayAugust26.mp4?vrtx=view-as-webpage +

    "Video of Lecture August 26, 2021":"https://www.uio.no/studier/emner/matnat/fys/FYS-STK4155/h21/forelesningsvideoer/LectureThursdayAugust26.mp4?vrtx=view-as-webpage

    -

    -Zoom link for lectures: https://msu.zoom.us/j/93311529525?pwd=a1VXSzY4aTFWVy9Rb05mNDJTZ09lZz09 +

    Zoom link for lectures: https://msu.zoom.us/j/93311529525?pwd=a1VXSzY4aTFWVy9Rb05mNDJTZ09lZz09

    • Meeting ID: 933 1152 9525
    • Passcode: 646102
    +

    Video of Lecture from Fall Semester 2020.

    -Video of Lecture from Fall Semester 2020. - -











    -

    Lectures and ComputerLab

    -

    -

    • Lectures: Thursday (12.15pm-2pm and Friday (12.15pm-2pm).
    • Weekly reading assignments and videos needed to solve projects and exercises.
    • @@ -386,17 +367,12 @@ The lectures will be recorded and updated videos will be posted after the lectur
    -











    -

    Announcement

    -

    -NORA AI competetion: See the link here https://www.nora.ai/Competition/image-segmentation.html +

    NORA AI competetion: See the link here https://www.nora.ai/Competition/image-segmentation.html

    -











    -

    Communication channels

    -









    -

    Course Format

    -

    -

    • Three compulsory projects. Electronic reports only using Canvas to hand in projects and git as version control software and GitHub for repository (or GitLab) of all your material.
    • Evaluation and grading: The three projects are graded and each counts 1/3 of the final mark. No final written or oral exam. -
      1. For the last project each group/participant submits a proposal or works with suggested (by us) proposals for the project.
      2. If possible, we would like to organize the last project as a workshop where each group makes a poster and presents this to all other participants of the course
      3. Poster session where all participants can study and discuss the other proposals.
      4. Based on feedback etc, each group finalizes the report and submits for grading.
      -
    • Python is the default programming language, but feel free to use C/C++ and/or Fortran or other programming languages. All source codes discussed during the lectures can be found at the webpage and github address of the course.
    -











    -

    Teachers

    -

    -

    Teachers : -

    • Morten Hjorth-Jensen, morten.hjorth-jensen@fys.uio.no
    • -
      • Phone: +47-48257387
      • Office: Department of Physics, University of Oslo, Eastern wing, room FØ470
      • Office hours: Anytime! Individual or group office hours can be arranged either in person or via zoom. Feel free to send an email for planning.
      -
    • Øyvind Sigmundson Schøyen, oyvinssc@student.matnat.uio.no
    • -
      • Office: Department of Physics, University of Oslo, Eastern wing, room FØ452
      -
    • Stian Dysthe Bilek stian.bilek@fys.uio.no
    • -
      • Office: Department of Physics, University of Oslo, Eastern wing, room FØ450
      -
    • Linus Ekstrøm, linueks@gmail.com, linus.ekstrom@fys.uio.no
    • Nicholas Karlsen, nicholaskarlsen1102@gmail.com, nicholas.karlsen@fys.uio.no
    • Bendik Steinsvåg Dalen, b.s.dalen@fys.uio.no
    • @@ -472,57 +431,44 @@ The lectures will be recorded and updated videos will be posted after the lectur
    -











    -

    Deadlines for projects (tentative)

    -

    1. Project 1: October 11 (available September 10) graded with feedback)
    2. -
    3. Project 2: November 15 (available October 12, graded with feedback)
    4. -
    5. Project 3: December 13 (available November 8, graded with feedback)
    6. +
    7. Project 2: November 20 (available October 12, graded with feedback)
    8. +
    9. Project 3: December 17 (available November 13, graded with feedback)
    - -Projects are handed in using Canvas. We use Github as repository for codes, benchmark calculations etc. Comments and feedback on projects only via Canvas. - - +

    Projects are handed in using Canvas. We use Github as repository for codes, benchmark calculations etc. Comments and feedback on projects only via Canvas.

    -











    -

    1. The lecture notes are collected as a jupyter-book at https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/intro.html.
    - -In addition to the lecture notes, we recommend the books of Bishop and Goodfellow et al. We will follow these texts closely and the weekly reading assignments refer to these two texts. The text by Hastie et al is also widely used in the Machine Learning community. Finally, we also recommend the hands-on text by Geron, see below. +

    In addition to the lecture notes, we recommend the books of Bishop and Goodfellow et al. We will follow these texts closely and the weekly reading assignments refer to these two texts. The text by Hastie et al is also widely used in the Machine Learning community. Finally, we also recommend the hands-on text by Geron, see below.

    1. Christopher M. Bishop, Pattern Recognition and Machine Learning, Springer, https://www.springer.com/gp/book/9780387310732.
    2. Ian Goodfellow, Yoshua Bengio, and Aaron Courville. The different chapters are available for free at https://www.deeplearningbook.org/. Chapters 2-14 are highly recommended. The lectures follow to a larg extent this text. The weekly plans will include reading suggestions from these two textbooks.
    - -Additional textbooks: +

    Additional textbooks:

    1. Trevor Hastie, Robert Tibshirani, Jerome H. Friedman, The Elements of Statistical Learning, Springer, https://www.springer.com/gp/book/9780387848570. This is a well-known text and serves as additional literature.
    2. Aurelien Geron, Hands‑On Machine Learning with Scikit‑Learn and TensorFlow, O'Reilly, https://www.oreilly.com/library/view/hands-on-machine-learning/9781492032632/. This text is very useful since it contains many code examples and hands-on applications of all algorithms discussed in this course.
    -









    -

    Prerequisites

    -

    -Basic knowledge in programming and mathematics, with an emphasis on +

    Basic knowledge in programming and mathematics, with an emphasis on linear algebra. Knowledge of Python or/and C++ as programming languages is strongly recommended and experience with Jupiter notebook is recommended. Required courses are the equivalents to the University @@ -531,19 +477,16 @@ of the corresponding computing and programming courses INF1000/INF1110 or MAT-INF1100/MAT-INF1100L/BIOS1100/KJM-INF1100. Most universities offer nowadays a basic programming course (often compulsory) where Python is the recurring programming language. +

    -











    -

    Learning outcomes

    -

    -

    -This course aims at giving you insights and knowledge about many of +

    This course aims at giving you insights and knowledge about many of the central algorithms used in Data Analysis and Machine Learning. The course is project based and through various numerical projects, normally three, you will be exposed to fundamental research problems @@ -556,6 +499,7 @@ Learning is applied to, get acquainted with computing facilities and learn to handle large scientific projects. A good scientific and ethical conduct is emphasized throughout the course. More specifically, after this course you will +

    • Learn about basic data analysis, statistical analysis, Bayesian statistics, Monte Carlo sampling, data optimization and machine learning;
    • @@ -572,29 +516,22 @@ specifically, after this course you will
    -











    -

    Topics covered in this course: Statistical analysis and optimization of data

    -

    -The course has two central parts +

    The course has two central parts

    1. Statistical analysis and optimization of data
    2. Machine learning
    +

    These topics will be scattered thorughout the course and may not necessarily be taught separately. Rather, we will often take an approach (during the lectures and project/exercise sessions) where say elements from statistical data analysis are mixed with specific Machine Learning algorithms

    -These topics will be scattered thorughout the course and may not necessarily be taught separately. Rather, we will often take an approach (during the lectures and project/exercise sessions) where say elements from statistical data analysis are mixed with specific Machine Learning algorithms - -

    Statistical analysis and optimization of data

    -

    -We plan to cover the following topics: - +

    We plan to cover the following topics:

    • Basic concepts, expectation values, variance, covariance, correlation functions and errors;
    • Simpler models, binomial distribution, the Poisson distribution, simple and multivariate normal distributions;
    • @@ -607,17 +544,13 @@ We plan to cover the following topics:
    -











    -

    Topics covered in this course: Machine Learning

    -

    -The following topics will be covered - +

    The following topics will be covered

    • Linear Regression and Logistic Regression;
    • Neural networks and deep learning, including convolutional and recurrent neural networks
    • @@ -627,23 +560,16 @@ The following topics will be covered
    • Boltzmann Machines
    • Unsupervised learning Dimensionality reduction, from PCA to clustering
    - -Hands-on demonstrations, exercises and projects aim at deepening your understanding of these topics. - - +

    Hands-on demonstrations, exercises and projects aim at deepening your understanding of these topics.

    -











    -

    -

    and discussed at the lab sessions

    -

    • GIT for version control, and GitHub or GitLab as repositories, highly recommended. This will be discussed during the first exercise session
    • Anaconda and other Python environments, see intro slides and links to programming resources at https://computationalscienceuio.github.io/RefreshProgrammingSkills/intro.html
    • @@ -651,13 +577,10 @@ Hands-on demonstrations, exercises and projects aim at deepening your understand
    -











    -

    Other courses on Data science and Machine Learning at UiO

    -

    -The link here 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. +

    The link here 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.

    1. STK2100 Machine learning and statistical methods for prediction and classification.
    2. @@ -672,18 +595,15 @@ The link here STK4051 Computational Statistics
    3. STK4021 Applied Bayesian Analysis and Numerical Methods
    -









    -

    Introduction

    -

    -Our emphasis throughout this series of lectures +

    Our emphasis throughout this series of lectures is on understanding the mathematical aspects of -different algorithms used in the fields of data analysis and machine learning. +different algorithms used in the fields of data analysis and machine learning. +

    -

    -However, where possible we will emphasize the +

    However, where possible we will emphasize the importance of using available software. We start thus with a hands-on and top-down approach to machine learning. The aim is thus to start with relevant data or data we have produced @@ -697,40 +617,38 @@ the data and predictions. We move thereafter to more interesting cases such as data from say experiments (below we will look at experimental nuclear binding energies as an example). These are examples where we can easily set up the data and then use machine learning algorithms included in for example -Scikit-Learn. +Scikit-Learn. +

    -

    -These examples will serve us the purpose of getting +

    These examples will serve us the purpose of getting started. Furthermore, they allow us to catch more than two birds with a stone. They will allow us to bring in some programming specific topics and tools as well as showing the power of various Python -libraries for machine learning and statistical data analysis. +libraries for machine learning and statistical data analysis. +

    -

    -Here, we will mainly focus on two +

    Here, we will mainly focus on two specific Python packages for Machine Learning, Scikit-Learn and Tensorflow (see below for links etc). Moreover, the examples we introduce will serve as inputs to many of our discussions later, as well as allowing you to set up models and produce your own data and get started with programming. +

    -











    -

    What is Machine Learning?

    -

    -Statistics, data science and machine learning form important fields of +

    Statistics, data science and machine learning form important fields of research in modern science. They describe how to learn and make predictions from data, as well as allowing us to extract important correlations about physical process and the underlying laws of motion in large data sets. The latter, big data sets, appear frequently in essentially all disciplines, from the traditional Science, Technology, Mathematics and Engineering fields to Life Science, Law, education -research, the Humanities and the Social Sciences. +research, the Humanities and the Social Sciences. +

    -

    -It has become more +

    It has become more and more common to see research projects on big data in for example the Social Sciences where extracting patterns from complicated survey data is one of many research directions. Having a solid grasp of data @@ -745,17 +663,17 @@ in the private or the public sector. This author has had several students or met students who have been hired recently based on their skills and competences in scientific computing and data science, often with marginal knowledge of machine learning. +

    -

    -Machine learning is a subfield of computer science, and is closely +

    Machine learning is a subfield of computer science, and is closely related to computational statistics. It evolved from the study of pattern recognition in artificial intelligence (AI) research, and has made contributions to AI tasks like computer vision, natural language processing and speech recognition. Many of the methods we will study are also -strongly rooted in basic mathematics and physics research. +strongly rooted in basic mathematics and physics research. +

    -

    -Ideally, machine learning represents the science of giving computers +

    Ideally, machine learning represents the science of giving computers the ability to learn without being explicitly programmed. The idea is that there exist generic algorithms which can be used to find patterns in a broad class of data sets without having to write code @@ -763,10 +681,10 @@ specifically for each problem. The algorithm will build its own logic based on the data. You should however always keep in mind that machines and algorithms are to a large extent developed by humans. The insights and knowledge we have about a specific system, play a central -role when we develop a specific machine learning algorithm. +role when we develop a specific machine learning algorithm. +

    -

    -Machine learning is an extremely rich field, in spite of its young +

    Machine learning is an extremely rich field, in spite of its young age. The increases we have seen during the last three decades in computational capabilities have been followed by developments of methods and techniques for analyzing and handling large date sets, @@ -786,14 +704,12 @@ solid command of linear algebra, multivariate theory, probability theory, statistical data analysis, understanding errors and Monte Carlo methods are central elements in a proper understanding of many of algorithms and methods we will discuss. +

    -











    -

    Types of Machine Learning

    -

    -The approaches to machine learning are many, but are often split into +

    The approaches to machine learning are many, but are often split into two main categories. In supervised learning we know the answer to a problem, and let the computer deduce the logic behind it. On the other hand, unsupervised learning is a method for finding patterns and @@ -802,49 +718,40 @@ Some authours also operate with a third category, namely reinforcement learning. This is a paradigm of learning inspired by behavioral psychology, where learning is achieved by trial-and-error, solely from rewards and punishment. +

    -

    -Another way to categorize machine learning tasks is to consider the +

    Another way to categorize machine learning tasks is to consider the desired output of a system. Some of the most common tasks are: +

    • Classification: Outputs are divided into two or more classes. The goal is to produce a model that assigns inputs into one of these classes. An example is to identify digits based on pictures of hand-written ones. Classification is typically supervised learning.
    • Regression: Finding a functional relationship between an input data set and a reference data set. The goal is to construct a function that maps input data to continuous output values.
    • Clustering: Data are divided into groups with certain common traits, without knowing the different groups beforehand. It is thus a form of unsupervised learning.
    -









    -

    Essential elements of ML

    -

    -The methods we cover have three main topics in common, irrespective of +

    The methods we cover have three main topics in common, irrespective of whether we deal with supervised or unsupervised learning. +

    -
    • The first ingredient is normally our data set (which can be subdivided into training, validation and test data). Many find the most difficult part of using Machine Learning to be the set up of your data in a meaningful way.
    • The second item is a model which is normally a function of some parameters. The model reflects our knowledge of the system (or lack thereof). As an example, if we know that our data show a behavior similar to what would be predicted by a polynomial, fitting our data to a polynomial of some degree would then determin our model.
    • The last ingredient is a so-called cost/loss function (or error or risk function) which allows us to present an estimate on how good our model is in reproducing the data it is supposed to train.
    - -











    -

    An optimization/minimization problem

    -

    -At the heart of basically all Machine Learning algorithms we will encounter so-called minimization or optimization algorithms. A large family of such methods are so-called gradient methods. +

    At the heart of basically all Machine Learning algorithms we will encounter so-called minimization or optimization algorithms. A large family of such methods are so-called gradient methods.

    -











    -

    A Frequentist approach to data analysis

    -

    -When you hear phrases like predictions and estimations and +

    When you hear phrases like predictions and estimations and correlations and causations, what do you think of? May be you think of the difference between classifying new data points and generating new data points. @@ -852,9 +759,9 @@ Or perhaps you consider that correlations represent some kind of symmetric state if \( A \) is correlated with \( B \), then \( B \) is correlated with \( A \). Causation on the other hand is directional, that is if \( A \) causes \( B \), \( B \) does not necessarily cause \( A \). +

    -

    -These concepts are in some sense the difference between machine +

    These concepts are in some sense the difference between machine learning and statistics. In machine learning and prediction based tasks, we are often interested in developing algorithms that are capable of learning patterns from given data in an automated fashion, @@ -863,51 +770,47 @@ assessments of newly given data. In many cases, our primary concern is the quality of the predictions or assessments, and we are less concerned about the underlying patterns that were learned in order to make these predictions. +

    -

    -In machine learning we normally use a so-called frequentist approach, +

    In machine learning we normally use a so-called frequentist approach, where the aim is to make predictions and find correlations. We focus less on for example extracting a probability distribution function (PDF). The PDF can be used in turn to make estimations and find causations such as given \( A \) what is the likelihood of finding \( B \). +

    -











    -

    What is a good model?

    -

    -In science and engineering we often end up in situations where we want to infer (or learn) a +

    In science and engineering we often end up in situations where we want to infer (or learn) a quantitative model \( M \) for a given set of sample points \( \boldsymbol{X} \in [x_1, x_2,\dots x_N] \). +

    -

    -As we will see repeatedely in these lectures, we could try to fit these data points to a model given by a +

    As we will see repeatedely in these lectures, we could try to fit these data points to a model given by a straight line, or if we wish to be more sophisticated to a more complex function. +

    -

    -The reason for inferring such a model is that it +

    The reason for inferring such a model is that it serves many useful purposes. On the one hand, the model can reveal information encoded in the data or underlying mechanisms from which the data were generated. For instance, we could discover important corelations that relate interesting physics interpretations. +

    -

    -In addition, it can simplify the representation of the given data set and help +

    In addition, it can simplify the representation of the given data set and help us in making predictions about future data samples. +

    -

    -A first important consideration to keep in mind is that inferring the correct model +

    A first important consideration to keep in mind is that inferring the correct model for a given data set is an elusive, if not impossible, task. The fundamental difficulty is that if we are not specific about what we mean by a correct model, there could easily be many different models that fit the given data set equally well. +

    -











    -

    What is a good model? Can we define it?

    -

    -The central question is this: what leads us to say that a model is correct or +

    The central question is this: what leads us to say that a model is correct or optimal for a given data set? To make the model inference problem well posed, i.e., to guarantee that there is a unique optimal model for the given data, we need to impose additional assumptions or restrictions on the class of models considered. To @@ -920,98 +823,90 @@ with the simplest possible class of models that is just necessary to describe th or solve the problem at hand. More precisely, the model class should be rich enough to contain at least one model that can fit the data to a desired accuracy and yet be restricted enough that it is relatively simple to find the best model for the given data. +

    -

    -Thus, the most popular strategy is to start from the +

    Thus, the most popular strategy is to start from the simplest class of models and increase the complexity of the models only when the simpler models become inadequate. For instance, if we work with a regression problem to fit a set of sample points, one may first try the simplest class of models, namely linear models, followed obviously by more complex models. +

    -

    -How to evaluate which model fits best the data is something we will come back to over and over again in these sets of lectures. +

    How to evaluate which model fits best the data is something we will come back to over and over again in these sets of lectures.

    -











    -

    Software and needed installations

    -

    -We will make extensive use of Python as programming language and its +

    We will make extensive use of Python as programming language and its myriad of available libraries. You will find Jupyter notebooks invaluable in your work. You can run R codes in the Jupyter/IPython notebooks, with the immediate benefit of visualizing your data. You can also use compiled languages like C++, Rust, Julia, Fortran etc if you prefer. The focus in these lectures will be on Python. +

    -

    -If you have Python installed (we strongly recommend Python3) and you feel +

    If you have Python installed (we strongly recommend Python3) and you feel pretty familiar with installing different packages, we recommend that you install the following Python packages via pip as +

    1. pip install numpy scipy matplotlib ipython scikit-learn mglearn sympy pandas pillow
    +

    For Python3, replace pip with pip3.

    -For Python3, replace pip with pip3. - -

    -For OSX users we recommend, after having installed Xcode, to +

    For OSX users we recommend, after having installed Xcode, to install brew. Brew allows for a seamless installation of additional software via for example +

    1. brew install python3
    - -For Linux users, with its variety of distributions like for example the widely popular Ubuntu distribution, +

    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 +

    1. sudo apt-get install python3 (or python for pyhton2.7)
    +

    etc etc.

    -etc etc. - -











    -

    Python installers

    -

    -If you don't want to perform these operations separately and venture +

    If you don't want to perform these operations separately and venture into the hassle of exploring how to set up dependencies and paths, we recommend two widely used distrubutions which set up all relevant dependencies for Python, namely +

    - -which is an open source +

    which 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. +

    - -is a Python +

    is a Python distribution for scientific and analytic computing distribution and analysis environment, available for free and under a commercial license. +

    -

    -Furthermore, Google's Colab is a free Jupyter notebook environment that requires +

    Furthermore, Google's Colab is a free Jupyter notebook environment that requires no setup and runs entirely in the cloud. Try it out! +

    -











    -

    Useful Python libraries

    -Here we list several useful Python libraries we strongly recommend (if you use anaconda many of these are already there) +

    Here we list several useful Python libraries we strongly recommend (if you use anaconda many of these are already there)

    • NumPy is a highly popular library for large, multi-dimensional arrays and matrices, along with a large collection of high-level mathematical functions to operate on these arrays
    • @@ -1026,13 +921,10 @@ Here we list several useful Python libraries we strongly recommend (if you use a
    • Keras is a high-level neural networks API, written in Python and capable of running on top of TensorFlow, CNTK, or Theano
    • And many more such as pytorch, Theano etc
    -









    -

    Installing R, C++, cython or Julia

    -

    -You will also find it convenient to utilize R. We will mainly +

    You will also find it convenient to utilize R. We will mainly use Python during our lectures and in various projects and exercises. Those of you already familiar with R should feel free to continue using R, keeping @@ -1042,25 +934,23 @@ notebook allows you to run R codes interactively in your browser. The software library R is really tailored for statistical data analysis and allows for an easy usage of the tools and algorithms we will discuss in these lectures. +

    -

    -To install R with Jupyter notebook +

    To install R with Jupyter notebook follow the link here +

    -











    -

    Installing R, C++, cython, Numba etc

    -

    -For the C++ aficionados, Jupyter/IPython notebook allows you also to +

    For the C++ aficionados, Jupyter/IPython notebook allows you also to install C++ and run codes written in this language interactively in the browser. Since we will emphasize writing many of the algorithms yourself, you can thus opt for either Python or C++ (or Fortran or other compiled languages) as programming languages. +

    -

    -To add more entropy, cython can also be used when running your +

    To add more entropy, cython can also be used when running your notebooks. It means that Python with the jupyter notebook setup allows you to integrate widely popular softwares and tools for scientific computing. Similarly, the @@ -1069,43 +959,56 @@ capabilities with minimal rewrites of your codes. With its versatility, including symbolic operations, Python offers a unique computational environment. Your jupyter notebook can easily be converted into a nicely rendered PDF file or a Latex file for -further processing. For example, convert to latex as +further processing. For example, convert to latex as +

    -

    - -

    pycod jupyter nbconvert filename.ipynb --to latex 
    -
    -

    -And to add more versatility, the Python package SymPy is a Python library for symbolic mathematics. It aims to become a full-featured computer algebra system (CAS) and is entirely written in Python. + +

    +
    +
    +
    +
    +
    pycod jupyter nbconvert filename.ipynb --to latex 
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    -

    -Finally, if you wish to use the light mark-up language +

    And to add more versatility, the Python package SymPy is a Python library for symbolic mathematics. It aims to become a full-featured computer algebra system (CAS) and is entirely written in Python.

    + +

    Finally, if you wish to use the light mark-up language doconce you can convert a standard ascii text file into various HTML formats, ipython notebooks, latex files, pdf files etc with minimal edits. These lectures were generated using doconce. +

    -











    -

    Numpy examples and Important Matrix and vector handling packages

    -

    -There are several central software libraries for linear algebra and eigenvalue problems. Several of the more +

    There are several central software libraries for linear algebra and eigenvalue problems. Several of the more popular ones have been wrapped into ofter software packages like those from the widely used text Numerical Recipes. The original source codes in many of the available packages are often taken from the widely used software package LAPACK, which follows two other popular packages developed in the 1970s, namely EISPACK and LINPACK. We describe them shortly here. +

    • LINPACK: package for linear equations and least square problems.
    • LAPACK:package for solving symmetric, unsymmetric and generalized eigenvalue problems. From LAPACK's website http://www.netlib.org it is possible to download for free all source codes from this library. Both C/C++ and Fortran versions are available.
    • BLAS (I, II and III): (Basic Linear Algebra Subprograms) are routines that provide standard building blocks for performing basic vector and matrix operations. Blas I is vector operations, II vector-matrix operations and III matrix-matrix operations. Highly parallelized and efficient codes, all available for download from http://www.netlib.org.
    -









    -

    Basic Matrix Features

    -

    Matrix properties reminder

    @@ -1124,15 +1027,14 @@ $$ \end{bmatrix} $$ -

    -The inverse of a matrix is defined by +

    The inverse of a matrix is defined by

    $$ \mathbf{A}^{-1} \cdot \mathbf{A} = I $$ -

    - + +
    @@ -1144,13 +1046,10 @@ $$
    Relations Name matrix elements
    \( A=\left(A^{\dagger}\right )^{-1} \) unitary \( \sum_k a_{ik}a_{jk}^{ < em>}=\sum_k a_{ki}^{ < /em> } a_{kj}=\delta_{ij} \)
    -

    -











    -

    Some famous Matrices

      @@ -1164,16 +1063,13 @@ $$
    • Upper banded with bandwidth \( p \): \( a_{ij}=0 \) for \( i < j+p \)
    • Banded, block upper triangular, block lower triangular....
    -









    -

    More Basic Matrix Features

    -

    Some Equivalent Statements

    -For an \( N\times N \) matrix \( \mathbf{A} \) the following properties are all equivalent +

    For an \( N\times N \) matrix \( \mathbf{A} \) the following properties are all equivalent

    • If the inverse of \( \mathbf{A} \) exists, \( \mathbf{A} \) is nonsingular.
    • @@ -1186,167 +1082,408 @@ For an \( N\times N \) matrix \( \mathbf{A} \) the following properties are all
    -











    -

    Numpy and arrays

    -Numpy provides an easy way to handle arrays in Python. The standard way to import this library is as +

    Numpy provides an easy way to handle arrays in Python. The standard way to import this library is as

    -

    -

    import numpy as np
    -
    -

    -Here follows a simple example where we set up an array of ten elements, all determined by random numbers drawn according to the normal distribution, -

    +

    +
    +
    +
    +
    +
    import numpy as np
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    Here follows a simple example where we set up an array of ten elements, all determined by random numbers drawn according to the normal distribution,

    -
    n = 10
    +
    +
    +
    +
    +
    +
    n = 10
     x = np.random.normal(size=n)
     print(x)
    -
    -

    -We defined a vector \( x \) with \( n=10 \) elements with its values given by the Normal distribution \( N(0,1) \). +

    +
    +
    + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    We defined a vector \( x \) with \( n=10 \) elements with its values given by the Normal distribution \( N(0,1) \). Another alternative is to declare a vector as follows -

    +

    -
    import numpy as np
    +
    +
    +
    +
    +
    +
    import numpy as np
     x = np.array([1, 2, 3])
     print(x)
    -
    -

    -Here we have defined a vector with three elements, with \( x_0=1 \), \( x_1=2 \) and \( x_2=3 \). Note that both Python and C++ +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    Here we have defined a vector with three elements, with \( x_0=1 \), \( x_1=2 \) and \( x_2=3 \). Note that both Python and C++ start numbering array elements from \( 0 \) and on. This means that a vector with \( n \) elements has a sequence of entities \( x_0, x_1, x_2, \dots, x_{n-1} \). We could also let (recommended) Numpy to compute the logarithms of a specific array as -

    +

    -
    import numpy as np
    +
    +
    +
    +
    +
    +
    import numpy as np
     x = np.log(np.array([4, 7, 8]))
     print(x)
    -
    -

    -In the last example we used Numpy's unary function \( np.log \). This function is +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    In the last example we used Numpy's unary function \( np.log \). This function is highly tuned to compute array elements since the code is vectorized and does not require looping. We normaly recommend that you use the Numpy intrinsic functions instead of the corresponding log function from Python's math module. The looping is done explicitely by the np.log function. The alternative, and slower way to compute the logarithms of a vector would be to write +

    -

    -

    import numpy as np
    +
    +
    +
    +
    +
    +
    import numpy as np
     from math import log
     x = np.array([4, 7, 8])
     for i in range(0, len(x)):
         x[i] = log(x[i])
     print(x)
    -
    -

    -We note that our code is much longer already and we need to import the log function from the math module. +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    We note that our code is much longer already and we need to import the log function from the math module. The attentive reader will also notice that the output is \( [1, 1, 2] \). Python interprets automagically our numbers as integers (like the automatic keyword in C++). To change this we could define our array elements to be double precision numbers as -

    +

    -
    import numpy as np
    +
    +
    +
    +
    +
    +
    import numpy as np
     x = np.log(np.array([4, 7, 8], dtype = np.float64))
     print(x)
    -
    -

    -or simply write them as double precision numbers (Python uses 64 bits as default for floating point type variables), that is -

    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    or simply write them as double precision numbers (Python uses 64 bits as default for floating point type variables), that is

    -
    import numpy as np
    +
    +
    +
    +
    +
    +
    import numpy as np
     x = np.log(np.array([4.0, 7.0, 8.0]))
     print(x)
    -
    -

    -To check the number of bytes (remember that one byte contains eight bits for double precision variables), you can use simple use the itemsize functionality (the array \( x \) is actually an object which inherits the functionalities defined in Numpy) as -

    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    To check the number of bytes (remember that one byte contains eight bits for double precision variables), you can use simple use the itemsize functionality (the array \( x \) is actually an object which inherits the functionalities defined in Numpy) as

    -
    import numpy as np
    +
    +
    +
    +
    +
    +
    import numpy as np
     x = np.log(np.array([4.0, 7.0, 8.0]))
     print(x.itemsize)
    -
    -

    -









    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +









    Matrices in Python

    -

    -Having defined vectors, we are now ready to try out matrices. We can +

    Having defined vectors, we are now ready to try out matrices. We can define a \( 3 \times 3 \) real matrix \( \boldsymbol{A} \) as (recall that we user lowercase letters for vectors and uppercase letters for matrices) +

    -

    -

    import numpy as np
    +
    +
    +
    +
    +
    +
    import numpy as np
     A = np.log(np.array([ [4.0, 7.0, 8.0], [3.0, 10.0, 11.0], [4.0, 5.0, 7.0] ]))
     print(A)
    -
    -

    -If we use the shape function we would get \( (3, 3) \) as output, that is verifying that our matrix is a \( 3\times 3 \) matrix. We can slice the matrix and print for example the first column (Python organized matrix elements in a row-major order, see below) as -

    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    If we use the shape function we would get \( (3, 3) \) as output, that is verifying that our matrix is a \( 3\times 3 \) matrix. We can slice the matrix and print for example the first column (Python organized matrix elements in a row-major order, see below) as

    -
    import numpy as np
    +
    +
    +
    +
    +
    +
    import numpy as np
     A = np.log(np.array([ [4.0, 7.0, 8.0], [3.0, 10.0, 11.0], [4.0, 5.0, 7.0] ]))
     # print the first column, row-major order and elements start with 0
     print(A[:,0]) 
    -
    -

    -We can continue this was by printing out other columns or rows. The example here prints out the second column -

    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    We can continue this was by printing out other columns or rows. The example here prints out the second column

    -
    import numpy as np
    +
    +
    +
    +
    +
    +
    import numpy as np
     A = np.log(np.array([ [4.0, 7.0, 8.0], [3.0, 10.0, 11.0], [4.0, 5.0, 7.0] ]))
     # print the first column, row-major order and elements start with 0
     print(A[1,:]) 
    -
    -

    -Numpy contains many other functionalities that allow us to slice, subdivide etc etc arrays. We strongly recommend that you look up the Numpy website for more details. Useful functions when defining a matrix are the np.zeros function which declares a matrix of a given dimension and sets all elements to zero -

    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    Numpy contains many other functionalities that allow us to slice, subdivide etc etc arrays. We strongly recommend that you look up the Numpy website for more details. Useful functions when defining a matrix are the np.zeros function which declares a matrix of a given dimension and sets all elements to zero

    -
    import numpy as np
    +
    +
    +
    +
    +
    +
    import numpy as np
     n = 10
     # define a matrix of dimension 10 x 10 and set all elements to zero
     A = np.zeros( (n, n) )
     print(A) 
    -
    -

    -or initializing all elements to -

    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    or initializing all elements to

    -
    import numpy as np
    +
    +
    +
    +
    +
    +
    import numpy as np
     n = 10
     # define a matrix of dimension 10 x 10 and set all elements to one
     A = np.ones( (n, n) )
     print(A) 
    -
    -

    -or as unitarily distributed random numbers (see the material on random number generators in the statistics part) -

    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    or as unitarily distributed random numbers (see the material on random number generators in the statistics part)

    -
    import numpy as np
    +
    +
    +
    +
    +
    +
    import numpy as np
     n = 10
     # define a matrix of dimension 10 x 10 and set all elements to random numbers with x \in [0, 1]
     A = np.random.rand(n, n)
     print(A) 
    -
    -

    -As we will see throughout these lectures, there are several extremely useful functionalities in Numpy. +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    As we will see throughout these lectures, there are several extremely useful functionalities in Numpy. As an example, consider the discussion of the covariance matrix. Suppose we have defined three vectors \( \boldsymbol{x}, \boldsymbol{y}, \boldsymbol{z} \) with \( n \) elements each. The covariance matrix is defined as +

    $$ \boldsymbol{\Sigma} = \begin{bmatrix} \sigma_{xx} & \sigma_{xy} & \sigma_{xz} \\ \sigma_{yx} & \sigma_{yy} & \sigma_{yz} \\ @@ -1354,13 +1491,14 @@ $$ \end{bmatrix}, $$ -where for example +

    where for example

    $$ \sigma_{xy} =\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})(y_i- \overline{y}). $$ -The Numpy function np.cov calculates the covariance elements using the factor \( 1/(n-1) \) instead of \( 1/n \) since it assumes we do not have the exact mean values. +

    The Numpy function np.cov calculates the covariance elements using the factor \( 1/(n-1) \) instead of \( 1/n \) since it assumes we do not have the exact mean values. The following simple function uses the np.vstack function which takes each vector of dimension \( 1\times n \) and produces a \( 3\times n \) matrix \( \boldsymbol{W} \) +

    $$ \boldsymbol{W} = \begin{bmatrix} x_0 & x_1 & x_2 & \dots & x_{n-2} & x_{n-1} \\ y_0 & y_1 & y_2 & \dots & y_{n-2} & y_{n-1} \\ @@ -1368,17 +1506,21 @@ $$ \end{bmatrix}, $$ -

    -which in turn is converted into into the \( 3\times 3 \) covariance matrix +

    which in turn is converted into into the \( 3\times 3 \) covariance matrix \( \boldsymbol{\Sigma} \) via the Numpy function np.cov(). We note that we can also calculate the mean value of each set of samples \( \boldsymbol{x} \) etc using the Numpy function np.mean(x). We can also extract the eigenvalues of the covariance matrix through the np.linalg.eig() function. +

    -

    -

    # Importing various packages
    +
    +
    +
    +
    +
    +
    # Importing various packages
     import numpy as np
     
     n = 100
    @@ -1393,11 +1535,26 @@ Sigma = np.cov(W)
     print(Sigma)
     Eigvals, Eigvecs = np.linalg.eig(Sigma)
     print(Eigvals)
    -
    -

    - +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    -
    import numpy as np
    +
    +
    +
    +
    +
    +
    import numpy as np
     import matplotlib.pyplot as plt
     from scipy import sparse
     eye = np.eye(4)
    @@ -1408,30 +1565,49 @@ x = np.linspace(-10,'x')
     plt.show()
    -
    -

    -









    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +









    Meet the Pandas

    -

    -



    +

    +
    +

    +
    +

    -

    -Another useful Python package is +

    Another useful Python package is pandas, which is an open source library providing high-performance, easy-to-use data structures and data analysis tools for Python. pandas stands for panel data, a term borrowed from econometrics and is an efficient library for data analysis with an emphasis on tabular data. pandas has two major classes, the DataFrame class with two-dimensional data objects and tabular data organized in columns and the class Series with a focus on one-dimensional data objects. Both classes allow you to index data easily as we will see in the examples below. -pandas allows you also to perform mathematical operations on the data, spanning from simple reshapings of vectors and matrices to statistical operations. +pandas allows you also to perform mathematical operations on the data, spanning from simple reshapings of vectors and matrices to statistical operations. +

    -

    -The following simple example shows how we can, in an easy way make tables of our data. Here we define a data set which includes names, place of birth and date of birth, and displays the data in an easy to read way. We will see repeated use of pandas, in particular in connection with classification of data. +

    The following simple example shows how we can, in an easy way make tables of our data. Here we define a data set which includes names, place of birth and date of birth, and displays the data in an easy to read way. We will see repeated use of pandas, in particular in connection with classification of data.

    -

    -

    import pandas as pd
    +
    +
    +
    +
    +
    +
    import pandas as pd
     from IPython.display import display
     data = {'First Name': ["Frodo", "Bilbo", "Aragorn II", "Samwise"],
             'Last Name': ["Baggins", "Baggins","Elessar","Gamgee"],
    @@ -1440,45 +1616,115 @@ data = {'First Name': [
    +    
    +
    +
    +
    +
    +
    +
    +
    + +

    In the above we have imported pandas with the shorthand pd, the latter has become the standard way we import pandas. We make then a list of various variables and reorganize the aboves lists into a DataFrame and then print out a neat table with specific column labels as Name, place of birth and date of birth. Displaying these results, we see that the indices are given by the default numbers from zero to three. pandas is extremely flexible and we can easily change the above indices by defining a new type of indexing as -

    +

    -
    data_pandas = pd.DataFrame(data,index=['Frodo','Bilbo','Aragorn','Sam'])
    +
    +
    +
    +
    +
    +
    data_pandas = pd.DataFrame(data,index=['Frodo','Bilbo','Aragorn','Sam'])
     display(data_pandas)
    -
    -

    -Thereafter we display the content of the row which begins with the index Aragorn -

    +

    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    Thereafter we display the content of the row which begins with the index Aragorn

    -
    display(data_pandas.loc['Aragorn'])
    -
    -

    -We can easily append data to this, for example -

    +

    +
    +
    +
    +
    +
    display(data_pandas.loc['Aragorn'])
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    We can easily append data to this, for example

    -
    new_hobbit = {'First Name': ["Peregrin"],
    +
    +
    +
    +
    +
    +
    new_hobbit = {'First Name': ["Peregrin"],
                   'Last Name': ["Took"],
                   'Place of birth': ["Shire"],
                   'Date of Birth T.A.': [2990]
                   }
     data_pandas=data_pandas.append(pd.DataFrame(new_hobbit, index=['Pippin']))
     display(data_pandas)
    -
    -

    -Here are other examples where we use the DataFrame functionality to handle arrays, now with more interesting features for us, namely numbers. We set up a matrix +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    Here are other examples where we use the DataFrame functionality to handle arrays, now with more interesting features for us, namely numbers. We set up a matrix of dimensionality \( 10\times 5 \) and compute the mean value and standard deviation of each column. Similarly, we can perform mathematial operations like squaring the matrix elements and many other operations. -

    +

    -
    import numpy as np
    +
    +
    +
    +
    +
    +
    import numpy as np
     import pandas as pd
     from IPython.display import display
     np.random.seed(100)
    @@ -1491,13 +1737,30 @@ display(df)
     print(df.mean())
     print(df.std())
     display(df**2)
    -
    -

    -Thereafter we can select specific columns only and plot final results -

    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    Thereafter we can select specific columns only and plot final results

    -
    df.columns = ['First', 'Second', 'Third', 'Fourth', 'Fifth']
    +
    +
    +
    +
    +
    +
    df.columns = ['First', 'Second', 'Third', 'Fourth', 'Fifth']
     df.index = np.arange(10)
     
     display(df)
    @@ -1515,49 +1778,71 @@ plt.show()
     
     df.plot.bar(figsize=(10,6), rot=15)
     plt.show()
    -
    -

    -We can produce a \( 4\times 4 \) matrix -

    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    We can produce a \( 4\times 4 \) matrix

    -
    b = np.arange(16).reshape((4,4))
    +
    +
    +
    +
    +
    +
    b = np.arange(16).reshape((4,4))
     print(b)
     df1 = pd.DataFrame(b)
     print(df1)
    -
    -

    -and many other operations. +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + -

    -The Series class is another important class included in +

    and many other operations.

    + +

    The Series class is another important class included in pandas. You can view it as a specialization of DataFrame but where we have just a single column of data. It shares many of the same features as _DataFrame. As with DataFrame, most operations are vectorized, achieving thereby a high performance when dealing with computations of arrays, in particular labeled arrays. As we will see below it leads also to a very concice code close to the mathematical operations we may be interested in. -For multidimensional arrays, we recommend strongly xarray. xarray has much of the same flexibility as pandas, but allows for the extension to higher dimensions than two. We will see examples later of the usage of both pandas and xarray. +For multidimensional arrays, we recommend strongly xarray. xarray has much of the same flexibility as pandas, but allows for the extension to higher dimensions than two. We will see examples later of the usage of both pandas and xarray. +

    -











    -

    Friday August 27

    -

    -"Video of Lecture August 27, 2021":"https://www.uio.no/studier/emner/matnat/fys/FYS-STK4155/h21/forelesningsvideoer/LectureThursdayAugust27.mp4?vrtx=view-as-webpage +

    "Video of Lecture August 27, 2021":"https://www.uio.no/studier/emner/matnat/fys/FYS-STK4155/h21/forelesningsvideoer/LectureThursdayAugust27.mp4?vrtx=view-as-webpage

    -

    -Video of Lecture from fall 2020 and Handwritten notes +

    Video of Lecture from fall 2020 and Handwritten notes

    -











    +

    Simple linear regression model using scikit-learn

    -

    Simple linear regression model using scikit-learn

    +

    We start with perhaps our simplest possible example, using Scikit-Learn to perform linear regression analysis on a data set produced by us.

    -

    -We start with perhaps our simplest possible example, using Scikit-Learn to perform linear regression analysis on a data set produced by us. - -

    -What follows is a simple Python code where we have defined a function +

    What follows is a simple Python code where we have defined a function \( y \) in terms of the variable \( x \). Both are defined as vectors with \( 100 \) entries. The numbers in the vector \( \boldsymbol{x} \) are given by random numbers generated with a uniform distribution with entries @@ -1565,9 +1850,9 @@ by random numbers generated with a uniform distribution with entries later). These values are then used to define a function \( y(x) \) (tabulated again as a vector) with a linear dependence on \( x \) plus a random noise added via the normal distribution. +

    -

    -The Numpy functions are imported used the import numpy as np +

    The Numpy functions are imported used the import numpy as np statement and the random number generator for the uniform distribution is called using the function np.random.rand(), where we specificy that we want \( 100 \) random variables. Using Numpy we define @@ -1576,13 +1861,13 @@ our case. With the Numpy function randn() we can compute random numbers with the normal distribution (mean value \( \mu \) equal to zero and variance \( \sigma^2 \) set to one) and produce the values of \( y \) assuming a linear dependence as function of \( x \) +

    $$ y = 2x+N(0,1), $$ -

    -where \( N(0,1) \) represents random numbers generated by the normal +

    where \( N(0,1) \) represents random numbers generated by the normal distribution. From Scikit-Learn we import then the LinearRegression functionality and make a prediction \( \tilde{y} = \alpha + \beta x \) using the function fit(x,y). We call the set of @@ -1590,22 +1875,26 @@ data \( (\boldsymbol{x},\boldsymbol{y}) \) for our training data. The Python pac scikit-learn has also a functionality which extracts the above fitting parameters \( \alpha \) and \( \beta \) (see below). Later we will distinguish between training data and test data. +

    -

    -For plotting we use the Python package +

    For plotting we use the Python package matplotlib which produces publication quality figures. Feel free to explore the extensive gallery of examples. In this example we plot our original values of \( x \) and \( y \) as well as the prediction ypredict (\( \tilde{y} \)), which attempts at fitting our data with a straight line. +

    -

    -The Python code follows here. -

    +

    The Python code follows here.

    -
    # Importing various packages
    +
    +
    +
    +
    +
    +
    # Importing various packages
     import numpy as np
     import matplotlib.pyplot as plt
     from sklearn.linear_model import LinearRegression
    @@ -1624,9 +1913,22 @@ plt.xlabel(r'$x$')
     plt.ylabel(r'$y$')
     plt.title(r'Simple Linear Regression')
     plt.show()
    -
    -

    -This example serves several aims. It allows us to demonstrate several +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    This example serves several aims. It allows us to demonstrate several aspects of data analysis and later machine learning algorithms. The immediate visualization shows that our linear fit is not impressive. It goes through the data points, but there are many @@ -1634,38 +1936,38 @@ outliers which are not reproduced by our linear regression. We could now play around with this small program and change for example the factor in front of \( x \) and the normal distribution. Try to change the function \( y \) to +

    $$ y = 10x+0.01 \times N(0,1), $$ -

    -where \( x \) is defined as before. Does the fit look better? Indeed, by +

    where \( x \) is defined as before. Does the fit look better? Indeed, by reducing the role of the noise given by the normal distribution we see immediately that our linear prediction seemingly reproduces better the training set. However, this testing 'by the eye' is obviouly not satisfactory in the long run. Here we have only defined the training data and our model, and have not discussed a more rigorous approach to the cost function. +

    -

    -We need more rigorous criteria in defining whether we have succeeded or +

    We need more rigorous criteria in defining whether we have succeeded or not in modeling our training data. You will be surprised to see that many scientists seldomly venture beyond this 'by the eye' approach. A standard approach for the cost function is the so-called \( \chi^2 \) function (a variant of the mean-squared error (MSE)) +

    $$ \chi^2 = \frac{1}{n} \sum_{i=0}^{n-1}\frac{(y_i-\tilde{y}_i)^2}{\sigma_i^2}, $$ -

    -where \( \sigma_i^2 \) is the variance (to be defined later) of the entry +

    where \( \sigma_i^2 \) is the variance (to be defined later) of the entry \( y_i \). We may not know the explicit value of \( \sigma_i^2 \), it serves however the aim of scaling the equations and make the cost function -dimensionless. +dimensionless. +

    -

    -Minimizing the cost function is a central aspect of +

    Minimizing the cost function is a central aspect of our discussions to come. Finding its minima as function of the model parameters (\( \alpha \) and \( \beta \) in our case) will be a recurring theme in these series of lectures. Essentially all machine learning @@ -1678,30 +1980,34 @@ employed are various variants of gradient methods. These will be discussed in more detail later. Again, you'll be surprised to hear that many practitioners minimize the above function ''by the eye', popularly dubbed as 'chi by the eye'. That is, change a parameter and see (visually and numerically) that -the \( \chi^2 \) function becomes smaller. +the \( \chi^2 \) function becomes smaller. +

    -

    -There are many ways to define the cost function. A simpler approach is to look at the relative difference between the training data and the predicted data, that is we define +

    There are many ways to define the cost function. A simpler approach is to look at the relative difference between the training data and the predicted data, that is we define the relative error (why would we prefer the MSE instead of the relative error?) as +

    $$ \epsilon_{\mathrm{relative}}= \frac{\vert \boldsymbol{y} -\boldsymbol{\tilde{y}}\vert}{\vert \boldsymbol{y}\vert}. $$ -

    -The squared cost function results in an arithmetic mean-unbiased +

    The squared cost function results in an arithmetic mean-unbiased estimator, and the absolute-value cost function results in a median-unbiased estimator (in the one-dimensional case, and a geometric median-unbiased estimator for the multi-dimensional case). The squared cost function has the disadvantage that it has the tendency to be dominated by outliers. +

    -

    -We can modify easily the above Python code and plot the relative error instead -

    +

    We can modify easily the above Python code and plot the relative error instead

    -
    import numpy as np
    +
    +
    +
    +
    +
    +
    import numpy as np
     import matplotlib.pyplot as plt
     from sklearn.linear_model import LinearRegression
     
    @@ -1717,26 +2023,44 @@ plt.xlabel(r'$x$')
     plt.ylabel(r'$\epsilon_{\mathrm{relative}}$')
     plt.title(r'Relative error')
     plt.show()
    -
    -

    -Depending on the parameter in front of the normal distribution, we may +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    Depending on the parameter in front of the normal distribution, we may have a small or larger relative error. Try to play around with different training data sets and study (graphically) the value of the relative error. +

    -

    -As mentioned above, Scikit-Learn has an impressive functionality. +

    As mentioned above, Scikit-Learn has an impressive functionality. We can for example extract the values of \( \alpha \) and \( \beta \) and their error estimates, or the variance and standard deviation and many -other properties from the statistical data analysis. +other properties from the statistical data analysis. +

    -

    -Here we show an +

    Here we show an example of the functionality of Scikit-Learn. -

    +

    -
    import numpy as np 
    +
    +
    +
    +
    +
    +
    import numpy as np 
     import matplotlib.pyplot as plt 
     from sklearn.linear_model import LinearRegression 
     from sklearn.metrics import mean_squared_error, r2_score, mean_squared_log_error, mean_absolute_error
    @@ -1763,84 +2087,101 @@ plt.xlabel(r'$x$')
     plt.ylabel(r'$y$')
     plt.title(r'Linear Regression fit ')
     plt.show()
    -
    -

    -The function coef gives us the parameter \( \beta \) of our fit while intercept yields +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    The function coef gives us the parameter \( \beta \) of our fit while intercept yields \( \alpha \). Depending on the constant in front of the normal distribution, we get values near or far from \( \alpha =2 \) and \( \beta =5 \). Try to play around with different parameters in front of the normal distribution. The function meansquarederror gives us the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error or loss defined as +

    $$ MSE(\boldsymbol{y},\boldsymbol{\tilde{y}}) = \frac{1}{n} \sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, $$ -

    -The smaller the value, the better the fit. Ideally we would like to +

    The smaller the value, the better the fit. Ideally we would like to have an MSE equal zero. The attentive reader has probably recognized this function as being similar to the \( \chi^2 \) function defined above. +

    -

    -The r2score function computes \( R^2 \), the coefficient of +

    The r2score function computes \( R^2 \), the coefficient of determination. It provides a measure of how well future samples are likely to be predicted by the model. Best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse). A constant model that always predicts the expected value of \( \boldsymbol{y} \), disregarding the input features, would get a \( R^2 \) score of \( 0.0 \). +

    -

    -If \( \tilde{\boldsymbol{y}}_i \) is the predicted value of the \( i-th \) sample and \( y_i \) is the corresponding true value, then the score \( R^2 \) is defined as +

    If \( \tilde{\boldsymbol{y}}_i \) is the predicted value of the \( i-th \) sample and \( y_i \) is the corresponding true value, then the score \( R^2 \) is defined as

    $$ R^2(\boldsymbol{y}, \tilde{\boldsymbol{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2}, $$ -where we have defined the mean value of \( \boldsymbol{y} \) as +

    where we have defined the mean value of \( \boldsymbol{y} \) as

    $$ \bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. $$ -Another quantity taht we will meet again in our discussions of regression analysis is +

    Another quantity taht we will meet again in our discussions of regression analysis is the mean absolute error (MAE), a risk metric corresponding to the expected value of the absolute error loss or what we call the \( l1 \)-norm loss. In our discussion above we presented the relative error. The MAE is defined as follows +

    $$ \text{MAE}(\boldsymbol{y}, \boldsymbol{\tilde{y}}) = \frac{1}{n} \sum_{i=0}^{n-1} \left| y_i - \tilde{y}_i \right|. $$ -We present the +

    We present the squared logarithmic (quadratic) error +

    $$ \text{MSLE}(\boldsymbol{y}, \boldsymbol{\tilde{y}}) = \frac{1}{n} \sum_{i=0}^{n - 1} (\log_e (1 + y_i) - \log_e (1 + \tilde{y}_i) )^2, $$ -

    -where \( \log_e (x) \) stands for the natural logarithm of \( x \). This error +

    where \( \log_e (x) \) stands for the natural logarithm of \( x \). This error estimate is best to use when targets having exponential growth, such as population counts, average sales of a commodity over a span of -years etc. +years etc. +

    -

    -Finally, another cost function is the Huber cost function used in robust regression. +

    Finally, another cost function is the Huber cost function used in robust regression.

    -

    -The rationale behind this possible cost function is its reduced +

    The rationale behind this possible cost function is its reduced sensitivity to outliers in the data set. In our discussions on dimensionality reduction and normalization of data we will meet other ways of dealing with outliers. +

    -

    -The Huber cost function is defined as +

    The Huber cost function is defined as

    $$ H_{\delta}(\boldsymbol{a})=\left\{\begin{array}{cc}\frac{1}{2} \boldsymbol{a}^{2}& \text{for }|\boldsymbol{a}|\leq \delta\\ \delta (|\boldsymbol{a}|-\frac{1}{2}\delta ),&\text{otherwise}.\end{array}\right. $$ -Here \( \boldsymbol{a}=\boldsymbol{y} - \boldsymbol{\tilde{y}} \). +

    Here \( \boldsymbol{a}=\boldsymbol{y} - \boldsymbol{\tilde{y}} \).

    -

    -We will discuss in more detail these and other functions in the +

    We will discuss in more detail these and other functions in the various lectures. We conclude this part with another example. Instead of a linear \( x \)-dependence we study now a cubic polynomial and use the polynomial regression analysis tools of scikit-learn. +

    -

    -

    import matplotlib.pyplot as plt
    +
    +
    +
    +
    +
    +
    import matplotlib.pyplot as plt
     import numpy as np
     import random
     from sklearn.linear_model import Ridge
    @@ -1870,74 +2211,85 @@ plt.show()
         return abs(np.sum(err))/len(err)
     
     print (error(y))
    -
    - +
    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    +

    To our real data: nuclear binding energies. Brief reminder on masses and binding energies

    -

    -Let us now dive into nuclear physics and remind ourselves briefly about some basic features about binding +

    Let us now dive into nuclear physics and remind ourselves briefly about some basic features about binding energies. A basic quantity which can be measured for the ground states of nuclei is the atomic mass \( M(N, Z) \) of the neutral atom with -atomic mass number \( A \) and charge \( Z \). The number of neutrons is \( N \). There are indeed several sophisticated experiments worldwide which allow us to measure this quantity to high precision (parts per million even). +atomic mass number \( A \) and charge \( Z \). The number of neutrons is \( N \). There are indeed several sophisticated experiments worldwide which allow us to measure this quantity to high precision (parts per million even). +

    -

    -Atomic masses are usually tabulated in terms of the mass excess defined by +

    Atomic masses are usually tabulated in terms of the mass excess defined by

    $$ \Delta M(N, Z) = M(N, Z) - uA, $$ -where \( u \) is the Atomic Mass Unit +

    where \( u \) is the Atomic Mass Unit

    $$ u = M(^{12}\mathrm{C})/12 = 931.4940954(57) \hspace{0.1cm} \mathrm{MeV}/c^2. $$ -The nucleon masses are +

    The nucleon masses are

    $$ m_p = 1.00727646693(9)u, $$ -and +

    and

    $$ m_n = 939.56536(8)\hspace{0.1cm} \mathrm{MeV}/c^2 = 1.0086649156(6)u. $$ -

    -In the 2016 mass evaluation of by W.J.Huang, G.Audi, M.Wang, F.G.Kondev, S.Naimi and X.Xu +

    In the 2016 mass evaluation of by W.J.Huang, G.Audi, M.Wang, F.G.Kondev, S.Naimi and X.Xu there are data on masses and decays of 3437 nuclei. +

    -

    -The nuclear binding energy is defined as the energy required to break +

    The nuclear binding energy is defined as the energy required to break up a given nucleus into its constituent parts of \( N \) neutrons and \( Z \) protons. In terms of the atomic masses \( M(N, Z) \) the binding energy is defined by +

    $$ BE(N, Z) = ZM_H c^2 + Nm_n c^2 - M(N, Z)c^2 , $$ -where \( M_H \) is the mass of the hydrogen atom and \( m_n \) is the mass of the neutron. +

    where \( M_H \) is the mass of the hydrogen atom and \( m_n \) is the mass of the neutron. In terms of the mass excess the binding energy is given by +

    $$ BE(N, Z) = Z\Delta_H c^2 + N\Delta_n c^2 -\Delta(N, Z)c^2 , $$ -where \( \Delta_H c^2 = 7.2890 \) MeV and \( \Delta_n c^2 = 8.0713 \) MeV. +

    where \( \Delta_H c^2 = 7.2890 \) MeV and \( \Delta_n c^2 = 8.0713 \) MeV.

    -

    -A popular and physically intuitive model which can be used to parametrize +

    A popular and physically intuitive model which can be used to parametrize the experimental binding energies as function of \( A \), is the so-called liquid drop model. The ansatz is based on the following expression +

    $$ BE(N,Z) = a_1A-a_2A^{2/3}-a_3\frac{Z^2}{A^{1/3}}-a_4\frac{(N-Z)^2}{A}, $$ -

    -where \( A \) stands for the number of nucleons and the $a_i$s are parameters which are determined by a fit -to the experimental data. +

    where \( A \) stands for the number of nucleons and the $a_i$s are parameters which are determined by a fit +to the experimental data. +

    -

    -To arrive at the above expression we have assumed that we can make the following assumptions: +

    To arrive at the above expression we have assumed that we can make the following assumptions:

    • There is a volume term \( a_1A \) proportional with the number of nucleons (the energy is also an extensive quantity). When an assembly of nucleons of the same size is packed together into the smallest volume, each interior nucleon has a certain number of other nucleons in contact with it. This contribution is proportional to the volume.
    • @@ -1945,24 +2297,26 @@ To arrive at the above expression we have assumed that we can make the following
    • There is a Coulomb energy term \( a_3\frac{Z^2}{A^{1/3}} \). The electric repulsion between each pair of protons in a nucleus yields less binding.
    • There is an asymmetry term \( a_4\frac{(N-Z)^2}{A} \). This term is associated with the Pauli exclusion principle and reflects the fact that the proton-neutron interaction is more attractive on the average than the neutron-neutron and proton-proton interactions.
    - -We could also add a so-called pairing term, which is a correction term that +

    We could also add a so-called pairing term, which is a correction term that arises from the tendency of proton pairs and neutron pairs to -occur. An even number of particles is more stable than an odd number. - +occur. An even number of particles is more stable than an odd number. +

    Organizing our data

    -

    -Let us start with reading and organizing our data. +

    Let us start with reading and organizing our data. We start with the compilation of masses and binding energies from 2016. After having downloaded this file to our own computer, we are now ready to read the file and start structuring our data. +

    -

    -We start with preparing folders for storing our calculations and the data file over masses and binding energies. We import also various modules that we will find useful in order to present various Machine Learning methods. Here we focus mainly on the functionality of scikit-learn. -

    +

    We start with preparing folders for storing our calculations and the data file over masses and binding energies. We import also various modules that we will find useful in order to present various Machine Learning methods. Here we focus mainly on the functionality of scikit-learn.

    -
    # Common imports
    +
    +
    +
    +
    +
    +
    # Common imports
     import numpy as np
     import pandas as pd
     import matplotlib.pyplot as plt
    @@ -1995,13 +2349,30 @@ DATA_ID = "DataFiles/"
         plt.savefig(image_path(fig_id) + ".png", format='png')
     
     infile = open(data_path("MassEval2016.dat"),'r')
    -
    -

    -Before we proceed, we define also a function for making our plots. You can obviously avoid this and simply set up various matplotlib commands every time you need them. You may however find it convenient to collect all such commands in one function and simply call this function. -

    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    Before we proceed, we define also a function for making our plots. You can obviously avoid this and simply set up various matplotlib commands every time you need them. You may however find it convenient to collect all such commands in one function and simply call this function.

    -
    from pylab import plt, mpl
    +
    +
    +
    +
    +
    +
    from pylab import plt, mpl
     plt.style.use('seaborn')
     mpl.rcParams['font.family'] = 'serif'
     
    @@ -2012,20 +2383,37 @@ mpl.rcParams['font.family'] = 0])
             plt.ylabel(axlabels[1])
         plt.legend(loc=0)
    -
    -

    -Our next step is to read the data on experimental binding energies and +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    Our next step is to read the data on experimental binding energies and reorganize them as functions of the mass number \( A \), the number of protons \( Z \) and neutrons \( N \) using pandas. Before we do this it is always useful (unless you have a binary file or other types of compressed data) to actually open the file and simply take a look at it! +

    -

    -In particular, the program that outputs the final nuclear masses is written in Fortran with a specific format. It means that we need to figure out the format and which columns contain the data we are interested in. Pandas comes with a function that reads formatted output. After having admired the file, we are now ready to start massaging it with pandas. The file begins with some basic format information. -

    +

    In particular, the program that outputs the final nuclear masses is written in Fortran with a specific format. It means that we need to figure out the format and which columns contain the data we are interested in. Pandas comes with a function that reads formatted output. After having admired the file, we are now ready to start massaging it with pandas. The file begins with some basic format information.

    -
    """                                                                                                                         
    +
    +
    +
    +
    +
    +
    """                                                                                                                         
     This is taken from the data file of the mass 2016 evaluation.                                                               
     All files are 3436 lines long with 124 character per line.                                                                  
            Headers are 39 lines long.                                                                                           
    @@ -2035,17 +2423,35 @@ In particular, the program that outputs the final nuclear masses is written in F
        widths=(1,3,5,5,5,1,3,4,1,13,11,11,9,1,2,11,9,1,3,1,12,11,1),                                                            
        Pandas has also a variable header, with length 39 in this case.                                                          
     """
    -
    -

    -The data we are interested in are in columns 2, 3, 4 and 11, giving us +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    The data we are interested in are in columns 2, 3, 4 and 11, giving us the number of neutrons, protons, mass numbers and binding energies, respectively. We add also for the sake of completeness the element name. The data are in fixed-width formatted lines and we will covert them into the pandas DataFrame structure. +

    -

    -

    # Read the experimental data with Pandas
    +
    +
    +
    +
    +
    +
    # Read the experimental data with Pandas
     Masses = pd.read_fwf(infile, usecols=(2,3,4,6,11),
                   names=('N', 'Z', 'A', 'Element', 'Ebinding'),
                   widths=(1,3,5,5,5,1,3,4,1,13,11,11,9,1,2,11,9,1,3,1,12,11,1),
    @@ -2063,58 +2469,129 @@ Masses['Ebinding'] /= 'A')
     # Find the rows of the grouped DataFrame with the maximum binding energy.
     Masses = Masses.apply(lambda t: t[t.Ebinding==t.Ebinding.max()])
    -
    -

    -We have now read in the data, grouped them according to the variables we are interested in. +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    We have now read in the data, grouped them according to the variables we are interested in. We see how easy it is to reorganize the data using pandas. If we were to do these operations in C/C++ or Fortran, we would have had to write various functions/subroutines which perform the above reorganizations for us. Having reorganized the data, we can now start to make some simple fits using both the functionalities in numpy and -Scikit-Learn afterwards. +Scikit-Learn afterwards. +

    -

    -Now we define five variables which contain +

    Now we define five variables which contain the number of nucleons \( A \), the number of protons \( Z \) and the number of neutrons \( N \), the element name and finally the energies themselves. -

    +

    -
    A = Masses['A']
    +
    +
    +
    +
    +
    +
    A = Masses['A']
     Z = Masses['Z']
     N = Masses['N']
     Element = Masses['Element']
     Energies = Masses['Ebinding']
     print(Masses)
    -
    -

    -The next step, and we will define this mathematically later, is to set up the so-called design matrix. We will throughout call this matrix \( \boldsymbol{X} \). +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    The next step, and we will define this mathematically later, is to set up the so-called design matrix. We will throughout call this matrix \( \boldsymbol{X} \). It has dimensionality \( p\times n \), where \( n \) is the number of data points and \( p \) are the so-called predictors. In our case here they are given by the number of polynomials in \( A \) we wish to include in the fit. -

    +

    -
    # Now we set up the design matrix X
    +
    +
    +
    +
    +
    +
    # Now we set up the design matrix X
     X = np.zeros((len(A),5))
     X[:,0] = 1
     X[:,1] = A
     X[:,2] = A**(2.0/3.0)
     X[:,3] = A**(-1.0/3.0)
     X[:,4] = A**(-1.0)
    -
    -

    -With scikitlearn we are now ready to use linear regression and fit our data. -

    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    With scikitlearn we are now ready to use linear regression and fit our data.

    -
    clf = skl.LinearRegression().fit(X, Energies)
    +
    +
    +
    +
    +
    +
    clf = skl.LinearRegression().fit(X, Energies)
     fity = clf.predict(X)
    -
    -

    -Pretty simple! +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    Pretty simple! Now we can print measures of how our fit is doing, the coefficients from the fits and plot the final fit together with our data. -

    +

    -
    # The mean squared error                               
    +
    +
    +
    +
    +
    +
    # The mean squared error                               
     print("Mean squared error: %.2f" % mean_squared_error(Energies, fity))
     # Explained variance score: 1 is perfect prediction                                 
     print('Variance score: %.2f' % r2_score(Energies, fity))
    @@ -2134,17 +2611,32 @@ ax.plot(Masses['A'], Masses["Masses2016")
     plt.show()
    -
    - +
    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    +

    Seeing the wood for the trees

    -

    -As a teaser, let us now see how we can do this with decision trees using scikit-learn. Later we will switch to so-called random forests! +

    As a teaser, let us now see how we can do this with decision trees using scikit-learn. Later we will switch to so-called random forests!

    -

    -

    #Decision Tree Regression
    +
    +
    +
    +
    +
    +
    #Decision Tree Regression
     from sklearn.tree import DecisionTreeRegressor
     regr_1=DecisionTreeRegressor(max_depth=5)
     regr_2=DecisionTreeRegressor(max_depth=7)
    @@ -2173,16 +2665,32 @@ save_fig("Masses2016Trees")
     plt.show()
     print(Masses)
     print(np.mean( (Energies-y_1)**2))
    -
    - +
    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    +

    And what about using neural networks?

    - -The seaborn package allows us to visualize data in an efficient way. Note that we use scikit-learn's multi-layer perceptron (or feed forward neural network) +

    The seaborn package allows us to visualize data in an efficient way. Note that we use scikit-learn's multi-layer perceptron (or feed forward neural network) functionality. -

    +

    -
    from sklearn.neural_network import MLPRegressor
    +
    +
    +
    +
    +
    +
    from sklearn.neural_network import MLPRegressor
     from sklearn.metrics import accuracy_score
     import seaborn as sns
     
    @@ -2211,30 +2719,38 @@ ax.set_title("Training Accuracy")
     ax.set_ylabel("$\eta$")
     ax.set_xlabel("$\lambda$")
     plt.show()
    -
    - +
    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    +

    A first summary

    -

    -The aim behind these introductory words was to present to you various +

    The aim behind these introductory words was to present to you various Python libraries and their functionalities, in particular libraries like numpy, pandas, xarray and matplotlib and other that make our life much easier -in handling various data sets and visualizing data. +in handling various data sets and visualizing data. +

    -

    -Furthermore, +

    Furthermore, Scikit-Learn allows us with few lines of code to implement popular Machine Learning algorithms for supervised learning. Later we will meet Tensorflow, a powerful library for deep learning. Now it is time to dive more into the details of various methods. We will start with linear regression and try to take a deeper look at what it entails. +

    -











    -

    Why Linear Regression (aka Ordinary Least Squares and family)

    -

    -Fitting a continuous function with linear parameterization in terms of the parameters \( \boldsymbol{\beta} \). - +

    Fitting a continuous function with linear parameterization in terms of the parameters \( \boldsymbol{\beta} \).

    • Method of choice for fitting a continuous function!
    • Gives an excellent introduction to central Machine Learning features with understandable pedagogical links to other methods like Neural Networks, Support Vector Machines etc
    • @@ -2246,50 +2762,42 @@ Fitting a continuous function with linear parameterization in terms of the param
    • Allows for easy hands-on understanding of gradient descent methods
    • and many more features
    - -For more discussions of Ridge and Lasso regression, Wessel van Wieringen's article is highly recommended. +

    For more discussions of Ridge and Lasso regression, Wessel van Wieringen's article is highly recommended. Similarly, Mehta et al's article is also recommended. +

    -











    -

    Regression analysis, overarching aims

    -

    -Regression modeling deals with the description of the sampling distribution of a given random variable \( y \) and how it varies as function of another variable or a set of such variables \( \boldsymbol{x} =[x_0, x_1,\dots, x_{n-1}]^T \). -The first variable is called the dependent, the outcome or the response variable while the set of variables \( \boldsymbol{x} \) is called the independent variable, or the predictor variable or the explanatory variable. - -

    -A regression model aims at finding a likelihood function \( p(\boldsymbol{y}\vert \boldsymbol{x}) \), that is the conditional distribution for \( \boldsymbol{y} \) with a given \( \boldsymbol{x} \). The estimation of \( p(\boldsymbol{y}\vert \boldsymbol{x}) \) is made using a data set with +

    Regression modeling deals with the description of the sampling distribution of a given random variable \( y \) and how it varies as function of another variable or a set of such variables \( \boldsymbol{x} =[x_0, x_1,\dots, x_{n-1}]^T \). +The first variable is called the dependent, the outcome or the response variable while the set of variables \( \boldsymbol{x} \) is called the independent variable, or the predictor variable or the explanatory variable. +

    +

    A regression model aims at finding a likelihood function \( p(\boldsymbol{y}\vert \boldsymbol{x}) \), that is the conditional distribution for \( \boldsymbol{y} \) with a given \( \boldsymbol{x} \). The estimation of \( p(\boldsymbol{y}\vert \boldsymbol{x}) \) is made using a data set with

    • \( n \) cases \( i = 0, 1, 2, \dots, n-1 \)
    • Response (target, dependent or outcome) variable \( y_i \) with \( i = 0, 1, 2, \dots, n-1 \)
    • \( p \) so-called explanatory (independent or predictor) variables \( \boldsymbol{x}_i=[x_{i0}, x_{i1}, \dots, x_{ip-1}] \) with \( i = 0, 1, 2, \dots, n-1 \) and explanatory variables running from \( 0 \) to \( p-1 \). See below for more explicit examples.
    - - The goal of the regression analysis is to extract/exploit relationship between \( \boldsymbol{y} \) and \( \boldsymbol{x} \) in or to infer causal dependencies, approximations to the likelihood functions, functional relationships and to make predictions, making fits and many other things. +

    The goal of the regression analysis is to extract/exploit relationship between \( \boldsymbol{y} \) and \( \boldsymbol{x} \) in or to infer causal dependencies, approximations to the likelihood functions, functional relationships and to make predictions, making fits and many other things.

    -











    -

    Regression analysis, overarching aims II

    -

    -Consider an experiment in which \( p \) characteristics of \( n \) samples are +

    Consider an experiment in which \( p \) characteristics of \( n \) samples are measured. The data from this experiment, for various explanatory variables \( p \) are normally represented by a matrix \( \mathbf{X} \). +

    -

    -The matrix \( \mathbf{X} \) is called the design +

    The matrix \( \mathbf{X} \) is called the design matrix. Additional information of the samples is available in the form of \( \boldsymbol{y} \) (also as above). The variable \( \boldsymbol{y} \) is generally referred to as the response variable. The aim of @@ -2299,73 +2807,62 @@ f(\mathbf{X}_{i,\ast}) \). When no prior knowledge on the form of \( f(\cdot) \) is available, it is common to assume a linear relationship between \( \boldsymbol{X} \) and \( \boldsymbol{y} \). This assumption gives rise to the linear regression model where \( \boldsymbol{\beta} = [\beta_0, \ldots, -\beta_{p-1}]^{T} \) are the regression parameters. - -

    -Linear regression gives us a set of analytical equations for the parameters \( \beta_j \). - +\beta_{p-1}]^{T} \) are the regression parameters. +

    +

    Linear regression gives us a set of analytical equations for the parameters \( \beta_j \).

    -











    -

    Examples

    -In order to understand the relation among the predictors \( p \), the set of data \( n \) and the target (outcome, output etc) \( \boldsymbol{y} \), -consider the model we discussed for describing nuclear binding energies. +

    In order to understand the relation among the predictors \( p \), the set of data \( n \) and the target (outcome, output etc) \( \boldsymbol{y} \), +consider the model we discussed for describing nuclear binding energies. +

    -

    -There we assumed that we could parametrize the data using a polynomial approximation based on the liquid drop model. +

    There we assumed that we could parametrize the data using a polynomial approximation based on the liquid drop model. Assuming +

    $$ BE(A) = a_0+a_1A+a_2A^{2/3}+a_3A^{-1/3}+a_4A^{-1}, $$ -we have five predictors, that is the intercept, the \( A \) dependent term, the \( A^{2/3} \) term and the \( A^{-1/3} \) and \( A^{-1} \) terms. +

    we have five predictors, that is the intercept, the \( A \) dependent term, the \( A^{2/3} \) term and the \( A^{-1/3} \) and \( A^{-1} \) terms. This gives \( p=0,1,2,3,4 \). Furthermore we have \( n \) entries for each predictor. It means that our design matrix is a \( p\times n \) matrix \( \boldsymbol{X} \). +

    -

    -Here the predictors are based on a model we have made. A popular data set which is widely encountered in ML applications is the -so-called credit card default data from Taiwan. The data set contains data on \( n=30000 \) credit card holders with predictors like gender, marital status, age, profession, education, etc. In total there are \( 24 \) such predictors or attributes leading to a design matrix of dimensionality \( 24 \times 30000 \). This is however a classification problem and we will come back to it when we discuss Logistic Regression. - - +

    Here the predictors are based on a model we have made. A popular data set which is widely encountered in ML applications is the +so-called credit card default data from Taiwan. The data set contains data on \( n=30000 \) credit card holders with predictors like gender, marital status, age, profession, education, etc. In total there are \( 24 \) such predictors or attributes leading to a design matrix of dimensionality \( 24 \times 30000 \). This is however a classification problem and we will come back to it when we discuss Logistic Regression. +

    -











    -

    General linear models

    -Before we proceed let us study a case from linear algebra where we aim at fitting a set of data \( \boldsymbol{y}=[y_0,y_1,\dots,y_{n-1}] \). We could think of these data as a result of an experiment or a complicated numerical experiment. These data are functions of a series of variables \( \boldsymbol{x}=[x_0,x_1,\dots,x_{n-1}] \), that is \( y_i = y(x_i) \) with \( i=0,1,2,\dots,n-1 \). The variables \( x_i \) could represent physical quantities like time, temperature, position etc. We assume that \( y(x) \) is a smooth function. +

    Before we proceed let us study a case from linear algebra where we aim at fitting a set of data \( \boldsymbol{y}=[y_0,y_1,\dots,y_{n-1}] \). We could think of these data as a result of an experiment or a complicated numerical experiment. These data are functions of a series of variables \( \boldsymbol{x}=[x_0,x_1,\dots,x_{n-1}] \), that is \( y_i = y(x_i) \) with \( i=0,1,2,\dots,n-1 \). The variables \( x_i \) could represent physical quantities like time, temperature, position etc. We assume that \( y(x) \) is a smooth function.

    -

    -Since obtaining these data points may not be trivial, we want to use these data to fit a function which can allow us to make predictions for values of \( y \) which are not in the present set. The perhaps simplest approach is to assume we can parametrize our function in terms of a polynomial of degree \( n-1 \) with \( n \) points, that is +

    Since obtaining these data points may not be trivial, we want to use these data to fit a function which can allow us to make predictions for values of \( y \) which are not in the present set. The perhaps simplest approach is to assume we can parametrize our function in terms of a polynomial of degree \( n-1 \) with \( n \) points, that is

    $$ y=y(x) \rightarrow y(x_i)=\tilde{y}_i+\epsilon_i=\sum_{j=0}^{n-1} \beta_j x_i^j+\epsilon_i, $$ -where \( \epsilon_i \) is the error in our approximation. - - +

    where \( \epsilon_i \) is the error in our approximation.

    -











    -

    Rewriting the fitting procedure as a linear algebra problem

    -For every set of values \( y_i,x_i \) we have thus the corresponding set of equations +

    For every set of values \( y_i,x_i \) we have thus the corresponding set of equations

    $$ \begin{align*} y_0&=\beta_0+\beta_1x_0^1+\beta_2x_0^2+\dots+\beta_{n-1}x_0^{n-1}+\epsilon_0\\ @@ -2378,29 +2875,27 @@ $$
    -











    -

    Rewriting the fitting procedure as a linear algebra problem, more details

    -Defining the vectors +

    Defining the vectors

    $$ \boldsymbol{y} = [y_0,y_1, y_2,\dots, y_{n-1}]^T, $$ -and +

    and

    $$ \boldsymbol{\beta} = [\beta_0,\beta_1, \beta_2,\dots, \beta_{n-1}]^T, $$ -and +

    and

    $$ \boldsymbol{\epsilon} = [\epsilon_0,\epsilon_1, \epsilon_2,\dots, \epsilon_{n-1}]^T, $$ -and the design matrix +

    and the design matrix

    $$ \boldsymbol{X}= \begin{bmatrix} @@ -2412,29 +2907,27 @@ $$ \end{bmatrix} $$ -we can rewrite our equations as +

    we can rewrite our equations as

    $$ \boldsymbol{y} = \boldsymbol{X}\boldsymbol{\beta}+\boldsymbol{\epsilon}. $$ -The above design matrix is called a Vandermonde matrix. +

    The above design matrix is called a Vandermonde matrix.

    -











    -

    Generalizing the fitting procedure as a linear algebra problem

    -

    -We are obviously not limited to the above polynomial expansions. We +

    We are obviously not limited to the above polynomial expansions. We could replace the various powers of \( x \) with elements of Fourier series or instead of \( x_i^j \) we could have \( \cos{(j x_i)} \) or \( \sin{(j x_i)} \), or time series or other orthogonal functions. For every set of values \( y_i,x_i \) we can then generalize the equations to +

    $$ \begin{align*} @@ -2448,19 +2941,17 @@ y_{n-1}&=\beta_0x_{n-1,0}+\beta_1x_{n-1,2}+\beta_2x_{n-1,2}+\dots+\beta_{n-1}x_{ \end{align*} $$ -

    + Note that we have \( p=n \) here. The matrix is symmetric. This is generally not the case!

    -











    -

    Generalizing the fitting procedure as a linear algebra problem

    -We redefine in turn the matrix \( \boldsymbol{X} \) as +

    We redefine in turn the matrix \( \boldsymbol{X} \) as

    $$ \boldsymbol{X}= \begin{bmatrix} @@ -2472,23 +2963,21 @@ x_{n-1,0}& x_{n-1,1} &x_{n-1,2}& \dots & \dots &x_{n-1,n-1}\\ \end{bmatrix} $$ -and without loss of generality we rewrite again our equations as +

    and without loss of generality we rewrite again our equations as

    $$ \boldsymbol{y} = \boldsymbol{X}\boldsymbol{\beta}+\boldsymbol{\epsilon}. $$ -The left-hand side of this equation is kwown. Our error vector \( \boldsymbol{\epsilon} \) and the parameter vector \( \boldsymbol{\beta} \) are our unknow quantities. How can we obtain the optimal set of \( \beta_i \) values? +

    The left-hand side of this equation is kwown. Our error vector \( \boldsymbol{\epsilon} \) and the parameter vector \( \boldsymbol{\beta} \) are our unknow quantities. How can we obtain the optimal set of \( \beta_i \) values?

    -











    -

    Optimizing our parameters

    -We have defined the matrix \( \boldsymbol{X} \) via the equations +

    We have defined the matrix \( \boldsymbol{X} \) via the equations

    $$ \begin{align*} y_0&=\beta_0x_{00}+\beta_1x_{01}+\beta_2x_{02}+\dots+\beta_{n-1}x_{0n-1}+\epsilon_0\\ @@ -2501,29 +2990,27 @@ y_{n-1}&=\beta_0x_{n-1,0}+\beta_1x_{n-1,2}+\beta_2x_{n-1,2}+\dots+\beta_{n-1}x_{ \end{align*} $$ -

    -As we noted above, we stayed with a system with the design matrix +

    As we noted above, we stayed with a system with the design matrix \( \boldsymbol{X}\in {\mathbb{R}}^{n\times n} \), that is we have \( p=n \). For reasons to come later (algorithmic arguments) we will hereafter define our matrix as \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \), with the predictors refering to the column numbers and the entries \( n \) being the row elements. - - +

    -











    -

    Our model for the nuclear binding energies

    -

    -In our introductory notes we looked at the so-called liquid drop model. Let us remind ourselves about what we did by looking at the code. +

    In our introductory notes we looked at the so-called liquid drop model. Let us remind ourselves about what we did by looking at the code.

    -

    -We restate the parts of the code we are most interested in. -

    +

    We restate the parts of the code we are most interested in.

    -
    # Common imports
    +
    +
    +
    +
    +
    +
    # Common imports
     import numpy as np
     import pandas as pd
     import matplotlib.pyplot as plt
    @@ -2592,73 +3079,81 @@ DesignMatrix = pd.DataFrame(X)
     DesignMatrix.index = A
     DesignMatrix.columns = ['1', 'A', 'A^(2/3)', 'A^(-1/3)', '1/A']
     display(DesignMatrix)
    -
    -

    -With \( \boldsymbol{\beta}\in {\mathbb{R}}^{p\times 1} \), it means that we will hereafter write our equations for the approximation as +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    With \( \boldsymbol{\beta}\in {\mathbb{R}}^{p\times 1} \), it means that we will hereafter write our equations for the approximation as

    $$ \boldsymbol{\tilde{y}}= \boldsymbol{X}\boldsymbol{\beta}, $$ -throughout these lectures. +

    throughout these lectures.

    -











    -

    Optimizing our parameters, more details

    -With the above we use the design matrix to define the approximation \( \boldsymbol{\tilde{y}} \) via the unknown quantity \( \boldsymbol{\beta} \) as +

    With the above we use the design matrix to define the approximation \( \boldsymbol{\tilde{y}} \) via the unknown quantity \( \boldsymbol{\beta} \) as

    $$ \boldsymbol{\tilde{y}}= \boldsymbol{X}\boldsymbol{\beta}, $$ -and in order to find the optimal parameters \( \beta_i \) instead of solving the above linear algebra problem, we define a function which gives a measure of the spread between the values \( y_i \) (which represent hopefully the exact values) and the parameterized values \( \tilde{y}_i \), namely +

    and in order to find the optimal parameters \( \beta_i \) instead of solving the above linear algebra problem, we define a function which gives a measure of the spread between the values \( y_i \) (which represent hopefully the exact values) and the parameterized values \( \tilde{y}_i \), namely

    $$ C(\boldsymbol{\beta})=\frac{1}{n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{\tilde{y}}\right)^T\left(\boldsymbol{y}-\boldsymbol{\tilde{y}}\right)\right\}, $$ -or using the matrix \( \boldsymbol{X} \) and in a more compact matrix-vector notation as +

    or using the matrix \( \boldsymbol{X} \) and in a more compact matrix-vector notation as

    $$ C(\boldsymbol{\beta})=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)^T\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)\right\}. $$ -This function is one possible way to define the so-called cost function. +

    This function is one possible way to define the so-called cost function.

    -

    -It is also common to define +

    It is also common to define the function \( C \) as +

    $$ C(\boldsymbol{\beta})=\frac{1}{2n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2, $$ -since when taking the first derivative with respect to the unknown parameters \( \beta \), the factor of \( 2 \) cancels out. +

    since when taking the first derivative with respect to the unknown parameters \( \beta \), the factor of \( 2 \) cancels out.

    -











    -

    Interpretations and optimizing our parameters

    -

    -The function +

    The function

    $$ C(\boldsymbol{\beta})=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)^T\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)\right\}, $$ -can be linked to the variance of the quantity \( y_i \) if we interpret the latter as the mean value. +

    can be linked to the variance of the quantity \( y_i \) if we interpret the latter as the mean value. When linking (see the discussion below) with the maximum likelihood approach below, we will indeed interpret \( y_i \) as a mean value +

    $$ y_{i}=\langle y_i \rangle = \beta_0x_{i,0}+\beta_1x_{i,1}+\beta_2x_{i,2}+\dots+\beta_{n-1}x_{i,n-1}+\epsilon_i, $$ -

    -where \( \langle y_i \rangle \) is the mean value. Keep in mind also that +

    where \( \langle y_i \rangle \) is the mean value. Keep in mind also that till now we have treated \( y_i \) as the exact value. Normally, the response (dependent or outcome) variable \( y_i \) the outcome of a numerical experiment or another type of experiment and is thus only an @@ -2666,57 +3161,52 @@ approximation to the true value. It is then always accompanied by an error estimate, often limited to a statistical error estimate given by the standard deviation discussed earlier. In the discussion here we will treat \( y_i \) as our exact value for the response variable. +

    -

    -In order to find the parameters \( \beta_i \) we will then minimize the spread of \( C(\boldsymbol{\beta}) \), that is we are going to solve the problem +

    In order to find the parameters \( \beta_i \) we will then minimize the spread of \( C(\boldsymbol{\beta}) \), that is we are going to solve the problem

    $$ {\displaystyle \min_{\boldsymbol{\beta}\in {\mathbb{R}}^{p}}}\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)^T\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)\right\}. $$ -In practical terms it means we will require +

    In practical terms it means we will require

    $$ \frac{\partial C(\boldsymbol{\beta})}{\partial \beta_j} = \frac{\partial }{\partial \beta_j}\left[ \frac{1}{n}\sum_{i=0}^{n-1}\left(y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}\right)^2\right]=0, $$ -which results in +

    which results in

    $$ \frac{\partial C(\boldsymbol{\beta})}{\partial \beta_j} = -\frac{2}{n}\left[ \sum_{i=0}^{n-1}x_{ij}\left(y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}\right)\right]=0, $$ -or in a matrix-vector form as +

    or in a matrix-vector form as

    $$ \frac{\partial C(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}} = 0 = \boldsymbol{X}^T\left( \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right). $$ - -
    -











    -

    Interpretations and optimizing our parameters

    -We can rewrite +

    We can rewrite

    $$ \frac{\partial C(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}} = 0 = \boldsymbol{X}^T\left( \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right), $$ -as +

    as

    $$ \boldsymbol{X}^T\boldsymbol{y} = \boldsymbol{X}^T\boldsymbol{X}\boldsymbol{\beta}, $$ -and if the matrix \( \boldsymbol{X}^T\boldsymbol{X} \) is invertible we have the solution +

    and if the matrix \( \boldsymbol{X}^T\boldsymbol{X} \) is invertible we have the solution

    $$ \boldsymbol{\beta} =\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}. $$ -

    -We note also that since our design matrix is defined as \( \boldsymbol{X}\in +

    We note also that since our design matrix is defined as \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \), the product \( \boldsymbol{X}^T\boldsymbol{X} \in {\mathbb{R}}^{p\times p} \). In the above case we have that \( p \ll n \), in our case \( p=5 \) meaning that we end up with inverting a small @@ -2725,26 +3215,24 @@ matrices to invert. The methods discussed here and for many other supervised learning algorithms like classification with logistic regression or support vector machines, exhibit dimensionalities which allow for the usage of direct linear algebra methods such as LU decomposition or Singular Value Decomposition (SVD) for finding the inverse of the matrix -\( \boldsymbol{X}^T\boldsymbol{X} \). +\( \boldsymbol{X}^T\boldsymbol{X} \). +

    -

    -Small question: Do you think the example we have at hand here (the nuclear binding energies) can lead to problems in inverting the matrix \( \boldsymbol{X}^T\boldsymbol{X} \)? What kind of problems can we expect? +

    Small question: Do you think the example we have at hand here (the nuclear binding energies) can lead to problems in inverting the matrix \( \boldsymbol{X}^T\boldsymbol{X} \)? What kind of problems can we expect?

    -











    -

    Some useful matrix and vector expressions

    -

    -The following matrix and vector relation will be useful here and for the rest of the course. Vectors are always written as boldfaced lower case letters and +

    The following matrix and vector relation will be useful here and for the rest of the course. Vectors are always written as boldfaced lower case letters and matrices as upper case boldfaced letters. +

    $$ \frac{\partial (\boldsymbol{b}^T\boldsymbol{a})}{\partial \boldsymbol{a}} = \boldsymbol{b}, @@ -2763,65 +3251,97 @@ $$ $$









    -

    Interpretations and optimizing our parameters

    -The residuals \( \boldsymbol{\epsilon} \) are in turn given by +

    The residuals \( \boldsymbol{\epsilon} \) are in turn given by

    $$ \boldsymbol{\epsilon} = \boldsymbol{y}-\boldsymbol{\tilde{y}} = \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}, $$ -and with +

    and with

    $$ \boldsymbol{X}^T\left( \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)= 0, $$ -we have +

    we have

    $$ \boldsymbol{X}^T\boldsymbol{\epsilon}=\boldsymbol{X}^T\left( \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)= 0, $$ -meaning that the solution for \( \boldsymbol{\beta} \) is the one which minimizes the residuals. Later we will link this with the maximum likelihood approach. - - +

    meaning that the solution for \( \boldsymbol{\beta} \) is the one which minimizes the residuals. Later we will link this with the maximum likelihood approach.

    -

    -Let us now return to our nuclear binding energies and simply code the above equations. +

    Let us now return to our nuclear binding energies and simply code the above equations.

    -











    -

    Own code for Ordinary Least Squares

    -

    -It is rather straightforward to implement the matrix inversion and obtain the parameters \( \boldsymbol{\beta} \). After having defined the matrix \( \boldsymbol{X} \) we simply need to +

    It is rather straightforward to implement the matrix inversion and obtain the parameters \( \boldsymbol{\beta} \). After having defined the matrix \( \boldsymbol{X} \) we simply need to write -

    +

    -
    # matrix inversion to find beta
    +
    +
    +
    +
    +
    +
    # matrix inversion to find beta
     beta = np.linalg.inv(X.T.dot(X)).dot(X.T).dot(Energies)
     # and then make the prediction
     ytilde = X @ beta
    -
    -

    -Alternatively, you can use the least squares functionality in Numpy as -

    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    Alternatively, you can use the least squares functionality in Numpy as

    -
    fit = np.linalg.lstsq(X, Energies, rcond =None)[0]
    +
    +
    +
    +
    +
    +
    fit = np.linalg.lstsq(X, Energies, rcond =None)[0]
     ytildenp = np.dot(fit,X.T)
    -
    -

    -And finally we plot our fit with and compare with data -

    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    And finally we plot our fit with and compare with data

    -
    Masses['Eapprox']  = ytilde
    +
    +
    +
    +
    +
    +
    Masses['Eapprox']  = ytilde
     # Generate a plot comparing the experimental with the fitted values values.
     fig, ax = plt.subplots()
     ax.set_xlabel(r'$A = N + Z$')
    @@ -2833,200 +3353,266 @@ ax.plot(Masses['A'], Masses["Masses2016OLS")
     plt.show()
    -
    -

    -









    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +









    Adding error analysis and training set up

    -

    -We can easily test our fit by computing the \( R2 \) score that we discussed in connection with the functionality of Scikit-Learn in the introductory slides. +

    We can easily test our fit by computing the \( R2 \) score that we discussed in connection with the functionality of Scikit-Learn in the introductory slides. Since we are not using Scikit-Learn here we can define our own \( R2 \) function as -

    +

    -
    def R2(y_data, y_model):
    +
    +
    +
    +
    +
    +
    def R2(y_data, y_model):
         return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)
    -
    -

    -and we would be using it as -

    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    and we would be using it as

    -
    print(R2(Energies,ytilde))
    -
    -

    -We can easily add our MSE score as -

    +

    +
    +
    +
    +
    +
    print(R2(Energies,ytilde))
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    We can easily add our MSE score as

    -
    def MSE(y_data,y_model):
    +
    +
    +
    +
    +
    +
    def MSE(y_data,y_model):
         n = np.size(y_model)
         return np.sum((y_data-y_model)**2)/n
     
     print(MSE(Energies,ytilde))
    -
    -

    -and finally the relative error as -

    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    and finally the relative error as

    -
    def RelativeError(y_data,y_model):
    +
    +
    +
    +
    +
    +
    def RelativeError(y_data,y_model):
         return abs((y_data-y_model)/y_data)
     print(RelativeError(Energies, ytilde))
    -
    -

    -









    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +









    The \( \chi^2 \) function

    -

    -Normally, the response (dependent or outcome) variable \( y_i \) is the +

    Normally, the response (dependent or outcome) variable \( y_i \) is the outcome of a numerical experiment or another type of experiment and is thus only an approximation to the true value. It is then always accompanied by an error estimate, often limited to a statistical error estimate given by the standard deviation discussed earlier. In the discussion here we will treat \( y_i \) as our exact value for the response variable. +

    -

    -Introducing the standard deviation \( \sigma_i \) for each measurement +

    Introducing the standard deviation \( \sigma_i \) for each measurement \( y_i \), we define now the \( \chi^2 \) function (omitting the \( 1/n \) term) as +

    $$ \chi^2(\boldsymbol{\beta})=\frac{1}{n}\sum_{i=0}^{n-1}\frac{\left(y_i-\tilde{y}_i\right)^2}{\sigma_i^2}=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{\tilde{y}}\right)^T\frac{1}{\boldsymbol{\Sigma^2}}\left(\boldsymbol{y}-\boldsymbol{\tilde{y}}\right)\right\}, $$ -where the matrix \( \boldsymbol{\Sigma} \) is a diagonal matrix with \( \sigma_i \) as matrix elements. - - +

    where the matrix \( \boldsymbol{\Sigma} \) is a diagonal matrix with \( \sigma_i \) as matrix elements.

    -











    -

    The \( \chi^2 \) function

    -

    -In order to find the parameters \( \beta_i \) we will then minimize the spread of \( \chi^2(\boldsymbol{\beta}) \) by requiring +

    In order to find the parameters \( \beta_i \) we will then minimize the spread of \( \chi^2(\boldsymbol{\beta}) \) by requiring

    $$ \frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \beta_j} = \frac{\partial }{\partial \beta_j}\left[ \frac{1}{n}\sum_{i=0}^{n-1}\left(\frac{y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}}{\sigma_i}\right)^2\right]=0, $$ -which results in +

    which results in

    $$ \frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \beta_j} = -\frac{2}{n}\left[ \sum_{i=0}^{n-1}\frac{x_{ij}}{\sigma_i}\left(\frac{y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}}{\sigma_i}\right)\right]=0, $$ -or in a matrix-vector form as +

    or in a matrix-vector form as

    $$ \frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}} = 0 = \boldsymbol{A}^T\left( \boldsymbol{b}-\boldsymbol{A}\boldsymbol{\beta}\right). $$ -where we have defined the matrix \( \boldsymbol{A} =\boldsymbol{X}/\boldsymbol{\Sigma} \) with matrix elements \( a_{ij} = x_{ij}/\sigma_i \) and the vector \( \boldsymbol{b} \) with elements \( b_i = y_i/\sigma_i \). +

    where we have defined the matrix \( \boldsymbol{A} =\boldsymbol{X}/\boldsymbol{\Sigma} \) with matrix elements \( a_{ij} = x_{ij}/\sigma_i \) and the vector \( \boldsymbol{b} \) with elements \( b_i = y_i/\sigma_i \).

    -











    -

    The \( \chi^2 \) function

    -

    -We can rewrite +

    We can rewrite

    $$ \frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}} = 0 = \boldsymbol{A}^T\left( \boldsymbol{b}-\boldsymbol{A}\boldsymbol{\beta}\right), $$ -as +

    as

    $$ \boldsymbol{A}^T\boldsymbol{b} = \boldsymbol{A}^T\boldsymbol{A}\boldsymbol{\beta}, $$ -and if the matrix \( \boldsymbol{A}^T\boldsymbol{A} \) is invertible we have the solution +

    and if the matrix \( \boldsymbol{A}^T\boldsymbol{A} \) is invertible we have the solution

    $$ \boldsymbol{\beta} =\left(\boldsymbol{A}^T\boldsymbol{A}\right)^{-1}\boldsymbol{A}^T\boldsymbol{b}. $$
    -











    -

    The \( \chi^2 \) function

    -

    -If we then introduce the matrix +

    If we then introduce the matrix

    $$ \boldsymbol{H} = \left(\boldsymbol{A}^T\boldsymbol{A}\right)^{-1}, $$ -we have then the following expression for the parameters \( \beta_j \) (the matrix elements of \( \boldsymbol{H} \) are \( h_{ij} \)) +

    we have then the following expression for the parameters \( \beta_j \) (the matrix elements of \( \boldsymbol{H} \) are \( h_{ij} \))

    $$ \beta_j = \sum_{k=0}^{p-1}h_{jk}\sum_{i=0}^{n-1}\frac{y_i}{\sigma_i}\frac{x_{ik}}{\sigma_i} = \sum_{k=0}^{p-1}h_{jk}\sum_{i=0}^{n-1}b_ia_{ik} $$ -We state without proof the expression for the uncertainty in the parameters \( \beta_j \) as (we leave this as an exercise) +

    We state without proof the expression for the uncertainty in the parameters \( \beta_j \) as (we leave this as an exercise)

    $$ \sigma^2(\beta_j) = \sum_{i=0}^{n-1}\sigma_i^2\left( \frac{\partial \beta_j}{\partial y_i}\right)^2, $$ -resulting in +

    resulting in

    $$ \sigma^2(\beta_j) = \left(\sum_{k=0}^{p-1}h_{jk}\sum_{i=0}^{n-1}a_{ik}\right)\left(\sum_{l=0}^{p-1}h_{jl}\sum_{m=0}^{n-1}a_{ml}\right) = h_{jj}! $$
    -











    -

    The \( \chi^2 \) function

    -The first step here is to approximate the function \( y \) with a first-order polynomial, that is we write +

    The first step here is to approximate the function \( y \) with a first-order polynomial, that is we write

    $$ y=y(x) \rightarrow y(x_i) \approx \beta_0+\beta_1 x_i. $$ -By computing the derivatives of \( \chi^2 \) with respect to \( \beta_0 \) and \( \beta_1 \) show that these are given by +

    By computing the derivatives of \( \chi^2 \) with respect to \( \beta_0 \) and \( \beta_1 \) show that these are given by

    $$ \frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \beta_0} = -2\left[ \frac{1}{n}\sum_{i=0}^{n-1}\left(\frac{y_i-\beta_0-\beta_1x_{i}}{\sigma_i^2}\right)\right]=0, $$ -and +

    and

    $$ \frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \beta_1} = -\frac{2}{n}\left[ \sum_{i=0}^{n-1}x_i\left(\frac{y_i-\beta_0-\beta_1x_{i}}{\sigma_i^2}\right)\right]=0. $$
    -











    -

    The \( \chi^2 \) function

    -

    -For a linear fit (a first-order polynomial) we don't need to invert a matrix!! +

    For a linear fit (a first-order polynomial) we don't need to invert a matrix!! Defining +

    $$ \gamma = \sum_{i=0}^{n-1}\frac{1}{\sigma_i^2}, $$ @@ -3051,8 +3637,7 @@ $$ \gamma_{xy} = \sum_{i=0}^{n-1}\frac{y_ix_{i}}{\sigma_i^2}, $$ -

    -we obtain +

    we obtain

    $$ \beta_0 = \frac{\gamma_{xx}\gamma_y-\gamma_x\gamma_y}{\gamma\gamma_{xx}-\gamma_x^2}, @@ -3063,50 +3648,48 @@ $$ \beta_1 = \frac{\gamma_{xy}\gamma-\gamma_x\gamma_y}{\gamma\gamma_{xx}-\gamma_x^2}. $$ -

    -This approach (different linear and non-linear regression) suffers +

    This approach (different linear and non-linear regression) suffers often from both being underdetermined and overdetermined in the unknown coefficients \( \beta_i \). A better approach is to use the Singular Value Decomposition (SVD) method discussed next week. - - +

    -











    -

    Fitting an Equation of State for Dense Nuclear Matter

    -

    -Before we continue, let us introduce yet another example. We are going to fit the +

    Before we continue, let us introduce yet another example. We are going to fit the nuclear equation of state using results from many-body calculations. The equation of state we have made available here, as function of density, has been derived using modern nucleon-nucleon potentials with the addition of three-body forces. This time the file is presented as a standard csv file. +

    -

    -The beginning of the Python code here is similar to what you have seen +

    The beginning of the Python code here is similar to what you have seen before, with the same initializations and declarations. We use also pandas again, rather extensively in order to organize our data. +

    -

    -The difference now is that we use Scikit-Learn's regression tools +

    The difference now is that we use Scikit-Learn's regression tools instead of our own matrix inversion implementation. Furthermore, we sneak in Ridge regression (to be discussed below) which includes a hyperparameter \( \lambda \), also to be explained below. +

    -











    -

    The code

    -

    -

    # Common imports
    +
    +
    +
    +
    +
    +
    # Common imports
     import os
     import numpy as np
     import pandas as pd
    @@ -3191,23 +3774,34 @@ ax.plot(EoS['Density'], EoS["EoSfitting")
     plt.show()
    -
    -

    -The above simple polynomial in density \( \rho \) gives an excellent fit -to the data. +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + -

    -We note also that there is a small deviation between the +

    The above simple polynomial in density \( \rho \) gives an excellent fit +to the data. +

    + +

    We note also that there is a small deviation between the standard OLS and the Ridge regression at higher densities. We discuss this in more detail below. +

    -











    -

    Splitting our Data in Training and Test data

    -

    -It is normal in essentially all Machine Learning studies to split the +

    It is normal in essentially all Machine Learning studies to split the data in a training set and a test set (sometimes also an additional validation set). Scikit-Learn has an own function for this. There is no explicit recipe for how much data should be included as training @@ -3217,11 +3811,16 @@ postpone a discussion of this splitting to the end of these notes and our discussion of the so-called bias-variance tradeoff. Here we limit ourselves to repeat the above equation of state fitting example but now splitting the data into a training set and a test set. +

    -

    -

    import os
    +
    +
    +
    +
    +
    +
    import os
     import numpy as np
     import pandas as pd
     import matplotlib.pyplot as plt
    @@ -3285,144 +3884,172 @@ ypredict = X_test @ beta
     print(R2(y_test,ypredict))
     print("Test MSE")
     print(MSE(y_test,ypredict))
    -
    -

    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +









    -

    Exercises for week 35

    -Here are three possible exercises for week 35 and the lab sessions of Wednesday September 1. +

    Here are three possible exercises for week 35 and the lab sessions of Wednesday September 1.

    -

    -

    Exercise 1: Setting up various Python environments

    -

    -The first exercise here is of a mere technical art. We want you to have - +

    The first exercise here is of a mere technical art. We want you to have

    • git as a version control software and to establish a user account on a provider like GitHub. Other providers like GitLab etc are equally fine. You can also use the University of Oslo GitHub facilities.
    • Install various Python packages
    - -We will make extensive use of Python as programming language and its +

    We will make extensive use of Python as programming language and its myriad of available libraries. You will find IPython/Jupyter notebooks invaluable in your work. You can run R codes in the Jupyter/IPython notebooks, with the immediate benefit of visualizing your data. You can also use compiled languages like C++, Rust, Fortran etc if you prefer. The focus in these lectures will be on Python. +

    -

    -If you have Python installed (we recommend Python3) and you feel +

    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 +

    1. pip install numpy scipy matplotlib ipython scikit-learn sympy pandas pillow
    - -For Tensorflow, we recommend following the instructions in the text of +

    For Tensorflow, we recommend following the instructions in the text of Aurelien Geron, Hands‑On Machine Learning with Scikit‑Learn and TensorFlow, O'Reilly +

    -

    -We will come back to tensorflow later. +

    We will come back to tensorflow later.

    -

    -For Python3, replace pip with pip3. +

    For Python3, replace pip with pip3.

    -

    -For OSX users we recommend, after having installed Xcode, to +

    For OSX users we recommend, after having installed Xcode, to install brew. Brew allows for a seamless installation of additional software via for example +

    1. brew install python3
    - -For Linux users, with its variety of distributions like for example the widely popular Ubuntu distribution, +

    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 +

    1. sudo apt-get install python3 (or python for Python2.7)
    - -If you don't want to perform these operations separately and venture +

    If you don't want to perform these operations separately and venture into the hassle of exploring how to set up dependencies and paths, we recommend two widely used distrubutions which set up all relevant dependencies for Python, namely +

    - -which is an open source +

    which 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. +

    - -is a Python +

    is a Python distribution for scientific and analytic computing distribution and analysis environment, available for free and under a commercial license. +

    -

    -We recommend using Anaconda if you are not too familiar with setting paths in a terminal environment. +

    We recommend using Anaconda if you are not too familiar with setting paths in a terminal environment.

    -

    -

    -

    Exercise 2: making your own data and exploring scikit-learn

    -

    -We will generate our own dataset for a function \( y(x) \) where \( x \in [0,1] \) and defined by random numbers computed with the uniform distribution. The function \( y \) is a quadratic polynomial in \( x \) with added stochastic noise according to the normal distribution \( \cal {N}(0,1) \). +

    We will generate our own dataset for a function \( y(x) \) where \( x \in [0,1] \) and defined by random numbers computed with the uniform distribution. The function \( y \) is a quadratic polynomial in \( x \) with added stochastic noise according to the normal distribution \( \cal {N}(0,1) \). The following simple Python instructions define our \( x \) and \( y \) values (with 100 data points). -

    +

    -
    x = np.random.rand(100,1)
    +
    +
    +
    +
    +
    +
    x = np.random.rand(100,1)
     y = 2.0+5*x*x+0.1*np.random.randn(100,1)
    -
    +
    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +
    1. Write your own code (following the examples under the regression notes) for computing the parametrization of the data set fitting a second-order polynomial.
    2. Use thereafter scikit-learn (see again the examples in the regression slides) and compare with your own code.
    3. Using scikit-learn, compute also the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error defined as
    - $$ MSE(\boldsymbol{y},\boldsymbol{\tilde{y}}) = \frac{1}{n} \sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, $$ -and the \( R^2 \) score function. +

    and the \( R^2 \) score function. If \( \tilde{\boldsymbol{y}}_i \) is the predicted value of the \( i-th \) sample and \( y_i \) is the corresponding true value, then the score \( R^2 \) is defined as +

    $$ R^2(\boldsymbol{y}, \tilde{\boldsymbol{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2}, $$ -where we have defined the mean value of \( \boldsymbol{y} \) as +

    where we have defined the mean value of \( \boldsymbol{y} \) as

    $$ \bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. $$ -You can use the functionality included in scikit-learn. If you feel for it, you can use your own program and define functions which compute the above two functions. +

    You can use the functionality included in scikit-learn. If you feel for it, you can use your own program and define functions which compute the above two functions. Discuss the meaning of these results. Try also to vary the coefficient in front of the added stochastic noise term and discuss the quality of the fits. +

    -

    +

    Solution. The code here is an example of where we define our own design matrix and fit parameters \( \beta \). -

    +

    -
    import os
    +
    +
    +
    +
    +
    +
    import os
     import numpy as np
     import pandas as pd
     import matplotlib.pyplot as plt
    @@ -3462,26 +4089,36 @@ ypredict = X_test @ beta
     print(R2(y_test,ypredict))
     print("Test MSE")
     print(MSE(y_test,ypredict))
    -
    -

    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + + -

    -

    -

    Exercise 3: Normalizing our data

    -

    -A much used approach before starting to train the data is to preprocess our +

    A much used approach before starting to train the data is to preprocess our data. Normally the data may need a rescaling and/or may be sensitive to extreme values. Scaling the data renders our inputs much more suitable for the algorithms we want to employ. +

    -

    -Scikit-Learn has several functions which allow us to rescale the +

    Scikit-Learn has several functions which allow us to rescale the data, normally resulting in much better results in terms of various accuracy scores. The StandardScaler function in Scikit-Learn ensures that for each feature/predictor we study the mean value is @@ -3490,18 +4127,18 @@ matrix). This scaling has the drawback that it does not ensure that we have a particular maximum or minimum in our data set. Another function included in Scikit-Learn is the MinMaxScaler which ensures that all features are exactly between \( 0 \) and \( 1 \). The +

    -

    -The Normalizer scales each data +

    The Normalizer scales each data point such that the feature vector has a euclidean length of one. In other words, it projects a data point on the circle (or sphere in the case of higher dimensions) with a radius of 1. This means every data point is scaled by a different number (by the inverse of it’s length). This normalization is often used when only the direction (or angle) of the data matters, not the length of the feature vector. +

    -

    -The RobustScaler works similarly to the StandardScaler in that it +

    The RobustScaler works similarly to the StandardScaler in that it ensures statistical properties for each feature that guarantee that they are on the same scale. However, the RobustScaler uses the median and quartiles, instead of mean and variance. This makes the @@ -3509,74 +4146,131 @@ RobustScaler ignore data points that are very different from the rest (like measurement errors). These odd data points are also called outliers, and might often lead to trouble for other scaling techniques. +

    -

    -It also common to split the data in a training set and a testing set. A typical split is to use \( 80\% \) of the data for training and the rest +

    It also common to split the data in a training set and a testing set. A typical split is to use \( 80\% \) of the data for training and the rest for testing. This can be done as follows with our design matrix \( \boldsymbol{X} \) and data \( \boldsymbol{y} \) (remember to import scikit-learn) -

    +

    -
    # split in training and test data
    +
    +
    +
    +
    +
    +
    # split in training and test data
     X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.2)
    -
    -

    -Then we can use the standard scaler to scale our data as -

    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    Then we can use the standard scaler to scale our data as

    -
    scaler = StandardScaler()
    +
    +
    +
    +
    +
    +
    scaler = StandardScaler()
     scaler.fit(X_train)
     X_train_scaled = scaler.transform(X_train)
     X_test_scaled = scaler.transform(X_test)
    -
    -

    -In this exercise we want you to to compute the MSE for the training +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    In this exercise we want you to to compute the MSE for the training data and the test data as function of the complexity of a polynomial, -that is the degree of a given polynomial. We want you also to compute the \( R2 \) score as function of the complexity of the model for both training data and test data. You should also run the calculation with and without scaling. +that is the degree of a given polynomial. We want you also to compute the \( R2 \) score as function of the complexity of the model for both training data and test data. You should also run the calculation with and without scaling. +

    -

    -One of +

    One of the aims is to reproduce Figure 2.11 of Hastie et al. +

    -

    -Our data is defined by \( x\in [-3,3] \) with a total of for example \( 100 \) data points. -

    +

    Our data is defined by \( x\in [-3,3] \) with a total of for example \( 100 \) data points.

    -
    np.random.seed()
    +
    +
    +
    +
    +
    +
    np.random.seed()
     n = 100
     maxdegree = 14
     # Make data set.
     x = np.linspace(-3, 3, n).reshape(-1, 1)
     y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
    -
    -

    -where \( y \) is the function we want to fit with a given polynomial. +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + +

    where \( y \) is the function we want to fit with a given polynomial.

    + +

    a) Write a first code which sets up a design matrix \( X \) defined by a fifth-order polynomial. Scale your data and split it in training and test data. +

    + + +

    b) Perform an ordinary least squares and compute the means squared error and the \( R2 \) factor for the training data and the test data, with and without scaling. +

    + + +

    c) Add now a model which allows you to make polynomials up to degree \( 15 \). Perform a standard OLS fitting of the training data and compute the MSE and \( R2 \) for the training and test data and plot both test and training data MSE and \( R2 \) as functions of the polynomial degree. Compare what you see with Figure 2.11 of Hastie et al. Comment your results. For which polynomial degree do you find an optimal MSE (smallest value)? +

    + + -

    - - -

    © 1999-2021, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
    - - - diff --git a/doc/pub/week34/html/week34.html b/doc/pub/week34/html/week34.html index 56bc5348d..ba58ee8f7 100644 --- a/doc/pub/week34/html/week34.html +++ b/doc/pub/week34/html/week34.html @@ -1,6 +1,7 @@ @@ -8,29 +9,97 @@ Automatically generated HTML file from DocOnce source - Week 34: Introduction to the course, Logistics and Practicalities - - - - +
    +

    Week 34: Introduction to the course, Logistics and Practicalities

    +
    - - -

    Week 34: Introduction to the course, Logistics and Practicalities

    - -

    -

    Morten Hjorth-Jensen [1, 2]
    - -

    +

    +[1] Department of Physics, University of Oslo +
    +
    +[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University +
    +
    +
    +

    Nov 13, 2021

    +
    +
    -
    [1] Department of Physics, University of Oslo
    -
    [2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
    -
    -

    -

    Oct 12, 2021

    -
    -











    -

    Overview of first week

    -

    -

    • Wednesday August 25: Introduction to software and repetition of Python Programming
    • Thursday August 26: First lecture: Presentation of the course, aims and content
    • @@ -327,59 +395,44 @@ MathJax.Hub.Config({
    -











    -

    Reading Recommendations

    -

    -For the reading assignments we use the following abbreviations: - +

    For the reading assignments we use the following abbreviations:

    • GBC: Goodfellow, Bengio, and Courville, Deep Learning
    • CMB: Christopher M. Bishop, Pattern Recognition and Machine Learning
    • HTF: Hastie, Tibshirani, and Friedman, The Elements of Statistical Learning
    • AG: Aurelien Geron, Hands‑On Machine Learning with Scikit‑Learn and TensorFlow
    - -Reading recommendations this week: Refresh linear algebra, GBC chapters 1 and 2. CMB sections 1.1 and 3.1. HTF chapters 2 and 3. Install scikit-learn. See lecture notes for week 34 at https://compphysics.github.io/MachineLearning/doc/web/course.html +

    Reading recommendations this week: Refresh linear algebra, GBC chapters 1 and 2. CMB sections 1.1 and 3.1. HTF chapters 2 and 3. Install scikit-learn. See lecture notes for week 34 at https://compphysics.github.io/MachineLearning/doc/web/course.html

    -











    -

    Thursday August 26

    -

    -The lectures will be recorded and updated videos will be posted after the lectures. +

    The lectures will be recorded and updated videos will be posted after the lectures.

    -

    -"Video of Lecture August 26, 2021":"https://www.uio.no/studier/emner/matnat/fys/FYS-STK4155/h21/forelesningsvideoer/LectureThursdayAugust26.mp4?vrtx=view-as-webpage +

    "Video of Lecture August 26, 2021":"https://www.uio.no/studier/emner/matnat/fys/FYS-STK4155/h21/forelesningsvideoer/LectureThursdayAugust26.mp4?vrtx=view-as-webpage

    -

    -Zoom link for lectures: https://msu.zoom.us/j/93311529525?pwd=a1VXSzY4aTFWVy9Rb05mNDJTZ09lZz09 +

    Zoom link for lectures: https://msu.zoom.us/j/93311529525?pwd=a1VXSzY4aTFWVy9Rb05mNDJTZ09lZz09

    • Meeting ID: 933 1152 9525
    • Passcode: 646102
    +

    Video of Lecture from Fall Semester 2020.

    -Video of Lecture from Fall Semester 2020. - -











    -

    Lectures and ComputerLab

    -

    -

    • Lectures: Thursday (12.15pm-2pm and Friday (12.15pm-2pm).
    • Weekly reading assignments and videos needed to solve projects and exercises.
    • @@ -391,17 +444,12 @@ The lectures will be recorded and updated videos will be posted after the lectur
    -











    -

    Announcement

    -

    -NORA AI competetion: See the link here https://www.nora.ai/Competition/image-segmentation.html +

    NORA AI competetion: See the link here https://www.nora.ai/Competition/image-segmentation.html

    -











    -

    Communication channels

    -









    -

    Course Format

    -

    -

    • Three compulsory projects. Electronic reports only using Canvas to hand in projects and git as version control software and GitHub for repository (or GitLab) of all your material.
    • Evaluation and grading: The three projects are graded and each counts 1/3 of the final mark. No final written or oral exam. -
      1. For the last project each group/participant submits a proposal or works with suggested (by us) proposals for the project.
      2. If possible, we would like to organize the last project as a workshop where each group makes a poster and presents this to all other participants of the course
      3. Poster session where all participants can study and discuss the other proposals.
      4. Based on feedback etc, each group finalizes the report and submits for grading.
      -
    • Python is the default programming language, but feel free to use C/C++ and/or Fortran or other programming languages. All source codes discussed during the lectures can be found at the webpage and github address of the course.
    -











    -

    Teachers

    -

    -

    Teachers : -

    • Morten Hjorth-Jensen, morten.hjorth-jensen@fys.uio.no
    • -
      • Phone: +47-48257387
      • Office: Department of Physics, University of Oslo, Eastern wing, room FØ470
      • Office hours: Anytime! Individual or group office hours can be arranged either in person or via zoom. Feel free to send an email for planning.
      -
    • Øyvind Sigmundson Schøyen, oyvinssc@student.matnat.uio.no
    • -
      • Office: Department of Physics, University of Oslo, Eastern wing, room FØ452
      -
    • Stian Dysthe Bilek stian.bilek@fys.uio.no
    • -
      • Office: Department of Physics, University of Oslo, Eastern wing, room FØ450
      -
    • Linus Ekstrøm, linueks@gmail.com, linus.ekstrom@fys.uio.no
    • Nicholas Karlsen, nicholaskarlsen1102@gmail.com, nicholas.karlsen@fys.uio.no
    • Bendik Steinsvåg Dalen, b.s.dalen@fys.uio.no
    • @@ -477,57 +508,44 @@ The lectures will be recorded and updated videos will be posted after the lectur
    -











    -

    Deadlines for projects (tentative)

    -

    1. Project 1: October 11 (available September 10) graded with feedback)
    2. -
    3. Project 2: November 15 (available October 12, graded with feedback)
    4. -
    5. Project 3: December 13 (available November 8, graded with feedback)
    6. +
    7. Project 2: November 20 (available October 12, graded with feedback)
    8. +
    9. Project 3: December 17 (available November 13, graded with feedback)
    - -Projects are handed in using Canvas. We use Github as repository for codes, benchmark calculations etc. Comments and feedback on projects only via Canvas. - - +

    Projects are handed in using Canvas. We use Github as repository for codes, benchmark calculations etc. Comments and feedback on projects only via Canvas.

    -











    -

    1. The lecture notes are collected as a jupyter-book at https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/intro.html.
    - -In addition to the lecture notes, we recommend the books of Bishop and Goodfellow et al. We will follow these texts closely and the weekly reading assignments refer to these two texts. The text by Hastie et al is also widely used in the Machine Learning community. Finally, we also recommend the hands-on text by Geron, see below. +

    In addition to the lecture notes, we recommend the books of Bishop and Goodfellow et al. We will follow these texts closely and the weekly reading assignments refer to these two texts. The text by Hastie et al is also widely used in the Machine Learning community. Finally, we also recommend the hands-on text by Geron, see below.

    1. Christopher M. Bishop, Pattern Recognition and Machine Learning, Springer, https://www.springer.com/gp/book/9780387310732.
    2. Ian Goodfellow, Yoshua Bengio, and Aaron Courville. The different chapters are available for free at https://www.deeplearningbook.org/. Chapters 2-14 are highly recommended. The lectures follow to a larg extent this text. The weekly plans will include reading suggestions from these two textbooks.
    - -Additional textbooks: +

    Additional textbooks:

    1. Trevor Hastie, Robert Tibshirani, Jerome H. Friedman, The Elements of Statistical Learning, Springer, https://www.springer.com/gp/book/9780387848570. This is a well-known text and serves as additional literature.
    2. Aurelien Geron, Hands‑On Machine Learning with Scikit‑Learn and TensorFlow, O'Reilly, https://www.oreilly.com/library/view/hands-on-machine-learning/9781492032632/. This text is very useful since it contains many code examples and hands-on applications of all algorithms discussed in this course.
    -









    -

    Prerequisites

    -

    -Basic knowledge in programming and mathematics, with an emphasis on +

    Basic knowledge in programming and mathematics, with an emphasis on linear algebra. Knowledge of Python or/and C++ as programming languages is strongly recommended and experience with Jupiter notebook is recommended. Required courses are the equivalents to the University @@ -536,19 +554,16 @@ of the corresponding computing and programming courses INF1000/INF1110 or MAT-INF1100/MAT-INF1100L/BIOS1100/KJM-INF1100. Most universities offer nowadays a basic programming course (often compulsory) where Python is the recurring programming language. +

    -











    -

    Learning outcomes

    -

    -

    -This course aims at giving you insights and knowledge about many of +

    This course aims at giving you insights and knowledge about many of the central algorithms used in Data Analysis and Machine Learning. The course is project based and through various numerical projects, normally three, you will be exposed to fundamental research problems @@ -561,6 +576,7 @@ Learning is applied to, get acquainted with computing facilities and learn to handle large scientific projects. A good scientific and ethical conduct is emphasized throughout the course. More specifically, after this course you will +

    • Learn about basic data analysis, statistical analysis, Bayesian statistics, Monte Carlo sampling, data optimization and machine learning;
    • @@ -577,29 +593,22 @@ specifically, after this course you will
    -











    -

    Topics covered in this course: Statistical analysis and optimization of data

    -

    -The course has two central parts +

    The course has two central parts

    1. Statistical analysis and optimization of data
    2. Machine learning
    +

    These topics will be scattered thorughout the course and may not necessarily be taught separately. Rather, we will often take an approach (during the lectures and project/exercise sessions) where say elements from statistical data analysis are mixed with specific Machine Learning algorithms

    -These topics will be scattered thorughout the course and may not necessarily be taught separately. Rather, we will often take an approach (during the lectures and project/exercise sessions) where say elements from statistical data analysis are mixed with specific Machine Learning algorithms - -

    Statistical analysis and optimization of data

    -

    -We plan to cover the following topics: - +

    We plan to cover the following topics:

    • Basic concepts, expectation values, variance, covariance, correlation functions and errors;
    • Simpler models, binomial distribution, the Poisson distribution, simple and multivariate normal distributions;
    • @@ -612,17 +621,13 @@ We plan to cover the following topics:
    -











    -

    Topics covered in this course: Machine Learning

    -

    -The following topics will be covered - +

    The following topics will be covered

    • Linear Regression and Logistic Regression;
    • Neural networks and deep learning, including convolutional and recurrent neural networks
    • @@ -632,23 +637,16 @@ The following topics will be covered
    • Boltzmann Machines
    • Unsupervised learning Dimensionality reduction, from PCA to clustering
    - -Hands-on demonstrations, exercises and projects aim at deepening your understanding of these topics. - - +

    Hands-on demonstrations, exercises and projects aim at deepening your understanding of these topics.

    -











    -

    -

    and discussed at the lab sessions

    -

    • GIT for version control, and GitHub or GitLab as repositories, highly recommended. This will be discussed during the first exercise session
    • Anaconda and other Python environments, see intro slides and links to programming resources at https://computationalscienceuio.github.io/RefreshProgrammingSkills/intro.html
    • @@ -656,13 +654,10 @@ Hands-on demonstrations, exercises and projects aim at deepening your understand
    -











    -

    Other courses on Data science and Machine Learning at UiO

    -

    -The link here 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. +

    The link here 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.

    1. STK2100 Machine learning and statistical methods for prediction and classification.
    2. @@ -677,18 +672,15 @@ The link here STK4051 Computational Statistics
    3. STK4021 Applied Bayesian Analysis and Numerical Methods
    -









    -

    Introduction

    -

    -Our emphasis throughout this series of lectures +

    Our emphasis throughout this series of lectures is on understanding the mathematical aspects of -different algorithms used in the fields of data analysis and machine learning. +different algorithms used in the fields of data analysis and machine learning. +

    -

    -However, where possible we will emphasize the +

    However, where possible we will emphasize the importance of using available software. We start thus with a hands-on and top-down approach to machine learning. The aim is thus to start with relevant data or data we have produced @@ -702,40 +694,38 @@ the data and predictions. We move thereafter to more interesting cases such as data from say experiments (below we will look at experimental nuclear binding energies as an example). These are examples where we can easily set up the data and then use machine learning algorithms included in for example -Scikit-Learn. +Scikit-Learn. +

    -

    -These examples will serve us the purpose of getting +

    These examples will serve us the purpose of getting started. Furthermore, they allow us to catch more than two birds with a stone. They will allow us to bring in some programming specific topics and tools as well as showing the power of various Python -libraries for machine learning and statistical data analysis. +libraries for machine learning and statistical data analysis. +

    -

    -Here, we will mainly focus on two +

    Here, we will mainly focus on two specific Python packages for Machine Learning, Scikit-Learn and Tensorflow (see below for links etc). Moreover, the examples we introduce will serve as inputs to many of our discussions later, as well as allowing you to set up models and produce your own data and get started with programming. +

    -











    -

    What is Machine Learning?

    -

    -Statistics, data science and machine learning form important fields of +

    Statistics, data science and machine learning form important fields of research in modern science. They describe how to learn and make predictions from data, as well as allowing us to extract important correlations about physical process and the underlying laws of motion in large data sets. The latter, big data sets, appear frequently in essentially all disciplines, from the traditional Science, Technology, Mathematics and Engineering fields to Life Science, Law, education -research, the Humanities and the Social Sciences. +research, the Humanities and the Social Sciences. +

    -

    -It has become more +

    It has become more and more common to see research projects on big data in for example the Social Sciences where extracting patterns from complicated survey data is one of many research directions. Having a solid grasp of data @@ -750,17 +740,17 @@ in the private or the public sector. This author has had several students or met students who have been hired recently based on their skills and competences in scientific computing and data science, often with marginal knowledge of machine learning. +

    -

    -Machine learning is a subfield of computer science, and is closely +

    Machine learning is a subfield of computer science, and is closely related to computational statistics. It evolved from the study of pattern recognition in artificial intelligence (AI) research, and has made contributions to AI tasks like computer vision, natural language processing and speech recognition. Many of the methods we will study are also -strongly rooted in basic mathematics and physics research. +strongly rooted in basic mathematics and physics research. +

    -

    -Ideally, machine learning represents the science of giving computers +

    Ideally, machine learning represents the science of giving computers the ability to learn without being explicitly programmed. The idea is that there exist generic algorithms which can be used to find patterns in a broad class of data sets without having to write code @@ -768,10 +758,10 @@ specifically for each problem. The algorithm will build its own logic based on the data. You should however always keep in mind that machines and algorithms are to a large extent developed by humans. The insights and knowledge we have about a specific system, play a central -role when we develop a specific machine learning algorithm. +role when we develop a specific machine learning algorithm. +

    -

    -Machine learning is an extremely rich field, in spite of its young +

    Machine learning is an extremely rich field, in spite of its young age. The increases we have seen during the last three decades in computational capabilities have been followed by developments of methods and techniques for analyzing and handling large date sets, @@ -791,14 +781,12 @@ solid command of linear algebra, multivariate theory, probability theory, statistical data analysis, understanding errors and Monte Carlo methods are central elements in a proper understanding of many of algorithms and methods we will discuss. +

    -











    -

    Types of Machine Learning

    -

    -The approaches to machine learning are many, but are often split into +

    The approaches to machine learning are many, but are often split into two main categories. In supervised learning we know the answer to a problem, and let the computer deduce the logic behind it. On the other hand, unsupervised learning is a method for finding patterns and @@ -807,49 +795,40 @@ Some authours also operate with a third category, namely reinforcement learning. This is a paradigm of learning inspired by behavioral psychology, where learning is achieved by trial-and-error, solely from rewards and punishment. +

    -

    -Another way to categorize machine learning tasks is to consider the +

    Another way to categorize machine learning tasks is to consider the desired output of a system. Some of the most common tasks are: +

    • Classification: Outputs are divided into two or more classes. The goal is to produce a model that assigns inputs into one of these classes. An example is to identify digits based on pictures of hand-written ones. Classification is typically supervised learning.
    • Regression: Finding a functional relationship between an input data set and a reference data set. The goal is to construct a function that maps input data to continuous output values.
    • Clustering: Data are divided into groups with certain common traits, without knowing the different groups beforehand. It is thus a form of unsupervised learning.
    -









    -

    Essential elements of ML

    -

    -The methods we cover have three main topics in common, irrespective of +

    The methods we cover have three main topics in common, irrespective of whether we deal with supervised or unsupervised learning. +

    -
    • The first ingredient is normally our data set (which can be subdivided into training, validation and test data). Many find the most difficult part of using Machine Learning to be the set up of your data in a meaningful way.
    • The second item is a model which is normally a function of some parameters. The model reflects our knowledge of the system (or lack thereof). As an example, if we know that our data show a behavior similar to what would be predicted by a polynomial, fitting our data to a polynomial of some degree would then determin our model.
    • The last ingredient is a so-called cost/loss function (or error or risk function) which allows us to present an estimate on how good our model is in reproducing the data it is supposed to train.
    - -











    -

    An optimization/minimization problem

    -

    -At the heart of basically all Machine Learning algorithms we will encounter so-called minimization or optimization algorithms. A large family of such methods are so-called gradient methods. +

    At the heart of basically all Machine Learning algorithms we will encounter so-called minimization or optimization algorithms. A large family of such methods are so-called gradient methods.

    -











    -

    A Frequentist approach to data analysis

    -

    -When you hear phrases like predictions and estimations and +

    When you hear phrases like predictions and estimations and correlations and causations, what do you think of? May be you think of the difference between classifying new data points and generating new data points. @@ -857,9 +836,9 @@ Or perhaps you consider that correlations represent some kind of symmetric state if \( A \) is correlated with \( B \), then \( B \) is correlated with \( A \). Causation on the other hand is directional, that is if \( A \) causes \( B \), \( B \) does not necessarily cause \( A \). +

    -

    -These concepts are in some sense the difference between machine +

    These concepts are in some sense the difference between machine learning and statistics. In machine learning and prediction based tasks, we are often interested in developing algorithms that are capable of learning patterns from given data in an automated fashion, @@ -868,51 +847,47 @@ assessments of newly given data. In many cases, our primary concern is the quality of the predictions or assessments, and we are less concerned about the underlying patterns that were learned in order to make these predictions. +

    -

    -In machine learning we normally use a so-called frequentist approach, +

    In machine learning we normally use a so-called frequentist approach, where the aim is to make predictions and find correlations. We focus less on for example extracting a probability distribution function (PDF). The PDF can be used in turn to make estimations and find causations such as given \( A \) what is the likelihood of finding \( B \). +

    -











    -

    What is a good model?

    -

    -In science and engineering we often end up in situations where we want to infer (or learn) a +

    In science and engineering we often end up in situations where we want to infer (or learn) a quantitative model \( M \) for a given set of sample points \( \boldsymbol{X} \in [x_1, x_2,\dots x_N] \). +

    -

    -As we will see repeatedely in these lectures, we could try to fit these data points to a model given by a +

    As we will see repeatedely in these lectures, we could try to fit these data points to a model given by a straight line, or if we wish to be more sophisticated to a more complex function. +

    -

    -The reason for inferring such a model is that it +

    The reason for inferring such a model is that it serves many useful purposes. On the one hand, the model can reveal information encoded in the data or underlying mechanisms from which the data were generated. For instance, we could discover important corelations that relate interesting physics interpretations. +

    -

    -In addition, it can simplify the representation of the given data set and help +

    In addition, it can simplify the representation of the given data set and help us in making predictions about future data samples. +

    -

    -A first important consideration to keep in mind is that inferring the correct model +

    A first important consideration to keep in mind is that inferring the correct model for a given data set is an elusive, if not impossible, task. The fundamental difficulty is that if we are not specific about what we mean by a correct model, there could easily be many different models that fit the given data set equally well. +

    -











    -

    What is a good model? Can we define it?

    -

    -The central question is this: what leads us to say that a model is correct or +

    The central question is this: what leads us to say that a model is correct or optimal for a given data set? To make the model inference problem well posed, i.e., to guarantee that there is a unique optimal model for the given data, we need to impose additional assumptions or restrictions on the class of models considered. To @@ -925,98 +900,90 @@ with the simplest possible class of models that is just necessary to describe th or solve the problem at hand. More precisely, the model class should be rich enough to contain at least one model that can fit the data to a desired accuracy and yet be restricted enough that it is relatively simple to find the best model for the given data. +

    -

    -Thus, the most popular strategy is to start from the +

    Thus, the most popular strategy is to start from the simplest class of models and increase the complexity of the models only when the simpler models become inadequate. For instance, if we work with a regression problem to fit a set of sample points, one may first try the simplest class of models, namely linear models, followed obviously by more complex models. +

    -

    -How to evaluate which model fits best the data is something we will come back to over and over again in these sets of lectures. +

    How to evaluate which model fits best the data is something we will come back to over and over again in these sets of lectures.

    -











    -

    Software and needed installations

    -

    -We will make extensive use of Python as programming language and its +

    We will make extensive use of Python as programming language and its myriad of available libraries. You will find Jupyter notebooks invaluable in your work. You can run R codes in the Jupyter/IPython notebooks, with the immediate benefit of visualizing your data. You can also use compiled languages like C++, Rust, Julia, Fortran etc if you prefer. The focus in these lectures will be on Python. +

    -

    -If you have Python installed (we strongly recommend Python3) and you feel +

    If you have Python installed (we strongly recommend Python3) and you feel pretty familiar with installing different packages, we recommend that you install the following Python packages via pip as +

    1. pip install numpy scipy matplotlib ipython scikit-learn mglearn sympy pandas pillow
    +

    For Python3, replace pip with pip3.

    -For Python3, replace pip with pip3. - -

    -For OSX users we recommend, after having installed Xcode, to +

    For OSX users we recommend, after having installed Xcode, to install brew. Brew allows for a seamless installation of additional software via for example +

    1. brew install python3
    - -For Linux users, with its variety of distributions like for example the widely popular Ubuntu distribution, +

    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 +

    1. sudo apt-get install python3 (or python for pyhton2.7)
    +

    etc etc.

    -etc etc. - -











    -

    Python installers

    -

    -If you don't want to perform these operations separately and venture +

    If you don't want to perform these operations separately and venture into the hassle of exploring how to set up dependencies and paths, we recommend two widely used distrubutions which set up all relevant dependencies for Python, namely +

    - -which is an open source +

    which 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. +

    - -is a Python +

    is a Python distribution for scientific and analytic computing distribution and analysis environment, available for free and under a commercial license. +

    -

    -Furthermore, Google's Colab is a free Jupyter notebook environment that requires +

    Furthermore, Google's Colab is a free Jupyter notebook environment that requires no setup and runs entirely in the cloud. Try it out! +

    -











    -

    Useful Python libraries

    -Here we list several useful Python libraries we strongly recommend (if you use anaconda many of these are already there) +

    Here we list several useful Python libraries we strongly recommend (if you use anaconda many of these are already there)

    • NumPy is a highly popular library for large, multi-dimensional arrays and matrices, along with a large collection of high-level mathematical functions to operate on these arrays
    • @@ -1031,13 +998,10 @@ Here we list several useful Python libraries we strongly recommend (if you use a
    • Keras is a high-level neural networks API, written in Python and capable of running on top of TensorFlow, CNTK, or Theano
    • And many more such as pytorch, Theano etc
    -









    -

    Installing R, C++, cython or Julia

    -

    -You will also find it convenient to utilize R. We will mainly +

    You will also find it convenient to utilize R. We will mainly use Python during our lectures and in various projects and exercises. Those of you already familiar with R should feel free to continue using R, keeping @@ -1047,25 +1011,23 @@ notebook allows you to run R codes interactively in your browser. The software library R is really tailored for statistical data analysis and allows for an easy usage of the tools and algorithms we will discuss in these lectures. +

    -

    -To install R with Jupyter notebook +

    To install R with Jupyter notebook follow the link here +

    -











    -

    Installing R, C++, cython, Numba etc

    -

    -For the C++ aficionados, Jupyter/IPython notebook allows you also to +

    For the C++ aficionados, Jupyter/IPython notebook allows you also to install C++ and run codes written in this language interactively in the browser. Since we will emphasize writing many of the algorithms yourself, you can thus opt for either Python or C++ (or Fortran or other compiled languages) as programming languages. +

    -

    -To add more entropy, cython can also be used when running your +

    To add more entropy, cython can also be used when running your notebooks. It means that Python with the jupyter notebook setup allows you to integrate widely popular softwares and tools for scientific computing. Similarly, the @@ -1074,43 +1036,56 @@ capabilities with minimal rewrites of your codes. With its versatility, including symbolic operations, Python offers a unique computational environment. Your jupyter notebook can easily be converted into a nicely rendered PDF file or a Latex file for -further processing. For example, convert to latex as +further processing. For example, convert to latex as +

    -

    - -

    pycod jupyter nbconvert filename.ipynb --to latex 
    -
    -

    -And to add more versatility, the Python package SymPy is a Python library for symbolic mathematics. It aims to become a full-featured computer algebra system (CAS) and is entirely written in Python. + +

    +
    +
    +
    +
    +
    pycod jupyter nbconvert filename.ipynb --to latex 
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    -

    -Finally, if you wish to use the light mark-up language +

    And to add more versatility, the Python package SymPy is a Python library for symbolic mathematics. It aims to become a full-featured computer algebra system (CAS) and is entirely written in Python.

    + +

    Finally, if you wish to use the light mark-up language doconce you can convert a standard ascii text file into various HTML formats, ipython notebooks, latex files, pdf files etc with minimal edits. These lectures were generated using doconce. +

    -











    -

    Numpy examples and Important Matrix and vector handling packages

    -

    -There are several central software libraries for linear algebra and eigenvalue problems. Several of the more +

    There are several central software libraries for linear algebra and eigenvalue problems. Several of the more popular ones have been wrapped into ofter software packages like those from the widely used text Numerical Recipes. The original source codes in many of the available packages are often taken from the widely used software package LAPACK, which follows two other popular packages developed in the 1970s, namely EISPACK and LINPACK. We describe them shortly here. +

    • LINPACK: package for linear equations and least square problems.
    • LAPACK:package for solving symmetric, unsymmetric and generalized eigenvalue problems. From LAPACK's website http://www.netlib.org it is possible to download for free all source codes from this library. Both C/C++ and Fortran versions are available.
    • BLAS (I, II and III): (Basic Linear Algebra Subprograms) are routines that provide standard building blocks for performing basic vector and matrix operations. Blas I is vector operations, II vector-matrix operations and III matrix-matrix operations. Highly parallelized and efficient codes, all available for download from http://www.netlib.org.
    -









    -

    Basic Matrix Features

    -

    Matrix properties reminder

    @@ -1129,15 +1104,14 @@ $$ \end{bmatrix} $$ -

    -The inverse of a matrix is defined by +

    The inverse of a matrix is defined by

    $$ \mathbf{A}^{-1} \cdot \mathbf{A} = I $$ -

    - + +
    @@ -1149,13 +1123,10 @@ $$
    Relations Name matrix elements
    \( A=\left(A^{\dagger}\right )^{-1} \) unitary \( \sum_k a_{ik}a_{jk}^{ < em>}=\sum_k a_{ki}^{ < /em> } a_{kj}=\delta_{ij} \)
    -

    -











    -

    Some famous Matrices

      @@ -1169,16 +1140,13 @@ $$
    • Upper banded with bandwidth \( p \): \( a_{ij}=0 \) for \( i < j+p \)
    • Banded, block upper triangular, block lower triangular....
    -









    -

    More Basic Matrix Features

    -

    Some Equivalent Statements

    -For an \( N\times N \) matrix \( \mathbf{A} \) the following properties are all equivalent +

    For an \( N\times N \) matrix \( \mathbf{A} \) the following properties are all equivalent

    • If the inverse of \( \mathbf{A} \) exists, \( \mathbf{A} \) is nonsingular.
    • @@ -1191,167 +1159,408 @@ For an \( N\times N \) matrix \( \mathbf{A} \) the following properties are all
    -











    -

    Numpy and arrays

    -Numpy provides an easy way to handle arrays in Python. The standard way to import this library is as +

    Numpy provides an easy way to handle arrays in Python. The standard way to import this library is as

    -

    -

    import numpy as np
    -
    -

    -Here follows a simple example where we set up an array of ten elements, all determined by random numbers drawn according to the normal distribution, -

    +

    +
    +
    +
    +
    +
    import numpy as np
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    Here follows a simple example where we set up an array of ten elements, all determined by random numbers drawn according to the normal distribution,

    -
    n = 10
    +
    +
    +
    +
    +
    +
    n = 10
     x = np.random.normal(size=n)
     print(x)
    -
    -

    -We defined a vector \( x \) with \( n=10 \) elements with its values given by the Normal distribution \( N(0,1) \). +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    We defined a vector \( x \) with \( n=10 \) elements with its values given by the Normal distribution \( N(0,1) \). Another alternative is to declare a vector as follows -

    +

    -
    import numpy as np
    +
    +
    +
    +
    +
    +
    import numpy as np
     x = np.array([1, 2, 3])
     print(x)
    -
    -

    -Here we have defined a vector with three elements, with \( x_0=1 \), \( x_1=2 \) and \( x_2=3 \). Note that both Python and C++ +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    Here we have defined a vector with three elements, with \( x_0=1 \), \( x_1=2 \) and \( x_2=3 \). Note that both Python and C++ start numbering array elements from \( 0 \) and on. This means that a vector with \( n \) elements has a sequence of entities \( x_0, x_1, x_2, \dots, x_{n-1} \). We could also let (recommended) Numpy to compute the logarithms of a specific array as -

    +

    -
    import numpy as np
    +
    +
    +
    +
    +
    +
    import numpy as np
     x = np.log(np.array([4, 7, 8]))
     print(x)
    -
    -

    -In the last example we used Numpy's unary function \( np.log \). This function is +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    In the last example we used Numpy's unary function \( np.log \). This function is highly tuned to compute array elements since the code is vectorized and does not require looping. We normaly recommend that you use the Numpy intrinsic functions instead of the corresponding log function from Python's math module. The looping is done explicitely by the np.log function. The alternative, and slower way to compute the logarithms of a vector would be to write +

    -

    -

    import numpy as np
    +
    +
    +
    +
    +
    +
    import numpy as np
     from math import log
     x = np.array([4, 7, 8])
     for i in range(0, len(x)):
         x[i] = log(x[i])
     print(x)
    -
    -

    -We note that our code is much longer already and we need to import the log function from the math module. +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    We note that our code is much longer already and we need to import the log function from the math module. The attentive reader will also notice that the output is \( [1, 1, 2] \). Python interprets automagically our numbers as integers (like the automatic keyword in C++). To change this we could define our array elements to be double precision numbers as -

    +

    -
    import numpy as np
    +
    +
    +
    +
    +
    +
    import numpy as np
     x = np.log(np.array([4, 7, 8], dtype = np.float64))
     print(x)
    -
    -

    -or simply write them as double precision numbers (Python uses 64 bits as default for floating point type variables), that is -

    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    or simply write them as double precision numbers (Python uses 64 bits as default for floating point type variables), that is

    -
    import numpy as np
    +
    +
    +
    +
    +
    +
    import numpy as np
     x = np.log(np.array([4.0, 7.0, 8.0]))
     print(x)
    -
    -

    -To check the number of bytes (remember that one byte contains eight bits for double precision variables), you can use simple use the itemsize functionality (the array \( x \) is actually an object which inherits the functionalities defined in Numpy) as -

    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    To check the number of bytes (remember that one byte contains eight bits for double precision variables), you can use simple use the itemsize functionality (the array \( x \) is actually an object which inherits the functionalities defined in Numpy) as

    -
    import numpy as np
    +
    +
    +
    +
    +
    +
    import numpy as np
     x = np.log(np.array([4.0, 7.0, 8.0]))
     print(x.itemsize)
    -
    -

    -









    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +









    Matrices in Python

    -

    -Having defined vectors, we are now ready to try out matrices. We can +

    Having defined vectors, we are now ready to try out matrices. We can define a \( 3 \times 3 \) real matrix \( \boldsymbol{A} \) as (recall that we user lowercase letters for vectors and uppercase letters for matrices) +

    -

    -

    import numpy as np
    +
    +
    +
    +
    +
    +
    import numpy as np
     A = np.log(np.array([ [4.0, 7.0, 8.0], [3.0, 10.0, 11.0], [4.0, 5.0, 7.0] ]))
     print(A)
    -
    -

    -If we use the shape function we would get \( (3, 3) \) as output, that is verifying that our matrix is a \( 3\times 3 \) matrix. We can slice the matrix and print for example the first column (Python organized matrix elements in a row-major order, see below) as -

    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    If we use the shape function we would get \( (3, 3) \) as output, that is verifying that our matrix is a \( 3\times 3 \) matrix. We can slice the matrix and print for example the first column (Python organized matrix elements in a row-major order, see below) as

    -
    import numpy as np
    +
    +
    +
    +
    +
    +
    import numpy as np
     A = np.log(np.array([ [4.0, 7.0, 8.0], [3.0, 10.0, 11.0], [4.0, 5.0, 7.0] ]))
     # print the first column, row-major order and elements start with 0
     print(A[:,0]) 
    -
    -

    -We can continue this was by printing out other columns or rows. The example here prints out the second column -

    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    We can continue this was by printing out other columns or rows. The example here prints out the second column

    -
    import numpy as np
    +
    +
    +
    +
    +
    +
    import numpy as np
     A = np.log(np.array([ [4.0, 7.0, 8.0], [3.0, 10.0, 11.0], [4.0, 5.0, 7.0] ]))
     # print the first column, row-major order and elements start with 0
     print(A[1,:]) 
    -
    -

    -Numpy contains many other functionalities that allow us to slice, subdivide etc etc arrays. We strongly recommend that you look up the Numpy website for more details. Useful functions when defining a matrix are the np.zeros function which declares a matrix of a given dimension and sets all elements to zero -

    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    Numpy contains many other functionalities that allow us to slice, subdivide etc etc arrays. We strongly recommend that you look up the Numpy website for more details. Useful functions when defining a matrix are the np.zeros function which declares a matrix of a given dimension and sets all elements to zero

    -
    import numpy as np
    +
    +
    +
    +
    +
    +
    import numpy as np
     n = 10
     # define a matrix of dimension 10 x 10 and set all elements to zero
     A = np.zeros( (n, n) )
     print(A) 
    -
    -

    -or initializing all elements to -

    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    or initializing all elements to

    -
    import numpy as np
    +
    +
    +
    +
    +
    +
    import numpy as np
     n = 10
     # define a matrix of dimension 10 x 10 and set all elements to one
     A = np.ones( (n, n) )
     print(A) 
    -
    -

    -or as unitarily distributed random numbers (see the material on random number generators in the statistics part) -

    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    or as unitarily distributed random numbers (see the material on random number generators in the statistics part)

    -
    import numpy as np
    +
    +
    +
    +
    +
    +
    import numpy as np
     n = 10
     # define a matrix of dimension 10 x 10 and set all elements to random numbers with x \in [0, 1]
     A = np.random.rand(n, n)
     print(A) 
    -
    -

    -As we will see throughout these lectures, there are several extremely useful functionalities in Numpy. +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    As we will see throughout these lectures, there are several extremely useful functionalities in Numpy. As an example, consider the discussion of the covariance matrix. Suppose we have defined three vectors \( \boldsymbol{x}, \boldsymbol{y}, \boldsymbol{z} \) with \( n \) elements each. The covariance matrix is defined as +

    $$ \boldsymbol{\Sigma} = \begin{bmatrix} \sigma_{xx} & \sigma_{xy} & \sigma_{xz} \\ \sigma_{yx} & \sigma_{yy} & \sigma_{yz} \\ @@ -1359,13 +1568,14 @@ $$ \end{bmatrix}, $$ -where for example +

    where for example

    $$ \sigma_{xy} =\frac{1}{n} \sum_{i=0}^{n-1}(x_i- \overline{x})(y_i- \overline{y}). $$ -The Numpy function np.cov calculates the covariance elements using the factor \( 1/(n-1) \) instead of \( 1/n \) since it assumes we do not have the exact mean values. +

    The Numpy function np.cov calculates the covariance elements using the factor \( 1/(n-1) \) instead of \( 1/n \) since it assumes we do not have the exact mean values. The following simple function uses the np.vstack function which takes each vector of dimension \( 1\times n \) and produces a \( 3\times n \) matrix \( \boldsymbol{W} \) +

    $$ \boldsymbol{W} = \begin{bmatrix} x_0 & x_1 & x_2 & \dots & x_{n-2} & x_{n-1} \\ y_0 & y_1 & y_2 & \dots & y_{n-2} & y_{n-1} \\ @@ -1373,17 +1583,21 @@ $$ \end{bmatrix}, $$ -

    -which in turn is converted into into the \( 3\times 3 \) covariance matrix +

    which in turn is converted into into the \( 3\times 3 \) covariance matrix \( \boldsymbol{\Sigma} \) via the Numpy function np.cov(). We note that we can also calculate the mean value of each set of samples \( \boldsymbol{x} \) etc using the Numpy function np.mean(x). We can also extract the eigenvalues of the covariance matrix through the np.linalg.eig() function. +

    -

    -

    # Importing various packages
    +
    +
    +
    +
    +
    +
    # Importing various packages
     import numpy as np
     
     n = 100
    @@ -1398,11 +1612,26 @@ Sigma = np.print(Sigma)
     Eigvals, Eigvecs = np.linalg.eig(Sigma)
     print(Eigvals)
    -
    -

    - +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    -
    import numpy as np
    +
    +
    +
    +
    +
    +
    import numpy as np
     import matplotlib.pyplot as plt
     from scipy import sparse
     eye = np.eye(4)
    @@ -1413,30 +1642,49 @@ x = np.l
     y = np.sin(x)
     plt.plot(x,y,marker='x')
     plt.show()
    -
    -

    -









    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +









    Meet the Pandas

    -

    -



    +

    +
    +

    +
    +

    -

    -Another useful Python package is +

    Another useful Python package is pandas, which is an open source library providing high-performance, easy-to-use data structures and data analysis tools for Python. pandas stands for panel data, a term borrowed from econometrics and is an efficient library for data analysis with an emphasis on tabular data. pandas has two major classes, the DataFrame class with two-dimensional data objects and tabular data organized in columns and the class Series with a focus on one-dimensional data objects. Both classes allow you to index data easily as we will see in the examples below. -pandas allows you also to perform mathematical operations on the data, spanning from simple reshapings of vectors and matrices to statistical operations. +pandas allows you also to perform mathematical operations on the data, spanning from simple reshapings of vectors and matrices to statistical operations. +

    -

    -The following simple example shows how we can, in an easy way make tables of our data. Here we define a data set which includes names, place of birth and date of birth, and displays the data in an easy to read way. We will see repeated use of pandas, in particular in connection with classification of data. +

    The following simple example shows how we can, in an easy way make tables of our data. Here we define a data set which includes names, place of birth and date of birth, and displays the data in an easy to read way. We will see repeated use of pandas, in particular in connection with classification of data.

    -

    -

    import pandas as pd
    +
    +
    +
    +
    +
    +
    import pandas as pd
     from IPython.display import display
     data = {'First Name': ["Frodo", "Bilbo", "Aragorn II", "Samwise"],
             'Last Name': ["Baggins", "Baggins","Elessar","Gamgee"],
    @@ -1445,45 +1693,115 @@ data = {'Fi
             }
     data_pandas = pd.DataFrame(data)
     display(data_pandas)
    -
    -

    -In the above we have imported pandas with the shorthand pd, the latter has become the standard way we import pandas. We make then a list of various variables +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    In the above we have imported pandas with the shorthand pd, the latter has become the standard way we import pandas. We make then a list of various variables and reorganize the aboves lists into a DataFrame and then print out a neat table with specific column labels as Name, place of birth and date of birth. Displaying these results, we see that the indices are given by the default numbers from zero to three. pandas is extremely flexible and we can easily change the above indices by defining a new type of indexing as -

    +

    -
    data_pandas = pd.DataFrame(data,index=['Frodo','Bilbo','Aragorn','Sam'])
    +
    +
    +
    +
    +
    +
    data_pandas = pd.DataFrame(data,index=['Frodo','Bilbo','Aragorn','Sam'])
     display(data_pandas)
    -
    -

    -Thereafter we display the content of the row which begins with the index Aragorn -

    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    Thereafter we display the content of the row which begins with the index Aragorn

    -
    display(data_pandas.loc['Aragorn'])
    -
    -

    -We can easily append data to this, for example -

    +

    +
    +
    +
    +
    +
    display(data_pandas.loc['Aragorn'])
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    We can easily append data to this, for example

    -
    new_hobbit = {'First Name': ["Peregrin"],
    +
    +
    +
    +
    +
    +
    new_hobbit = {'First Name': ["Peregrin"],
                   'Last Name': ["Took"],
                   'Place of birth': ["Shire"],
                   'Date of Birth T.A.': [2990]
                   }
     data_pandas=data_pandas.append(pd.DataFrame(new_hobbit, index=['Pippin']))
     display(data_pandas)
    -
    -

    -Here are other examples where we use the DataFrame functionality to handle arrays, now with more interesting features for us, namely numbers. We set up a matrix +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    Here are other examples where we use the DataFrame functionality to handle arrays, now with more interesting features for us, namely numbers. We set up a matrix of dimensionality \( 10\times 5 \) and compute the mean value and standard deviation of each column. Similarly, we can perform mathematial operations like squaring the matrix elements and many other operations. -

    +

    -
    import numpy as np
    +
    +
    +
    +
    +
    +
    import numpy as np
     import pandas as pd
     from IPython.display import display
     np.random.seed(100)
    @@ -1496,13 +1814,30 @@ display(df)
     print(df.mean())
     print(df.std())
     display(df**2)
    -
    -

    -Thereafter we can select specific columns only and plot final results -

    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    Thereafter we can select specific columns only and plot final results

    -
    df.columns = ['First', 'Second', 'Third', 'Fourth', 'Fifth']
    +
    +
    +
    +
    +
    +
    df.columns = ['First', 'Second', 'Third', 'Fourth', 'Fifth']
     df.index = np.arange(10)
     
     display(df)
    @@ -1520,49 +1855,71 @@ plt.show()
     
     df.plot.bar(figsize=(10,6), rot=15)
     plt.show()
    -
    -

    -We can produce a \( 4\times 4 \) matrix -

    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    We can produce a \( 4\times 4 \) matrix

    -
    b = np.arange(16).reshape((4,4))
    +
    +
    +
    +
    +
    +
    b = np.arange(16).reshape((4,4))
     print(b)
     df1 = pd.DataFrame(b)
     print(df1)
    -
    -

    -and many other operations. +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + -

    -The Series class is another important class included in +

    and many other operations.

    + +

    The Series class is another important class included in pandas. You can view it as a specialization of DataFrame but where we have just a single column of data. It shares many of the same features as _DataFrame. As with DataFrame, most operations are vectorized, achieving thereby a high performance when dealing with computations of arrays, in particular labeled arrays. As we will see below it leads also to a very concice code close to the mathematical operations we may be interested in. -For multidimensional arrays, we recommend strongly xarray. xarray has much of the same flexibility as pandas, but allows for the extension to higher dimensions than two. We will see examples later of the usage of both pandas and xarray. +For multidimensional arrays, we recommend strongly xarray. xarray has much of the same flexibility as pandas, but allows for the extension to higher dimensions than two. We will see examples later of the usage of both pandas and xarray. +

    -











    -

    Friday August 27

    -

    -"Video of Lecture August 27, 2021":"https://www.uio.no/studier/emner/matnat/fys/FYS-STK4155/h21/forelesningsvideoer/LectureThursdayAugust27.mp4?vrtx=view-as-webpage +

    "Video of Lecture August 27, 2021":"https://www.uio.no/studier/emner/matnat/fys/FYS-STK4155/h21/forelesningsvideoer/LectureThursdayAugust27.mp4?vrtx=view-as-webpage

    -

    -Video of Lecture from fall 2020 and Handwritten notes +

    Video of Lecture from fall 2020 and Handwritten notes

    -











    +

    Simple linear regression model using scikit-learn

    -

    Simple linear regression model using scikit-learn

    +

    We start with perhaps our simplest possible example, using Scikit-Learn to perform linear regression analysis on a data set produced by us.

    -

    -We start with perhaps our simplest possible example, using Scikit-Learn to perform linear regression analysis on a data set produced by us. - -

    -What follows is a simple Python code where we have defined a function +

    What follows is a simple Python code where we have defined a function \( y \) in terms of the variable \( x \). Both are defined as vectors with \( 100 \) entries. The numbers in the vector \( \boldsymbol{x} \) are given by random numbers generated with a uniform distribution with entries @@ -1570,9 +1927,9 @@ by random numbers generated with a uniform distribution with entries later). These values are then used to define a function \( y(x) \) (tabulated again as a vector) with a linear dependence on \( x \) plus a random noise added via the normal distribution. +

    -

    -The Numpy functions are imported used the import numpy as np +

    The Numpy functions are imported used the import numpy as np statement and the random number generator for the uniform distribution is called using the function np.random.rand(), where we specificy that we want \( 100 \) random variables. Using Numpy we define @@ -1581,13 +1938,13 @@ our case. With the Numpy function randn() we can compute random numbers with the normal distribution (mean value \( \mu \) equal to zero and variance \( \sigma^2 \) set to one) and produce the values of \( y \) assuming a linear dependence as function of \( x \) +

    $$ y = 2x+N(0,1), $$ -

    -where \( N(0,1) \) represents random numbers generated by the normal +

    where \( N(0,1) \) represents random numbers generated by the normal distribution. From Scikit-Learn we import then the LinearRegression functionality and make a prediction \( \tilde{y} = \alpha + \beta x \) using the function fit(x,y). We call the set of @@ -1595,22 +1952,26 @@ data \( (\boldsymbol{x},\boldsymbol{y}) \) for our training data. The Python pac scikit-learn has also a functionality which extracts the above fitting parameters \( \alpha \) and \( \beta \) (see below). Later we will distinguish between training data and test data. +

    -

    -For plotting we use the Python package +

    For plotting we use the Python package matplotlib which produces publication quality figures. Feel free to explore the extensive gallery of examples. In this example we plot our original values of \( x \) and \( y \) as well as the prediction ypredict (\( \tilde{y} \)), which attempts at fitting our data with a straight line. +

    -

    -The Python code follows here. -

    +

    The Python code follows here.

    -
    # Importing various packages
    +
    +
    +
    +
    +
    +
    # Importing various packages
     import numpy as np
     import matplotlib.pyplot as plt
     from sklearn.linear_model import LinearRegression
    @@ -1629,9 +1990,22 @@ plt.xlabel(r
     plt.ylabel(r'$y$')
     plt.title(r'Simple Linear Regression')
     plt.show()
    -
    -

    -This example serves several aims. It allows us to demonstrate several +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    This example serves several aims. It allows us to demonstrate several aspects of data analysis and later machine learning algorithms. The immediate visualization shows that our linear fit is not impressive. It goes through the data points, but there are many @@ -1639,38 +2013,38 @@ outliers which are not reproduced by our linear regression. We could now play around with this small program and change for example the factor in front of \( x \) and the normal distribution. Try to change the function \( y \) to +

    $$ y = 10x+0.01 \times N(0,1), $$ -

    -where \( x \) is defined as before. Does the fit look better? Indeed, by +

    where \( x \) is defined as before. Does the fit look better? Indeed, by reducing the role of the noise given by the normal distribution we see immediately that our linear prediction seemingly reproduces better the training set. However, this testing 'by the eye' is obviouly not satisfactory in the long run. Here we have only defined the training data and our model, and have not discussed a more rigorous approach to the cost function. +

    -

    -We need more rigorous criteria in defining whether we have succeeded or +

    We need more rigorous criteria in defining whether we have succeeded or not in modeling our training data. You will be surprised to see that many scientists seldomly venture beyond this 'by the eye' approach. A standard approach for the cost function is the so-called \( \chi^2 \) function (a variant of the mean-squared error (MSE)) +

    $$ \chi^2 = \frac{1}{n} \sum_{i=0}^{n-1}\frac{(y_i-\tilde{y}_i)^2}{\sigma_i^2}, $$ -

    -where \( \sigma_i^2 \) is the variance (to be defined later) of the entry +

    where \( \sigma_i^2 \) is the variance (to be defined later) of the entry \( y_i \). We may not know the explicit value of \( \sigma_i^2 \), it serves however the aim of scaling the equations and make the cost function -dimensionless. +dimensionless. +

    -

    -Minimizing the cost function is a central aspect of +

    Minimizing the cost function is a central aspect of our discussions to come. Finding its minima as function of the model parameters (\( \alpha \) and \( \beta \) in our case) will be a recurring theme in these series of lectures. Essentially all machine learning @@ -1683,30 +2057,34 @@ employed are various variants of gradient methods. These will be discussed in more detail later. Again, you'll be surprised to hear that many practitioners minimize the above function ''by the eye', popularly dubbed as 'chi by the eye'. That is, change a parameter and see (visually and numerically) that -the \( \chi^2 \) function becomes smaller. +the \( \chi^2 \) function becomes smaller. +

    -

    -There are many ways to define the cost function. A simpler approach is to look at the relative difference between the training data and the predicted data, that is we define +

    There are many ways to define the cost function. A simpler approach is to look at the relative difference between the training data and the predicted data, that is we define the relative error (why would we prefer the MSE instead of the relative error?) as +

    $$ \epsilon_{\mathrm{relative}}= \frac{\vert \boldsymbol{y} -\boldsymbol{\tilde{y}}\vert}{\vert \boldsymbol{y}\vert}. $$ -

    -The squared cost function results in an arithmetic mean-unbiased +

    The squared cost function results in an arithmetic mean-unbiased estimator, and the absolute-value cost function results in a median-unbiased estimator (in the one-dimensional case, and a geometric median-unbiased estimator for the multi-dimensional case). The squared cost function has the disadvantage that it has the tendency to be dominated by outliers. +

    -

    -We can modify easily the above Python code and plot the relative error instead -

    +

    We can modify easily the above Python code and plot the relative error instead

    -
    import numpy as np
    +
    +
    +
    +
    +
    +
    import numpy as np
     import matplotlib.pyplot as plt
     from sklearn.linear_model import LinearRegression
     
    @@ -1722,26 +2100,44 @@ plt.xlabel(r
     plt.ylabel(r'$\epsilon_{\mathrm{relative}}$')
     plt.title(r'Relative error')
     plt.show()
    -
    -

    -Depending on the parameter in front of the normal distribution, we may +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    Depending on the parameter in front of the normal distribution, we may have a small or larger relative error. Try to play around with different training data sets and study (graphically) the value of the relative error. +

    -

    -As mentioned above, Scikit-Learn has an impressive functionality. +

    As mentioned above, Scikit-Learn has an impressive functionality. We can for example extract the values of \( \alpha \) and \( \beta \) and their error estimates, or the variance and standard deviation and many -other properties from the statistical data analysis. +other properties from the statistical data analysis. +

    -

    -Here we show an +

    Here we show an example of the functionality of Scikit-Learn. -

    +

    -
    import numpy as np 
    +
    +
    +
    +
    +
    +
    import numpy as np 
     import matplotlib.pyplot as plt 
     from sklearn.linear_model import LinearRegression 
     from sklearn.metrics import mean_squared_error, r2_score, mean_squared_log_error, mean_absolute_error
    @@ -1768,84 +2164,101 @@ plt.xlabel(r
     plt.ylabel(r'$y$')
     plt.title(r'Linear Regression fit ')
     plt.show()
    -
    -

    -The function coef gives us the parameter \( \beta \) of our fit while intercept yields +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    The function coef gives us the parameter \( \beta \) of our fit while intercept yields \( \alpha \). Depending on the constant in front of the normal distribution, we get values near or far from \( \alpha =2 \) and \( \beta =5 \). Try to play around with different parameters in front of the normal distribution. The function meansquarederror gives us the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error or loss defined as +

    $$ MSE(\boldsymbol{y},\boldsymbol{\tilde{y}}) = \frac{1}{n} \sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, $$ -

    -The smaller the value, the better the fit. Ideally we would like to +

    The smaller the value, the better the fit. Ideally we would like to have an MSE equal zero. The attentive reader has probably recognized this function as being similar to the \( \chi^2 \) function defined above. +

    -

    -The r2score function computes \( R^2 \), the coefficient of +

    The r2score function computes \( R^2 \), the coefficient of determination. It provides a measure of how well future samples are likely to be predicted by the model. Best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse). A constant model that always predicts the expected value of \( \boldsymbol{y} \), disregarding the input features, would get a \( R^2 \) score of \( 0.0 \). +

    -

    -If \( \tilde{\boldsymbol{y}}_i \) is the predicted value of the \( i-th \) sample and \( y_i \) is the corresponding true value, then the score \( R^2 \) is defined as +

    If \( \tilde{\boldsymbol{y}}_i \) is the predicted value of the \( i-th \) sample and \( y_i \) is the corresponding true value, then the score \( R^2 \) is defined as

    $$ R^2(\boldsymbol{y}, \tilde{\boldsymbol{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2}, $$ -where we have defined the mean value of \( \boldsymbol{y} \) as +

    where we have defined the mean value of \( \boldsymbol{y} \) as

    $$ \bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. $$ -Another quantity taht we will meet again in our discussions of regression analysis is +

    Another quantity taht we will meet again in our discussions of regression analysis is the mean absolute error (MAE), a risk metric corresponding to the expected value of the absolute error loss or what we call the \( l1 \)-norm loss. In our discussion above we presented the relative error. The MAE is defined as follows +

    $$ \text{MAE}(\boldsymbol{y}, \boldsymbol{\tilde{y}}) = \frac{1}{n} \sum_{i=0}^{n-1} \left| y_i - \tilde{y}_i \right|. $$ -We present the +

    We present the squared logarithmic (quadratic) error +

    $$ \text{MSLE}(\boldsymbol{y}, \boldsymbol{\tilde{y}}) = \frac{1}{n} \sum_{i=0}^{n - 1} (\log_e (1 + y_i) - \log_e (1 + \tilde{y}_i) )^2, $$ -

    -where \( \log_e (x) \) stands for the natural logarithm of \( x \). This error +

    where \( \log_e (x) \) stands for the natural logarithm of \( x \). This error estimate is best to use when targets having exponential growth, such as population counts, average sales of a commodity over a span of -years etc. +years etc. +

    -

    -Finally, another cost function is the Huber cost function used in robust regression. +

    Finally, another cost function is the Huber cost function used in robust regression.

    -

    -The rationale behind this possible cost function is its reduced +

    The rationale behind this possible cost function is its reduced sensitivity to outliers in the data set. In our discussions on dimensionality reduction and normalization of data we will meet other ways of dealing with outliers. +

    -

    -The Huber cost function is defined as +

    The Huber cost function is defined as

    $$ H_{\delta}(\boldsymbol{a})=\left\{\begin{array}{cc}\frac{1}{2} \boldsymbol{a}^{2}& \text{for }|\boldsymbol{a}|\leq \delta\\ \delta (|\boldsymbol{a}|-\frac{1}{2}\delta ),&\text{otherwise}.\end{array}\right. $$ -Here \( \boldsymbol{a}=\boldsymbol{y} - \boldsymbol{\tilde{y}} \). +

    Here \( \boldsymbol{a}=\boldsymbol{y} - \boldsymbol{\tilde{y}} \).

    -

    -We will discuss in more detail these and other functions in the +

    We will discuss in more detail these and other functions in the various lectures. We conclude this part with another example. Instead of a linear \( x \)-dependence we study now a cubic polynomial and use the polynomial regression analysis tools of scikit-learn. +

    -

    -

    import matplotlib.pyplot as plt
    +
    +
    +
    +
    +
    +
    import matplotlib.pyplot as plt
     import numpy as np
     import random
     from sklearn.linear_model import Ridge
    @@ -1875,74 +2288,85 @@ plt.show()
         return abs(np.sum(err))/len(err)
     
     print (error(y))
    -
    - +
    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    +

    To our real data: nuclear binding energies. Brief reminder on masses and binding energies

    -

    -Let us now dive into nuclear physics and remind ourselves briefly about some basic features about binding +

    Let us now dive into nuclear physics and remind ourselves briefly about some basic features about binding energies. A basic quantity which can be measured for the ground states of nuclei is the atomic mass \( M(N, Z) \) of the neutral atom with -atomic mass number \( A \) and charge \( Z \). The number of neutrons is \( N \). There are indeed several sophisticated experiments worldwide which allow us to measure this quantity to high precision (parts per million even). +atomic mass number \( A \) and charge \( Z \). The number of neutrons is \( N \). There are indeed several sophisticated experiments worldwide which allow us to measure this quantity to high precision (parts per million even). +

    -

    -Atomic masses are usually tabulated in terms of the mass excess defined by +

    Atomic masses are usually tabulated in terms of the mass excess defined by

    $$ \Delta M(N, Z) = M(N, Z) - uA, $$ -where \( u \) is the Atomic Mass Unit +

    where \( u \) is the Atomic Mass Unit

    $$ u = M(^{12}\mathrm{C})/12 = 931.4940954(57) \hspace{0.1cm} \mathrm{MeV}/c^2. $$ -The nucleon masses are +

    The nucleon masses are

    $$ m_p = 1.00727646693(9)u, $$ -and +

    and

    $$ m_n = 939.56536(8)\hspace{0.1cm} \mathrm{MeV}/c^2 = 1.0086649156(6)u. $$ -

    -In the 2016 mass evaluation of by W.J.Huang, G.Audi, M.Wang, F.G.Kondev, S.Naimi and X.Xu +

    In the 2016 mass evaluation of by W.J.Huang, G.Audi, M.Wang, F.G.Kondev, S.Naimi and X.Xu there are data on masses and decays of 3437 nuclei. +

    -

    -The nuclear binding energy is defined as the energy required to break +

    The nuclear binding energy is defined as the energy required to break up a given nucleus into its constituent parts of \( N \) neutrons and \( Z \) protons. In terms of the atomic masses \( M(N, Z) \) the binding energy is defined by +

    $$ BE(N, Z) = ZM_H c^2 + Nm_n c^2 - M(N, Z)c^2 , $$ -where \( M_H \) is the mass of the hydrogen atom and \( m_n \) is the mass of the neutron. +

    where \( M_H \) is the mass of the hydrogen atom and \( m_n \) is the mass of the neutron. In terms of the mass excess the binding energy is given by +

    $$ BE(N, Z) = Z\Delta_H c^2 + N\Delta_n c^2 -\Delta(N, Z)c^2 , $$ -where \( \Delta_H c^2 = 7.2890 \) MeV and \( \Delta_n c^2 = 8.0713 \) MeV. +

    where \( \Delta_H c^2 = 7.2890 \) MeV and \( \Delta_n c^2 = 8.0713 \) MeV.

    -

    -A popular and physically intuitive model which can be used to parametrize +

    A popular and physically intuitive model which can be used to parametrize the experimental binding energies as function of \( A \), is the so-called liquid drop model. The ansatz is based on the following expression +

    $$ BE(N,Z) = a_1A-a_2A^{2/3}-a_3\frac{Z^2}{A^{1/3}}-a_4\frac{(N-Z)^2}{A}, $$ -

    -where \( A \) stands for the number of nucleons and the $a_i$s are parameters which are determined by a fit -to the experimental data. +

    where \( A \) stands for the number of nucleons and the $a_i$s are parameters which are determined by a fit +to the experimental data. +

    -

    -To arrive at the above expression we have assumed that we can make the following assumptions: +

    To arrive at the above expression we have assumed that we can make the following assumptions:

    • There is a volume term \( a_1A \) proportional with the number of nucleons (the energy is also an extensive quantity). When an assembly of nucleons of the same size is packed together into the smallest volume, each interior nucleon has a certain number of other nucleons in contact with it. This contribution is proportional to the volume.
    • @@ -1950,24 +2374,26 @@ To arrive at the above expression we have assumed that we can make the following
    • There is a Coulomb energy term \( a_3\frac{Z^2}{A^{1/3}} \). The electric repulsion between each pair of protons in a nucleus yields less binding.
    • There is an asymmetry term \( a_4\frac{(N-Z)^2}{A} \). This term is associated with the Pauli exclusion principle and reflects the fact that the proton-neutron interaction is more attractive on the average than the neutron-neutron and proton-proton interactions.
    - -We could also add a so-called pairing term, which is a correction term that +

    We could also add a so-called pairing term, which is a correction term that arises from the tendency of proton pairs and neutron pairs to -occur. An even number of particles is more stable than an odd number. - +occur. An even number of particles is more stable than an odd number. +

    Organizing our data

    -

    -Let us start with reading and organizing our data. +

    Let us start with reading and organizing our data. We start with the compilation of masses and binding energies from 2016. After having downloaded this file to our own computer, we are now ready to read the file and start structuring our data. +

    -

    -We start with preparing folders for storing our calculations and the data file over masses and binding energies. We import also various modules that we will find useful in order to present various Machine Learning methods. Here we focus mainly on the functionality of scikit-learn. -

    +

    We start with preparing folders for storing our calculations and the data file over masses and binding energies. We import also various modules that we will find useful in order to present various Machine Learning methods. Here we focus mainly on the functionality of scikit-learn.

    -
    # Common imports
    +
    +
    +
    +
    +
    +
    # Common imports
     import numpy as np
     import pandas as pd
     import matplotlib.pyplot as plt
    @@ -2000,13 +2426,30 @@ DATA_ID = "
         plt.savefig(image_path(fig_id) + ".png", format='png')
     
     infile = open(data_path("MassEval2016.dat"),'r')
    -
    -

    -Before we proceed, we define also a function for making our plots. You can obviously avoid this and simply set up various matplotlib commands every time you need them. You may however find it convenient to collect all such commands in one function and simply call this function. -

    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    Before we proceed, we define also a function for making our plots. You can obviously avoid this and simply set up various matplotlib commands every time you need them. You may however find it convenient to collect all such commands in one function and simply call this function.

    -
    from pylab import plt, mpl
    +
    +
    +
    +
    +
    +
    from pylab import plt, mpl
     plt.style.use('seaborn')
     mpl.rcParams['font.family'] = 'serif'
     
    @@ -2017,20 +2460,37 @@ mpl.rcParams[&#
             plt.xlabel(axlabels[0])
             plt.ylabel(axlabels[1])
         plt.legend(loc=0)
    -
    -

    -Our next step is to read the data on experimental binding energies and +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    Our next step is to read the data on experimental binding energies and reorganize them as functions of the mass number \( A \), the number of protons \( Z \) and neutrons \( N \) using pandas. Before we do this it is always useful (unless you have a binary file or other types of compressed data) to actually open the file and simply take a look at it! +

    -

    -In particular, the program that outputs the final nuclear masses is written in Fortran with a specific format. It means that we need to figure out the format and which columns contain the data we are interested in. Pandas comes with a function that reads formatted output. After having admired the file, we are now ready to start massaging it with pandas. The file begins with some basic format information. -

    +

    In particular, the program that outputs the final nuclear masses is written in Fortran with a specific format. It means that we need to figure out the format and which columns contain the data we are interested in. Pandas comes with a function that reads formatted output. After having admired the file, we are now ready to start massaging it with pandas. The file begins with some basic format information.

    -
    """                                                                                                                         
    +
    +
    +
    +
    +
    +
    """                                                                                                                         
     This is taken from the data file of the mass 2016 evaluation.                                                               
     All files are 3436 lines long with 124 character per line.                                                                  
            Headers are 39 lines long.                                                                                           
    @@ -2040,17 +2500,35 @@ In particular, the program that outputs the final nuclear masses is written in F
        widths=(1,3,5,5,5,1,3,4,1,13,11,11,9,1,2,11,9,1,3,1,12,11,1),                                                            
        Pandas has also a variable header, with length 39 in this case.                                                          
     """
    -
    -

    -The data we are interested in are in columns 2, 3, 4 and 11, giving us +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    The data we are interested in are in columns 2, 3, 4 and 11, giving us the number of neutrons, protons, mass numbers and binding energies, respectively. We add also for the sake of completeness the element name. The data are in fixed-width formatted lines and we will covert them into the pandas DataFrame structure. +

    -

    -

    # Read the experimental data with Pandas
    +
    +
    +
    +
    +
    +
    # Read the experimental data with Pandas
     Masses = pd.read_fwf(infile, usecols=(2,3,4,6,11),
                   names=('N', 'Z', 'A', 'Element', 'Ebinding'),
                   widths=(1,3,5,5,5,1,3,4,1,13,11,11,9,1,2,11,9,1,3,1,12,11,1),
    @@ -2068,58 +2546,129 @@ Masses['Ebinding'] = Masses.groupby('A')
     # Find the rows of the grouped DataFrame with the maximum binding energy.
     Masses = Masses.apply(lambda t: t[t.Ebinding==t.Ebinding.max()])
    -
    -

    -We have now read in the data, grouped them according to the variables we are interested in. +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    We have now read in the data, grouped them according to the variables we are interested in. We see how easy it is to reorganize the data using pandas. If we were to do these operations in C/C++ or Fortran, we would have had to write various functions/subroutines which perform the above reorganizations for us. Having reorganized the data, we can now start to make some simple fits using both the functionalities in numpy and -Scikit-Learn afterwards. +Scikit-Learn afterwards. +

    -

    -Now we define five variables which contain +

    Now we define five variables which contain the number of nucleons \( A \), the number of protons \( Z \) and the number of neutrons \( N \), the element name and finally the energies themselves. -

    +

    -
    A = Masses['A']
    +
    +
    +
    +
    +
    +
    A = Masses['A']
     Z = Masses['Z']
     N = Masses['N']
     Element = Masses['Element']
     Energies = Masses['Ebinding']
     print(Masses)
    -
    -

    -The next step, and we will define this mathematically later, is to set up the so-called design matrix. We will throughout call this matrix \( \boldsymbol{X} \). +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    The next step, and we will define this mathematically later, is to set up the so-called design matrix. We will throughout call this matrix \( \boldsymbol{X} \). It has dimensionality \( p\times n \), where \( n \) is the number of data points and \( p \) are the so-called predictors. In our case here they are given by the number of polynomials in \( A \) we wish to include in the fit. -

    +

    -
    # Now we set up the design matrix X
    +
    +
    +
    +
    +
    +
    # Now we set up the design matrix X
     X = np.zeros((len(A),5))
     X[:,0] = 1
     X[:,1] = A
     X[:,2] = A**(2.0/3.0)
     X[:,3] = A**(-1.0/3.0)
     X[:,4] = A**(-1.0)
    -
    -

    -With scikitlearn we are now ready to use linear regression and fit our data. -

    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    With scikitlearn we are now ready to use linear regression and fit our data.

    -
    clf = skl.LinearRegression().fit(X, Energies)
    +
    +
    +
    +
    +
    +
    clf = skl.LinearRegression().fit(X, Energies)
     fity = clf.predict(X)
    -
    -

    -Pretty simple! +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    Pretty simple! Now we can print measures of how our fit is doing, the coefficients from the fits and plot the final fit together with our data. -

    +

    -
    # The mean squared error                               
    +
    +
    +
    +
    +
    +
    # The mean squared error                               
     print("Mean squared error: %.2f" % mean_squared_error(Energies, fity))
     # Explained variance score: 1 is perfect prediction                                 
     print('Variance score: %.2f' % r2_score(Energies, fity))
    @@ -2139,17 +2688,32 @@ ax.plot(Masses[
     ax.legend()
     save_fig("Masses2016")
     plt.show()
    -
    - +
    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    +

    Seeing the wood for the trees

    -

    -As a teaser, let us now see how we can do this with decision trees using scikit-learn. Later we will switch to so-called random forests! +

    As a teaser, let us now see how we can do this with decision trees using scikit-learn. Later we will switch to so-called random forests!

    -

    -

    #Decision Tree Regression
    +
    +
    +
    +
    +
    +
    #Decision Tree Regression
     from sklearn.tree import DecisionTreeRegressor
     regr_1=DecisionTreeRegressor(max_depth=5)
     regr_2=DecisionTreeRegressor(max_depth=7)
    @@ -2178,16 +2742,32 @@ save_fig("Masses2016Trees")
     plt.show()
     print(Masses)
     print(np.mean( (Energies-y_1)**2))
    -
    - +
    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    +

    And what about using neural networks?

    - -The seaborn package allows us to visualize data in an efficient way. Note that we use scikit-learn's multi-layer perceptron (or feed forward neural network) +

    The seaborn package allows us to visualize data in an efficient way. Note that we use scikit-learn's multi-layer perceptron (or feed forward neural network) functionality. -

    +

    -
    from sklearn.neural_network import MLPRegressor
    +
    +
    +
    +
    +
    +
    from sklearn.neural_network import MLPRegressor
     from sklearn.metrics import accuracy_score
     import seaborn as sns
     
    @@ -2216,30 +2796,38 @@ ax.set_title(&q
     ax.set_ylabel("$\eta$")
     ax.set_xlabel("$\lambda$")
     plt.show()
    -
    - +
    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    +

    A first summary

    -

    -The aim behind these introductory words was to present to you various +

    The aim behind these introductory words was to present to you various Python libraries and their functionalities, in particular libraries like numpy, pandas, xarray and matplotlib and other that make our life much easier -in handling various data sets and visualizing data. +in handling various data sets and visualizing data. +

    -

    -Furthermore, +

    Furthermore, Scikit-Learn allows us with few lines of code to implement popular Machine Learning algorithms for supervised learning. Later we will meet Tensorflow, a powerful library for deep learning. Now it is time to dive more into the details of various methods. We will start with linear regression and try to take a deeper look at what it entails. +

    -











    -

    Why Linear Regression (aka Ordinary Least Squares and family)

    -

    -Fitting a continuous function with linear parameterization in terms of the parameters \( \boldsymbol{\beta} \). - +

    Fitting a continuous function with linear parameterization in terms of the parameters \( \boldsymbol{\beta} \).

    • Method of choice for fitting a continuous function!
    • Gives an excellent introduction to central Machine Learning features with understandable pedagogical links to other methods like Neural Networks, Support Vector Machines etc
    • @@ -2251,50 +2839,42 @@ Fitting a continuous function with linear parameterization in terms of the param
    • Allows for easy hands-on understanding of gradient descent methods
    • and many more features
    - -For more discussions of Ridge and Lasso regression, Wessel van Wieringen's article is highly recommended. +

    For more discussions of Ridge and Lasso regression, Wessel van Wieringen's article is highly recommended. Similarly, Mehta et al's article is also recommended. +

    -











    -

    Regression analysis, overarching aims

    -

    -Regression modeling deals with the description of the sampling distribution of a given random variable \( y \) and how it varies as function of another variable or a set of such variables \( \boldsymbol{x} =[x_0, x_1,\dots, x_{n-1}]^T \). -The first variable is called the dependent, the outcome or the response variable while the set of variables \( \boldsymbol{x} \) is called the independent variable, or the predictor variable or the explanatory variable. - -

    -A regression model aims at finding a likelihood function \( p(\boldsymbol{y}\vert \boldsymbol{x}) \), that is the conditional distribution for \( \boldsymbol{y} \) with a given \( \boldsymbol{x} \). The estimation of \( p(\boldsymbol{y}\vert \boldsymbol{x}) \) is made using a data set with +

    Regression modeling deals with the description of the sampling distribution of a given random variable \( y \) and how it varies as function of another variable or a set of such variables \( \boldsymbol{x} =[x_0, x_1,\dots, x_{n-1}]^T \). +The first variable is called the dependent, the outcome or the response variable while the set of variables \( \boldsymbol{x} \) is called the independent variable, or the predictor variable or the explanatory variable. +

    +

    A regression model aims at finding a likelihood function \( p(\boldsymbol{y}\vert \boldsymbol{x}) \), that is the conditional distribution for \( \boldsymbol{y} \) with a given \( \boldsymbol{x} \). The estimation of \( p(\boldsymbol{y}\vert \boldsymbol{x}) \) is made using a data set with

    • \( n \) cases \( i = 0, 1, 2, \dots, n-1 \)
    • Response (target, dependent or outcome) variable \( y_i \) with \( i = 0, 1, 2, \dots, n-1 \)
    • \( p \) so-called explanatory (independent or predictor) variables \( \boldsymbol{x}_i=[x_{i0}, x_{i1}, \dots, x_{ip-1}] \) with \( i = 0, 1, 2, \dots, n-1 \) and explanatory variables running from \( 0 \) to \( p-1 \). See below for more explicit examples.
    - - The goal of the regression analysis is to extract/exploit relationship between \( \boldsymbol{y} \) and \( \boldsymbol{x} \) in or to infer causal dependencies, approximations to the likelihood functions, functional relationships and to make predictions, making fits and many other things. +

    The goal of the regression analysis is to extract/exploit relationship between \( \boldsymbol{y} \) and \( \boldsymbol{x} \) in or to infer causal dependencies, approximations to the likelihood functions, functional relationships and to make predictions, making fits and many other things.

    -











    -

    Regression analysis, overarching aims II

    -

    -Consider an experiment in which \( p \) characteristics of \( n \) samples are +

    Consider an experiment in which \( p \) characteristics of \( n \) samples are measured. The data from this experiment, for various explanatory variables \( p \) are normally represented by a matrix \( \mathbf{X} \). +

    -

    -The matrix \( \mathbf{X} \) is called the design +

    The matrix \( \mathbf{X} \) is called the design matrix. Additional information of the samples is available in the form of \( \boldsymbol{y} \) (also as above). The variable \( \boldsymbol{y} \) is generally referred to as the response variable. The aim of @@ -2304,73 +2884,62 @@ f(\mathbf{X}_{i,\ast}) \). When no prior knowledge on the form of \( f(\cdot) \) is available, it is common to assume a linear relationship between \( \boldsymbol{X} \) and \( \boldsymbol{y} \). This assumption gives rise to the linear regression model where \( \boldsymbol{\beta} = [\beta_0, \ldots, -\beta_{p-1}]^{T} \) are the regression parameters. - -

    -Linear regression gives us a set of analytical equations for the parameters \( \beta_j \). - +\beta_{p-1}]^{T} \) are the regression parameters. +

    +

    Linear regression gives us a set of analytical equations for the parameters \( \beta_j \).

    -











    -

    Examples

    -In order to understand the relation among the predictors \( p \), the set of data \( n \) and the target (outcome, output etc) \( \boldsymbol{y} \), -consider the model we discussed for describing nuclear binding energies. +

    In order to understand the relation among the predictors \( p \), the set of data \( n \) and the target (outcome, output etc) \( \boldsymbol{y} \), +consider the model we discussed for describing nuclear binding energies. +

    -

    -There we assumed that we could parametrize the data using a polynomial approximation based on the liquid drop model. +

    There we assumed that we could parametrize the data using a polynomial approximation based on the liquid drop model. Assuming +

    $$ BE(A) = a_0+a_1A+a_2A^{2/3}+a_3A^{-1/3}+a_4A^{-1}, $$ -we have five predictors, that is the intercept, the \( A \) dependent term, the \( A^{2/3} \) term and the \( A^{-1/3} \) and \( A^{-1} \) terms. +

    we have five predictors, that is the intercept, the \( A \) dependent term, the \( A^{2/3} \) term and the \( A^{-1/3} \) and \( A^{-1} \) terms. This gives \( p=0,1,2,3,4 \). Furthermore we have \( n \) entries for each predictor. It means that our design matrix is a \( p\times n \) matrix \( \boldsymbol{X} \). +

    -

    -Here the predictors are based on a model we have made. A popular data set which is widely encountered in ML applications is the -so-called credit card default data from Taiwan. The data set contains data on \( n=30000 \) credit card holders with predictors like gender, marital status, age, profession, education, etc. In total there are \( 24 \) such predictors or attributes leading to a design matrix of dimensionality \( 24 \times 30000 \). This is however a classification problem and we will come back to it when we discuss Logistic Regression. - - +

    Here the predictors are based on a model we have made. A popular data set which is widely encountered in ML applications is the +so-called credit card default data from Taiwan. The data set contains data on \( n=30000 \) credit card holders with predictors like gender, marital status, age, profession, education, etc. In total there are \( 24 \) such predictors or attributes leading to a design matrix of dimensionality \( 24 \times 30000 \). This is however a classification problem and we will come back to it when we discuss Logistic Regression. +

    -











    -

    General linear models

    -Before we proceed let us study a case from linear algebra where we aim at fitting a set of data \( \boldsymbol{y}=[y_0,y_1,\dots,y_{n-1}] \). We could think of these data as a result of an experiment or a complicated numerical experiment. These data are functions of a series of variables \( \boldsymbol{x}=[x_0,x_1,\dots,x_{n-1}] \), that is \( y_i = y(x_i) \) with \( i=0,1,2,\dots,n-1 \). The variables \( x_i \) could represent physical quantities like time, temperature, position etc. We assume that \( y(x) \) is a smooth function. +

    Before we proceed let us study a case from linear algebra where we aim at fitting a set of data \( \boldsymbol{y}=[y_0,y_1,\dots,y_{n-1}] \). We could think of these data as a result of an experiment or a complicated numerical experiment. These data are functions of a series of variables \( \boldsymbol{x}=[x_0,x_1,\dots,x_{n-1}] \), that is \( y_i = y(x_i) \) with \( i=0,1,2,\dots,n-1 \). The variables \( x_i \) could represent physical quantities like time, temperature, position etc. We assume that \( y(x) \) is a smooth function.

    -

    -Since obtaining these data points may not be trivial, we want to use these data to fit a function which can allow us to make predictions for values of \( y \) which are not in the present set. The perhaps simplest approach is to assume we can parametrize our function in terms of a polynomial of degree \( n-1 \) with \( n \) points, that is +

    Since obtaining these data points may not be trivial, we want to use these data to fit a function which can allow us to make predictions for values of \( y \) which are not in the present set. The perhaps simplest approach is to assume we can parametrize our function in terms of a polynomial of degree \( n-1 \) with \( n \) points, that is

    $$ y=y(x) \rightarrow y(x_i)=\tilde{y}_i+\epsilon_i=\sum_{j=0}^{n-1} \beta_j x_i^j+\epsilon_i, $$ -where \( \epsilon_i \) is the error in our approximation. - - +

    where \( \epsilon_i \) is the error in our approximation.

    -











    -

    Rewriting the fitting procedure as a linear algebra problem

    -For every set of values \( y_i,x_i \) we have thus the corresponding set of equations +

    For every set of values \( y_i,x_i \) we have thus the corresponding set of equations

    $$ \begin{align*} y_0&=\beta_0+\beta_1x_0^1+\beta_2x_0^2+\dots+\beta_{n-1}x_0^{n-1}+\epsilon_0\\ @@ -2383,29 +2952,27 @@ $$
    -











    -

    Rewriting the fitting procedure as a linear algebra problem, more details

    -Defining the vectors +

    Defining the vectors

    $$ \boldsymbol{y} = [y_0,y_1, y_2,\dots, y_{n-1}]^T, $$ -and +

    and

    $$ \boldsymbol{\beta} = [\beta_0,\beta_1, \beta_2,\dots, \beta_{n-1}]^T, $$ -and +

    and

    $$ \boldsymbol{\epsilon} = [\epsilon_0,\epsilon_1, \epsilon_2,\dots, \epsilon_{n-1}]^T, $$ -and the design matrix +

    and the design matrix

    $$ \boldsymbol{X}= \begin{bmatrix} @@ -2417,29 +2984,27 @@ $$ \end{bmatrix} $$ -we can rewrite our equations as +

    we can rewrite our equations as

    $$ \boldsymbol{y} = \boldsymbol{X}\boldsymbol{\beta}+\boldsymbol{\epsilon}. $$ -The above design matrix is called a Vandermonde matrix. +

    The above design matrix is called a Vandermonde matrix.

    -











    -

    Generalizing the fitting procedure as a linear algebra problem

    -

    -We are obviously not limited to the above polynomial expansions. We +

    We are obviously not limited to the above polynomial expansions. We could replace the various powers of \( x \) with elements of Fourier series or instead of \( x_i^j \) we could have \( \cos{(j x_i)} \) or \( \sin{(j x_i)} \), or time series or other orthogonal functions. For every set of values \( y_i,x_i \) we can then generalize the equations to +

    $$ \begin{align*} @@ -2453,19 +3018,17 @@ y_{n-1}&=\beta_0x_{n-1,0}+\beta_1x_{n-1,2}+\beta_2x_{n-1,2}+\dots+\beta_{n-1}x_{ \end{align*} $$ -

    + Note that we have \( p=n \) here. The matrix is symmetric. This is generally not the case!

    -











    -

    Generalizing the fitting procedure as a linear algebra problem

    -We redefine in turn the matrix \( \boldsymbol{X} \) as +

    We redefine in turn the matrix \( \boldsymbol{X} \) as

    $$ \boldsymbol{X}= \begin{bmatrix} @@ -2477,23 +3040,21 @@ x_{n-1,0}& x_{n-1,1} &x_{n-1,2}& \dots & \dots &x_{n-1,n-1}\\ \end{bmatrix} $$ -and without loss of generality we rewrite again our equations as +

    and without loss of generality we rewrite again our equations as

    $$ \boldsymbol{y} = \boldsymbol{X}\boldsymbol{\beta}+\boldsymbol{\epsilon}. $$ -The left-hand side of this equation is kwown. Our error vector \( \boldsymbol{\epsilon} \) and the parameter vector \( \boldsymbol{\beta} \) are our unknow quantities. How can we obtain the optimal set of \( \beta_i \) values? +

    The left-hand side of this equation is kwown. Our error vector \( \boldsymbol{\epsilon} \) and the parameter vector \( \boldsymbol{\beta} \) are our unknow quantities. How can we obtain the optimal set of \( \beta_i \) values?

    -











    -

    Optimizing our parameters

    -We have defined the matrix \( \boldsymbol{X} \) via the equations +

    We have defined the matrix \( \boldsymbol{X} \) via the equations

    $$ \begin{align*} y_0&=\beta_0x_{00}+\beta_1x_{01}+\beta_2x_{02}+\dots+\beta_{n-1}x_{0n-1}+\epsilon_0\\ @@ -2506,29 +3067,27 @@ y_{n-1}&=\beta_0x_{n-1,0}+\beta_1x_{n-1,2}+\beta_2x_{n-1,2}+\dots+\beta_{n-1}x_{ \end{align*} $$ -

    -As we noted above, we stayed with a system with the design matrix +

    As we noted above, we stayed with a system with the design matrix \( \boldsymbol{X}\in {\mathbb{R}}^{n\times n} \), that is we have \( p=n \). For reasons to come later (algorithmic arguments) we will hereafter define our matrix as \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \), with the predictors refering to the column numbers and the entries \( n \) being the row elements. - - +

    -











    -

    Our model for the nuclear binding energies

    -

    -In our introductory notes we looked at the so-called liquid drop model. Let us remind ourselves about what we did by looking at the code. +

    In our introductory notes we looked at the so-called liquid drop model. Let us remind ourselves about what we did by looking at the code.

    -

    -We restate the parts of the code we are most interested in. -

    +

    We restate the parts of the code we are most interested in.

    -
    # Common imports
    +
    +
    +
    +
    +
    +
    # Common imports
     import numpy as np
     import pandas as pd
     import matplotlib.pyplot as plt
    @@ -2597,73 +3156,81 @@ DesignMatrix = pd.index = A
     DesignMatrix.columns = ['1', 'A', 'A^(2/3)', 'A^(-1/3)', '1/A']
     display(DesignMatrix)
    -
    -

    -With \( \boldsymbol{\beta}\in {\mathbb{R}}^{p\times 1} \), it means that we will hereafter write our equations for the approximation as +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    With \( \boldsymbol{\beta}\in {\mathbb{R}}^{p\times 1} \), it means that we will hereafter write our equations for the approximation as

    $$ \boldsymbol{\tilde{y}}= \boldsymbol{X}\boldsymbol{\beta}, $$ -throughout these lectures. +

    throughout these lectures.

    -











    -

    Optimizing our parameters, more details

    -With the above we use the design matrix to define the approximation \( \boldsymbol{\tilde{y}} \) via the unknown quantity \( \boldsymbol{\beta} \) as +

    With the above we use the design matrix to define the approximation \( \boldsymbol{\tilde{y}} \) via the unknown quantity \( \boldsymbol{\beta} \) as

    $$ \boldsymbol{\tilde{y}}= \boldsymbol{X}\boldsymbol{\beta}, $$ -and in order to find the optimal parameters \( \beta_i \) instead of solving the above linear algebra problem, we define a function which gives a measure of the spread between the values \( y_i \) (which represent hopefully the exact values) and the parameterized values \( \tilde{y}_i \), namely +

    and in order to find the optimal parameters \( \beta_i \) instead of solving the above linear algebra problem, we define a function which gives a measure of the spread between the values \( y_i \) (which represent hopefully the exact values) and the parameterized values \( \tilde{y}_i \), namely

    $$ C(\boldsymbol{\beta})=\frac{1}{n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{\tilde{y}}\right)^T\left(\boldsymbol{y}-\boldsymbol{\tilde{y}}\right)\right\}, $$ -or using the matrix \( \boldsymbol{X} \) and in a more compact matrix-vector notation as +

    or using the matrix \( \boldsymbol{X} \) and in a more compact matrix-vector notation as

    $$ C(\boldsymbol{\beta})=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)^T\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)\right\}. $$ -This function is one possible way to define the so-called cost function. +

    This function is one possible way to define the so-called cost function.

    -

    -It is also common to define +

    It is also common to define the function \( C \) as +

    $$ C(\boldsymbol{\beta})=\frac{1}{2n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2, $$ -since when taking the first derivative with respect to the unknown parameters \( \beta \), the factor of \( 2 \) cancels out. +

    since when taking the first derivative with respect to the unknown parameters \( \beta \), the factor of \( 2 \) cancels out.

    -











    -

    Interpretations and optimizing our parameters

    -

    -The function +

    The function

    $$ C(\boldsymbol{\beta})=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)^T\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)\right\}, $$ -can be linked to the variance of the quantity \( y_i \) if we interpret the latter as the mean value. +

    can be linked to the variance of the quantity \( y_i \) if we interpret the latter as the mean value. When linking (see the discussion below) with the maximum likelihood approach below, we will indeed interpret \( y_i \) as a mean value +

    $$ y_{i}=\langle y_i \rangle = \beta_0x_{i,0}+\beta_1x_{i,1}+\beta_2x_{i,2}+\dots+\beta_{n-1}x_{i,n-1}+\epsilon_i, $$ -

    -where \( \langle y_i \rangle \) is the mean value. Keep in mind also that +

    where \( \langle y_i \rangle \) is the mean value. Keep in mind also that till now we have treated \( y_i \) as the exact value. Normally, the response (dependent or outcome) variable \( y_i \) the outcome of a numerical experiment or another type of experiment and is thus only an @@ -2671,57 +3238,52 @@ approximation to the true value. It is then always accompanied by an error estimate, often limited to a statistical error estimate given by the standard deviation discussed earlier. In the discussion here we will treat \( y_i \) as our exact value for the response variable. +

    -

    -In order to find the parameters \( \beta_i \) we will then minimize the spread of \( C(\boldsymbol{\beta}) \), that is we are going to solve the problem +

    In order to find the parameters \( \beta_i \) we will then minimize the spread of \( C(\boldsymbol{\beta}) \), that is we are going to solve the problem

    $$ {\displaystyle \min_{\boldsymbol{\beta}\in {\mathbb{R}}^{p}}}\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)^T\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)\right\}. $$ -In practical terms it means we will require +

    In practical terms it means we will require

    $$ \frac{\partial C(\boldsymbol{\beta})}{\partial \beta_j} = \frac{\partial }{\partial \beta_j}\left[ \frac{1}{n}\sum_{i=0}^{n-1}\left(y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}\right)^2\right]=0, $$ -which results in +

    which results in

    $$ \frac{\partial C(\boldsymbol{\beta})}{\partial \beta_j} = -\frac{2}{n}\left[ \sum_{i=0}^{n-1}x_{ij}\left(y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}\right)\right]=0, $$ -or in a matrix-vector form as +

    or in a matrix-vector form as

    $$ \frac{\partial C(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}} = 0 = \boldsymbol{X}^T\left( \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right). $$ - -
    -











    -

    Interpretations and optimizing our parameters

    -We can rewrite +

    We can rewrite

    $$ \frac{\partial C(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}} = 0 = \boldsymbol{X}^T\left( \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right), $$ -as +

    as

    $$ \boldsymbol{X}^T\boldsymbol{y} = \boldsymbol{X}^T\boldsymbol{X}\boldsymbol{\beta}, $$ -and if the matrix \( \boldsymbol{X}^T\boldsymbol{X} \) is invertible we have the solution +

    and if the matrix \( \boldsymbol{X}^T\boldsymbol{X} \) is invertible we have the solution

    $$ \boldsymbol{\beta} =\left(\boldsymbol{X}^T\boldsymbol{X}\right)^{-1}\boldsymbol{X}^T\boldsymbol{y}. $$ -

    -We note also that since our design matrix is defined as \( \boldsymbol{X}\in +

    We note also that since our design matrix is defined as \( \boldsymbol{X}\in {\mathbb{R}}^{n\times p} \), the product \( \boldsymbol{X}^T\boldsymbol{X} \in {\mathbb{R}}^{p\times p} \). In the above case we have that \( p \ll n \), in our case \( p=5 \) meaning that we end up with inverting a small @@ -2730,26 +3292,24 @@ matrices to invert. The methods discussed here and for many other supervised learning algorithms like classification with logistic regression or support vector machines, exhibit dimensionalities which allow for the usage of direct linear algebra methods such as LU decomposition or Singular Value Decomposition (SVD) for finding the inverse of the matrix -\( \boldsymbol{X}^T\boldsymbol{X} \). +\( \boldsymbol{X}^T\boldsymbol{X} \). +

    -

    -Small question: Do you think the example we have at hand here (the nuclear binding energies) can lead to problems in inverting the matrix \( \boldsymbol{X}^T\boldsymbol{X} \)? What kind of problems can we expect? +

    Small question: Do you think the example we have at hand here (the nuclear binding energies) can lead to problems in inverting the matrix \( \boldsymbol{X}^T\boldsymbol{X} \)? What kind of problems can we expect?

    -











    -

    Some useful matrix and vector expressions

    -

    -The following matrix and vector relation will be useful here and for the rest of the course. Vectors are always written as boldfaced lower case letters and +

    The following matrix and vector relation will be useful here and for the rest of the course. Vectors are always written as boldfaced lower case letters and matrices as upper case boldfaced letters. +

    $$ \frac{\partial (\boldsymbol{b}^T\boldsymbol{a})}{\partial \boldsymbol{a}} = \boldsymbol{b}, @@ -2768,65 +3328,97 @@ $$ $$









    -

    Interpretations and optimizing our parameters

    -The residuals \( \boldsymbol{\epsilon} \) are in turn given by +

    The residuals \( \boldsymbol{\epsilon} \) are in turn given by

    $$ \boldsymbol{\epsilon} = \boldsymbol{y}-\boldsymbol{\tilde{y}} = \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}, $$ -and with +

    and with

    $$ \boldsymbol{X}^T\left( \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)= 0, $$ -we have +

    we have

    $$ \boldsymbol{X}^T\boldsymbol{\epsilon}=\boldsymbol{X}^T\left( \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)= 0, $$ -meaning that the solution for \( \boldsymbol{\beta} \) is the one which minimizes the residuals. Later we will link this with the maximum likelihood approach. - - +

    meaning that the solution for \( \boldsymbol{\beta} \) is the one which minimizes the residuals. Later we will link this with the maximum likelihood approach.

    -

    -Let us now return to our nuclear binding energies and simply code the above equations. +

    Let us now return to our nuclear binding energies and simply code the above equations.

    -











    -

    Own code for Ordinary Least Squares

    -

    -It is rather straightforward to implement the matrix inversion and obtain the parameters \( \boldsymbol{\beta} \). After having defined the matrix \( \boldsymbol{X} \) we simply need to +

    It is rather straightforward to implement the matrix inversion and obtain the parameters \( \boldsymbol{\beta} \). After having defined the matrix \( \boldsymbol{X} \) we simply need to write -

    +

    -
    # matrix inversion to find beta
    +
    +
    +
    +
    +
    +
    # matrix inversion to find beta
     beta = np.linalg.inv(X.T.dot(X)).dot(X.T).dot(Energies)
     # and then make the prediction
     ytilde = X @ beta
    -
    -

    -Alternatively, you can use the least squares functionality in Numpy as -

    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    Alternatively, you can use the least squares functionality in Numpy as

    -
    fit = np.linalg.lstsq(X, Energies, rcond =None)[0]
    +
    +
    +
    +
    +
    +
    fit = np.linalg.lstsq(X, Energies, rcond =None)[0]
     ytildenp = np.dot(fit,X.T)
    -
    -

    -And finally we plot our fit with and compare with data -

    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    And finally we plot our fit with and compare with data

    -
    Masses['Eapprox']  = ytilde
    +
    +
    +
    +
    +
    +
    Masses['Eapprox']  = ytilde
     # Generate a plot comparing the experimental with the fitted values values.
     fig, ax = plt.subplots()
     ax.set_xlabel(r'$A = N + Z$')
    @@ -2838,200 +3430,266 @@ ax.plot(Masses[
     ax.legend()
     save_fig("Masses2016OLS")
     plt.show()
    -
    -

    -









    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +









    Adding error analysis and training set up

    -

    -We can easily test our fit by computing the \( R2 \) score that we discussed in connection with the functionality of Scikit-Learn in the introductory slides. +

    We can easily test our fit by computing the \( R2 \) score that we discussed in connection with the functionality of Scikit-Learn in the introductory slides. Since we are not using Scikit-Learn here we can define our own \( R2 \) function as -

    +

    -
    def R2(y_data, y_model):
    +
    +
    +
    +
    +
    +
    def R2(y_data, y_model):
         return 1 - np.sum((y_data - y_model) ** 2) / np.sum((y_data - np.mean(y_data)) ** 2)
    -
    -

    -and we would be using it as -

    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    and we would be using it as

    -
    print(R2(Energies,ytilde))
    -
    -

    -We can easily add our MSE score as -

    +

    +
    +
    +
    +
    +
    print(R2(Energies,ytilde))
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    We can easily add our MSE score as

    -
    def MSE(y_data,y_model):
    +
    +
    +
    +
    +
    +
    def MSE(y_data,y_model):
         n = np.size(y_model)
         return np.sum((y_data-y_model)**2)/n
     
     print(MSE(Energies,ytilde))
    -
    -

    -and finally the relative error as -

    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    and finally the relative error as

    -
    def RelativeError(y_data,y_model):
    +
    +
    +
    +
    +
    +
    def RelativeError(y_data,y_model):
         return abs((y_data-y_model)/y_data)
     print(RelativeError(Energies, ytilde))
    -
    -

    -









    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +









    The \( \chi^2 \) function

    -

    -Normally, the response (dependent or outcome) variable \( y_i \) is the +

    Normally, the response (dependent or outcome) variable \( y_i \) is the outcome of a numerical experiment or another type of experiment and is thus only an approximation to the true value. It is then always accompanied by an error estimate, often limited to a statistical error estimate given by the standard deviation discussed earlier. In the discussion here we will treat \( y_i \) as our exact value for the response variable. +

    -

    -Introducing the standard deviation \( \sigma_i \) for each measurement +

    Introducing the standard deviation \( \sigma_i \) for each measurement \( y_i \), we define now the \( \chi^2 \) function (omitting the \( 1/n \) term) as +

    $$ \chi^2(\boldsymbol{\beta})=\frac{1}{n}\sum_{i=0}^{n-1}\frac{\left(y_i-\tilde{y}_i\right)^2}{\sigma_i^2}=\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{\tilde{y}}\right)^T\frac{1}{\boldsymbol{\Sigma^2}}\left(\boldsymbol{y}-\boldsymbol{\tilde{y}}\right)\right\}, $$ -where the matrix \( \boldsymbol{\Sigma} \) is a diagonal matrix with \( \sigma_i \) as matrix elements. - - +

    where the matrix \( \boldsymbol{\Sigma} \) is a diagonal matrix with \( \sigma_i \) as matrix elements.

    -











    -

    The \( \chi^2 \) function

    -

    -In order to find the parameters \( \beta_i \) we will then minimize the spread of \( \chi^2(\boldsymbol{\beta}) \) by requiring +

    In order to find the parameters \( \beta_i \) we will then minimize the spread of \( \chi^2(\boldsymbol{\beta}) \) by requiring

    $$ \frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \beta_j} = \frac{\partial }{\partial \beta_j}\left[ \frac{1}{n}\sum_{i=0}^{n-1}\left(\frac{y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}}{\sigma_i}\right)^2\right]=0, $$ -which results in +

    which results in

    $$ \frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \beta_j} = -\frac{2}{n}\left[ \sum_{i=0}^{n-1}\frac{x_{ij}}{\sigma_i}\left(\frac{y_i-\beta_0x_{i,0}-\beta_1x_{i,1}-\beta_2x_{i,2}-\dots-\beta_{n-1}x_{i,n-1}}{\sigma_i}\right)\right]=0, $$ -or in a matrix-vector form as +

    or in a matrix-vector form as

    $$ \frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}} = 0 = \boldsymbol{A}^T\left( \boldsymbol{b}-\boldsymbol{A}\boldsymbol{\beta}\right). $$ -where we have defined the matrix \( \boldsymbol{A} =\boldsymbol{X}/\boldsymbol{\Sigma} \) with matrix elements \( a_{ij} = x_{ij}/\sigma_i \) and the vector \( \boldsymbol{b} \) with elements \( b_i = y_i/\sigma_i \). +

    where we have defined the matrix \( \boldsymbol{A} =\boldsymbol{X}/\boldsymbol{\Sigma} \) with matrix elements \( a_{ij} = x_{ij}/\sigma_i \) and the vector \( \boldsymbol{b} \) with elements \( b_i = y_i/\sigma_i \).

    -











    -

    The \( \chi^2 \) function

    -

    -We can rewrite +

    We can rewrite

    $$ \frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}} = 0 = \boldsymbol{A}^T\left( \boldsymbol{b}-\boldsymbol{A}\boldsymbol{\beta}\right), $$ -as +

    as

    $$ \boldsymbol{A}^T\boldsymbol{b} = \boldsymbol{A}^T\boldsymbol{A}\boldsymbol{\beta}, $$ -and if the matrix \( \boldsymbol{A}^T\boldsymbol{A} \) is invertible we have the solution +

    and if the matrix \( \boldsymbol{A}^T\boldsymbol{A} \) is invertible we have the solution

    $$ \boldsymbol{\beta} =\left(\boldsymbol{A}^T\boldsymbol{A}\right)^{-1}\boldsymbol{A}^T\boldsymbol{b}. $$
    -











    -

    The \( \chi^2 \) function

    -

    -If we then introduce the matrix +

    If we then introduce the matrix

    $$ \boldsymbol{H} = \left(\boldsymbol{A}^T\boldsymbol{A}\right)^{-1}, $$ -we have then the following expression for the parameters \( \beta_j \) (the matrix elements of \( \boldsymbol{H} \) are \( h_{ij} \)) +

    we have then the following expression for the parameters \( \beta_j \) (the matrix elements of \( \boldsymbol{H} \) are \( h_{ij} \))

    $$ \beta_j = \sum_{k=0}^{p-1}h_{jk}\sum_{i=0}^{n-1}\frac{y_i}{\sigma_i}\frac{x_{ik}}{\sigma_i} = \sum_{k=0}^{p-1}h_{jk}\sum_{i=0}^{n-1}b_ia_{ik} $$ -We state without proof the expression for the uncertainty in the parameters \( \beta_j \) as (we leave this as an exercise) +

    We state without proof the expression for the uncertainty in the parameters \( \beta_j \) as (we leave this as an exercise)

    $$ \sigma^2(\beta_j) = \sum_{i=0}^{n-1}\sigma_i^2\left( \frac{\partial \beta_j}{\partial y_i}\right)^2, $$ -resulting in +

    resulting in

    $$ \sigma^2(\beta_j) = \left(\sum_{k=0}^{p-1}h_{jk}\sum_{i=0}^{n-1}a_{ik}\right)\left(\sum_{l=0}^{p-1}h_{jl}\sum_{m=0}^{n-1}a_{ml}\right) = h_{jj}! $$
    -











    -

    The \( \chi^2 \) function

    -The first step here is to approximate the function \( y \) with a first-order polynomial, that is we write +

    The first step here is to approximate the function \( y \) with a first-order polynomial, that is we write

    $$ y=y(x) \rightarrow y(x_i) \approx \beta_0+\beta_1 x_i. $$ -By computing the derivatives of \( \chi^2 \) with respect to \( \beta_0 \) and \( \beta_1 \) show that these are given by +

    By computing the derivatives of \( \chi^2 \) with respect to \( \beta_0 \) and \( \beta_1 \) show that these are given by

    $$ \frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \beta_0} = -2\left[ \frac{1}{n}\sum_{i=0}^{n-1}\left(\frac{y_i-\beta_0-\beta_1x_{i}}{\sigma_i^2}\right)\right]=0, $$ -and +

    and

    $$ \frac{\partial \chi^2(\boldsymbol{\beta})}{\partial \beta_1} = -\frac{2}{n}\left[ \sum_{i=0}^{n-1}x_i\left(\frac{y_i-\beta_0-\beta_1x_{i}}{\sigma_i^2}\right)\right]=0. $$
    -











    -

    The \( \chi^2 \) function

    -

    -For a linear fit (a first-order polynomial) we don't need to invert a matrix!! +

    For a linear fit (a first-order polynomial) we don't need to invert a matrix!! Defining +

    $$ \gamma = \sum_{i=0}^{n-1}\frac{1}{\sigma_i^2}, $$ @@ -3056,8 +3714,7 @@ $$ \gamma_{xy} = \sum_{i=0}^{n-1}\frac{y_ix_{i}}{\sigma_i^2}, $$ -

    -we obtain +

    we obtain

    $$ \beta_0 = \frac{\gamma_{xx}\gamma_y-\gamma_x\gamma_y}{\gamma\gamma_{xx}-\gamma_x^2}, @@ -3068,50 +3725,48 @@ $$ \beta_1 = \frac{\gamma_{xy}\gamma-\gamma_x\gamma_y}{\gamma\gamma_{xx}-\gamma_x^2}. $$ -

    -This approach (different linear and non-linear regression) suffers +

    This approach (different linear and non-linear regression) suffers often from both being underdetermined and overdetermined in the unknown coefficients \( \beta_i \). A better approach is to use the Singular Value Decomposition (SVD) method discussed next week. - - +

    -











    -

    Fitting an Equation of State for Dense Nuclear Matter

    -

    -Before we continue, let us introduce yet another example. We are going to fit the +

    Before we continue, let us introduce yet another example. We are going to fit the nuclear equation of state using results from many-body calculations. The equation of state we have made available here, as function of density, has been derived using modern nucleon-nucleon potentials with the addition of three-body forces. This time the file is presented as a standard csv file. +

    -

    -The beginning of the Python code here is similar to what you have seen +

    The beginning of the Python code here is similar to what you have seen before, with the same initializations and declarations. We use also pandas again, rather extensively in order to organize our data. +

    -

    -The difference now is that we use Scikit-Learn's regression tools +

    The difference now is that we use Scikit-Learn's regression tools instead of our own matrix inversion implementation. Furthermore, we sneak in Ridge regression (to be discussed below) which includes a hyperparameter \( \lambda \), also to be explained below. +

    -











    -

    The code

    -

    -

    # Common imports
    +
    +
    +
    +
    +
    +
    # Common imports
     import os
     import numpy as np
     import pandas as pd
    @@ -3196,23 +3851,34 @@ ax.plot(EoS[
     ax.legend()
     save_fig("EoSfitting")
     plt.show()
    -
    -

    -The above simple polynomial in density \( \rho \) gives an excellent fit -to the data. +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + -

    -We note also that there is a small deviation between the +

    The above simple polynomial in density \( \rho \) gives an excellent fit +to the data. +

    + +

    We note also that there is a small deviation between the standard OLS and the Ridge regression at higher densities. We discuss this in more detail below. +

    -











    -

    Splitting our Data in Training and Test data

    -

    -It is normal in essentially all Machine Learning studies to split the +

    It is normal in essentially all Machine Learning studies to split the data in a training set and a test set (sometimes also an additional validation set). Scikit-Learn has an own function for this. There is no explicit recipe for how much data should be included as training @@ -3222,11 +3888,16 @@ postpone a discussion of this splitting to the end of these notes and our discussion of the so-called bias-variance tradeoff. Here we limit ourselves to repeat the above equation of state fitting example but now splitting the data into a training set and a test set. +

    -

    -

    import os
    +
    +
    +
    +
    +
    +
    import os
     import numpy as np
     import pandas as pd
     import matplotlib.pyplot as plt
    @@ -3290,144 +3961,172 @@ ypredict = X_test print(R2(y_test,ypredict))
     print("Test MSE")
     print(MSE(y_test,ypredict))
    -
    -

    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +









    -

    Exercises for week 35

    -Here are three possible exercises for week 35 and the lab sessions of Wednesday September 1. +

    Here are three possible exercises for week 35 and the lab sessions of Wednesday September 1.

    -

    -

    Exercise 1: Setting up various Python environments

    -

    -The first exercise here is of a mere technical art. We want you to have - +

    The first exercise here is of a mere technical art. We want you to have

    • git as a version control software and to establish a user account on a provider like GitHub. Other providers like GitLab etc are equally fine. You can also use the University of Oslo GitHub facilities.
    • Install various Python packages
    - -We will make extensive use of Python as programming language and its +

    We will make extensive use of Python as programming language and its myriad of available libraries. You will find IPython/Jupyter notebooks invaluable in your work. You can run R codes in the Jupyter/IPython notebooks, with the immediate benefit of visualizing your data. You can also use compiled languages like C++, Rust, Fortran etc if you prefer. The focus in these lectures will be on Python. +

    -

    -If you have Python installed (we recommend Python3) and you feel +

    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 +

    1. pip install numpy scipy matplotlib ipython scikit-learn sympy pandas pillow
    - -For Tensorflow, we recommend following the instructions in the text of +

    For Tensorflow, we recommend following the instructions in the text of Aurelien Geron, Hands‑On Machine Learning with Scikit‑Learn and TensorFlow, O'Reilly +

    -

    -We will come back to tensorflow later. +

    We will come back to tensorflow later.

    -

    -For Python3, replace pip with pip3. +

    For Python3, replace pip with pip3.

    -

    -For OSX users we recommend, after having installed Xcode, to +

    For OSX users we recommend, after having installed Xcode, to install brew. Brew allows for a seamless installation of additional software via for example +

    1. brew install python3
    - -For Linux users, with its variety of distributions like for example the widely popular Ubuntu distribution, +

    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 +

    1. sudo apt-get install python3 (or python for Python2.7)
    - -If you don't want to perform these operations separately and venture +

    If you don't want to perform these operations separately and venture into the hassle of exploring how to set up dependencies and paths, we recommend two widely used distrubutions which set up all relevant dependencies for Python, namely +

    - -which is an open source +

    which 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. +

    - -is a Python +

    is a Python distribution for scientific and analytic computing distribution and analysis environment, available for free and under a commercial license. +

    -

    -We recommend using Anaconda if you are not too familiar with setting paths in a terminal environment. +

    We recommend using Anaconda if you are not too familiar with setting paths in a terminal environment.

    -

    -

    -

    Exercise 2: making your own data and exploring scikit-learn

    -

    -We will generate our own dataset for a function \( y(x) \) where \( x \in [0,1] \) and defined by random numbers computed with the uniform distribution. The function \( y \) is a quadratic polynomial in \( x \) with added stochastic noise according to the normal distribution \( \cal {N}(0,1) \). +

    We will generate our own dataset for a function \( y(x) \) where \( x \in [0,1] \) and defined by random numbers computed with the uniform distribution. The function \( y \) is a quadratic polynomial in \( x \) with added stochastic noise according to the normal distribution \( \cal {N}(0,1) \). The following simple Python instructions define our \( x \) and \( y \) values (with 100 data points). -

    +

    -
    x = np.random.rand(100,1)
    +
    +
    +
    +
    +
    +
    x = np.random.rand(100,1)
     y = 2.0+5*x*x+0.1*np.random.randn(100,1)
    -
    +
    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +
    1. Write your own code (following the examples under the regression notes) for computing the parametrization of the data set fitting a second-order polynomial.
    2. Use thereafter scikit-learn (see again the examples in the regression slides) and compare with your own code.
    3. Using scikit-learn, compute also the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error defined as
    - $$ MSE(\boldsymbol{y},\boldsymbol{\tilde{y}}) = \frac{1}{n} \sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, $$ -and the \( R^2 \) score function. +

    and the \( R^2 \) score function. If \( \tilde{\boldsymbol{y}}_i \) is the predicted value of the \( i-th \) sample and \( y_i \) is the corresponding true value, then the score \( R^2 \) is defined as +

    $$ R^2(\boldsymbol{y}, \tilde{\boldsymbol{y}}) = 1 - \frac{\sum_{i=0}^{n - 1} (y_i - \tilde{y}_i)^2}{\sum_{i=0}^{n - 1} (y_i - \bar{y})^2}, $$ -where we have defined the mean value of \( \boldsymbol{y} \) as +

    where we have defined the mean value of \( \boldsymbol{y} \) as

    $$ \bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. $$ -You can use the functionality included in scikit-learn. If you feel for it, you can use your own program and define functions which compute the above two functions. +

    You can use the functionality included in scikit-learn. If you feel for it, you can use your own program and define functions which compute the above two functions. Discuss the meaning of these results. Try also to vary the coefficient in front of the added stochastic noise term and discuss the quality of the fits. +

    -

    +

    Solution. The code here is an example of where we define our own design matrix and fit parameters \( \beta \). -

    +

    -
    import os
    +
    +
    +
    +
    +
    +
    import os
     import numpy as np
     import pandas as pd
     import matplotlib.pyplot as plt
    @@ -3467,26 +4166,36 @@ ypredict = X_test print(R2(y_test,ypredict))
     print("Test MSE")
     print(MSE(y_test,ypredict))
    -
    -

    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + + -

    -

    -

    Exercise 3: Normalizing our data

    -

    -A much used approach before starting to train the data is to preprocess our +

    A much used approach before starting to train the data is to preprocess our data. Normally the data may need a rescaling and/or may be sensitive to extreme values. Scaling the data renders our inputs much more suitable for the algorithms we want to employ. +

    -

    -Scikit-Learn has several functions which allow us to rescale the +

    Scikit-Learn has several functions which allow us to rescale the data, normally resulting in much better results in terms of various accuracy scores. The StandardScaler function in Scikit-Learn ensures that for each feature/predictor we study the mean value is @@ -3495,18 +4204,18 @@ matrix). This scaling has the drawback that it does not ensure that we have a particular maximum or minimum in our data set. Another function included in Scikit-Learn is the MinMaxScaler which ensures that all features are exactly between \( 0 \) and \( 1 \). The +

    -

    -The Normalizer scales each data +

    The Normalizer scales each data point such that the feature vector has a euclidean length of one. In other words, it projects a data point on the circle (or sphere in the case of higher dimensions) with a radius of 1. This means every data point is scaled by a different number (by the inverse of it’s length). This normalization is often used when only the direction (or angle) of the data matters, not the length of the feature vector. +

    -

    -The RobustScaler works similarly to the StandardScaler in that it +

    The RobustScaler works similarly to the StandardScaler in that it ensures statistical properties for each feature that guarantee that they are on the same scale. However, the RobustScaler uses the median and quartiles, instead of mean and variance. This makes the @@ -3514,74 +4223,131 @@ RobustScaler ignore data points that are very different from the rest (like measurement errors). These odd data points are also called outliers, and might often lead to trouble for other scaling techniques. +

    -

    -It also common to split the data in a training set and a testing set. A typical split is to use \( 80\% \) of the data for training and the rest +

    It also common to split the data in a training set and a testing set. A typical split is to use \( 80\% \) of the data for training and the rest for testing. This can be done as follows with our design matrix \( \boldsymbol{X} \) and data \( \boldsymbol{y} \) (remember to import scikit-learn) -

    +

    -
    # split in training and test data
    +
    +
    +
    +
    +
    +
    # split in training and test data
     X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.2)
    -
    -

    -Then we can use the standard scaler to scale our data as -

    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    Then we can use the standard scaler to scale our data as

    -
    scaler = StandardScaler()
    +
    +
    +
    +
    +
    +
    scaler = StandardScaler()
     scaler.fit(X_train)
     X_train_scaled = scaler.transform(X_train)
     X_test_scaled = scaler.transform(X_test)
    -
    -

    -In this exercise we want you to to compute the MSE for the training +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    In this exercise we want you to to compute the MSE for the training data and the test data as function of the complexity of a polynomial, -that is the degree of a given polynomial. We want you also to compute the \( R2 \) score as function of the complexity of the model for both training data and test data. You should also run the calculation with and without scaling. +that is the degree of a given polynomial. We want you also to compute the \( R2 \) score as function of the complexity of the model for both training data and test data. You should also run the calculation with and without scaling. +

    -

    -One of +

    One of the aims is to reproduce Figure 2.11 of Hastie et al. +

    -

    -Our data is defined by \( x\in [-3,3] \) with a total of for example \( 100 \) data points. -

    +

    Our data is defined by \( x\in [-3,3] \) with a total of for example \( 100 \) data points.

    -
    np.random.seed()
    +
    +
    +
    +
    +
    +
    np.random.seed()
     n = 100
     maxdegree = 14
     # Make data set.
     x = np.linspace(-3, 3, n).reshape(-1, 1)
     y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
    -
    -

    -where \( y \) is the function we want to fit with a given polynomial. +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + +

    where \( y \) is the function we want to fit with a given polynomial.

    + +

    a) Write a first code which sets up a design matrix \( X \) defined by a fifth-order polynomial. Scale your data and split it in training and test data. +

    + + +

    b) Perform an ordinary least squares and compute the means squared error and the \( R2 \) factor for the training data and the test data, with and without scaling. +

    + + +

    c) Add now a model which allows you to make polynomials up to degree \( 15 \). Perform a standard OLS fitting of the training data and compute the MSE and \( R2 \) for the training and test data and plot both test and training data MSE and \( R2 \) as functions of the polynomial degree. Compare what you see with Figure 2.11 of Hastie et al. Comment your results. For which polynomial degree do you find an optimal MSE (smallest value)? +

    + + -

    - - -

    © 1999-2021, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
    - - - diff --git a/doc/pub/week34/ipynb/ipynb-week34-src.tar.gz b/doc/pub/week34/ipynb/ipynb-week34-src.tar.gz index c9c5818ce..fb3386a2f 100644 Binary files a/doc/pub/week34/ipynb/ipynb-week34-src.tar.gz and b/doc/pub/week34/ipynb/ipynb-week34-src.tar.gz differ diff --git a/doc/pub/week34/ipynb/week34.ipynb b/doc/pub/week34/ipynb/week34.ipynb index 3c16b014b..a4065e2da 100644 --- a/doc/pub/week34/ipynb/week34.ipynb +++ b/doc/pub/week34/ipynb/week34.ipynb @@ -2,25 +2,38 @@ "cells": [ { "cell_type": "markdown", - "metadata": {}, + "id": "778fa583", + "metadata": { + "editable": true + }, + "source": [ + "\n", + "" + ] + }, + { + "cell_type": "markdown", + "id": "a6b35c1f", + "metadata": { + "editable": true + }, "source": [ - "\n", "# Week 34: Introduction to the course, Logistics and Practicalities\n", - "\n", - " \n", "**Morten Hjorth-Jensen**, Department of Physics, University of Oslo and Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University\n", "\n", - "Date: **Oct 12, 2021**\n", - "\n", - "Copyright 1999-2021, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", + "Date: **Nov 13, 2021**\n", "\n", + "Copyright 1999-2021, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license" + ] + }, + { + "cell_type": "markdown", + "id": "fc8efbd6", + "metadata": { + "editable": true + }, + "source": [ "## Overview of first week\n", "\n", " * Wednesday August 25: Introduction to software and repetition of Python Programming\n", @@ -31,10 +44,16 @@ "\n", " * Friday August 27: Linear regression \n", "\n", - " * Computer lab: Wednesdays, 8am-6pm. First time: Wednesday August 25.\n", - "\n", - "\n", - "\n", + " * Computer lab: Wednesdays, 8am-6pm. First time: Wednesday August 25." + ] + }, + { + "cell_type": "markdown", + "id": "4e83c342", + "metadata": { + "editable": true + }, + "source": [ "## Reading Recommendations\n", "\n", "For the reading assignments we use the following abbreviations:\n", @@ -46,32 +65,38 @@ "\n", "* AG: Aurelien Geron, Hands‑On Machine Learning with Scikit‑Learn and TensorFlow\n", "\n", - "Reading recommendations this week: Refresh linear algebra, GBC chapters 1 and 2. CMB sections 1.1 and 3.1. HTF chapters 2 and 3. Install scikit-learn. See lecture notes for week 34 at \n", - "\n", - "\n", - "\n", - "\n", + "Reading recommendations this week: Refresh linear algebra, GBC chapters 1 and 2. CMB sections 1.1 and 3.1. HTF chapters 2 and 3. Install scikit-learn. See lecture notes for week 34 at " + ] + }, + { + "cell_type": "markdown", + "id": "fcee1694", + "metadata": { + "editable": true + }, + "source": [ "## Thursday August 26\n", "\n", - "\n", - "\n", - "\n", "The lectures will be recorded and updated videos will be posted after the lectures. \n", "\n", "\"Video of Lecture August 26, 2021\":\"https://www.uio.no/studier/emner/matnat/fys/FYS-STK4155/h21/forelesningsvideoer/LectureThursdayAugust26.mp4?vrtx=view-as-webpage\n", "\n", - "\n", "**Zoom link for lectures**: \n", "\n", "* Meeting ID: 933 1152 9525\n", "\n", "* Passcode: 646102\n", "\n", - "[Video of Lecture from Fall Semester 2020](https://www.uio.no/studier/emner/matnat/fys/FYS-STK4155/h20/forelesningsvideoer/zoom_0.mp4?vrtx=view-as-webpage).\n", - "\n", - "\n", - "\n", - "\n", + "[Video of Lecture from Fall Semester 2020](https://www.uio.no/studier/emner/matnat/fys/FYS-STK4155/h20/forelesningsvideoer/zoom_0.mp4?vrtx=view-as-webpage)." + ] + }, + { + "cell_type": "markdown", + "id": "e9c0ae5d", + "metadata": { + "editable": true + }, + "source": [ "## Lectures and ComputerLab\n", "\n", " * Lectures: Thursday (12.15pm-2pm and Friday (12.15pm-2pm). \n", @@ -84,24 +109,44 @@ "\n", " * Weekly plans and all other information are on the official webpage.\n", "\n", - " * No final exam, three projects that are graded and have to be approved.\n", - "\n", - "\n", - "\n", - "\n", + " * No final exam, three projects that are graded and have to be approved." + ] + }, + { + "cell_type": "markdown", + "id": "e862726a", + "metadata": { + "editable": true + }, + "source": [ "## Announcement\n", "\n", - "**NORA AI competetion:** See the link here \n", - "\n", - "\n", + "**NORA AI competetion:** See the link here " + ] + }, + { + "cell_type": "markdown", + "id": "b7e9a904", + "metadata": { + "editable": true + }, + "source": [ "## Communication channels\n", "\n", "* Chat and communications via , GDPR safe\n", "\n", "* **Slack** channel: machinelearninguio.slack.com\n", "\n", - "* **Piazza** : enlist at \n", - "\n", + "* **Piazza** : enlist at " + ] + }, + { + "cell_type": "markdown", + "id": "cb950912", + "metadata": { + "editable": true + }, + "source": [ "## Course Format\n", "\n", " * Three compulsory projects. Electronic reports only using [Canvas](https://www.uio.no/english/services/it/education/canvas/) to hand in projects and [git](https://git-scm.com/) as version control software and [GitHub](https://github.com/) for repository (or [GitLab](https://about.gitlab.com/)) of all your material.\n", @@ -116,17 +161,18 @@ "\n", "d. Based on feedback etc, each group finalizes the report and submits for grading. \n", "\n", - "\n", - " * Python is the default programming language, but feel free to use C/C++ and/or Fortran or other programming languages. All source codes discussed during the lectures can be found at the webpage and [github address](https://github.com/CompPhysics/MachineLearning/tree/master/doc/Programs) of the course.\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", + " * Python is the default programming language, but feel free to use C/C++ and/or Fortran or other programming languages. All source codes discussed during the lectures can be found at the webpage and [github address](https://github.com/CompPhysics/MachineLearning/tree/master/doc/Programs) of the course." + ] + }, + { + "cell_type": "markdown", + "id": "4f4f5449", + "metadata": { + "editable": true + }, + "source": [ "## Teachers\n", "\n", - "\n", "**Teachers :**\n", "* Morten Hjorth-Jensen, morten.hjorth-jensen@fys.uio.no\n", "\n", @@ -136,44 +182,50 @@ "\n", " * **Office hours**: *Anytime*! Individual or group office hours can be arranged either in person or via zoom. Feel free to send an email for planning. \n", "\n", - "\n", "* Øyvind Sigmundson Schøyen, oyvinssc@student.matnat.uio.no\n", "\n", " * **Office**: Department of Physics, University of Oslo, Eastern wing, room FØ452\n", "\n", - "\n", "* Stian Dysthe Bilek stian.bilek@fys.uio.no\n", "\n", " * **Office**: Department of Physics, University of Oslo, Eastern wing, room FØ450\n", "\n", - "\n", "* Linus Ekstrøm, linueks@gmail.com, linus.ekstrom@fys.uio.no\n", "\n", "* Nicholas Karlsen, nicholaskarlsen1102@gmail.com, nicholas.karlsen@fys.uio.no\n", "\n", "* Bendik Steinsvåg Dalen, b.s.dalen@fys.uio.no\n", "\n", - "* Philip Karim Sørli Niane, p.k.s.niane@fys.uio.no\n", - "\n", - "\n", - "\n", + "* Philip Karim Sørli Niane, p.k.s.niane@fys.uio.no" + ] + }, + { + "cell_type": "markdown", + "id": "0de9f263", + "metadata": { + "editable": true + }, + "source": [ "## Deadlines for projects (tentative)\n", "\n", - "\n", "1. Project 1: October 11 (available September 10) graded with feedback)\n", "\n", - "2. Project 2: November 15 (available October 12, graded with feedback)\n", - "\n", - "3. Project 3: December 13 (available November 8, graded with feedback)\n", - "\n", - "Projects are handed in using **Canvas**. We use Github as repository for codes, benchmark calculations etc. Comments and feedback on projects only via **Canvas**.\n", - "\n", - "\n", + "2. Project 2: November 20 (available October 12, graded with feedback)\n", "\n", + "3. Project 3: December 17 (available November 13, graded with feedback)\n", "\n", + "Projects are handed in using **Canvas**. We use Github as repository for codes, benchmark calculations etc. Comments and feedback on projects only via **Canvas**." + ] + }, + { + "cell_type": "markdown", + "id": "39cb9d48", + "metadata": { + "editable": true + }, + "source": [ "## Recommended textbooks\n", "\n", - "\n", "1. The lecture notes are collected as a jupyter-book at \n", "\n", "In addition to the lecture notes, we recommend the books of Bishop and Goodfellow et al. We will follow these texts closely and the weekly reading assignments refer to these two texts. The text by Hastie et al is also widely used in the Machine Learning community. Finally, we also recommend the hands-on text by Geron, see below.\n", @@ -186,8 +238,16 @@ "\n", "1. Trevor Hastie, Robert Tibshirani, Jerome H. Friedman, The Elements of Statistical Learning, Springer, This is a well-known text and serves as additional literature.\n", "\n", - "2. Aurelien Geron, Hands‑On Machine Learning with Scikit‑Learn and TensorFlow, O'Reilly, This text is very useful since it contains many code examples and hands-on applications of all algorithms discussed in this course.\n", - "\n", + "2. Aurelien Geron, Hands‑On Machine Learning with Scikit‑Learn and TensorFlow, O'Reilly, This text is very useful since it contains many code examples and hands-on applications of all algorithms discussed in this course." + ] + }, + { + "cell_type": "markdown", + "id": "45351170", + "metadata": { + "editable": true + }, + "source": [ "## Prerequisites\n", "\n", "Basic knowledge in programming and mathematics, with an emphasis on\n", @@ -198,14 +258,18 @@ "of the corresponding computing and programming courses INF1000/INF1110\n", "or MAT-INF1100/MAT-INF1100L/BIOS1100/KJM-INF1100. Most universities\n", "offer nowadays a basic programming course (often compulsory) where\n", - "Python is the recurring programming language.\n", - "\n", - "\n", - "\n", + "Python is the recurring programming language." + ] + }, + { + "cell_type": "markdown", + "id": "071161a1", + "metadata": { + "editable": true + }, + "source": [ "## Learning outcomes\n", "\n", - "\n", - "\n", "This course aims at giving you insights and knowledge about many of\n", "the central algorithms used in Data Analysis and Machine Learning.\n", "The course is project based and through various numerical projects,\n", @@ -238,10 +302,16 @@ "\n", "* Autoencoders and Reinforcement Learning;\n", "\n", - "* 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++ and/or Fortran (Fortran2003 or later) or Julia or other.\n", - "\n", - "\n", - "\n", + "* 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++ and/or Fortran (Fortran2003 or later) or Julia or other." + ] + }, + { + "cell_type": "markdown", + "id": "638641fd", + "metadata": { + "editable": true + }, + "source": [ "## Topics covered in this course: Statistical analysis and optimization of data\n", "\n", "The course has two central parts\n", @@ -254,7 +324,6 @@ "\n", "**Statistical analysis and optimization of data.**\n", "\n", - "\n", "We plan to cover the following topics:\n", "* Basic concepts, expectation values, variance, covariance, correlation functions and errors;\n", "\n", @@ -268,11 +337,16 @@ "\n", "* Estimation of errors and resampling techniques such as the cross-validation, blocking, bootstrapping and jackknife methods;\n", "\n", - "* Principal Component Analysis (PCA) and its mathematical foundation\n", - "\n", - "\n", - "\n", - "\n", + "* Principal Component Analysis (PCA) and its mathematical foundation" + ] + }, + { + "cell_type": "markdown", + "id": "4d686486", + "metadata": { + "editable": true + }, + "source": [ "## Topics covered in this course: Machine Learning\n", "\n", "The following topics will be covered\n", @@ -290,25 +364,32 @@ "\n", "* Unsupervised learning Dimensionality reduction, from PCA to clustering\n", "\n", - "Hands-on demonstrations, exercises and projects aim at deepening your understanding of these topics.\n", - "\n", - "\n", - "\n", - "\n", + "Hands-on demonstrations, exercises and projects aim at deepening your understanding of these topics." + ] + }, + { + "cell_type": "markdown", + "id": "448b469d", + "metadata": { + "editable": true + }, + "source": [ "## Extremely useful tools, strongly recommended\n", "\n", "**and discussed at the lab sessions.**\n", "\n", " * GIT for version control, and GitHub or GitLab as repositories, highly recommended. This will be discussed during the first exercise session\n", "\n", - " * Anaconda and other Python environments, see intro slides and links to programming resources at \n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", + " * Anaconda and other Python environments, see intro slides and links to programming resources at " + ] + }, + { + "cell_type": "markdown", + "id": "6fa4bed1", + "metadata": { + "editable": true + }, + "source": [ "## Other courses on Data science and Machine Learning at UiO\n", "\n", "The link here gives an excellent overview of courses on Machine learning at UiO.\n", @@ -333,8 +414,16 @@ "\n", "10. [STK4051 Computational Statistics](https://www.uio.no/studier/emner/matnat/math/STK4051/index-eng.html)\n", "\n", - "11. [STK4021 Applied Bayesian Analysis and Numerical Methods](https://www.uio.no/studier/emner/matnat/math/STK4021/index-eng.html)\n", - "\n", + "11. [STK4021 Applied Bayesian Analysis and Numerical Methods](https://www.uio.no/studier/emner/matnat/math/STK4021/index-eng.html)" + ] + }, + { + "cell_type": "markdown", + "id": "f2061698", + "metadata": { + "editable": true + }, + "source": [ "## Introduction\n", "\n", "Our emphasis throughout this series of lectures \n", @@ -368,9 +457,16 @@ "Tensorflow (see below for links etc). Moreover, the examples we\n", "introduce will serve as inputs to many of our discussions later, as\n", "well as allowing you to set up models and produce your own data and\n", - "get started with programming.\n", - "\n", - "\n", + "get started with programming." + ] + }, + { + "cell_type": "markdown", + "id": "80ee1e31", + "metadata": { + "editable": true + }, + "source": [ "## What is Machine Learning?\n", "\n", "Statistics, data science and machine learning form important fields of\n", @@ -434,12 +530,18 @@ "solid command of linear algebra, multivariate theory, probability\n", "theory, statistical data analysis, understanding errors and Monte\n", "Carlo methods are central elements in a proper understanding of many\n", - "of algorithms and methods we will discuss.\n", - "\n", - "\n", + "of algorithms and methods we will discuss." + ] + }, + { + "cell_type": "markdown", + "id": "aaddb93e", + "metadata": { + "editable": true + }, + "source": [ "## Types of Machine Learning\n", "\n", - "\n", "The approaches to machine learning are many, but are often split into\n", "two main categories. In *supervised learning* we know the answer to a\n", "problem, and let the computer deduce the logic behind it. On the other\n", @@ -457,8 +559,16 @@ "\n", " * Regression: Finding a functional relationship between an input data set and a reference data set. The goal is to construct a function that maps input data to continuous output values.\n", "\n", - " * Clustering: Data are divided into groups with certain common traits, without knowing the different groups beforehand. It is thus a form of unsupervised learning.\n", - "\n", + " * Clustering: Data are divided into groups with certain common traits, without knowing the different groups beforehand. It is thus a form of unsupervised learning." + ] + }, + { + "cell_type": "markdown", + "id": "2260de85", + "metadata": { + "editable": true + }, + "source": [ "## Essential elements of ML\n", "\n", "The methods we cover have three main topics in common, irrespective of\n", @@ -467,16 +577,28 @@ "\n", "* The second item is a model which is normally a function of some parameters. The model reflects our knowledge of the system (or lack thereof). As an example, if we know that our data show a behavior similar to what would be predicted by a polynomial, fitting our data to a polynomial of some degree would then determin our model. \n", "\n", - "* The last ingredient is a so-called **cost/loss** function (or error or risk function) which allows us to present an estimate on how good our model is in reproducing the data it is supposed to train. \n", - "\n", - "\n", - "\n", - "\n", - "\n", + "* The last ingredient is a so-called **cost/loss** function (or error or risk function) which allows us to present an estimate on how good our model is in reproducing the data it is supposed to train." + ] + }, + { + "cell_type": "markdown", + "id": "f559e833", + "metadata": { + "editable": true + }, + "source": [ "## An optimization/minimization problem\n", "\n", - "At the heart of basically all Machine Learning algorithms we will encounter so-called minimization or optimization algorithms. A large family of such methods are so-called **gradient methods**.\n", - "\n", + "At the heart of basically all Machine Learning algorithms we will encounter so-called minimization or optimization algorithms. A large family of such methods are so-called **gradient methods**." + ] + }, + { + "cell_type": "markdown", + "id": "97d9dee8", + "metadata": { + "editable": true + }, + "source": [ "## A Frequentist approach to data analysis\n", "\n", "When you hear phrases like **predictions and estimations** and\n", @@ -502,9 +624,16 @@ "where the aim is to make predictions and find correlations. We focus\n", "less on for example extracting a probability distribution function (PDF). The PDF can be\n", "used in turn to make estimations and find causations such as given $A$\n", - "what is the likelihood of finding $B$.\n", - "\n", - "\n", + "what is the likelihood of finding $B$." + ] + }, + { + "cell_type": "markdown", + "id": "d3c059e8", + "metadata": { + "editable": true + }, + "source": [ "## What is a good model?\n", "\n", "In science and engineering we often end up in situations where we want to infer (or learn) a\n", @@ -525,12 +654,18 @@ "A first important consideration to keep in mind is that inferring the *correct* model\n", "for a given data set is an elusive, if not impossible, task. The fundamental difficulty\n", "is that if we are not specific about what we mean by a *correct* model, there\n", - "could easily be many different models that fit the given data set *equally well*.\n", - "\n", - "\n", + "could easily be many different models that fit the given data set *equally well*." + ] + }, + { + "cell_type": "markdown", + "id": "0bdeab16", + "metadata": { + "editable": true + }, + "source": [ "## What is a good model? Can we define it?\n", "\n", - "\n", "The central question is this: what leads us to say that a model is correct or\n", "optimal for a given data set? To make the model inference problem well posed, i.e.,\n", "to guarantee that there is a unique optimal model for the given data, we need to\n", @@ -550,15 +685,16 @@ "simpler models become inadequate. For instance, if we work with a regression problem to fit a set of sample points, one\n", "may first try the simplest class of models, namely linear models, followed obviously by more complex models.\n", "\n", - "How to evaluate which model fits best the data is something we will come back to over and over again in these sets of lectures.\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", + "How to evaluate which model fits best the data is something we will come back to over and over again in these sets of lectures." + ] + }, + { + "cell_type": "markdown", + "id": "1c060598", + "metadata": { + "editable": true + }, + "source": [ "## Software and needed installations\n", "\n", "We will make extensive use of Python as programming language and its\n", @@ -569,7 +705,6 @@ "Rust, Julia, Fortran etc if you prefer. The focus in these lectures will be\n", "on Python.\n", "\n", - "\n", "If you have Python installed (we strongly recommend Python3) and you feel\n", "pretty familiar with installing different packages, we recommend that\n", "you install the following Python packages via **pip** as \n", @@ -589,9 +724,16 @@ "\n", "1. sudo apt-get install python3 (or python for pyhton2.7)\n", "\n", - "etc etc. \n", - "\n", - "\n", + "etc etc." + ] + }, + { + "cell_type": "markdown", + "id": "6cc9ab21", + "metadata": { + "editable": true + }, + "source": [ "## Python installers\n", "\n", "If you don't want to perform these operations separately and venture\n", @@ -615,8 +757,16 @@ "license.\n", "\n", "Furthermore, [Google's Colab](https://colab.research.google.com/notebooks/welcome.ipynb) is a free Jupyter notebook environment that requires \n", - "no setup and runs entirely in the cloud. Try it out!\n", - "\n", + "no setup and runs entirely in the cloud. Try it out!" + ] + }, + { + "cell_type": "markdown", + "id": "b4220192", + "metadata": { + "editable": true + }, + "source": [ "## Useful Python libraries\n", "Here we list several useful Python libraries we strongly recommend (if you use anaconda many of these are already there)\n", "\n", @@ -640,8 +790,16 @@ "\n", "* [Keras](https://keras.io/) is a high-level neural networks API, written in Python and capable of running on top of TensorFlow, CNTK, or Theano\n", "\n", - "* And many more such as [pytorch](https://pytorch.org/), [Theano](https://pypi.org/project/Theano/) etc \n", - "\n", + "* And many more such as [pytorch](https://pytorch.org/), [Theano](https://pypi.org/project/Theano/) etc" + ] + }, + { + "cell_type": "markdown", + "id": "601d504c", + "metadata": { + "editable": true + }, + "source": [ "## Installing R, C++, cython or Julia\n", "\n", "You will also find it convenient to utilize **R**. We will mainly\n", @@ -656,13 +814,18 @@ "lectures.\n", "\n", "To install **R** with Jupyter notebook \n", - "[follow the link here](https://mpacer.org/maths/r-kernel-for-ipython-notebook)\n", - "\n", - "\n", - "\n", + "[follow the link here](https://mpacer.org/maths/r-kernel-for-ipython-notebook)" + ] + }, + { + "cell_type": "markdown", + "id": "a4beb747", + "metadata": { + "editable": true + }, + "source": [ "## Installing R, C++, cython, Numba etc\n", "\n", - "\n", "For the C++ aficionados, Jupyter/IPython notebook allows you also to\n", "install C++ and run codes written in this language interactively in\n", "the browser. Since we will emphasize writing many of the algorithms\n", @@ -683,22 +846,35 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "87030410", + "metadata": { + "editable": true + }, "source": [ " pycod jupyter nbconvert filename.ipynb --to latex \n" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "973375a2", + "metadata": { + "editable": true + }, "source": [ "And to add more versatility, the Python package [SymPy](http://www.sympy.org/en/index.html) is a Python library for symbolic mathematics. It aims to become a full-featured computer algebra system (CAS) and is entirely written in Python. \n", "\n", "Finally, if you wish to use the light mark-up language \n", "[doconce](https://github.com/hplgit/doconce) you can convert a standard ascii text file into various HTML \n", - "formats, ipython notebooks, latex files, pdf files etc with minimal edits. These lectures were generated using **doconce**.\n", - "\n", - "\n", + "formats, ipython notebooks, latex files, pdf files etc with minimal edits. These lectures were generated using **doconce**." + ] + }, + { + "cell_type": "markdown", + "id": "bbd99efa", + "metadata": { + "editable": true + }, + "source": [ "## Numpy examples and Important Matrix and vector handling packages\n", "\n", "There are several central software libraries for linear algebra and eigenvalue problems. Several of the more\n", @@ -710,8 +886,16 @@ "\n", " * LAPACK:package for solving symmetric, unsymmetric and generalized eigenvalue problems. From LAPACK's website it is possible to download for free all source codes from this library. Both C/C++ and Fortran versions are available.\n", "\n", - " * BLAS (I, II and III): (Basic Linear Algebra Subprograms) are routines that provide standard building blocks for performing basic vector and matrix operations. Blas I is vector operations, II vector-matrix operations and III matrix-matrix operations. Highly parallelized and efficient codes, all available for download from .\n", - "\n", + " * BLAS (I, II and III): (Basic Linear Algebra Subprograms) are routines that provide standard building blocks for performing basic vector and matrix operations. Blas I is vector operations, II vector-matrix operations and III matrix-matrix operations. Highly parallelized and efficient codes, all available for download from ." + ] + }, + { + "cell_type": "markdown", + "id": "3b716073", + "metadata": { + "editable": true + }, + "source": [ "## Basic Matrix Features\n", "\n", "**Matrix properties reminder.**" @@ -719,7 +903,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "02ae660b", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\mathbf{A} =\n", @@ -739,14 +926,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "7950a446", + "metadata": { + "editable": true + }, "source": [ "The inverse of a matrix is defined by" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "1bd26546", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\mathbf{A}^{-1} \\cdot \\mathbf{A} = I\n", @@ -755,9 +948,12 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "c9631af0", + "metadata": { + "editable": true + }, "source": [ - "\n", + "
    \n", "\n", "\n", "\n", @@ -768,10 +964,16 @@ "\n", "\n", "\n", - "
    Relations Name matrix elements
    $A=A^{\\dagger}$ hermitian $a_{ij}=a_{ji}^{*}$
    $A=\\left(A^{\\dagger}\\right )^{-1}$ unitary $\\sum_k a_{ik}a_{jk}^{*}=\\sum_k a_{ki}^{ * } a_{kj}=\\delta_{ij}$
    \n", - "\n", - "\n", - "\n", + "" + ] + }, + { + "cell_type": "markdown", + "id": "a47420ee", + "metadata": { + "editable": true + }, + "source": [ "### Some famous Matrices\n", "\n", " * Diagonal if $a_{ij}=0$ for $i\\ne j$\n", @@ -790,8 +992,16 @@ "\n", " * Upper banded with bandwidth $p$: $a_{ij}=0$ for $i\u001b[0;34m\u001b[0m\n\u001b[1;32m 3\u001b[0m \u001b[0;32mimport\u001b[0m \u001b[0mnumpy\u001b[0m \u001b[0;32mas\u001b[0m \u001b[0mnp\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[0;32mimport\u001b[0m \u001b[0mmatplotlib\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mpyplot\u001b[0m \u001b[0;32mas\u001b[0m \u001b[0mplt\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 5\u001b[0;31m \u001b[0;32mfrom\u001b[0m \u001b[0mscipy\u001b[0m \u001b[0;32mimport\u001b[0m \u001b[0msparse\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 6\u001b[0m \u001b[0meye\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mnp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0meye\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m4\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 7\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0meye\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", - "\u001b[0;31mModuleNotFoundError\u001b[0m: No module named 'scipy'" - ] - } - ], + "id": "f10c8b39", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], "source": [ "%matplotlib inline\n", "\n", @@ -1367,15 +1537,18 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "646fca17", + "metadata": { + "editable": true + }, "source": [ "## Meet the Pandas\n", "\n", - "\n", "\n", "\n", - "

    Figure 1:

    \n", "\n", + "

    Figure 1:

    \n", + "\n", "\n", "Another useful Python package is\n", "[pandas](https://pandas.pydata.org/), which is an open source library\n", @@ -1390,80 +1563,12 @@ { "cell_type": "code", "execution_count": 17, - "metadata": {}, - "outputs": [ - { - "data": { - "text/html": [ - "
    \n", - "\n", - "\n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - "
    First NameLast NamePlace of birthDate of Birth T.A.
    0FrodoBagginsShire2968
    1BilboBagginsShire2890
    2Aragorn IIElessarEriador2931
    3SamwiseGamgeeShire2980
    \n", - "
    " - ], - "text/plain": [ - " First Name Last Name Place of birth Date of Birth T.A.\n", - "0 Frodo Baggins Shire 2968\n", - "1 Bilbo Baggins Shire 2890\n", - "2 Aragorn II Elessar Eriador 2931\n", - "3 Samwise Gamgee Shire 2980" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], + "id": "95d49d4c", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], "source": [ "import pandas as pd\n", "from IPython.display import display\n", @@ -1478,7 +1583,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "38790248", + "metadata": { + "editable": true + }, "source": [ "In the above we have imported **pandas** with the shorthand **pd**, the latter has become the standard way we import **pandas**. We make then a list of various variables\n", "and reorganize the aboves lists into a **DataFrame** and then print out a neat table with specific column labels as *Name*, *place of birth* and *date of birth*.\n", @@ -1489,80 +1597,12 @@ { "cell_type": "code", "execution_count": 18, - "metadata": {}, - "outputs": [ - { - "data": { - "text/html": [ - "
    \n", - "\n", - "\n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - "
    First NameLast NamePlace of birthDate of Birth T.A.
    FrodoFrodoBagginsShire2968
    BilboBilboBagginsShire2890
    AragornAragorn IIElessarEriador2931
    SamSamwiseGamgeeShire2980
    \n", - "
    " - ], - "text/plain": [ - " First Name Last Name Place of birth Date of Birth T.A.\n", - "Frodo Frodo Baggins Shire 2968\n", - "Bilbo Bilbo Baggins Shire 2890\n", - "Aragorn Aragorn II Elessar Eriador 2931\n", - "Sam Samwise Gamgee Shire 2980" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], + "id": "e630cc31", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], "source": [ "data_pandas = pd.DataFrame(data,index=['Frodo','Bilbo','Aragorn','Sam'])\n", "display(data_pandas)" @@ -1570,7 +1610,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "d0d27d68", + "metadata": { + "editable": true + }, "source": [ "Thereafter we display the content of the row which begins with the index **Aragorn**" ] @@ -1578,29 +1621,22 @@ { "cell_type": "code", "execution_count": 19, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "First Name Aragorn II\n", - "Last Name Elessar\n", - "Place of birth Eriador\n", - "Date of Birth T.A. 2931\n", - "Name: Aragorn, dtype: object" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], + "id": "2591ed5d", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], "source": [ "display(data_pandas.loc['Aragorn'])" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "85bf5f70", + "metadata": { + "editable": true + }, "source": [ "We can easily append data to this, for example" ] @@ -1608,88 +1644,12 @@ { "cell_type": "code", "execution_count": 20, - "metadata": {}, - "outputs": [ - { - "data": { - "text/html": [ - "
    \n", - "\n", - "\n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - "
    First NameLast NamePlace of birthDate of Birth T.A.
    FrodoFrodoBagginsShire2968
    BilboBilboBagginsShire2890
    AragornAragorn IIElessarEriador2931
    SamSamwiseGamgeeShire2980
    PippinPeregrinTookShire2990
    \n", - "
    " - ], - "text/plain": [ - " First Name Last Name Place of birth Date of Birth T.A.\n", - "Frodo Frodo Baggins Shire 2968\n", - "Bilbo Bilbo Baggins Shire 2890\n", - "Aragorn Aragorn II Elessar Eriador 2931\n", - "Sam Samwise Gamgee Shire 2980\n", - "Pippin Peregrin Took Shire 2990" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], + "id": "9bbe0db8", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], "source": [ "new_hobbit = {'First Name': [\"Peregrin\"],\n", " 'Last Name': [\"Took\"],\n", @@ -1702,7 +1662,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "d9ebb24b", + "metadata": { + "editable": true + }, "source": [ "Here are other examples where we use the **DataFrame** functionality to handle arrays, now with more interesting features for us, namely numbers. We set up a matrix \n", "of dimensionality $10\\times 5$ and compute the mean value and standard deviation of each column. Similarly, we can perform mathematial operations like squaring the matrix elements and many other operations." @@ -1711,287 +1674,12 @@ { "cell_type": "code", "execution_count": 21, - "metadata": {}, - "outputs": [ - { - "data": { - "text/html": [ - "
    \n", - "\n", - "\n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - "
    01234
    0-1.7497650.3426801.153036-0.2524360.981321
    10.5142190.221180-1.070043-0.1894960.255001
    2-0.4580270.435163-0.5835950.8168470.672721
    3-0.104411-0.5312801.029733-0.438136-1.118318
    41.6189821.541605-0.251879-0.8424360.184519
    50.9370820.7310001.361556-0.3262380.055676
    60.222400-1.443217-0.7563520.8164540.750445
    7-0.4559471.189622-1.690617-1.356399-1.232435
    8-0.544439-0.6681720.007315-0.6129391.299748
    9-1.733096-0.9833100.357508-1.6135791.470714
    \n", - "
    " - ], - "text/plain": [ - " 0 1 2 3 4\n", - "0 -1.749765 0.342680 1.153036 -0.252436 0.981321\n", - "1 0.514219 0.221180 -1.070043 -0.189496 0.255001\n", - "2 -0.458027 0.435163 -0.583595 0.816847 0.672721\n", - "3 -0.104411 -0.531280 1.029733 -0.438136 -1.118318\n", - "4 1.618982 1.541605 -0.251879 -0.842436 0.184519\n", - "5 0.937082 0.731000 1.361556 -0.326238 0.055676\n", - "6 0.222400 -1.443217 -0.756352 0.816454 0.750445\n", - "7 -0.455947 1.189622 -1.690617 -1.356399 -1.232435\n", - "8 -0.544439 -0.668172 0.007315 -0.612939 1.299748\n", - "9 -1.733096 -0.983310 0.357508 -1.613579 1.470714" - ] - }, - "metadata": {}, - "output_type": "display_data" - }, - { - "name": "stdout", - "output_type": "stream", - "text": [ - "0 -0.175300\n", - "1 0.083527\n", - "2 -0.044334\n", - "3 -0.399836\n", - "4 0.331939\n", - "dtype: float64\n", - "0 1.069584\n", - "1 0.965548\n", - "2 1.018232\n", - "3 0.793167\n", - "4 0.918992\n", - "dtype: float64\n" - ] - }, - { - "data": { - "text/html": [ - "
    \n", - "\n", - "\n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - "
    01234
    03.0616790.1174301.3294920.0637240.962990
    10.2644210.0489201.1449930.0359090.065026
    20.2097890.1893670.3405830.6672390.452553
    30.0109020.2822591.0603490.1919631.250636
    42.6211022.3765470.0634430.7096980.034047
    50.8781230.5343621.8538350.1064310.003100
    60.0494622.0828750.5720690.6665970.563167
    70.2078881.4152012.8581851.8398181.518895
    80.2964140.4464530.0000540.3756941.689345
    93.0036200.9668990.1278122.6036362.162999
    \n", - "
    " - ], - "text/plain": [ - " 0 1 2 3 4\n", - "0 3.061679 0.117430 1.329492 0.063724 0.962990\n", - "1 0.264421 0.048920 1.144993 0.035909 0.065026\n", - "2 0.209789 0.189367 0.340583 0.667239 0.452553\n", - "3 0.010902 0.282259 1.060349 0.191963 1.250636\n", - "4 2.621102 2.376547 0.063443 0.709698 0.034047\n", - "5 0.878123 0.534362 1.853835 0.106431 0.003100\n", - "6 0.049462 2.082875 0.572069 0.666597 0.563167\n", - "7 0.207888 1.415201 2.858185 1.839818 1.518895\n", - "8 0.296414 0.446453 0.000054 0.375694 1.689345\n", - "9 3.003620 0.966899 0.127812 2.603636 2.162999" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], + "id": "f5f4acfb", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], "source": [ "import numpy as np\n", "import pandas as pd\n", @@ -2010,7 +1698,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "0b4ef9f6", + "metadata": { + "editable": true + }, "source": [ "Thereafter we can select specific columns only and plot final results" ] @@ -2018,188 +1709,12 @@ { "cell_type": "code", "execution_count": 22, - "metadata": {}, - "outputs": [ - { - "data": { - "text/html": [ - "
    \n", - "\n", - "\n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - "
    FirstSecondThirdFourthFifth
    0-1.7497650.3426801.153036-0.2524360.981321
    10.5142190.221180-1.070043-0.1894960.255001
    2-0.4580270.435163-0.5835950.8168470.672721
    3-0.104411-0.5312801.029733-0.438136-1.118318
    41.6189821.541605-0.251879-0.8424360.184519
    50.9370820.7310001.361556-0.3262380.055676
    60.222400-1.443217-0.7563520.8164540.750445
    7-0.4559471.189622-1.690617-1.356399-1.232435
    8-0.544439-0.6681720.007315-0.6129391.299748
    9-1.733096-0.9833100.357508-1.6135791.470714
    \n", - "
    " - ], - "text/plain": [ - " First Second Third Fourth Fifth\n", - "0 -1.749765 0.342680 1.153036 -0.252436 0.981321\n", - "1 0.514219 0.221180 -1.070043 -0.189496 0.255001\n", - "2 -0.458027 0.435163 -0.583595 0.816847 0.672721\n", - "3 -0.104411 -0.531280 1.029733 -0.438136 -1.118318\n", - "4 1.618982 1.541605 -0.251879 -0.842436 0.184519\n", - "5 0.937082 0.731000 1.361556 -0.326238 0.055676\n", - "6 0.222400 -1.443217 -0.756352 0.816454 0.750445\n", - "7 -0.455947 1.189622 -1.690617 -1.356399 -1.232435\n", - "8 -0.544439 -0.668172 0.007315 -0.612939 1.299748\n", - "9 -1.733096 -0.983310 0.357508 -1.613579 1.470714" - ] - }, - "metadata": {}, - "output_type": "display_data" - }, - { - "name": "stdout", - "output_type": "stream", - "text": [ - "0.08352721390288316\n", - "\n", - "Int64Index: 10 entries, 0 to 9\n", - "Data columns (total 5 columns):\n", - " # Column Non-Null Count Dtype \n", - "--- ------ -------------- ----- \n", - " 0 First 10 non-null float64\n", - " 1 Second 10 non-null float64\n", - " 2 Third 10 non-null float64\n", - " 3 Fourth 10 non-null float64\n", - " 4 Fifth 10 non-null float64\n", - "dtypes: float64(5)\n", - "memory usage: 480.0 bytes\n", - "None\n", - " First Second Third Fourth Fifth\n", - "count 10.000000 10.000000 10.000000 10.000000 10.000000\n", - "mean -0.175300 0.083527 -0.044334 -0.399836 0.331939\n", - "std 1.069584 0.965548 1.018232 0.793167 0.918992\n", - "min -1.749765 -1.443217 -1.690617 -1.613579 -1.232435\n", - "25% -0.522836 -0.633949 -0.713163 -0.785061 0.087887\n", - "50% -0.280179 0.281930 -0.122282 -0.382187 0.463861\n", - "75% 0.441264 0.657041 0.861676 -0.205231 0.923602\n", - "max 1.618982 1.541605 1.361556 0.816847 1.470714\n" - ] - }, - { - "data": { - "image/png": "iVBORw0KGgoAAAANSUhEUgAAAlIAAAFkCAYAAADrFNVeAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjQuMywgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/MnkTPAAAACXBIWXMAAAsTAAALEwEAmpwYAACqXklEQVR4nOyddXhc17W330GxNIIRM9iyzBQz23HiJA6THeakaZu0Kffe3q+3t5yGsQ2zQw44ie2YmS2jbDFLMyOc0fCc8/0xsmzHJBiUz/s8fmSNzpyzRkt7n99Ze+21ZKIoikhISEhISEhISPQZub8NkJCQkJCQkJAIViQhJSEhISEhISHRTyQhJSEhISEhISHRTyQhJSEhISEhISHRTyQhJSEhISEhISHRTyQhJSEhISEhISHRT5T+uKheb/T6NWJjw2lrM3v9OhLeQ/Jh8CP5MPiRfBjcSP7zDFpt1Dl/NmgjUkqlwt8mSAwQyYfBj+TD4EfyYXAj+c/7DFohJSEhISEhISHhbSQhJSEhISEhISHRTyQhJSEhISEhISHRTyQhJSEhISEhISHRTyQhJSEhISEhISHRTyQhJSEhISEhISHRTyQhJSEhISEhISHRT/xSkDNQOXLkEC+++CxOp5OJEycBYLfbsdvtHDiwn1dffROFovc1Ob755itmzJhNVNS5C3lJSEhISEhIBC+SkDqFoqIRjB07HovFwr33PgiAzWZj9+6d/OQnP0Mmk/XpfN988xVjx46XhJSEhISEhMQgJSCF1NMfF3OgvMWj5xyVF89jN47u03ucTicvv/w848dP4MYbF/Pcc6/Q0mLgn//8K0OHFqJSqVm/fg3vvPMRL7zwDLm5+dTWVnPZZVdis1lpampk2bIPyMrK4pprbvDo55GQkJCQkJDwPwEppPzN3r27eea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+ByuXj++aeJiYnBbrfT2dnJE0/8mqqqSj788F0yMjKprq5iyZI7iIuL53/+53eIokBWVg5lZce59NLLWbz4WgCefvofOJ1OUlPT0Ol0Hv3sEhISEhISwYDd0oy+/H1EwU547Ehi0xcFtIgCDwgpuVzeI6KcTifNzc3k5OQM2DB/oFaree65V3nvvTe57bY3ycjI4s4776WpqRGHw8ndd9+PKIosXXoDkyZNYcOGdTgcDu666z4Avv56OQB/+csfefzxX1BYWMThw4f461//l5dffp3bbruTV155gccee4K2tjZ++tOHWLz4WrZu3UxtbS1PPvksAJs2bfDXr0BCQkJCQsIvOKwt6MreRXBZCYsZSnzW4oAXUeDBHKlNmzbx5ptvMnv2bEaOHHneY2Njw1Eqz9177g/zf+ops/qMVjuGSZOexuVysWrVKn79619yzTXXYDK18/nnHwAwbFghgmChoaGawsL8ntLxd999O+BuYjxy5FA0mihGjy6kvLwUrTYKjSacgoI8tNootNoobDYrWm0UOl0dQ4bk9ZwnNzcbjSb8vCXpLxak30HwI/kw+JF8GNwEg//sljZKjr6H4OwiKq6A/LF3Ileo/G1Wr/CYkJoxYwYzZszgl7/8Je+99x5Lly4957FtbWZPXfac9Ke/UGNjA2+++R9+85v/BmDMmMmoVGo0mgREUc61194KQFzcOkJDY0hLy+bYsdKe6yxf/gnXXHMDeXkFHDhQwrBhwzl06Cj5+QXo9Uba283YbM6e410uAb3eiFabxsaNW3per6ioor3dPKj6I/WHwdYj6mJE8mHwI/kwuAkG/7kcJppL38Rpa0cdkU5M+vW0tFoBq79N6+F8YnTAQqqsrIy6ujpmz54NQHp6OnV1dQM9rV+IiIiks7ODZ599koiISBobG3j44R9zxRWLefHFZ3nttVdQKNyRtFmz5nDllVfz/PNP89prr+ByucjNzQPg17/+L95//2127dpBTU01v/rVf2G321m58hvKy0spKTlCRUU5JpOJ9evXMGvWXLZv38pf//q/JCYmASIrV35DYeEwwsMj/PgbkZCQkJCQ8B4upwVd2bs4ba2owpJJzF2CXKH2t1l9QiaKojiQE9TU1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34ahw8fxv333y90aX7H774zqqqqEBcXB7VaDQAoKSnBxx9/zCAlIZf/r9ftdkOr1QpUDXnj3XffRUlJCRobG2G1WoUuh+aopqYGHo8Hf/jDHzA5OYmwsDA8/PDDQpdFc6DVaqFSqTAxMYGQkBBYrVakp6cLXZZf8rsgNTQ0hKCgoJnfBwcHY2hoSMCKaD6OHDmCdevWITU1VehSaJZaWlpw7tw5fOc730FjY6PQ5ZAXent7UVVVhZ///OfQ6XT47ne/C5VKhQceeEDo0miWgoOD8b3vfQ/PPvssoqKiEBMTg6SkJKHL8kt+t9g8IiICFotl5vcTExOIiIgQsCLy1smTJ/HZZ5/h+eefF7oUmoMjR45ArVbj1VdfxenTp1FdXY3XX39d6LJoDoKCgrB8+XLodDoAwIoVK3Dq1CmBq6K5qK+vx2uvvYZXXnkFL730EvR6Pf77v/9b6LL8kt+NSBUVFaG3txdTU1NQq9WoqKjAY489JnRZNEcff/wxysvL8S//8i8YGBhAb28viouLhS6LZuHpp5+eed9ut8NqteKJJ54QriCas8LCQoyOjsLlckGhUKC3txfJyclCl0Vz0N/fj7CwsJm1bVFRUTAajQJX5Z/88tDiY8eO4dChQ9Dr9VCpVLzjS2Jqa2vxla98ZWZxudVqxbZt2zitIDGHDh3C7t274XA4sG3bNmzevFnokmgOjhw5gpMnT0Kv18NoNGLnzp2840tCXC4XfvKTn0Cj0UCn06G5uRnPP/88DAaD0KX5Hb8MUkRERESLwe/WSBEREREtFgYpIiIiIi8xSBERERF5iUGKiIiIyEsMUkREREReYpAiIiIi8hKDFBEREZGXGKSIiIiIvPT/AYYRgDOUasVWAAAAAElFTkSuQmCC\n", - "text/plain": [ - "
    " - ] - }, - "metadata": {}, - "output_type": "display_data" - }, - { - "data": { - "image/png": "iVBORw0KGgoAAAANSUhEUgAAAlsAAAFlCAYAAADcXS0xAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjQuMywgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/MnkT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f/1rfffddxowYICSkpLUv39/T5flNitWrFB6erp69eql3NxcvffeeyouLvZ0WW6zevVqHTlyRD179tSBAwe0cuVKff/99x6tqd6Hrbffflvt2rVT27ZtNWTIEP3rX//Szp07PV2WW5w4cUJDhw7Vbbfdpm+++UaS55dS3WnYsGG69957lZCQoI4dOyojI8PTJbnVkCFDNGDAALVv317NmzeX3W6Xr6/3v2QvPwfT0tLUvXt3+fj46NixY5JkqTA5ZMgQ9enTR4WFhfrnP/+pzMxMT5fkVu+9954qKip07Ngxbd261VL9hYWFad68efqP//gP9evXTxUVFcrOzvZ0WW6zadMmtW7dWu3bt1ebNm0kSYGBgZb4+2C32/Xll18qISFBbdu21d13361du3bpu+++82hd3v/O7YKysjJ16NBBhw4dkiTFxcUpJCREe/fu9XBl7hEfH69OnTopOjpaX375pSTrhK1bbrlFd955pwICAiRJLVu2VGxsrIercq+hQ4eqcePG+tvf/qb9+/erbdu2stvtni7LZT4+Pjp48KAiIiI0fPhw+fj4aO/evcrJybFEmLysadOmSk1NVUREhMrLyzVz5kwdPnzY02W5RXl5uaKiorRp0yY1bdpUMTExWrlypdavX+/p0twiICBAt956qySpoKBAYWFhio6O9nBV7jN48GBt2rRJy5Yt07Fjx1ReXq7s7GxLfPpRUlKitm3batu2bZKkZs2aKSsrSwcPHvRoXdZ5Z7sBPj4+atasmeN/ZGFhYWrcuLHjD7i38/X11U033aROnTpp//79jjEruPJNISMjQ0ePHtWwYcNUUFDgwarcr7y8XDExMZo8ebI2b96sJUuWeLokt7hw4YIyMzOVnp6uY8eOadOmTUpLS/N0WW7Vr18/jR07VvHx8brnnnuUkJCgv/3tb54uyy0uv/4yMjIUGxurfv36qWfPnvryyy8t8x+6y3x9fbV9+3Z17tzZ06W4zahRo9S2bVs1adJEY8aM0YULFzR//nxLPHZBQUG65557tGfPHn366afau3evevXqpaCgII/WZY2/vDfI19dXPXv21MGDB3Xx4kUFBATo5MmTjmVVK/D19dWtt96qsrIy5ebmerocI/bt26cxY8YoPz9fqampKikp8XRJbmO325WQkKCEhAR1795dJSUllvjVV2Zmppo1a6bw8HAlJSUpJiZGsbGxlnizvywwMFCBgYGSJH9/fxUVFSkiIsLDVbmHj4+P+vTpo8DAQNlsNvn6+qqkpETt2rVTaWmpp8tzq4CAADVt2lQ5OTmeLsVtsrOz9f777+vBBx9U27Zt1aFDB0VGRlrmP6t9+vTRrFmzdMstt2jkyJHy8/NTfHy8R2uq979GvO2225SYmKiVK1cqNDRUwcHBat26tafLcqvS0lLl5eVpypQpmjhxojp16uTpktxm8+bNWrFihf7xj3/o8OHDuvPOO1VaWqqbbrrJ06W5LD8/X5s2bVJRUZGCg4O1c+dODR482OO/qnGHESNGOFZHPv30U+3Zs0ebNm1SeHi4mjRp4uHq3KOgoEDvv/++ysrKFBoaquLiYku99rp166bOnTtr+fLluuWWW5SZmakhQ4ZY4rV3pc8++0wxMTGKiIiwzC+6b775ZnXt2lWvv/66YmJitHPnTt17772W+kViVlaWjhw5olOnTikqKkoxMTEercenwkr/lbxBdrtdGRkZKisrU8eOHeXn52eZF5Xdbtfnn3+u06dPq2vXrkpMTLREX5ctX75cWVlZevjhh5WQkGC5N/rNmzfr9OnT6tevn2JiYiwRtK5ks9mUnZ2tmJgY+ftb7/9+X3zxhbKysnT77berVatWlnv8CgoKlJGRoYCAAMXFxVnqvfOyzMxMVVRUqG3btp4uxa0yMzP17bff6tZbb1WbNm0s99z88ssvtXPnTg0YMEBt2rTx+FdoCFsAAAAG1evvbAEAAJhG2AIAADCIsAUAAGAQYQsAAMAgwhYAAIBBhC0AAACDCFsAAAAG/X8idFJ0xKGYiQAAAABJRU5ErkJggg==\n", - "text/plain": [ - "
    " - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], + "id": "f70279c1", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], "source": [ "df.columns = ['First', 'Second', 'Third', 'Fourth', 'Fifth']\n", "df.index = np.arange(10)\n", @@ -2223,7 +1738,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "963e3f64", + "metadata": { + "editable": true + }, "source": [ "We can produce a $4\\times 4$ matrix" ] @@ -2231,24 +1749,12 @@ { "cell_type": "code", "execution_count": 23, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "[[ 0 1 2 3]\n", - " [ 4 5 6 7]\n", - " [ 8 9 10 11]\n", - " [12 13 14 15]]\n", - " 0 1 2 3\n", - "0 0 1 2 3\n", - "1 4 5 6 7\n", - "2 8 9 10 11\n", - "3 12 13 14 15\n" - ] - } - ], + "id": "8f579fb1", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], "source": [ "b = np.arange(16).reshape((4,4))\n", "print(b)\n", @@ -2258,7 +1764,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "970a7544", + "metadata": { + "editable": true + }, "source": [ "and many other operations. \n", "\n", @@ -2267,21 +1776,30 @@ "we have just a single column of data. It shares many of the same features as _DataFrame. As with **DataFrame**,\n", "most operations are vectorized, achieving thereby a high performance when dealing with computations of arrays, in particular labeled arrays.\n", "As we will see below it leads also to a very concice code close to the mathematical operations we may be interested in.\n", - "For multidimensional arrays, we recommend strongly [xarray](http://xarray.pydata.org/en/stable/). **xarray** has much of the same flexibility as **pandas**, but allows for the extension to higher dimensions than two. We will see examples later of the usage of both **pandas** and **xarray**. \n", - "\n", - "\n", + "For multidimensional arrays, we recommend strongly [xarray](http://xarray.pydata.org/en/stable/). **xarray** has much of the same flexibility as **pandas**, but allows for the extension to higher dimensions than two. We will see examples later of the usage of both **pandas** and **xarray**." + ] + }, + { + "cell_type": "markdown", + "id": "691ca1d1", + "metadata": { + "editable": true + }, + "source": [ "## Friday August 27\n", "\n", - "\n", "\"Video of Lecture August 27, 2021\":\"https://www.uio.no/studier/emner/matnat/fys/FYS-STK4155/h21/forelesningsvideoer/LectureThursdayAugust27.mp4?vrtx=view-as-webpage\n", "\n", - "\n", - "\n", - "[Video of Lecture from fall 2020](https://www.uio.no/studier/emner/matnat/fys/FYS-STK3155/h20/forelesningsvideoer/LectureAug21.mp4?vrtx=view-as-webpage) and [Handwritten notes](https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/NotesAugust21.pdf)\n", - "\n", - "\n", - "\n", - "\n", + "[Video of Lecture from fall 2020](https://www.uio.no/studier/emner/matnat/fys/FYS-STK3155/h20/forelesningsvideoer/LectureAug21.mp4?vrtx=view-as-webpage) and [Handwritten notes](https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/NotesAugust21.pdf)" + ] + }, + { + "cell_type": "markdown", + "id": "d378c442", + "metadata": { + "editable": true + }, + "source": [ "### Simple linear regression model using **scikit-learn**\n", "\n", "We start with perhaps our simplest possible example, using **Scikit-Learn** to perform linear regression analysis on a data set produced by us. \n", @@ -2295,7 +1813,6 @@ "(tabulated again as a vector) with a linear dependence on $x$ plus a\n", "random noise added via the normal distribution.\n", "\n", - "\n", "The Numpy functions are imported used the **import numpy as np**\n", "statement and the random number generator for the uniform distribution\n", "is called using the function **np.random.rand()**, where we specificy\n", @@ -2309,7 +1826,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "e5ab3567", + "metadata": { + "editable": true + }, "source": [ "$$\n", "y = 2x+N(0,1),\n", @@ -2318,7 +1838,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "48638276", + "metadata": { + "editable": true + }, "source": [ "where $N(0,1)$ represents random numbers generated by the normal\n", "distribution. From **Scikit-Learn** we import then the\n", @@ -2343,20 +1866,12 @@ { "cell_type": "code", "execution_count": 24, - "metadata": {}, - "outputs": [ - { - "ename": "ModuleNotFoundError", - "evalue": "No module named 'sklearn'", - "output_type": "error", - "traceback": [ - "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", - "\u001b[0;31mModuleNotFoundError\u001b[0m Traceback (most recent call last)", - "\u001b[0;32m/var/folders/td/3yk470mj5p931p9dtkk0y6jw0000gn/T/ipykernel_12115/2268754013.py\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0;32mimport\u001b[0m \u001b[0mnumpy\u001b[0m \u001b[0;32mas\u001b[0m \u001b[0mnp\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 3\u001b[0m \u001b[0;32mimport\u001b[0m \u001b[0mmatplotlib\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mpyplot\u001b[0m \u001b[0;32mas\u001b[0m \u001b[0mplt\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 4\u001b[0;31m \u001b[0;32mfrom\u001b[0m \u001b[0msklearn\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mlinear_model\u001b[0m \u001b[0;32mimport\u001b[0m \u001b[0mLinearRegression\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 5\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 6\u001b[0m \u001b[0mx\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mnp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mrandom\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mrand\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m100\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", - "\u001b[0;31mModuleNotFoundError\u001b[0m: No module named 'sklearn'" - ] - } - ], + "id": "5d268e23", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], "source": [ "# Importing various packages\n", "import numpy as np\n", @@ -2381,7 +1896,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "a0bc9fe7", + "metadata": { + "editable": true + }, "source": [ "This example serves several aims. It allows us to demonstrate several\n", "aspects of data analysis and later machine learning algorithms. The\n", @@ -2395,7 +1913,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "2fa1f5fd", + "metadata": { + "editable": true + }, "source": [ "$$\n", "y = 10x+0.01 \\times N(0,1),\n", @@ -2404,7 +1925,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "69c2a007", + "metadata": { + "editable": true + }, "source": [ "where $x$ is defined as before. Does the fit look better? Indeed, by\n", "reducing the role of the noise given by the normal distribution we see immediately that\n", @@ -2422,7 +1946,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "c946d217", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\chi^2 = \\frac{1}{n}\n", @@ -2432,7 +1959,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "88362352", + "metadata": { + "editable": true + }, "source": [ "where $\\sigma_i^2$ is the variance (to be defined later) of the entry\n", "$y_i$. We may not know the explicit value of $\\sigma_i^2$, it serves\n", @@ -2460,7 +1990,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "cf70f181", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\epsilon_{\\mathrm{relative}}= \\frac{\\vert \\boldsymbol{y} -\\boldsymbol{\\tilde{y}}\\vert}{\\vert \\boldsymbol{y}\\vert}.\n", @@ -2469,7 +2002,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "45b3e51a", + "metadata": { + "editable": true + }, "source": [ "The squared cost function results in an arithmetic mean-unbiased\n", "estimator, and the absolute-value cost function results in a\n", @@ -2483,8 +2019,12 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, + "execution_count": 25, + "id": "acbb097e", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "import numpy as np\n", @@ -2507,7 +2047,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "906ec623", + "metadata": { + "editable": true + }, "source": [ "Depending on the parameter in front of the normal distribution, we may\n", "have a small or larger relative error. Try to play around with\n", @@ -2525,8 +2068,12 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, + "execution_count": 26, + "id": "ae576654", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "import numpy as np \n", @@ -2560,7 +2107,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "4fa873c4", + "metadata": { + "editable": true + }, "source": [ "The function **coef** gives us the parameter $\\beta$ of our fit while **intercept** yields \n", "$\\alpha$. Depending on the constant in front of the normal distribution, we get values near or far from $\\alpha =2$ and $\\beta =5$. Try to play around with different parameters in front of the normal distribution. The function **meansquarederror** gives us the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error or loss defined as" @@ -2568,7 +2118,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "28e7c10c", + "metadata": { + "editable": true + }, "source": [ "$$\n", "MSE(\\boldsymbol{y},\\boldsymbol{\\tilde{y}}) = \\frac{1}{n}\n", @@ -2578,7 +2131,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "f7dc1729", + "metadata": { + "editable": true + }, "source": [ "The smaller the value, the better the fit. Ideally we would like to\n", "have an MSE equal zero. The attentive reader has probably recognized\n", @@ -2596,7 +2152,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "8a05b954", + "metadata": { + "editable": true + }, "source": [ "$$\n", "R^2(\\boldsymbol{y}, \\tilde{\\boldsymbol{y}}) = 1 - \\frac{\\sum_{i=0}^{n - 1} (y_i - \\tilde{y}_i)^2}{\\sum_{i=0}^{n - 1} (y_i - \\bar{y})^2},\n", @@ -2605,14 +2164,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "e580bea2", + "metadata": { + "editable": true + }, "source": [ "where we have defined the mean value of $\\boldsymbol{y}$ as" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "0c51facd", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\bar{y} = \\frac{1}{n} \\sum_{i=0}^{n - 1} y_i.\n", @@ -2621,7 +2186,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "62a0f4f7", + "metadata": { + "editable": true + }, "source": [ "Another quantity taht we will meet again in our discussions of regression analysis is \n", " the mean absolute error (MAE), a risk metric corresponding to the expected value of the absolute error loss or what we call the $l1$-norm loss. In our discussion above we presented the relative error.\n", @@ -2630,7 +2198,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "f785e614", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\text{MAE}(\\boldsymbol{y}, \\boldsymbol{\\tilde{y}}) = \\frac{1}{n} \\sum_{i=0}^{n-1} \\left| y_i - \\tilde{y}_i \\right|.\n", @@ -2639,7 +2210,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "bf583443", + "metadata": { + "editable": true + }, "source": [ "We present the \n", "squared logarithmic (quadratic) error" @@ -2647,7 +2221,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "724378dc", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\text{MSLE}(\\boldsymbol{y}, \\boldsymbol{\\tilde{y}}) = \\frac{1}{n} \\sum_{i=0}^{n - 1} (\\log_e (1 + y_i) - \\log_e (1 + \\tilde{y}_i) )^2,\n", @@ -2656,14 +2233,16 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "0f2058ae", + "metadata": { + "editable": true + }, "source": [ "where $\\log_e (x)$ stands for the natural logarithm of $x$. This error\n", "estimate is best to use when targets having exponential growth, such\n", "as population counts, average sales of a commodity over a span of\n", "years etc. \n", "\n", - "\n", "Finally, another cost function is the Huber cost function used in robust regression.\n", "\n", "The rationale behind this possible cost function is its reduced\n", @@ -2676,7 +2255,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "e7caa601", + "metadata": { + "editable": true + }, "source": [ "$$\n", "H_{\\delta}(\\boldsymbol{a})=\\left\\{\\begin{array}{cc}\\frac{1}{2} \\boldsymbol{a}^{2}& \\text{for }|\\boldsymbol{a}|\\leq \\delta\\\\ \\delta (|\\boldsymbol{a}|-\\frac{1}{2}\\delta ),&\\text{otherwise}.\\end{array}\\right.\n", @@ -2685,11 +2267,13 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "0fe54ee3", + "metadata": { + "editable": true + }, "source": [ "Here $\\boldsymbol{a}=\\boldsymbol{y} - \\boldsymbol{\\tilde{y}}$.\n", "\n", - "\n", "We will discuss in more detail these and other functions in the\n", "various lectures. We conclude this part with another example. Instead\n", "of a linear $x$-dependence we study now a cubic polynomial and use the\n", @@ -2698,8 +2282,12 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, + "execution_count": 27, + "id": "07b7f404", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "import matplotlib.pyplot as plt\n", @@ -2736,7 +2324,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "2a3e7169", + "metadata": { + "editable": true + }, "source": [ "### To our real data: nuclear binding energies. Brief reminder on masses and binding energies\n", "\n", @@ -2750,7 +2341,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "ffb61b21", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\Delta M(N, Z) = M(N, Z) - uA,\n", @@ -2759,14 +2353,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "dae62975", + "metadata": { + "editable": true + }, "source": [ "where $u$ is the Atomic Mass Unit" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "47c55cae", + "metadata": { + "editable": true + }, "source": [ "$$\n", "u = M(^{12}\\mathrm{C})/12 = 931.4940954(57) \\hspace{0.1cm} \\mathrm{MeV}/c^2.\n", @@ -2775,14 +2375,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "ba0c4ef5", + "metadata": { + "editable": true + }, "source": [ "The nucleon masses are" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "d44a78b4", + "metadata": { + "editable": true + }, "source": [ "$$\n", "m_p = 1.00727646693(9)u,\n", @@ -2791,14 +2397,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "e478b442", + "metadata": { + "editable": true + }, "source": [ "and" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "bc08de2b", + "metadata": { + "editable": true + }, "source": [ "$$\n", "m_n = 939.56536(8)\\hspace{0.1cm} \\mathrm{MeV}/c^2 = 1.0086649156(6)u.\n", @@ -2807,7 +2419,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "e5e9dae9", + "metadata": { + "editable": true + }, "source": [ "In the [2016 mass evaluation of by W.J.Huang, G.Audi, M.Wang, F.G.Kondev, S.Naimi and X.Xu](http://nuclearmasses.org/resources_folder/Wang_2017_Chinese_Phys_C_41_030003.pdf)\n", "there are data on masses and decays of 3437 nuclei.\n", @@ -2820,7 +2435,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "55a50874", + "metadata": { + "editable": true + }, "source": [ "$$\n", "BE(N, Z) = ZM_H c^2 + Nm_n c^2 - M(N, Z)c^2 ,\n", @@ -2829,7 +2447,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "0722bdc3", + "metadata": { + "editable": true + }, "source": [ "where $M_H$ is the mass of the hydrogen atom and $m_n$ is the mass of the neutron.\n", "In terms of the mass excess the binding energy is given by" @@ -2837,7 +2458,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "1ad2c13d", + "metadata": { + "editable": true + }, "source": [ "$$\n", "BE(N, Z) = Z\\Delta_H c^2 + N\\Delta_n c^2 -\\Delta(N, Z)c^2 ,\n", @@ -2846,11 +2470,13 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "b55ccbf6", + "metadata": { + "editable": true + }, "source": [ "where $\\Delta_H c^2 = 7.2890$ MeV and $\\Delta_n c^2 = 8.0713$ MeV.\n", "\n", - "\n", "A popular and physically intuitive model which can be used to parametrize \n", "the experimental binding energies as function of $A$, is the so-called \n", "**liquid drop model**. The ansatz is based on the following expression" @@ -2858,7 +2484,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "e9bc1ac6", + "metadata": { + "editable": true + }, "source": [ "$$\n", "BE(N,Z) = a_1A-a_2A^{2/3}-a_3\\frac{Z^2}{A^{1/3}}-a_4\\frac{(N-Z)^2}{A},\n", @@ -2867,14 +2496,14 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "47174561", + "metadata": { + "editable": true + }, "source": [ "where $A$ stands for the number of nucleons and the $a_i$s are parameters which are determined by a fit \n", "to the experimental data. \n", "\n", - "\n", - "\n", - "\n", "To arrive at the above expression we have assumed that we can make the following assumptions:\n", "\n", " * There is a volume term $a_1A$ proportional with the number of nucleons (the energy is also an extensive quantity). When an assembly of nucleons of the same size is packed together into the smallest volume, each interior nucleon has a certain number of other nucleons in contact with it. This contribution is proportional to the volume.\n", @@ -2887,23 +2516,33 @@ "\n", "We could also add a so-called pairing term, which is a correction term that\n", "arises from the tendency of proton pairs and neutron pairs to\n", - "occur. An even number of particles is more stable than an odd number. \n", - "\n", - "\n", + "occur. An even number of particles is more stable than an odd number." + ] + }, + { + "cell_type": "markdown", + "id": "3a54d55d", + "metadata": { + "editable": true + }, + "source": [ "### Organizing our data\n", "\n", "Let us start with reading and organizing our data. \n", "We start with the compilation of masses and binding energies from 2016.\n", "After having downloaded this file to our own computer, we are now ready to read the file and start structuring our data.\n", "\n", - "\n", "We start with preparing folders for storing our calculations and the data file over masses and binding energies. We import also various modules that we will find useful in order to present various Machine Learning methods. Here we focus mainly on the functionality of **scikit-learn**." ] }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, + "execution_count": 28, + "id": "6a858ae6", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "# Common imports\n", @@ -2943,15 +2582,22 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "37694bf4", + "metadata": { + "editable": true + }, "source": [ "Before we proceed, we define also a function for making our plots. You can obviously avoid this and simply set up various **matplotlib** commands every time you need them. You may however find it convenient to collect all such commands in one function and simply call this function." ] }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, + "execution_count": 29, + "id": "0d909cb1", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "from pylab import plt, mpl\n", @@ -2969,7 +2615,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "476a0da3", + "metadata": { + "editable": true + }, "source": [ "Our next step is to read the data on experimental binding energies and\n", "reorganize them as functions of the mass number $A$, the number of\n", @@ -2977,14 +2626,17 @@ "always useful (unless you have a binary file or other types of compressed\n", "data) to actually open the file and simply take a look at it!\n", "\n", - "\n", "In particular, the program that outputs the final nuclear masses is written in Fortran with a specific format. It means that we need to figure out the format and which columns contain the data we are interested in. Pandas comes with a function that reads formatted output. After having admired the file, we are now ready to start massaging it with **pandas**. The file begins with some basic format information." ] }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, + "execution_count": 30, + "id": "808a944d", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "\"\"\" \n", @@ -3001,7 +2653,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "f13998e8", + "metadata": { + "editable": true + }, "source": [ "The data we are interested in are in columns 2, 3, 4 and 11, giving us\n", "the number of neutrons, protons, mass numbers and binding energies,\n", @@ -3011,8 +2666,12 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, + "execution_count": 31, + "id": "87734ea5", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "# Read the experimental data with Pandas\n", @@ -3037,7 +2696,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "c5cd7bf2", + "metadata": { + "editable": true + }, "source": [ "We have now read in the data, grouped them according to the variables we are interested in. \n", "We see how easy it is to reorganize the data using **pandas**. If we\n", @@ -3053,8 +2715,12 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, + "execution_count": 32, + "id": "135551a3", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "A = Masses['A']\n", @@ -3067,7 +2733,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "9f4a6509", + "metadata": { + "editable": true + }, "source": [ "The next step, and we will define this mathematically later, is to set up the so-called **design matrix**. We will throughout call this matrix $\\boldsymbol{X}$.\n", "It has dimensionality $p\\times n$, where $n$ is the number of data points and $p$ are the so-called predictors. In our case here they are given by the number of polynomials in $A$ we wish to include in the fit." @@ -3075,8 +2744,12 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, + "execution_count": 33, + "id": "02c2d4c3", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "# Now we set up the design matrix X\n", @@ -3090,15 +2763,22 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "10be1594", + "metadata": { + "editable": true + }, "source": [ "With **scikitlearn** we are now ready to use linear regression and fit our data." ] }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, + "execution_count": 34, + "id": "65a53863", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "clf = skl.LinearRegression().fit(X, Energies)\n", @@ -3107,7 +2787,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "86f51dcf", + "metadata": { + "editable": true + }, "source": [ "Pretty simple! \n", "Now we can print measures of how our fit is doing, the coefficients from the fits and plot the final fit together with our data." @@ -3115,8 +2798,12 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, + "execution_count": 35, + "id": "b13eba7f", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "# The mean squared error \n", @@ -3143,7 +2830,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "279b2fb0", + "metadata": { + "editable": true + }, "source": [ "### Seeing the wood for the trees\n", "\n", @@ -3152,8 +2842,12 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, + "execution_count": 36, + "id": "84d1e91b", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "\n", @@ -3190,7 +2884,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "8bead0b5", + "metadata": { + "editable": true + }, "source": [ "### And what about using neural networks?\n", "\n", @@ -3200,8 +2897,12 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, + "execution_count": 37, + "id": "96646081", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "from sklearn.neural_network import MLPRegressor\n", @@ -3237,7 +2938,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "93ebbcd3", + "metadata": { + "editable": true + }, "source": [ "## A first summary\n", "\n", @@ -3249,9 +2953,16 @@ "Furthermore,\n", "**Scikit-Learn** allows us with few lines of code to implement popular\n", "Machine Learning algorithms for supervised learning. Later we will meet **Tensorflow**, a powerful library for deep learning. \n", - "Now it is time to dive more into the details of various methods. We will start with linear regression and try to take a deeper look at what it entails.\n", - "\n", - "\n", + "Now it is time to dive more into the details of various methods. We will start with linear regression and try to take a deeper look at what it entails." + ] + }, + { + "cell_type": "markdown", + "id": "129b1e89", + "metadata": { + "editable": true + }, + "source": [ "## Why Linear Regression (aka Ordinary Least Squares and family)\n", "\n", "Fitting a continuous function with linear parameterization in terms of the parameters $\\boldsymbol{\\beta}$.\n", @@ -3274,9 +2985,16 @@ "* and many more features\n", "\n", "For more discussions of Ridge and Lasso regression, [Wessel van Wieringen's](https://arxiv.org/abs/1509.09169) article is highly recommended.\n", - "Similarly, [Mehta et al's article](https://arxiv.org/abs/1803.08823) is also recommended.\n", - "\n", - "\n", + "Similarly, [Mehta et al's article](https://arxiv.org/abs/1803.08823) is also recommended." + ] + }, + { + "cell_type": "markdown", + "id": "465172ea", + "metadata": { + "editable": true + }, + "source": [ "## Regression analysis, overarching aims\n", "\n", "Regression modeling deals with the description of the sampling distribution of a given random variable $y$ and how it varies as function of another variable or a set of such variables $\\boldsymbol{x} =[x_0, x_1,\\dots, x_{n-1}]^T$. \n", @@ -3289,13 +3007,18 @@ "\n", "* $p$ so-called explanatory (independent or predictor) variables $\\boldsymbol{x}_i=[x_{i0}, x_{i1}, \\dots, x_{ip-1}]$ with $i = 0, 1, 2, \\dots, n-1$ and explanatory variables running from $0$ to $p-1$. See below for more explicit examples. \n", "\n", - " The goal of the regression analysis is to extract/exploit relationship between $\\boldsymbol{y}$ and $\\boldsymbol{x}$ in or to infer causal dependencies, approximations to the likelihood functions, functional relationships and to make predictions, making fits and many other things.\n", - "\n", - "\n", - "\n", + " The goal of the regression analysis is to extract/exploit relationship between $\\boldsymbol{y}$ and $\\boldsymbol{x}$ in or to infer causal dependencies, approximations to the likelihood functions, functional relationships and to make predictions, making fits and many other things." + ] + }, + { + "cell_type": "markdown", + "id": "b7cf94d8", + "metadata": { + "editable": true + }, + "source": [ "## Regression analysis, overarching aims II\n", "\n", - "\n", "Consider an experiment in which $p$ characteristics of $n$ samples are\n", "measured. The data from this experiment, for various explanatory variables $p$ are normally represented by a matrix \n", "$\\mathbf{X}$.\n", @@ -3312,12 +3035,16 @@ "the *linear regression model* where $\\boldsymbol{\\beta} = [\\beta_0, \\ldots,\n", "\\beta_{p-1}]^{T}$ are the *regression parameters*. \n", "\n", - "Linear regression gives us a set of analytical equations for the parameters $\\beta_j$.\n", - "\n", - "\n", - "\n", - "\n", - "\n", + "Linear regression gives us a set of analytical equations for the parameters $\\beta_j$." + ] + }, + { + "cell_type": "markdown", + "id": "3b98d102", + "metadata": { + "editable": true + }, + "source": [ "## Examples\n", "In order to understand the relation among the predictors $p$, the set of data $n$ and the target (outcome, output etc) $\\boldsymbol{y}$,\n", "consider the model we discussed for describing nuclear binding energies. \n", @@ -3328,7 +3055,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "a3814cbf", + "metadata": { + "editable": true + }, "source": [ "$$\n", "BE(A) = a_0+a_1A+a_2A^{2/3}+a_3A^{-1/3}+a_4A^{-1},\n", @@ -3337,21 +3067,26 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "34db7d71", + "metadata": { + "editable": true + }, "source": [ "we have five predictors, that is the intercept, the $A$ dependent term, the $A^{2/3}$ term and the $A^{-1/3}$ and $A^{-1}$ terms.\n", "This gives $p=0,1,2,3,4$. Furthermore we have $n$ entries for each predictor. It means that our design matrix is a \n", "$p\\times n$ matrix $\\boldsymbol{X}$.\n", "\n", "Here the predictors are based on a model we have made. A popular data set which is widely encountered in ML applications is the\n", - "so-called [credit card default data from Taiwan](https://www.sciencedirect.com/science/article/pii/S0957417407006719?via%3Dihub). The data set contains data on $n=30000$ credit card holders with predictors like gender, marital status, age, profession, education, etc. In total there are $24$ such predictors or attributes leading to a design matrix of dimensionality $24 \\times 30000$. This is however a classification problem and we will come back to it when we discuss Logistic Regression.\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", + "so-called [credit card default data from Taiwan](https://www.sciencedirect.com/science/article/pii/S0957417407006719?via%3Dihub). The data set contains data on $n=30000$ credit card holders with predictors like gender, marital status, age, profession, education, etc. In total there are $24$ such predictors or attributes leading to a design matrix of dimensionality $24 \\times 30000$. This is however a classification problem and we will come back to it when we discuss Logistic Regression." + ] + }, + { + "cell_type": "markdown", + "id": "0f3d34aa", + "metadata": { + "editable": true + }, + "source": [ "## General linear models\n", "Before we proceed let us study a case from linear algebra where we aim at fitting a set of data $\\boldsymbol{y}=[y_0,y_1,\\dots,y_{n-1}]$. We could think of these data as a result of an experiment or a complicated numerical experiment. These data are functions of a series of variables $\\boldsymbol{x}=[x_0,x_1,\\dots,x_{n-1}]$, that is $y_i = y(x_i)$ with $i=0,1,2,\\dots,n-1$. The variables $x_i$ could represent physical quantities like time, temperature, position etc. We assume that $y(x)$ is a smooth function. \n", "\n", @@ -3360,7 +3095,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "3ae8a917", + "metadata": { + "editable": true + }, "source": [ "$$\n", "y=y(x) \\rightarrow y(x_i)=\\tilde{y}_i+\\epsilon_i=\\sum_{j=0}^{n-1} \\beta_j x_i^j+\\epsilon_i,\n", @@ -3369,20 +3107,31 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "85b75da7", + "metadata": { + "editable": true + }, + "source": [ + "where $\\epsilon_i$ is the error in our approximation." + ] + }, + { + "cell_type": "markdown", + "id": "b1ad5988", + "metadata": { + "editable": true + }, "source": [ - "where $\\epsilon_i$ is the error in our approximation.\n", - "\n", - "\n", - "\n", - "\n", "## Rewriting the fitting procedure as a linear algebra problem\n", "For every set of values $y_i,x_i$ we have thus the corresponding set of equations" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "d31fc0eb", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\begin{align*}\n", @@ -3397,7 +3146,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "f0c96fe6", + "metadata": { + "editable": true + }, "source": [ "## Rewriting the fitting procedure as a linear algebra problem, more details\n", "Defining the vectors" @@ -3405,7 +3157,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "e05fb474", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{y} = [y_0,y_1, y_2,\\dots, y_{n-1}]^T,\n", @@ -3414,14 +3169,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "832b4a52", + "metadata": { + "editable": true + }, "source": [ "and" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "2a04c6b0", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{\\beta} = [\\beta_0,\\beta_1, \\beta_2,\\dots, \\beta_{n-1}]^T,\n", @@ -3430,14 +3191,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "95feb9c7", + "metadata": { + "editable": true + }, "source": [ "and" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "9388dae6", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{\\epsilon} = [\\epsilon_0,\\epsilon_1, \\epsilon_2,\\dots, \\epsilon_{n-1}]^T,\n", @@ -3446,14 +3213,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "4b407da6", + "metadata": { + "editable": true + }, "source": [ "and the design matrix" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "d6f77716", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{X}=\n", @@ -3469,14 +3242,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "7ac4ebe7", + "metadata": { + "editable": true + }, "source": [ "we can rewrite our equations as" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "666e3761", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{y} = \\boldsymbol{X}\\boldsymbol{\\beta}+\\boldsymbol{\\epsilon}.\n", @@ -3485,13 +3264,21 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "7281f3db", + "metadata": { + "editable": true + }, + "source": [ + "The above design matrix is called a [Vandermonde matrix](https://en.wikipedia.org/wiki/Vandermonde_matrix)." + ] + }, + { + "cell_type": "markdown", + "id": "b6402b93", + "metadata": { + "editable": true + }, "source": [ - "The above design matrix is called a [Vandermonde matrix](https://en.wikipedia.org/wiki/Vandermonde_matrix).\n", - "\n", - "\n", - "\n", - "\n", "## Generalizing the fitting procedure as a linear algebra problem\n", "\n", "We are obviously not limited to the above polynomial expansions. We\n", @@ -3503,7 +3290,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "be28ea6a", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\begin{align*}\n", @@ -3520,20 +3310,31 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "d6ff0add", + "metadata": { + "editable": true + }, + "source": [ + "**Note that we have $p=n$ here. The matrix is symmetric. This is generally not the case!**" + ] + }, + { + "cell_type": "markdown", + "id": "10f87413", + "metadata": { + "editable": true + }, "source": [ - "**Note that we have $p=n$ here. The matrix is symmetric. This is generally not the case!**\n", - "\n", - "\n", - "\n", - "\n", "## Generalizing the fitting procedure as a linear algebra problem\n", "We redefine in turn the matrix $\\boldsymbol{X}$ as" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "2fc2d589", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{X}=\n", @@ -3549,14 +3350,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "49448051", + "metadata": { + "editable": true + }, "source": [ "and without loss of generality we rewrite again our equations as" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "c96a1d13", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{y} = \\boldsymbol{X}\\boldsymbol{\\beta}+\\boldsymbol{\\epsilon}.\n", @@ -3565,20 +3372,31 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "34f05f37", + "metadata": { + "editable": true + }, + "source": [ + "The left-hand side of this equation is kwown. Our error vector $\\boldsymbol{\\epsilon}$ and the parameter vector $\\boldsymbol{\\beta}$ are our unknow quantities. How can we obtain the optimal set of $\\beta_i$ values?" + ] + }, + { + "cell_type": "markdown", + "id": "e6ff72db", + "metadata": { + "editable": true + }, "source": [ - "The left-hand side of this equation is kwown. Our error vector $\\boldsymbol{\\epsilon}$ and the parameter vector $\\boldsymbol{\\beta}$ are our unknow quantities. How can we obtain the optimal set of $\\beta_i$ values?\n", - "\n", - "\n", - "\n", - "\n", "## Optimizing our parameters\n", "We have defined the matrix $\\boldsymbol{X}$ via the equations" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "39aef328", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\begin{align*}\n", @@ -3595,15 +3413,23 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "0a4e3a65", + "metadata": { + "editable": true + }, "source": [ "As we noted above, we stayed with a system with the design matrix \n", " $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times n}$, that is we have $p=n$. For reasons to come later (algorithmic arguments) we will hereafter define \n", - "our matrix as $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times p}$, with the predictors refering to the column numbers and the entries $n$ being the row elements.\n", - "\n", - "\n", - "\n", - "\n", + "our matrix as $\\boldsymbol{X}\\in {\\mathbb{R}}^{n\\times p}$, with the predictors refering to the column numbers and the entries $n$ being the row elements." + ] + }, + { + "cell_type": "markdown", + "id": "523fbdc7", + "metadata": { + "editable": true + }, + "source": [ "## Our model for the nuclear binding energies\n", "\n", "In our [introductory notes](https://compphysics.github.io/MachineLearning/doc/pub/How2ReadData/html/How2ReadData.html) we looked at the so-called [liquid drop model](https://en.wikipedia.org/wiki/Semi-empirical_mass_formula). Let us remind ourselves about what we did by looking at the code.\n", @@ -3613,8 +3439,12 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, + "execution_count": 38, + "id": "65375fc3", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "# Common imports\n", @@ -3690,14 +3520,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "a6b35fe6", + "metadata": { + "editable": true + }, "source": [ "With $\\boldsymbol{\\beta}\\in {\\mathbb{R}}^{p\\times 1}$, it means that we will hereafter write our equations for the approximation as" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "b4a0e652", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{\\tilde{y}}= \\boldsymbol{X}\\boldsymbol{\\beta},\n", @@ -3706,18 +3542,31 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "040adc2c", + "metadata": { + "editable": true + }, + "source": [ + "throughout these lectures." + ] + }, + { + "cell_type": "markdown", + "id": "8cb88980", + "metadata": { + "editable": true + }, "source": [ - "throughout these lectures. \n", - "\n", - "\n", "## Optimizing our parameters, more details\n", "With the above we use the design matrix to define the approximation $\\boldsymbol{\\tilde{y}}$ via the unknown quantity $\\boldsymbol{\\beta}$ as" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "fc947e4c", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{\\tilde{y}}= \\boldsymbol{X}\\boldsymbol{\\beta},\n", @@ -3726,14 +3575,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "c54ed44f", + "metadata": { + "editable": true + }, "source": [ "and in order to find the optimal parameters $\\beta_i$ instead of solving the above linear algebra problem, we define a function which gives a measure of the spread between the values $y_i$ (which represent hopefully the exact values) and the parameterized values $\\tilde{y}_i$, namely" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "9700bc2a", + "metadata": { + "editable": true + }, "source": [ "$$\n", "C(\\boldsymbol{\\beta})=\\frac{1}{n}\\sum_{i=0}^{n-1}\\left(y_i-\\tilde{y}_i\\right)^2=\\frac{1}{n}\\left\\{\\left(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}}\\right)^T\\left(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}}\\right)\\right\\},\n", @@ -3742,14 +3597,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "6486ad4b", + "metadata": { + "editable": true + }, "source": [ "or using the matrix $\\boldsymbol{X}$ and in a more compact matrix-vector notation as" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "b17f3473", + "metadata": { + "editable": true + }, "source": [ "$$\n", "C(\\boldsymbol{\\beta})=\\frac{1}{n}\\left\\{\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)^T\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)\\right\\}.\n", @@ -3758,19 +3619,23 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "511ef4cd", + "metadata": { + "editable": true + }, "source": [ "This function is one possible way to define the so-called cost function.\n", "\n", - "\n", - "\n", "It is also common to define\n", "the function $C$ as" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "15a9cc37", + "metadata": { + "editable": true + }, "source": [ "$$\n", "C(\\boldsymbol{\\beta})=\\frac{1}{2n}\\sum_{i=0}^{n-1}\\left(y_i-\\tilde{y}_i\\right)^2,\n", @@ -3779,13 +3644,21 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "367d1bd9", + "metadata": { + "editable": true + }, + "source": [ + "since when taking the first derivative with respect to the unknown parameters $\\beta$, the factor of $2$ cancels out." + ] + }, + { + "cell_type": "markdown", + "id": "300db0a3", + "metadata": { + "editable": true + }, "source": [ - "since when taking the first derivative with respect to the unknown parameters $\\beta$, the factor of $2$ cancels out.\n", - "\n", - "\n", - "\n", - "\n", "## Interpretations and optimizing our parameters\n", "\n", "The function" @@ -3793,7 +3666,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "78ad2d59", + "metadata": { + "editable": true + }, "source": [ "$$\n", "C(\\boldsymbol{\\beta})=\\frac{1}{n}\\left\\{\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)^T\\left(\\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)\\right\\},\n", @@ -3802,7 +3678,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "adb62030", + "metadata": { + "editable": true + }, "source": [ "can be linked to the variance of the quantity $y_i$ if we interpret the latter as the mean value. \n", "When linking (see the discussion below) with the maximum likelihood approach below, we will indeed interpret $y_i$ as a mean value" @@ -3810,7 +3689,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "4cb086a5", + "metadata": { + "editable": true + }, "source": [ "$$\n", "y_{i}=\\langle y_i \\rangle = \\beta_0x_{i,0}+\\beta_1x_{i,1}+\\beta_2x_{i,2}+\\dots+\\beta_{n-1}x_{i,n-1}+\\epsilon_i,\n", @@ -3819,7 +3701,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "f5164d25", + "metadata": { + "editable": true + }, "source": [ "where $\\langle y_i \\rangle$ is the mean value. Keep in mind also that\n", "till now we have treated $y_i$ as the exact value. Normally, the\n", @@ -3835,7 +3720,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "171787e6", + "metadata": { + "editable": true + }, "source": [ "$$\n", "{\\displaystyle \\min_{\\boldsymbol{\\beta}\\in\n", @@ -3845,14 +3733,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "bc2e0510", + "metadata": { + "editable": true + }, "source": [ "In practical terms it means we will require" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "e5649cfc", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\frac{\\partial C(\\boldsymbol{\\beta})}{\\partial \\beta_j} = \\frac{\\partial }{\\partial \\beta_j}\\left[ \\frac{1}{n}\\sum_{i=0}^{n-1}\\left(y_i-\\beta_0x_{i,0}-\\beta_1x_{i,1}-\\beta_2x_{i,2}-\\dots-\\beta_{n-1}x_{i,n-1}\\right)^2\\right]=0,\n", @@ -3861,14 +3755,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "134777d3", + "metadata": { + "editable": true + }, "source": [ "which results in" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "18b005f8", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\frac{\\partial C(\\boldsymbol{\\beta})}{\\partial \\beta_j} = -\\frac{2}{n}\\left[ \\sum_{i=0}^{n-1}x_{ij}\\left(y_i-\\beta_0x_{i,0}-\\beta_1x_{i,1}-\\beta_2x_{i,2}-\\dots-\\beta_{n-1}x_{i,n-1}\\right)\\right]=0,\n", @@ -3877,14 +3777,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "b34ed0d9", + "metadata": { + "editable": true + }, "source": [ "or in a matrix-vector form as" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "7cc13452", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\frac{\\partial C(\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}} = 0 = \\boldsymbol{X}^T\\left( \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right).\n", @@ -3893,7 +3799,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "31f0b7c2", + "metadata": { + "editable": true + }, "source": [ "## Interpretations and optimizing our parameters\n", "We can rewrite" @@ -3901,7 +3810,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "feb09e6a", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\frac{\\partial C(\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}} = 0 = \\boldsymbol{X}^T\\left( \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right),\n", @@ -3910,14 +3822,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "4c1fbe44", + "metadata": { + "editable": true + }, "source": [ "as" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "12a694e5", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{X}^T\\boldsymbol{y} = \\boldsymbol{X}^T\\boldsymbol{X}\\boldsymbol{\\beta},\n", @@ -3926,14 +3844,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "ba26ca19", + "metadata": { + "editable": true + }, "source": [ "and if the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$ is invertible we have the solution" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "39958365", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{\\beta} =\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}.\n", @@ -3942,7 +3866,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "bcc1b272", + "metadata": { + "editable": true + }, "source": [ "We note also that since our design matrix is defined as $\\boldsymbol{X}\\in\n", "{\\mathbb{R}}^{n\\times p}$, the product $\\boldsymbol{X}^T\\boldsymbol{X} \\in\n", @@ -3955,12 +3882,16 @@ "allow for the usage of direct linear algebra methods such as **LU** decomposition or **Singular Value Decomposition** (SVD) for finding the inverse of the matrix\n", "$\\boldsymbol{X}^T\\boldsymbol{X}$.\n", "\n", - "\n", - "\n", - "**Small question**: Do you think the example we have at hand here (the nuclear binding energies) can lead to problems in inverting the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$? What kind of problems can we expect?\n", - "\n", - "\n", - "\n", + "**Small question**: Do you think the example we have at hand here (the nuclear binding energies) can lead to problems in inverting the matrix $\\boldsymbol{X}^T\\boldsymbol{X}$? What kind of problems can we expect?" + ] + }, + { + "cell_type": "markdown", + "id": "5dc4f920", + "metadata": { + "editable": true + }, + "source": [ "## Some useful matrix and vector expressions\n", "\n", "The following matrix and vector relation will be useful here and for the rest of the course. Vectors are always written as boldfaced lower case letters and \n", @@ -3969,79 +3900,46 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "f341bf32", + "metadata": { + "editable": true + }, "source": [ - "4\n", - "8\n", - " \n", - "<\n", - "<\n", - "<\n", - "!\n", - "!\n", - "M\n", - "A\n", - "T\n", - "H\n", - "_\n", - "B\n", - "L\n", - "O\n", - "C\n", - "K" + "$$\n", + "\\frac{\\partial (\\boldsymbol{b}^T\\boldsymbol{a})}{\\partial \\boldsymbol{a}} = \\boldsymbol{b},\n", + "$$" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "e5aa6d33", + "metadata": { + "editable": true + }, "source": [ - "4\n", - "9\n", - " \n", - "<\n", - "<\n", - "<\n", - "!\n", - "!\n", - "M\n", - "A\n", - "T\n", - "H\n", - "_\n", - "B\n", - "L\n", - "O\n", - "C\n", - "K" + "$$\n", + "\\frac{\\partial (\\boldsymbol{a}^T\\boldsymbol{A}\\boldsymbol{a})}{\\partial \\boldsymbol{a}} = (\\boldsymbol{A}+\\boldsymbol{A}^T)\\boldsymbol{a},\n", + "$$" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "e0163aef", + "metadata": { + "editable": true + }, "source": [ - "5\n", - "0\n", - " \n", - "<\n", - "<\n", - "<\n", - "!\n", - "!\n", - "M\n", - "A\n", - "T\n", - "H\n", - "_\n", - "B\n", - "L\n", - "O\n", - "C\n", - "K" + "$$\n", + "\\frac{\\partial tr(\\boldsymbol{B}\\boldsymbol{A})}{\\partial \\boldsymbol{A}} = \\boldsymbol{B}^T,\n", + "$$" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "f3d8529d", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\frac{\\partial \\log{\\vert\\boldsymbol{A}\\vert}}{\\partial \\boldsymbol{A}} = (\\boldsymbol{A}^{-1})^T.\n", @@ -4050,7 +3948,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "926fae33", + "metadata": { + "editable": true + }, "source": [ "## Interpretations and optimizing our parameters\n", "The residuals $\\boldsymbol{\\epsilon}$ are in turn given by" @@ -4058,7 +3959,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "459363f3", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{\\epsilon} = \\boldsymbol{y}-\\boldsymbol{\\tilde{y}} = \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta},\n", @@ -4067,14 +3971,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "c1ae7c6c", + "metadata": { + "editable": true + }, "source": [ "and with" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "52de9181", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{X}^T\\left( \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)= 0,\n", @@ -4083,14 +3993,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "b4619337", + "metadata": { + "editable": true + }, "source": [ "we have" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "e384b941", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{X}^T\\boldsymbol{\\epsilon}=\\boldsymbol{X}^T\\left( \\boldsymbol{y}-\\boldsymbol{X}\\boldsymbol{\\beta}\\right)= 0,\n", @@ -4099,15 +4015,23 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "4123b6f6", + "metadata": { + "editable": true + }, "source": [ "meaning that the solution for $\\boldsymbol{\\beta}$ is the one which minimizes the residuals. Later we will link this with the maximum likelihood approach.\n", "\n", - "\n", - "\n", - "\n", - "Let us now return to our nuclear binding energies and simply code the above equations. \n", - "\n", + "Let us now return to our nuclear binding energies and simply code the above equations." + ] + }, + { + "cell_type": "markdown", + "id": "8f1c0df4", + "metadata": { + "editable": true + }, + "source": [ "## Own code for Ordinary Least Squares\n", "\n", "It is rather straightforward to implement the matrix inversion and obtain the parameters $\\boldsymbol{\\beta}$. After having defined the matrix $\\boldsymbol{X}$ we simply need to \n", @@ -4116,8 +4040,12 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, + "execution_count": 39, + "id": "f06d4256", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "# matrix inversion to find beta\n", @@ -4128,15 +4056,22 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "cdf3d845", + "metadata": { + "editable": true + }, "source": [ "Alternatively, you can use the least squares functionality in **Numpy** as" ] }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, + "execution_count": 40, + "id": "bff161d1", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "fit = np.linalg.lstsq(X, Energies, rcond =None)[0]\n", @@ -4145,15 +4080,22 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "1ba8de37", + "metadata": { + "editable": true + }, "source": [ "And finally we plot our fit with and compare with data" ] }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, + "execution_count": 41, + "id": "ff3cb363", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "Masses['Eapprox'] = ytilde\n", @@ -4172,7 +4114,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "367e150e", + "metadata": { + "editable": true + }, "source": [ "## Adding error analysis and training set up\n", "\n", @@ -4182,8 +4127,12 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, + "execution_count": 42, + "id": "e75d549e", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "def R2(y_data, y_model):\n", @@ -4192,15 +4141,22 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "5937c2eb", + "metadata": { + "editable": true + }, "source": [ "and we would be using it as" ] }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, + "execution_count": 43, + "id": "6e4a7267", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "print(R2(Energies,ytilde))" @@ -4208,15 +4164,22 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "af9b5785", + "metadata": { + "editable": true + }, "source": [ "We can easily add our **MSE** score as" ] }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, + "execution_count": 44, + "id": "1eda8437", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "def MSE(y_data,y_model):\n", @@ -4228,15 +4191,22 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "b5d3d853", + "metadata": { + "editable": true + }, "source": [ "and finally the relative error as" ] }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, + "execution_count": 45, + "id": "5166df6e", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "def RelativeError(y_data,y_model):\n", @@ -4246,7 +4216,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "236c30eb", + "metadata": { + "editable": true + }, "source": [ "## The $\\chi^2$ function\n", "\n", @@ -4265,7 +4238,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "50a6a65f", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\chi^2(\\boldsymbol{\\beta})=\\frac{1}{n}\\sum_{i=0}^{n-1}\\frac{\\left(y_i-\\tilde{y}_i\\right)^2}{\\sigma_i^2}=\\frac{1}{n}\\left\\{\\left(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}}\\right)^T\\frac{1}{\\boldsymbol{\\Sigma^2}}\\left(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}}\\right)\\right\\},\n", @@ -4274,12 +4250,21 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "1f7a0ed2", + "metadata": { + "editable": true + }, + "source": [ + "where the matrix $\\boldsymbol{\\Sigma}$ is a diagonal matrix with $\\sigma_i$ as matrix elements." + ] + }, + { + "cell_type": "markdown", + "id": "254e32f6", + "metadata": { + "editable": true + }, "source": [ - "where the matrix $\\boldsymbol{\\Sigma}$ is a diagonal matrix with $\\sigma_i$ as matrix elements.\n", - "\n", - "\n", - "\n", "## The $\\chi^2$ function\n", "\n", "In order to find the parameters $\\beta_i$ we will then minimize the spread of $\\chi^2(\\boldsymbol{\\beta})$ by requiring" @@ -4287,7 +4272,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "309cb707", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\frac{\\partial \\chi^2(\\boldsymbol{\\beta})}{\\partial \\beta_j} = \\frac{\\partial }{\\partial \\beta_j}\\left[ \\frac{1}{n}\\sum_{i=0}^{n-1}\\left(\\frac{y_i-\\beta_0x_{i,0}-\\beta_1x_{i,1}-\\beta_2x_{i,2}-\\dots-\\beta_{n-1}x_{i,n-1}}{\\sigma_i}\\right)^2\\right]=0,\n", @@ -4296,14 +4284,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "ed0d9230", + "metadata": { + "editable": true + }, "source": [ "which results in" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "6e729fff", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\frac{\\partial \\chi^2(\\boldsymbol{\\beta})}{\\partial \\beta_j} = -\\frac{2}{n}\\left[ \\sum_{i=0}^{n-1}\\frac{x_{ij}}{\\sigma_i}\\left(\\frac{y_i-\\beta_0x_{i,0}-\\beta_1x_{i,1}-\\beta_2x_{i,2}-\\dots-\\beta_{n-1}x_{i,n-1}}{\\sigma_i}\\right)\\right]=0,\n", @@ -4312,14 +4306,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "4b8c3db8", + "metadata": { + "editable": true + }, "source": [ "or in a matrix-vector form as" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "0f38e855", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\frac{\\partial \\chi^2(\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}} = 0 = \\boldsymbol{A}^T\\left( \\boldsymbol{b}-\\boldsymbol{A}\\boldsymbol{\\beta}\\right).\n", @@ -4328,12 +4328,21 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "e9810355", + "metadata": { + "editable": true + }, + "source": [ + "where we have defined the matrix $\\boldsymbol{A} =\\boldsymbol{X}/\\boldsymbol{\\Sigma}$ with matrix elements $a_{ij} = x_{ij}/\\sigma_i$ and the vector $\\boldsymbol{b}$ with elements $b_i = y_i/\\sigma_i$." + ] + }, + { + "cell_type": "markdown", + "id": "d64064a7", + "metadata": { + "editable": true + }, "source": [ - "where we have defined the matrix $\\boldsymbol{A} =\\boldsymbol{X}/\\boldsymbol{\\Sigma}$ with matrix elements $a_{ij} = x_{ij}/\\sigma_i$ and the vector $\\boldsymbol{b}$ with elements $b_i = y_i/\\sigma_i$.\n", - "\n", - "\n", - "\n", "## The $\\chi^2$ function\n", "\n", "We can rewrite" @@ -4341,7 +4350,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "ca671f7b", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\frac{\\partial \\chi^2(\\boldsymbol{\\beta})}{\\partial \\boldsymbol{\\beta}} = 0 = \\boldsymbol{A}^T\\left( \\boldsymbol{b}-\\boldsymbol{A}\\boldsymbol{\\beta}\\right),\n", @@ -4350,14 +4362,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "857dac9b", + "metadata": { + "editable": true + }, "source": [ "as" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "6f16b544", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{A}^T\\boldsymbol{b} = \\boldsymbol{A}^T\\boldsymbol{A}\\boldsymbol{\\beta},\n", @@ -4366,14 +4384,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "7152f392", + "metadata": { + "editable": true + }, "source": [ "and if the matrix $\\boldsymbol{A}^T\\boldsymbol{A}$ is invertible we have the solution" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "0d6ac746", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{\\beta} =\\left(\\boldsymbol{A}^T\\boldsymbol{A}\\right)^{-1}\\boldsymbol{A}^T\\boldsymbol{b}.\n", @@ -4382,7 +4406,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "62cc38ae", + "metadata": { + "editable": true + }, "source": [ "## The $\\chi^2$ function\n", "\n", @@ -4391,7 +4418,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "eeb7f574", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{H} = \\left(\\boldsymbol{A}^T\\boldsymbol{A}\\right)^{-1},\n", @@ -4400,14 +4430,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "9963ae15", + "metadata": { + "editable": true + }, "source": [ "we have then the following expression for the parameters $\\beta_j$ (the matrix elements of $\\boldsymbol{H}$ are $h_{ij}$)" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "4e816631", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\beta_j = \\sum_{k=0}^{p-1}h_{jk}\\sum_{i=0}^{n-1}\\frac{y_i}{\\sigma_i}\\frac{x_{ik}}{\\sigma_i} = \\sum_{k=0}^{p-1}h_{jk}\\sum_{i=0}^{n-1}b_ia_{ik}\n", @@ -4416,14 +4452,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "75595bb9", + "metadata": { + "editable": true + }, "source": [ "We state without proof the expression for the uncertainty in the parameters $\\beta_j$ as (we leave this as an exercise)" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "278292fc", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\sigma^2(\\beta_j) = \\sum_{i=0}^{n-1}\\sigma_i^2\\left( \\frac{\\partial \\beta_j}{\\partial y_i}\\right)^2,\n", @@ -4432,14 +4474,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "82c2439c", + "metadata": { + "editable": true + }, "source": [ "resulting in" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "59ff6249", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\sigma^2(\\beta_j) = \\left(\\sum_{k=0}^{p-1}h_{jk}\\sum_{i=0}^{n-1}a_{ik}\\right)\\left(\\sum_{l=0}^{p-1}h_{jl}\\sum_{m=0}^{n-1}a_{ml}\\right) = h_{jj}!\n", @@ -4448,7 +4496,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "eb2dc41e", + "metadata": { + "editable": true + }, "source": [ "## The $\\chi^2$ function\n", "The first step here is to approximate the function $y$ with a first-order polynomial, that is we write" @@ -4456,7 +4507,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "723aa239", + "metadata": { + "editable": true + }, "source": [ "$$\n", "y=y(x) \\rightarrow y(x_i) \\approx \\beta_0+\\beta_1 x_i.\n", @@ -4465,14 +4519,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "b513b90f", + "metadata": { + "editable": true + }, "source": [ "By computing the derivatives of $\\chi^2$ with respect to $\\beta_0$ and $\\beta_1$ show that these are given by" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "62903cbc", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\frac{\\partial \\chi^2(\\boldsymbol{\\beta})}{\\partial \\beta_0} = -2\\left[ \\frac{1}{n}\\sum_{i=0}^{n-1}\\left(\\frac{y_i-\\beta_0-\\beta_1x_{i}}{\\sigma_i^2}\\right)\\right]=0,\n", @@ -4481,14 +4541,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "207584d4", + "metadata": { + "editable": true + }, "source": [ "and" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "6c910491", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\frac{\\partial \\chi^2(\\boldsymbol{\\beta})}{\\partial \\beta_1} = -\\frac{2}{n}\\left[ \\sum_{i=0}^{n-1}x_i\\left(\\frac{y_i-\\beta_0-\\beta_1x_{i}}{\\sigma_i^2}\\right)\\right]=0.\n", @@ -4497,7 +4563,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "1bc61f61", + "metadata": { + "editable": true + }, "source": [ "## The $\\chi^2$ function\n", "\n", @@ -4507,7 +4576,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "d573377f", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\gamma = \\sum_{i=0}^{n-1}\\frac{1}{\\sigma_i^2},\n", @@ -4516,7 +4588,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "3cbeb35c", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\gamma_x = \\sum_{i=0}^{n-1}\\frac{x_{i}}{\\sigma_i^2},\n", @@ -4525,7 +4600,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "c91cb43e", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\gamma_y = \\sum_{i=0}^{n-1}\\left(\\frac{y_i}{\\sigma_i^2}\\right),\n", @@ -4534,7 +4612,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "e20a004b", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\gamma_{xx} = \\sum_{i=0}^{n-1}\\frac{x_ix_{i}}{\\sigma_i^2},\n", @@ -4543,7 +4624,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "a116dd64", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\gamma_{xy} = \\sum_{i=0}^{n-1}\\frac{y_ix_{i}}{\\sigma_i^2},\n", @@ -4552,14 +4636,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "f1fa634c", + "metadata": { + "editable": true + }, "source": [ "we obtain" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "d83177be", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\beta_0 = \\frac{\\gamma_{xx}\\gamma_y-\\gamma_x\\gamma_y}{\\gamma\\gamma_{xx}-\\gamma_x^2},\n", @@ -4568,7 +4658,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "ff3efe3f", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\beta_1 = \\frac{\\gamma_{xy}\\gamma-\\gamma_x\\gamma_y}{\\gamma\\gamma_{xx}-\\gamma_x^2}.\n", @@ -4577,16 +4670,24 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "b94950d4", + "metadata": { + "editable": true + }, "source": [ "This approach (different linear and non-linear regression) suffers\n", "often from both being underdetermined and overdetermined in the\n", "unknown coefficients $\\beta_i$. A better approach is to use the\n", - "Singular Value Decomposition (SVD) method discussed next week.\n", - "\n", - "\n", - "\n", - "\n", + "Singular Value Decomposition (SVD) method discussed next week." + ] + }, + { + "cell_type": "markdown", + "id": "8889337c", + "metadata": { + "editable": true + }, + "source": [ "## Fitting an Equation of State for Dense Nuclear Matter\n", "\n", "Before we continue, let us introduce yet another example. We are going to fit the\n", @@ -4604,15 +4705,27 @@ "The difference now is that we use **Scikit-Learn's** regression tools\n", "instead of our own matrix inversion implementation. Furthermore, we\n", "sneak in **Ridge** regression (to be discussed below) which includes a\n", - "hyperparameter $\\lambda$, also to be explained below.\n", - "\n", + "hyperparameter $\\lambda$, also to be explained below." + ] + }, + { + "cell_type": "markdown", + "id": "79eeb561", + "metadata": { + "editable": true + }, + "source": [ "## The code" ] }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, + "execution_count": 46, + "id": "194a1d1a", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "# Common imports\n", @@ -4704,16 +4817,26 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "a8dcc692", + "metadata": { + "editable": true + }, "source": [ "The above simple polynomial in density $\\rho$ gives an excellent fit\n", "to the data. \n", "\n", "We note also that there is a small deviation between the\n", "standard OLS and the Ridge regression at higher densities. We discuss this in more detail\n", - "below.\n", - "\n", - "\n", + "below." + ] + }, + { + "cell_type": "markdown", + "id": "12a0253c", + "metadata": { + "editable": true + }, + "source": [ "## Splitting our Data in Training and Test data\n", "\n", "It is normal in essentially all Machine Learning studies to split the\n", @@ -4730,8 +4853,12 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, + "execution_count": 47, + "id": "5ff33c4e", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "import os\n", @@ -4802,16 +4929,22 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "4befc696", + "metadata": { + "editable": true + }, "source": [ "## Exercises for week 35\n", - "Here are three possible exercises for week 35 and the lab sessions of Wednesday September 1.\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", + "Here are three possible exercises for week 35 and the lab sessions of Wednesday September 1." + ] + }, + { + "cell_type": "markdown", + "id": "f833fa2b", + "metadata": { + "editable": true + }, + "source": [ "## Exercise 1: Setting up various Python environments\n", "\n", "The first exercise here is of a mere technical art. We want you to have \n", @@ -4871,15 +5004,16 @@ "analysis environment, available for free and under a commercial\n", "license.\n", "\n", - "We recommend using **Anaconda** if you are not too familiar with setting paths in a terminal environment.\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", + "We recommend using **Anaconda** if you are not too familiar with setting paths in a terminal environment." + ] + }, + { + "cell_type": "markdown", + "id": "21b7c11f", + "metadata": { + "editable": true + }, + "source": [ "## Exercise 2: making your own data and exploring scikit-learn\n", "\n", "We will generate our own dataset for a function $y(x)$ where $x \\in [0,1]$ and defined by random numbers computed with the uniform distribution. The function $y$ is a quadratic polynomial in $x$ with added stochastic noise according to the normal distribution $\\cal {N}(0,1)$.\n", @@ -4888,8 +5022,12 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, + "execution_count": 48, + "id": "9213ce7d", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "x = np.random.rand(100,1)\n", @@ -4898,7 +5036,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "0166974f", + "metadata": { + "editable": true + }, "source": [ "1. Write your own code (following the examples under the [regression notes](https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/chapter1.html)) for computing the parametrization of the data set fitting a second-order polynomial. \n", "\n", @@ -4909,7 +5050,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "982d42cb", + "metadata": { + "editable": true + }, "source": [ "$$\n", "MSE(\\boldsymbol{y},\\boldsymbol{\\tilde{y}}) = \\frac{1}{n}\n", @@ -4919,7 +5063,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "9d32cf1a", + "metadata": { + "editable": true + }, "source": [ "and the $R^2$ score function.\n", "If $\\tilde{\\boldsymbol{y}}_i$ is the predicted value of the $i-th$ sample and $y_i$ is the corresponding true value, then the score $R^2$ is defined as" @@ -4927,7 +5074,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "f07e5904", + "metadata": { + "editable": true + }, "source": [ "$$\n", "R^2(\\boldsymbol{y}, \\tilde{\\boldsymbol{y}}) = 1 - \\frac{\\sum_{i=0}^{n - 1} (y_i - \\tilde{y}_i)^2}{\\sum_{i=0}^{n - 1} (y_i - \\bar{y})^2},\n", @@ -4936,14 +5086,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "3c91a4d7", + "metadata": { + "editable": true + }, "source": [ "where we have defined the mean value of $\\boldsymbol{y}$ as" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "22dce6cd", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\bar{y} = \\frac{1}{n} \\sum_{i=0}^{n - 1} y_i.\n", @@ -4952,12 +5108,14 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "63dbfea2", + "metadata": { + "editable": true + }, "source": [ "You can use the functionality included in scikit-learn. If you feel for it, you can use your own program and define functions which compute the above two functions. \n", "Discuss the meaning of these results. Try also to vary the coefficient in front of the added stochastic noise term and discuss the quality of the fits.\n", "\n", - "\n", "\n", "**Solution.**\n", "The code here is an example of where we define our own design matrix and fit parameters $\\beta$." @@ -4965,8 +5123,12 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, + "execution_count": 49, + "id": "c007a8f7", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "import os\n", @@ -5013,17 +5175,21 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "093a802e", + "metadata": { + "editable": true + }, + "source": [ + "" + ] + }, + { + "cell_type": "markdown", + "id": "a4fd1970", + "metadata": { + "editable": true + }, "source": [ - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", "## Exercise 3: Normalizing our data\n", "\n", "A much used approach before starting to train the data is to preprocess our\n", @@ -5041,7 +5207,6 @@ "function included in **Scikit-Learn** is the **MinMaxScaler** which\n", "ensures that all features are exactly between $0$ and $1$. The\n", "\n", - "\n", "The **Normalizer** scales each data\n", "point such that the feature vector has a euclidean length of one. In other words, it\n", "projects a data point on the circle (or sphere in the case of higher dimensions) with a\n", @@ -5059,15 +5224,18 @@ "outliers, and might often lead to trouble for other scaling\n", "techniques.\n", "\n", - "\n", "It also common to split the data in a **training** set and a **testing** set. A typical split is to use $80\\%$ of the data for training and the rest\n", "for testing. This can be done as follows with our design matrix $\\boldsymbol{X}$ and data $\\boldsymbol{y}$ (remember to import **scikit-learn**)" ] }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, + "execution_count": 50, + "id": "27b4f807", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "# split in training and test data\n", @@ -5076,15 +5244,22 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "78154d99", + "metadata": { + "editable": true + }, "source": [ "Then we can use the standard scaler to scale our data as" ] }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, + "execution_count": 51, + "id": "709a18d0", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "scaler = StandardScaler()\n", @@ -5095,7 +5270,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "2362e332", + "metadata": { + "editable": true + }, "source": [ "In this exercise we want you to to compute the MSE for the training\n", "data and the test data as function of the complexity of a polynomial,\n", @@ -5104,15 +5282,17 @@ "One of \n", "the aims is to reproduce Figure 2.11 of [Hastie et al](https://github.com/CompPhysics/MLErasmus/blob/master/doc/Textbooks/elementsstat.pdf).\n", "\n", - "\n", - "\n", "Our data is defined by $x\\in [-3,3]$ with a total of for example $100$ data points." ] }, { "cell_type": "code", - "execution_count": null, - "metadata": {}, + "execution_count": 52, + "id": "47021865", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "np.random.seed()\n", @@ -5125,44 +5305,49 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "eb6cf432", + "metadata": { + "editable": true + }, + "source": [ + "where $y$ is the function we want to fit with a given polynomial." + ] + }, + { + "cell_type": "markdown", + "id": "b61a59b9", + "metadata": { + "editable": true + }, "source": [ - "where $y$ is the function we want to fit with a given polynomial.\n", - "\n", - "\n", "**a)**\n", - "Write a first code which sets up a design matrix $X$ defined by a fifth-order polynomial. Scale your data and split it in training and test data.\n", - "\n", + "Write a first code which sets up a design matrix $X$ defined by a fifth-order polynomial. Scale your data and split it in training and test data." + ] + }, + { + "cell_type": "markdown", + "id": "c334b79a", + "metadata": { + "editable": true + }, + "source": [ "**b)**\n", - "Perform an ordinary least squares and compute the means squared error and the $R2$ factor for the training data and the test data, with and without scaling.\n", - "\n", + "Perform an ordinary least squares and compute the means squared error and the $R2$ factor for the training data and the test data, with and without scaling." + ] + }, + { + "cell_type": "markdown", + "id": "5164c62c", + "metadata": { + "editable": true + }, + "source": [ "**c)**\n", - "Add now a model which allows you to make polynomials up to degree $15$. Perform a standard OLS fitting of the training data and compute the MSE and $R2$ for the training and test data and plot both test and training data MSE and $R2$ as functions of the polynomial degree. Compare what you see with Figure 2.11 of Hastie et al. Comment your results. For which polynomial degree do you find an optimal MSE (smallest value)?\n", - "\n", - "\n", - "" + "Add now a model which allows you to make polynomials up to degree $15$. Perform a standard OLS fitting of the training data and compute the MSE and $R2$ for the training and test data and plot both test and training data MSE and $R2$ as functions of the polynomial degree. Compare what you see with Figure 2.11 of Hastie et al. Comment your results. For which polynomial degree do you find an optimal MSE (smallest value)?" ] } ], - "metadata": { - "kernelspec": { - "display_name": "Python 3 (ipykernel)", - "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.9.7" - } - }, + "metadata": {}, "nbformat": 4, - "nbformat_minor": 4 + "nbformat_minor": 5 } diff --git a/doc/pub/week45/html/._week45-bs000.html b/doc/pub/week45/html/._week45-bs000.html index d7e0ee14e..901aa91ec 100644 --- a/doc/pub/week45/html/._week45-bs000.html +++ b/doc/pub/week45/html/._week45-bs000.html @@ -409,7 +409,7 @@ MathJax.Hub.Config({
    -

    Nov 11, 2021

    +

    Nov 12, 2021


    diff --git a/doc/pub/week45/html/._week45-bs001.html b/doc/pub/week45/html/._week45-bs001.html index dde0d8852..f3e305299 100644 --- a/doc/pub/week45/html/._week45-bs001.html +++ b/doc/pub/week45/html/._week45-bs001.html @@ -395,7 +395,13 @@ MathJax.Hub.Config({
    • Thursday: Basics of Decision Trees, Bagging and Voting
    • +
    • Friday: More on Bagging, Voting, Random Forests and start Boosting
    • +
    diff --git a/doc/pub/week45/html/._week45-bs074.html b/doc/pub/week45/html/._week45-bs074.html index c5771590b..2d0592881 100644 --- a/doc/pub/week45/html/._week45-bs074.html +++ b/doc/pub/week45/html/._week45-bs074.html @@ -403,7 +403,6 @@ MathJax.Hub.Config({ import numpy as np from sklearn.model_selection import train_test_split from sklearn.ensemble import GradientBoostingRegressor -from sklearn.preprocessing import StandardScaler import scikitplot as skplt from sklearn.metrics import mean_squared_error @@ -419,15 +418,11 @@ bias = np.= np.zeros(maxdegree) polydegree = np.zeros(maxdegree) X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2) -scaler = StandardScaler() -scaler.fit(X_train) -X_train_scaled = scaler.transform(X_train) -X_test_scaled = scaler.transform(X_test) for degree in range(1,maxdegree): model = GradientBoostingRegressor(max_depth=degree, n_estimators=100, learning_rate=1.0) - model.fit(X_train_scaled,y_train) - y_pred = model.predict(X_test_scaled) + model.fit(X_train,y_train) + y_pred = model.predict(X_test) polydegree[degree] = degree error[degree] = np.mean( np.mean((y_test - y_pred)**2) ) bias[degree] = np.mean( (y_test - np.mean(y_pred))**2 ) diff --git a/doc/pub/week45/html/._week45-bs077.html b/doc/pub/week45/html/._week45-bs077.html index 0a6233b53..a197627de 100644 --- a/doc/pub/week45/html/._week45-bs077.html +++ b/doc/pub/week45/html/._week45-bs077.html @@ -404,7 +404,6 @@ MathJax.Hub.Config({ import numpy as np from sklearn.model_selection import train_test_split import xgboost as xgb -from sklearn.preprocessing import StandardScaler import scikitplot as skplt from sklearn.metrics import mean_squared_error @@ -420,16 +419,12 @@ bias = np.= np.zeros(maxdegree) polydegree = np.zeros(maxdegree) X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2) -scaler = StandardScaler() -scaler.fit(X_train) -X_train_scaled = scaler.transform(X_train) -X_test_scaled = scaler.transform(X_test) for degree in range(maxdegree): model = xgb.XGBRegressor(objective ='reg:squarederror', colsaobjective ='reg:squarederror', colsample_bytree = 0.3, learning_rate = 0.1,max_depth = degree, alpha = 10, n_estimators = 200) - model.fit(X_train_scaled,y_train) - y_pred = model.predict(X_test_scaled) + model.fit(X_train,y_train) + y_pred = model.predict(X_test) polydegree[degree] = degree error[degree] = np.mean( np.mean((y_test - y_pred)**2) ) bias[degree] = np.mean( (y_test - np.mean(y_pred))**2 ) diff --git a/doc/pub/week45/html/week45-bs.html b/doc/pub/week45/html/week45-bs.html index d7e0ee14e..901aa91ec 100644 --- a/doc/pub/week45/html/week45-bs.html +++ b/doc/pub/week45/html/week45-bs.html @@ -409,7 +409,7 @@ MathJax.Hub.Config({
    -

    Nov 11, 2021

    +

    Nov 12, 2021


    diff --git a/doc/pub/week45/html/week45-reveal.html b/doc/pub/week45/html/week45-reveal.html index 762a6b33a..170e4bc6c 100644 --- a/doc/pub/week45/html/week45-reveal.html +++ b/doc/pub/week45/html/week45-reveal.html @@ -184,7 +184,7 @@ MathJax.Hub.Config({
    -

    Nov 11, 2021

    +

    Nov 12, 2021


    @@ -199,7 +199,17 @@ MathJax.Hub.Config({

    • Thursday: Basics of Decision Trees, Bagging and Voting
    • + +

    • Friday: More on Bagging, Voting, Random Forests and start Boosting
    • + +

    @@ -3069,7 +3079,6 @@ $$ import numpy as np from sklearn.model_selection import train_test_split from sklearn.ensemble import GradientBoostingRegressor -from sklearn.preprocessing import StandardScaler import scikitplot as skplt from sklearn.metrics import mean_squared_error @@ -3085,15 +3094,11 @@ bias = np.zeros(maxdegree) variance = np.zeros(maxdegree) polydegree = np.zeros(maxdegree) X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2) -scaler = StandardScaler() -scaler.fit(X_train) -X_train_scaled = scaler.transform(X_train) -X_test_scaled = scaler.transform(X_test) for degree in range(1,maxdegree): model = GradientBoostingRegressor(max_depth=degree, n_estimators=100, learning_rate=1.0) - model.fit(X_train_scaled,y_train) - y_pred = model.predict(X_test_scaled) + model.fit(X_train,y_train) + y_pred = model.predict(X_test) polydegree[degree] = degree error[degree] = np.mean( np.mean((y_test - y_pred)**2) ) bias[degree] = np.mean( (y_test - np.mean(y_pred))**2 ) @@ -3225,7 +3230,6 @@ sketch for efficient proposal calculation. It introduces a novel sparsity-aware import numpy as np from sklearn.model_selection import train_test_split import xgboost as xgb -from sklearn.preprocessing import StandardScaler import scikitplot as skplt from sklearn.metrics import mean_squared_error @@ -3241,16 +3245,12 @@ bias = np.zeros(maxdegree) variance = np.zeros(maxdegree) polydegree = np.zeros(maxdegree) X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2) -scaler = StandardScaler() -scaler.fit(X_train) -X_train_scaled = scaler.transform(X_train) -X_test_scaled = scaler.transform(X_test) for degree in range(maxdegree): model = xgb.XGBRegressor(objective ='reg:squarederror', colsaobjective ='reg:squarederror', colsample_bytree = 0.3, learning_rate = 0.1,max_depth = degree, alpha = 10, n_estimators = 200) - model.fit(X_train_scaled,y_train) - y_pred = model.predict(X_test_scaled) + model.fit(X_train,y_train) + y_pred = model.predict(X_test) polydegree[degree] = degree error[degree] = np.mean( np.mean((y_test - y_pred)**2) ) bias[degree] = np.mean( (y_test - np.mean(y_pred))**2 ) diff --git a/doc/pub/week45/html/week45-solarized.html b/doc/pub/week45/html/week45-solarized.html index 008366e74..130e927d3 100644 --- a/doc/pub/week45/html/week45-solarized.html +++ b/doc/pub/week45/html/week45-solarized.html @@ -332,7 +332,7 @@ MathJax.Hub.Config({
    -

    Nov 11, 2021

    +

    Nov 12, 2021


    @@ -341,7 +341,13 @@ MathJax.Hub.Config({
    • Thursday: Basics of Decision Trees, Bagging and Voting
    • +
    • Friday: More on Bagging, Voting, Random Forests and start Boosting
    • +
    Videos @@ -3042,7 +3048,6 @@ $$ import numpy as np from sklearn.model_selection import train_test_split from sklearn.ensemble import GradientBoostingRegressor -from sklearn.preprocessing import StandardScaler import scikitplot as skplt from sklearn.metrics import mean_squared_error @@ -3058,15 +3063,11 @@ bias = np.zeros(maxdegree) variance = np.zeros(maxdegree) polydegree = np.zeros(maxdegree) X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2) -scaler = StandardScaler() -scaler.fit(X_train) -X_train_scaled = scaler.transform(X_train) -X_test_scaled = scaler.transform(X_test) for degree in range(1,maxdegree): model = GradientBoostingRegressor(max_depth=degree, n_estimators=100, learning_rate=1.0) - model.fit(X_train_scaled,y_train) - y_pred = model.predict(X_test_scaled) + model.fit(X_train,y_train) + y_pred = model.predict(X_test) polydegree[degree] = degree error[degree] = np.mean( np.mean((y_test - y_pred)**2) ) bias[degree] = np.mean( (y_test - np.mean(y_pred))**2 ) @@ -3197,7 +3198,6 @@ sketch for efficient proposal calculation. It introduces a novel sparsity-aware import numpy as np from sklearn.model_selection import train_test_split import xgboost as xgb -from sklearn.preprocessing import StandardScaler import scikitplot as skplt from sklearn.metrics import mean_squared_error @@ -3213,16 +3213,12 @@ bias = np.zeros(maxdegree) variance = np.zeros(maxdegree) polydegree = np.zeros(maxdegree) X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2) -scaler = StandardScaler() -scaler.fit(X_train) -X_train_scaled = scaler.transform(X_train) -X_test_scaled = scaler.transform(X_test) for degree in range(maxdegree): model = xgb.XGBRegressor(objective ='reg:squarederror', colsaobjective ='reg:squarederror', colsample_bytree = 0.3, learning_rate = 0.1,max_depth = degree, alpha = 10, n_estimators = 200) - model.fit(X_train_scaled,y_train) - y_pred = model.predict(X_test_scaled) + model.fit(X_train,y_train) + y_pred = model.predict(X_test) polydegree[degree] = degree error[degree] = np.mean( np.mean((y_test - y_pred)**2) ) bias[degree] = np.mean( (y_test - np.mean(y_pred))**2 ) diff --git a/doc/pub/week45/html/week45.html b/doc/pub/week45/html/week45.html index aaac23f18..265eada00 100644 --- a/doc/pub/week45/html/week45.html +++ b/doc/pub/week45/html/week45.html @@ -409,7 +409,7 @@ MathJax.Hub.Config({
    -

    Nov 11, 2021

    +

    Nov 12, 2021


    @@ -418,7 +418,13 @@ MathJax.Hub.Config({
    • Thursday: Basics of Decision Trees, Bagging and Voting
    • +
    • Friday: More on Bagging, Voting, Random Forests and start Boosting
    • +
    Videos @@ -3119,7 +3125,6 @@ $$ import numpy as np from sklearn.model_selection import train_test_split from sklearn.ensemble import GradientBoostingRegressor -from sklearn.preprocessing import StandardScaler import scikitplot as skplt from sklearn.metrics import mean_squared_error @@ -3135,15 +3140,11 @@ bias = np.= np.zeros(maxdegree) polydegree = np.zeros(maxdegree) X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2) -scaler = StandardScaler() -scaler.fit(X_train) -X_train_scaled = scaler.transform(X_train) -X_test_scaled = scaler.transform(X_test) for degree in range(1,maxdegree): model = GradientBoostingRegressor(max_depth=degree, n_estimators=100, learning_rate=1.0) - model.fit(X_train_scaled,y_train) - y_pred = model.predict(X_test_scaled) + model.fit(X_train,y_train) + y_pred = model.predict(X_test) polydegree[degree] = degree error[degree] = np.mean( np.mean((y_test - y_pred)**2) ) bias[degree] = np.mean( (y_test - np.mean(y_pred))**2 ) @@ -3274,7 +3275,6 @@ sketch for efficient proposal calculation. It introduces a novel sparsity-aware import numpy as np from sklearn.model_selection import train_test_split import xgboost as xgb -from sklearn.preprocessing import StandardScaler import scikitplot as skplt from sklearn.metrics import mean_squared_error @@ -3290,16 +3290,12 @@ bias = np.= np.zeros(maxdegree) polydegree = np.zeros(maxdegree) X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2) -scaler = StandardScaler() -scaler.fit(X_train) -X_train_scaled = scaler.transform(X_train) -X_test_scaled = scaler.transform(X_test) for degree in range(maxdegree): model = xgb.XGBRegressor(objective ='reg:squarederror', colsaobjective ='reg:squarederror', colsample_bytree = 0.3, learning_rate = 0.1,max_depth = degree, alpha = 10, n_estimators = 200) - model.fit(X_train_scaled,y_train) - y_pred = model.predict(X_test_scaled) + model.fit(X_train,y_train) + y_pred = model.predict(X_test) polydegree[degree] = degree error[degree] = np.mean( np.mean((y_test - y_pred)**2) ) bias[degree] = np.mean( (y_test - np.mean(y_pred))**2 ) diff --git a/doc/pub/week45/ipynb/DataFiles/cancer.dot b/doc/pub/week45/ipynb/DataFiles/cancer.dot index 5b4b48a9b..9525ed631 100644 --- a/doc/pub/week45/ipynb/DataFiles/cancer.dot +++ b/doc/pub/week45/ipynb/DataFiles/cancer.dot @@ -1,57 +1,57 @@ digraph Tree { node [shape=box, style="filled, rounded", color="black", fontname=helvetica] ; edge [fontname=helvetica] ; -0 [label="worst perimeter <= 106.05\ngini = 0.465\nsamples = 426\nvalue = [[269, 157]\n[157, 269]]", fillcolor="#e5813908"] ; -1 [label="worst concave points <= 0.159\ngini = 0.067\nsamples = 259\nvalue = [[250, 9]\n[9, 250]]", fillcolor="#e58139db"] ; +0 [label="worst perimeter <= 106.05\ngini = 0.465\nsamples = 426\nvalue = [[269, 157]\n[157, 269]]", fillcolor="#fefbf9"] ; +1 [label="worst concave points <= 0.159\ngini = 0.067\nsamples = 259\nvalue = [[250, 9]\n[9, 250]]", fillcolor="#e99355"] ; 0 -> 1 [labeldistance=2.5, labelangle=45, headlabel="True"] ; -2 [label="worst concave points <= 0.135\ngini = 0.031\nsamples = 253\nvalue = [[249, 4]\n[4, 249]]", fillcolor="#e58139ee"] ; +2 [label="worst concave points <= 0.135\ngini = 0.031\nsamples = 253\nvalue = [[249, 4]\n[4, 249]]", fillcolor="#e78946"] ; 1 -> 2 ; -3 [label="radius error <= 0.643\ngini = 0.008\nsamples = 242\nvalue = [[241, 1]\n[1, 241]]", fillcolor="#e58139fb"] ; +3 [label="radius error <= 0.643\ngini = 0.008\nsamples = 242\nvalue = [[241, 1]\n[1, 241]]", fillcolor="#e5833c"] ; 2 -> 3 ; -4 [label="gini = 0.0\nsamples = 239\nvalue = [[239, 0]\n[0, 239]]", fillcolor="#e58139ff"] ; +4 [label="gini = 0.0\nsamples = 239\nvalue = [[239, 0]\n[0, 239]]", fillcolor="#e58139"] ; 3 -> 4 ; -5 [label="worst symmetry <= 0.208\ngini = 0.444\nsamples = 3\nvalue = [[2, 1]\n[1, 2]]", fillcolor="#e5813913"] ; +5 [label="mean perimeter <= 78.51\ngini = 0.444\nsamples = 3\nvalue = [[2, 1]\n[1, 2]]", fillcolor="#fdf6f0"] ; 3 -> 5 ; -6 [label="gini = 0.0\nsamples = 1\nvalue = [[0, 1]\n[1, 0]]", fillcolor="#e58139ff"] ; +6 [label="gini = 0.0\nsamples = 1\nvalue = [[0, 1]\n[1, 0]]", fillcolor="#e58139"] ; 5 -> 6 ; -7 [label="gini = 0.0\nsamples = 2\nvalue = [[2, 0]\n[0, 2]]", fillcolor="#e58139ff"] ; +7 [label="gini = 0.0\nsamples = 2\nvalue = [[2, 0]\n[0, 2]]", fillcolor="#e58139"] ; 5 -> 7 ; -8 [label="worst texture <= 29.455\ngini = 0.397\nsamples = 11\nvalue = [[8, 3]\n[3, 8]]", fillcolor="#e581392c"] ; +8 [label="mean texture <= 20.84\ngini = 0.397\nsamples = 11\nvalue = [[8, 3]\n[3, 8]]", fillcolor="#fae9dd"] ; 2 -> 8 ; -9 [label="gini = 0.0\nsamples = 8\nvalue = [[8, 0]\n[0, 8]]", fillcolor="#e58139ff"] ; +9 [label="gini = 0.0\nsamples = 8\nvalue = [[8, 0]\n[0, 8]]", fillcolor="#e58139"] ; 8 -> 9 ; -10 [label="gini = 0.0\nsamples = 3\nvalue = [[0, 3]\n[3, 0]]", fillcolor="#e58139ff"] ; +10 [label="gini = 0.0\nsamples = 3\nvalue = [[0, 3]\n[3, 0]]", fillcolor="#e58139"] ; 8 -> 10 ; -11 [label="mean texture <= 16.22\ngini = 0.278\nsamples = 6\nvalue = [[1, 5]\n[5, 1]]", fillcolor="#e581396b"] ; +11 [label="worst texture <= 24.785\ngini = 0.278\nsamples = 6\nvalue = [[1, 5]\n[5, 1]]", fillcolor="#f4caac"] ; 1 -> 11 ; -12 [label="gini = 0.0\nsamples = 1\nvalue = [[1, 0]\n[0, 1]]", fillcolor="#e58139ff"] ; +12 [label="gini = 0.0\nsamples = 1\nvalue = [[1, 0]\n[0, 1]]", fillcolor="#e58139"] ; 11 -> 12 ; -13 [label="gini = 0.0\nsamples = 5\nvalue = [[0, 5]\n[5, 0]]", fillcolor="#e58139ff"] ; +13 [label="gini = 0.0\nsamples = 5\nvalue = [[0, 5]\n[5, 0]]", fillcolor="#e58139"] ; 11 -> 13 ; -14 [label="worst texture <= 20.645\ngini = 0.202\nsamples = 167\nvalue = [[19, 148]\n[148, 19]]", fillcolor="#e5813994"] ; +14 [label="worst texture <= 20.645\ngini = 0.202\nsamples = 167\nvalue = [[19, 148]\n[148, 19]]", fillcolor="#f0b68c"] ; 0 -> 14 [labeldistance=2.5, labelangle=-45, headlabel="False"] ; -15 [label="worst radius <= 17.74\ngini = 0.375\nsamples = 16\nvalue = [[12, 4]\n[4, 12]]", fillcolor="#e5813938"] ; +15 [label="worst perimeter <= 116.8\ngini = 0.375\nsamples = 16\nvalue = [[12, 4]\n[4, 12]]", fillcolor="#f9e3d4"] ; 14 -> 15 ; -16 [label="gini = 0.0\nsamples = 11\nvalue = [[11, 0]\n[0, 11]]", fillcolor="#e58139ff"] ; +16 [label="gini = 0.0\nsamples = 11\nvalue = [[11, 0]\n[0, 11]]", fillcolor="#e58139"] ; 15 -> 16 ; -17 [label="mean texture <= 13.745\ngini = 0.32\nsamples = 5\nvalue = [[1, 4]\n[4, 1]]", fillcolor="#e5813955"] ; +17 [label="worst compactness <= 0.126\ngini = 0.32\nsamples = 5\nvalue = [[1, 4]\n[4, 1]]", fillcolor="#f6d5bd"] ; 15 -> 17 ; -18 [label="gini = 0.0\nsamples = 1\nvalue = [[1, 0]\n[0, 1]]", fillcolor="#e58139ff"] ; +18 [label="gini = 0.0\nsamples = 1\nvalue = [[1, 0]\n[0, 1]]", fillcolor="#e58139"] ; 17 -> 18 ; -19 [label="gini = 0.0\nsamples = 4\nvalue = [[0, 4]\n[4, 0]]", fillcolor="#e58139ff"] ; +19 [label="gini = 0.0\nsamples = 4\nvalue = [[0, 4]\n[4, 0]]", fillcolor="#e58139"] ; 17 -> 19 ; -20 [label="mean concave points <= 0.049\ngini = 0.088\nsamples = 151\nvalue = [[7, 144]\n[144, 7]]", fillcolor="#e58139d0"] ; +20 [label="mean concave points <= 0.049\ngini = 0.088\nsamples = 151\nvalue = [[7, 144]\n[144, 7]]", fillcolor="#ea985d"] ; 14 -> 20 ; -21 [label="concave points error <= 0.01\ngini = 0.48\nsamples = 15\nvalue = [[6, 9]\n[9, 6]]", fillcolor="#e5813900"] ; +21 [label="concave points error <= 0.01\ngini = 0.48\nsamples = 15\nvalue = [[6, 9]\n[9, 6]]", fillcolor="#ffffff"] ; 20 -> 21 ; -22 [label="gini = 0.0\nsamples = 9\nvalue = [[0, 9]\n[9, 0]]", fillcolor="#e58139ff"] ; +22 [label="gini = 0.0\nsamples = 9\nvalue = [[0, 9]\n[9, 0]]", fillcolor="#e58139"] ; 21 -> 22 ; -23 [label="gini = 0.0\nsamples = 6\nvalue = [[6, 0]\n[0, 6]]", fillcolor="#e58139ff"] ; +23 [label="gini = 0.0\nsamples = 6\nvalue = [[6, 0]\n[0, 6]]", fillcolor="#e58139"] ; 21 -> 23 ; -24 [label="worst smoothness <= 0.096\ngini = 0.015\nsamples = 136\nvalue = [[1, 135]\n[135, 1]]", fillcolor="#e58139f7"] ; +24 [label="fractal dimension error <= 0.013\ngini = 0.015\nsamples = 136\nvalue = [[1, 135]\n[135, 1]]", fillcolor="#e6853f"] ; 20 -> 24 ; -25 [label="gini = 0.0\nsamples = 1\nvalue = [[1, 0]\n[0, 1]]", fillcolor="#e58139ff"] ; +25 [label="gini = 0.0\nsamples = 135\nvalue = [[0, 135]\n[135, 0]]", fillcolor="#e58139"] ; 24 -> 25 ; -26 [label="gini = 0.0\nsamples = 135\nvalue = [[0, 135]\n[135, 0]]", fillcolor="#e58139ff"] ; +26 [label="gini = 0.0\nsamples = 1\nvalue = [[1, 0]\n[0, 1]]", fillcolor="#e58139"] ; 24 -> 26 ; } \ No newline at end of file diff --git a/doc/pub/week45/ipynb/DataFiles/cancer.png b/doc/pub/week45/ipynb/DataFiles/cancer.png index 2ceb5e1f8..1a31a10b2 100644 Binary files a/doc/pub/week45/ipynb/DataFiles/cancer.png and b/doc/pub/week45/ipynb/DataFiles/cancer.png differ diff --git a/doc/pub/week45/ipynb/DataFiles/ride.dot b/doc/pub/week45/ipynb/DataFiles/ride.dot index 50aaa7638..b9d720cda 100644 --- a/doc/pub/week45/ipynb/DataFiles/ride.dot +++ b/doc/pub/week45/ipynb/DataFiles/ride.dot @@ -1,13 +1,13 @@ digraph Tree { node [shape=box, style="filled, rounded", color="black", fontname=helvetica] ; edge [fontname=helvetica] ; -0 [label="X[7] <= 0.5\ngini = 0.48\nsamples = 15\nvalue = [4, 10, 1]", fillcolor="#39e5818b"] ; -1 [label="X[1] <= 0.5\ngini = 0.408\nsamples = 14\nvalue = [4, 10, 0]", fillcolor="#39e58199"] ; +0 [label="X[9] <= 0.5\ngini = 0.48\nsamples = 15\nvalue = [4, 10, 1]", fillcolor="#93f1ba"] ; +1 [label="X[1] <= 0.5\ngini = 0.408\nsamples = 14\nvalue = [4, 10, 0]", fillcolor="#88efb3"] ; 0 -> 1 [labeldistance=2.5, labelangle=45, headlabel="True"] ; -2 [label="gini = 0.48\nsamples = 10\nvalue = [4, 6, 0]", fillcolor="#39e58155"] ; +2 [label="gini = 0.48\nsamples = 10\nvalue = [4, 6, 0]", fillcolor="#bdf6d5"] ; 1 -> 2 ; -3 [label="gini = 0.0\nsamples = 4\nvalue = [0, 4, 0]", fillcolor="#39e581ff"] ; +3 [label="gini = 0.0\nsamples = 4\nvalue = [0, 4, 0]", fillcolor="#39e581"] ; 1 -> 3 ; -4 [label="gini = 0.0\nsamples = 1\nvalue = [0, 0, 1]", fillcolor="#8139e5ff"] ; +4 [label="gini = 0.0\nsamples = 1\nvalue = [0, 0, 1]", fillcolor="#8139e5"] ; 0 -> 4 [labeldistance=2.5, labelangle=-45, headlabel="False"] ; } \ No newline at end of file diff --git a/doc/pub/week45/ipynb/Results/FigureFiles/gdclassiffiercgain.png b/doc/pub/week45/ipynb/Results/FigureFiles/gdclassiffiercgain.png index 097599daa..455369c77 100644 Binary files a/doc/pub/week45/ipynb/Results/FigureFiles/gdclassiffiercgain.png and b/doc/pub/week45/ipynb/Results/FigureFiles/gdclassiffiercgain.png differ diff --git a/doc/pub/week45/ipynb/Results/FigureFiles/gdclassiffierconfusion.png b/doc/pub/week45/ipynb/Results/FigureFiles/gdclassiffierconfusion.png index 731ee99b4..bd2dd5adf 100644 Binary files a/doc/pub/week45/ipynb/Results/FigureFiles/gdclassiffierconfusion.png and b/doc/pub/week45/ipynb/Results/FigureFiles/gdclassiffierconfusion.png differ diff --git a/doc/pub/week45/ipynb/Results/FigureFiles/gdclassiffierroc.png b/doc/pub/week45/ipynb/Results/FigureFiles/gdclassiffierroc.png index 8fbf286fe..458ffab47 100644 Binary files a/doc/pub/week45/ipynb/Results/FigureFiles/gdclassiffierroc.png and b/doc/pub/week45/ipynb/Results/FigureFiles/gdclassiffierroc.png differ diff --git a/doc/pub/week45/ipynb/Results/FigureFiles/gdregression.png b/doc/pub/week45/ipynb/Results/FigureFiles/gdregression.png index 5592de634..87fe1263d 100644 Binary files a/doc/pub/week45/ipynb/Results/FigureFiles/gdregression.png and b/doc/pub/week45/ipynb/Results/FigureFiles/gdregression.png differ diff --git a/doc/pub/week45/ipynb/Results/FigureFiles/xdclassiffierconfusion.png b/doc/pub/week45/ipynb/Results/FigureFiles/xdclassiffierconfusion.png index 6c0f198b3..3ab2f6024 100644 Binary files a/doc/pub/week45/ipynb/Results/FigureFiles/xdclassiffierconfusion.png and b/doc/pub/week45/ipynb/Results/FigureFiles/xdclassiffierconfusion.png differ diff --git a/doc/pub/week45/ipynb/Results/FigureFiles/xdclassiffierroc.png b/doc/pub/week45/ipynb/Results/FigureFiles/xdclassiffierroc.png index f8ef6a3f0..a9d37df15 100644 Binary files a/doc/pub/week45/ipynb/Results/FigureFiles/xdclassiffierroc.png and b/doc/pub/week45/ipynb/Results/FigureFiles/xdclassiffierroc.png differ diff --git a/doc/pub/week45/ipynb/ipynb-week45-src.tar.gz b/doc/pub/week45/ipynb/ipynb-week45-src.tar.gz index 29c0c400c..3f9b9d4f1 100644 Binary files a/doc/pub/week45/ipynb/ipynb-week45-src.tar.gz and b/doc/pub/week45/ipynb/ipynb-week45-src.tar.gz differ diff --git a/doc/pub/week45/ipynb/week45.ipynb b/doc/pub/week45/ipynb/week45.ipynb index f90efa101..6e4df27da 100644 --- a/doc/pub/week45/ipynb/week45.ipynb +++ b/doc/pub/week45/ipynb/week45.ipynb @@ -2,8 +2,10 @@ "cells": [ { "cell_type": "markdown", - "id": "6038c455", - "metadata": {}, + "id": "d71eb6c5", + "metadata": { + "editable": true + }, "source": [ "\n", @@ -12,28 +14,36 @@ }, { "cell_type": "markdown", - "id": "85e8fd68", - "metadata": {}, + "id": "1df06d26", + "metadata": { + "editable": true + }, "source": [ "# Week 45: Decisions Trees, Random Forests, Bagging and Boosting\n", "**Morten Hjorth-Jensen**, Department of Physics, University of Oslo and Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University\n", "\n", - "Date: **Nov 11, 2021**\n", + "Date: **Nov 12, 2021**\n", "\n", "Copyright 1999-2021, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license" ] }, { "cell_type": "markdown", - "id": "f8028a3d", - "metadata": {}, + "id": "b7a1161b", + "metadata": { + "editable": true + }, "source": [ "## Overview of week 45\n", "\n", "* Thursday: Basics of Decision Trees, Bagging and Voting\n", "\n", + " * [Video of Lecture](https://www.uio.no/studier/emner/matnat/fys/FYS-STK3155/h21/forelesningsvideoer/LectureNovember11.mp4?vrtx=view-as-webpage)\n", + "\n", "* Friday: More on Bagging, Voting, Random Forests and start Boosting\n", "\n", + " * [Video of Lecture](https://www.uio.no/studier/emner/matnat/fys/FYS-STK3155/h21/forelesningsvideoer/LectureNovember12.mp4?vrtx=view-as-webpage)\n", + "\n", "**Videos.**\n", "\n", "1. [Video on Decision trees](https://www.youtube.com/watch?v=RmajweUFKvM&ab_channel=Simplilearn)\n", @@ -47,8 +57,10 @@ }, { "cell_type": "markdown", - "id": "87e9cace", - "metadata": {}, + "id": "913d58ae", + "metadata": { + "editable": true + }, "source": [ "## Decision trees, overarching aims\n", "\n", @@ -76,8 +88,10 @@ }, { "cell_type": "markdown", - "id": "7cbc9228", - "metadata": {}, + "id": "d7c78ce6", + "metadata": { + "editable": true + }, "source": [ "## Basics of a tree\n", "\n", @@ -94,8 +108,10 @@ }, { "cell_type": "markdown", - "id": "8d8cad8e", - "metadata": {}, + "id": "709ddb15", + "metadata": { + "editable": true + }, "source": [ "## A Sketch of a Tree, Regression problem\n", "\n", @@ -104,8 +120,10 @@ }, { "cell_type": "markdown", - "id": "1910a78f", - "metadata": {}, + "id": "7263f409", + "metadata": { + "editable": true + }, "source": [ "## A Sketch of a Tree, Classification problem\n", "\n", @@ -114,8 +132,10 @@ }, { "cell_type": "markdown", - "id": "b8ad32fa", - "metadata": {}, + "id": "f3bf9834", + "metadata": { + "editable": true + }, "source": [ "## A typical Decision Tree with its pertinent Jargon, Classification Problem\n", "\n", @@ -130,8 +150,10 @@ }, { "cell_type": "markdown", - "id": "b4f17c84", - "metadata": {}, + "id": "d94d7df0", + "metadata": { + "editable": true + }, "source": [ "## General Features\n", "\n", @@ -151,8 +173,10 @@ }, { "cell_type": "markdown", - "id": "9d2b7455", - "metadata": {}, + "id": "8a2e7d0c", + "metadata": { + "editable": true + }, "source": [ "## How do we set it up?\n", "\n", @@ -172,8 +196,10 @@ }, { "cell_type": "markdown", - "id": "f9c47829", - "metadata": {}, + "id": "d92b12fb", + "metadata": { + "editable": true + }, "source": [ "## Decision trees and Regression" ] @@ -181,8 +207,11 @@ { "cell_type": "code", "execution_count": 1, - "id": "a9b40c02", - "metadata": {}, + "id": "523164e5", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "%matplotlib inline\n", @@ -279,8 +308,10 @@ }, { "cell_type": "markdown", - "id": "46f5b18a", - "metadata": {}, + "id": "1de5c8b3", + "metadata": { + "editable": true + }, "source": [ "## Building a tree, regression\n", "\n", @@ -299,8 +330,10 @@ }, { "cell_type": "markdown", - "id": "9016ab06", - "metadata": {}, + "id": "f1f09db0", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\sum_{j=1}^J\\sum_{i\\in R_j}(y_i-\\overline{y}_{R_j})^2,\n", @@ -309,8 +342,10 @@ }, { "cell_type": "markdown", - "id": "3c493861", - "metadata": {}, + "id": "a5a2cc1c", + "metadata": { + "editable": true + }, "source": [ "where $\\overline{y}_{R_j}$ is the mean response for the training observations \n", "within box $j$." @@ -318,8 +353,10 @@ }, { "cell_type": "markdown", - "id": "5b4203d6", - "metadata": {}, + "id": "af076102", + "metadata": { + "editable": true + }, "source": [ "## A top-down approach, recursive binary splitting\n", "\n", @@ -338,8 +375,10 @@ }, { "cell_type": "markdown", - "id": "38afe033", - "metadata": {}, + "id": "5eb6d984", + "metadata": { + "editable": true + }, "source": [ "## Making a tree\n", "\n", @@ -349,8 +388,10 @@ }, { "cell_type": "markdown", - "id": "5ee51e92", - "metadata": {}, + "id": "45c717a3", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\left\\{X\\vert x_j < s\\right\\},\n", @@ -359,16 +400,20 @@ }, { "cell_type": "markdown", - "id": "d44d4233", - "metadata": {}, + "id": "6de48c4a", + "metadata": { + "editable": true + }, "source": [ "and" ] }, { "cell_type": "markdown", - "id": "42b18eb4", - "metadata": {}, + "id": "1d7bc7d4", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\left\\{X\\vert x_j \\geq s\\right\\},\n", @@ -377,16 +422,20 @@ }, { "cell_type": "markdown", - "id": "40ea65e5", - "metadata": {}, + "id": "6626aa85", + "metadata": { + "editable": true + }, "source": [ "so that we obtain the lowest MSE, that is" ] }, { "cell_type": "markdown", - "id": "5765dd31", - "metadata": {}, + "id": "51de015f", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\sum_{i:x_i\\in R_j}(y_i-\\overline{y}_{R_1})^2+\\sum_{i:x_i\\in R_2}(y_i-\\overline{y}_{R_2})^2,\n", @@ -395,8 +444,10 @@ }, { "cell_type": "markdown", - "id": "c441521b", - "metadata": {}, + "id": "6953c3ae", + "metadata": { + "editable": true + }, "source": [ "which we want to minimize by considering all predictors\n", "$x_1,x_2,\\dots,x_p$. We consider also all possible values of $s$ for\n", @@ -426,8 +477,10 @@ }, { "cell_type": "markdown", - "id": "4600886b", - "metadata": {}, + "id": "7aca88a8", + "metadata": { + "editable": true + }, "source": [ "## Pruning the tree\n", "\n", @@ -448,8 +501,10 @@ }, { "cell_type": "markdown", - "id": "2c95bc5f", - "metadata": {}, + "id": "019f4cdd", + "metadata": { + "editable": true + }, "source": [ "## Cost complexity pruning\n", "\n", @@ -458,8 +513,10 @@ }, { "cell_type": "markdown", - "id": "b37ec50f", - "metadata": {}, + "id": "f3ad5e81", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\sum_{m=1}^{\\overline{T}}\\sum_{i:x_i\\in R_m}(y_i-\\overline{y}_{R_m})^2+\\alpha\\overline{T},\n", @@ -468,8 +525,10 @@ }, { "cell_type": "markdown", - "id": "1cad8e0d", - "metadata": {}, + "id": "3e3a3e77", + "metadata": { + "editable": true + }, "source": [ "is as small as possible. Here $\\overline{T}$ is \n", "the number of terminal nodes of the tree $T$ , $R_m$ is the\n", @@ -494,8 +553,10 @@ }, { "cell_type": "markdown", - "id": "cc370b93", - "metadata": {}, + "id": "e1feb8ab", + "metadata": { + "editable": true + }, "source": [ "## Schematic Regression Procedure\n", "\n", @@ -518,8 +579,10 @@ }, { "cell_type": "markdown", - "id": "fa639bd0", - "metadata": {}, + "id": "8132c098", + "metadata": { + "editable": true + }, "source": [ "## A Classification Tree\n", "\n", @@ -539,8 +602,10 @@ }, { "cell_type": "markdown", - "id": "c4334771", - "metadata": {}, + "id": "b528637d", + "metadata": { + "editable": true + }, "source": [ "## Growing a classification tree\n", "\n", @@ -564,8 +629,10 @@ }, { "cell_type": "markdown", - "id": "65e09794", - "metadata": {}, + "id": "c0160307", + "metadata": { + "editable": true + }, "source": [ "## Classification tree, how to split nodes\n", "\n", @@ -581,8 +648,10 @@ }, { "cell_type": "markdown", - "id": "2351ab6b", - "metadata": {}, + "id": "9566f2d5", + "metadata": { + "editable": true + }, "source": [ "$$\n", "p_{mk} = \\frac{1}{N_m}\\sum_{i\\in R_m}I(y_i=k).\n", @@ -591,8 +660,10 @@ }, { "cell_type": "markdown", - "id": "827a3f8d", - "metadata": {}, + "id": "295bf58a", + "metadata": { + "editable": true + }, "source": [ "We let $p_{mk}$ represent the majority class of observations in region\n", "$m$. The three most common ways of splitting a node are given by\n", @@ -602,8 +673,10 @@ }, { "cell_type": "markdown", - "id": "35f85c1c", - "metadata": {}, + "id": "3883a13b", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\frac{1}{N_m}\\sum_{i\\in R_m}I(y_i\\ne k) = 1-p_{mk}.\n", @@ -612,16 +685,20 @@ }, { "cell_type": "markdown", - "id": "b1909c9f", - "metadata": {}, + "id": "5106f192", + "metadata": { + "editable": true + }, "source": [ "* Gini index $g$" ] }, { "cell_type": "markdown", - "id": "4c72e5c9", - "metadata": {}, + "id": "f77521cf", + "metadata": { + "editable": true + }, "source": [ "$$\n", "g = \\sum_{k\\ne k'} p_{mk}p_{mk'}=\\sum_{k=1}^K p_{mk}(1-p_{mk}).\n", @@ -630,16 +707,20 @@ }, { "cell_type": "markdown", - "id": "9354027b", - "metadata": {}, + "id": "635df28e", + "metadata": { + "editable": true + }, "source": [ "* Information entropy or just entropy $s$" ] }, { "cell_type": "markdown", - "id": "cd7b6f3e", - "metadata": {}, + "id": "f526ea0a", + "metadata": { + "editable": true + }, "source": [ "$$\n", "s = -\\sum_{k=1}^K p_{mk}\\log{p_{mk}}.\n", @@ -648,8 +729,10 @@ }, { "cell_type": "markdown", - "id": "9fe8b307", - "metadata": {}, + "id": "28fb5149", + "metadata": { + "editable": true + }, "source": [ "## Gini Index (or Coefficient or Impurity)\n", "\n", @@ -668,8 +751,10 @@ }, { "cell_type": "markdown", - "id": "a39f2477", - "metadata": {}, + "id": "0243971a", + "metadata": { + "editable": true + }, "source": [ "## Why binary splits?\n", "\n", @@ -681,8 +766,10 @@ }, { "cell_type": "markdown", - "id": "e3274b4e", - "metadata": {}, + "id": "73268cad", + "metadata": { + "editable": true + }, "source": [ "## Computing a Tree using the Gini Index\n", "\n", @@ -705,8 +792,10 @@ }, { "cell_type": "markdown", - "id": "6a3183bd", - "metadata": {}, + "id": "186f184a", + "metadata": { + "editable": true + }, "source": [ "## The Table\n", "\n", @@ -731,8 +820,10 @@ }, { "cell_type": "markdown", - "id": "e5d4eb28", - "metadata": {}, + "id": "9a03c3f0", + "metadata": { + "editable": true + }, "source": [ "## Computing the various Gini Indices\n", "\n", @@ -746,8 +837,10 @@ }, { "cell_type": "markdown", - "id": "98bac75b", - "metadata": {}, + "id": "a08a0c21", + "metadata": { + "editable": true + }, "source": [ "## Computing the various Gini Indices, Hours slept\n", "\n", @@ -758,8 +851,10 @@ }, { "cell_type": "markdown", - "id": "263f4079", - "metadata": {}, + "id": "c2bee1e5", + "metadata": { + "editable": true + }, "source": [ "## Computing the various Gini Indices, Hours studied\n", "\n", @@ -772,14 +867,17 @@ }, { "cell_type": "markdown", - "id": "16de86aa", - "metadata": {}, + "id": "ed4e4a72", + "metadata": { + "editable": true + }, "source": [ "## A possible code using Scikit-Learn" ] }, { "cell_type": "code", +<<<<<<< HEAD "execution_count": 3, "id": "6206aec1", "metadata": {}, @@ -842,6 +940,15 @@ "output_type": "execute_result" } ], +======= + "execution_count": 2, + "id": "ab9c3c9e", + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], +>>>>>>> 6e6a5c152c3f30dc18b12384198cdca878013a84 "source": [ "# Common imports\n", "import numpy as np\n", @@ -914,8 +1021,10 @@ }, { "cell_type": "markdown", - "id": "280ae557", - "metadata": {}, + "id": "53b32143", + "metadata": { + "editable": true + }, "source": [ "## Visualizing Trees, More examples" ] @@ -923,8 +1032,11 @@ { "cell_type": "code", "execution_count": 3, - "id": "6c8124ac", - "metadata": {}, + "id": "97b9b51a", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "import os\n", @@ -964,8 +1076,10 @@ }, { "cell_type": "markdown", - "id": "8a5e6e58", - "metadata": {}, + "id": "94672c7b", + "metadata": { + "editable": true + }, "source": [ "## Visualizing the Tree, The Moons" ] @@ -973,8 +1087,11 @@ { "cell_type": "code", "execution_count": 4, - "id": "7fc84427", - "metadata": {}, + "id": "d7275b36", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "# Common imports\n", @@ -1005,8 +1122,10 @@ }, { "cell_type": "markdown", - "id": "51420499", - "metadata": {}, + "id": "bbe3f31b", + "metadata": { + "editable": true + }, "source": [ "## Other ways of visualizing the trees\n", "\n", @@ -1016,8 +1135,11 @@ { "cell_type": "code", "execution_count": 5, - "id": "d01a0b57", - "metadata": {}, + "id": "b0df5a5d", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "from sklearn.datasets import load_iris\n", @@ -1031,8 +1153,10 @@ }, { "cell_type": "markdown", - "id": "0d5f2779", - "metadata": {}, + "id": "3437610f", + "metadata": { + "editable": true + }, "source": [ "## Printing out as text\n", "\n", @@ -1043,8 +1167,11 @@ { "cell_type": "code", "execution_count": 6, - "id": "18b6d8ae", - "metadata": {}, + "id": "43043846", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "from sklearn.datasets import load_iris\n", @@ -1059,8 +1186,10 @@ }, { "cell_type": "markdown", - "id": "17129339", - "metadata": {}, + "id": "ec6a0a6b", + "metadata": { + "editable": true + }, "source": [ "## Algorithms for Setting up Decision Trees\n", "\n", @@ -1077,8 +1206,10 @@ }, { "cell_type": "markdown", - "id": "08011876", - "metadata": {}, + "id": "c1b10c09", + "metadata": { + "editable": true + }, "source": [ "## The CART algorithm for Classification\n", "\n", @@ -1092,8 +1223,10 @@ }, { "cell_type": "markdown", - "id": "624b8153", - "metadata": {}, + "id": "a49ec55d", + "metadata": { + "editable": true + }, "source": [ "$$\n", "C(k,t_k) = \\frac{m_{\\mathrm{left}}}{m}G_{\\mathrm{left}}+ \\frac{m_{\\mathrm{right}}}{m}G_{\\mathrm{right}},\n", @@ -1102,8 +1235,10 @@ }, { "cell_type": "markdown", - "id": "353969b6", - "metadata": {}, + "id": "2e34a49a", + "metadata": { + "editable": true + }, "source": [ "where $G_{\\mathrm{left/right}}$ measures the impurity of the left/right subset and $m_{\\mathrm{left/right}}$\n", " is the number of instances in the left/right subset\n", @@ -1117,8 +1252,10 @@ }, { "cell_type": "markdown", - "id": "bcdb3558", - "metadata": {}, + "id": "3f121670", + "metadata": { + "editable": true + }, "source": [ "## The CART algorithm for Regression\n", "\n", @@ -1128,8 +1265,10 @@ }, { "cell_type": "markdown", - "id": "661abdb2", - "metadata": {}, + "id": "2d433e86", + "metadata": { + "editable": true + }, "source": [ "$$\n", "C(k,t_k) = \\frac{m_{\\mathrm{left}}}{m}\\mathrm{MSE}_{\\mathrm{left}}+ \\frac{m_{\\mathrm{right}}}{m}\\mathrm{MSE}_{\\mathrm{right}}.\n", @@ -1138,16 +1277,20 @@ }, { "cell_type": "markdown", - "id": "b1baa1b7", - "metadata": {}, + "id": "e4792af3", + "metadata": { + "editable": true + }, "source": [ "Here the MSE for a specific node is defined as" ] }, { "cell_type": "markdown", - "id": "5aeb1ed8", - "metadata": {}, + "id": "498bb7f5", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\mathrm{MSE}_{\\mathrm{node}}=\\frac{1}{m_\\mathrm{node}}\\sum_{i\\in \\mathrm{node}}(\\overline{y}_{\\mathrm{node}}-y_i)^2,\n", @@ -1156,16 +1299,20 @@ }, { "cell_type": "markdown", - "id": "d7f66eb1", - "metadata": {}, + "id": "1c9fc558", + "metadata": { + "editable": true + }, "source": [ "with" ] }, { "cell_type": "markdown", - "id": "6bcb07d8", - "metadata": {}, + "id": "cc97af93", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\overline{y}_{\\mathrm{node}}=\\frac{1}{m_\\mathrm{node}}\\sum_{i\\in \\mathrm{node}}y_i,\n", @@ -1174,8 +1321,10 @@ }, { "cell_type": "markdown", - "id": "a5cd6be2", - "metadata": {}, + "id": "a72479bf", + "metadata": { + "editable": true + }, "source": [ "the mean value of all observations in a specific node.\n", "\n", @@ -1185,8 +1334,10 @@ }, { "cell_type": "markdown", - "id": "f7c1aca8", - "metadata": {}, + "id": "ffd2b1bc", + "metadata": { + "editable": true + }, "source": [ "## Computing the Gini index\n", "\n", @@ -1227,8 +1378,10 @@ }, { "cell_type": "markdown", - "id": "dd90d405", - "metadata": {}, + "id": "7b5515fc", + "metadata": { + "editable": true + }, "source": [ "## Simple Python Code to read in Data and perform Classification" ] @@ -1236,8 +1389,11 @@ { "cell_type": "code", "execution_count": 7, - "id": "055dfb75", - "metadata": {}, + "id": "1119f5c2", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "# Common imports\n", @@ -1311,8 +1467,10 @@ }, { "cell_type": "markdown", - "id": "8fa370be", - "metadata": {}, + "id": "bedf0437", + "metadata": { + "editable": true + }, "source": [ "## Computing the Gini Factor\n", "\n", @@ -1327,8 +1485,11 @@ { "cell_type": "code", "execution_count": 8, - "id": "2eae920c", - "metadata": {}, + "id": "d2263dc0", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "# Split a dataset based on an attribute and an attribute value\n", @@ -1395,8 +1556,10 @@ }, { "cell_type": "markdown", - "id": "76e6b68a", - "metadata": {}, + "id": "019e9ebc", + "metadata": { + "editable": true + }, "source": [ "## Entropy and the ID3 algorithm\n", "\n", @@ -1432,8 +1595,10 @@ }, { "cell_type": "markdown", - "id": "c3ef1baf", - "metadata": {}, + "id": "81ce1017", + "metadata": { + "editable": true + }, "source": [ "## Cancer Data again now with Decision Trees and other Methods" ] @@ -1441,8 +1606,11 @@ { "cell_type": "code", "execution_count": 9, - "id": "7637aca8", - "metadata": {}, + "id": "954f3552", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "import matplotlib.pyplot as plt\n", @@ -1490,8 +1658,10 @@ }, { "cell_type": "markdown", - "id": "e2a20f84", - "metadata": {}, + "id": "d3514614", + "metadata": { + "editable": true + }, "source": [ "## Another example, the moons again" ] @@ -1499,8 +1669,11 @@ { "cell_type": "code", "execution_count": 10, - "id": "6dc739e6", - "metadata": {}, + "id": "078ce1b7", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "from __future__ import division, print_function, unicode_literals\n", @@ -1571,8 +1744,10 @@ }, { "cell_type": "markdown", - "id": "ffd5aca0", - "metadata": {}, + "id": "c82a61fc", + "metadata": { + "editable": true + }, "source": [ "## Playing around with regions" ] @@ -1580,8 +1755,11 @@ { "cell_type": "code", "execution_count": 11, - "id": "a535e0a3", - "metadata": {}, + "id": "0ea9eba1", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "np.random.seed(6)\n", @@ -1608,8 +1786,10 @@ }, { "cell_type": "markdown", - "id": "c43dd40f", - "metadata": {}, + "id": "f2903f07", + "metadata": { + "editable": true + }, "source": [ "## Regression trees" ] @@ -1617,8 +1797,11 @@ { "cell_type": "code", "execution_count": 12, - "id": "2f92a4bc", - "metadata": {}, + "id": "cf34aea5", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "# Quadratic training set + noise\n", @@ -1632,8 +1815,11 @@ { "cell_type": "code", "execution_count": 13, - "id": "786d574c", - "metadata": {}, + "id": "e96caea7", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "from sklearn.tree import DecisionTreeRegressor\n", @@ -1644,8 +1830,10 @@ }, { "cell_type": "markdown", - "id": "4667ad89", - "metadata": {}, + "id": "abb62276", + "metadata": { + "editable": true + }, "source": [ "## Final regressor code" ] @@ -1653,8 +1841,11 @@ { "cell_type": "code", "execution_count": 14, - "id": "1a164143", - "metadata": {}, + "id": "48922f75", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "from sklearn.tree import DecisionTreeRegressor\n", @@ -1700,8 +1891,11 @@ { "cell_type": "code", "execution_count": 15, - "id": "39ad2aed", - "metadata": {}, + "id": "02d670bf", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "tree_reg1 = DecisionTreeRegressor(random_state=42)\n", @@ -1736,8 +1930,10 @@ }, { "cell_type": "markdown", - "id": "5b0a0240", - "metadata": {}, + "id": "3d0adddc", + "metadata": { + "editable": true + }, "source": [ "## Pros and cons of trees, pros\n", "\n", @@ -1758,8 +1954,10 @@ }, { "cell_type": "markdown", - "id": "f05ef6f9", - "metadata": {}, + "id": "ef1bc9bb", + "metadata": { + "editable": true + }, "source": [ "## Disadvantages\n", "\n", @@ -1784,8 +1982,10 @@ }, { "cell_type": "markdown", - "id": "50ea5d1d", - "metadata": {}, + "id": "af41a2c0", + "metadata": { + "editable": true + }, "source": [ "## Ensemble Methods: From a Single Tree to Many Trees and Extreme Boosting, Meet the Jungle of Methods\n", "\n", @@ -1813,8 +2013,10 @@ }, { "cell_type": "markdown", - "id": "3dfb29fa", - "metadata": {}, + "id": "90461b56", + "metadata": { + "editable": true + }, "source": [ "## An Overview of Ensemble Methods\n", "\n", @@ -1827,8 +2029,10 @@ }, { "cell_type": "markdown", - "id": "9505410d", - "metadata": {}, + "id": "8eaefb2c", + "metadata": { + "editable": true + }, "source": [ "## Bagging\n", "\n", @@ -1847,8 +2051,10 @@ }, { "cell_type": "markdown", - "id": "807639f2", - "metadata": {}, + "id": "e5bdc60e", + "metadata": { + "editable": true + }, "source": [ "## More bagging\n", "\n", @@ -1877,8 +2083,10 @@ }, { "cell_type": "markdown", - "id": "a3763486", - "metadata": {}, + "id": "32637cbd", + "metadata": { + "editable": true + }, "source": [ "## Making your own Bootstrap: Changing the Level of the Decision Tree\n", "\n", @@ -1889,8 +2097,11 @@ { "cell_type": "code", "execution_count": 16, - "id": "e9d87bdd", - "metadata": {}, + "id": "84a0ab7f", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "\n", @@ -1949,8 +2160,10 @@ }, { "cell_type": "markdown", - "id": "daf49858", - "metadata": {}, + "id": "966c5bfa", + "metadata": { + "editable": true + }, "source": [ "## Why Voting?\n", "\n", @@ -1971,8 +2184,10 @@ }, { "cell_type": "markdown", - "id": "6a146f2d", - "metadata": {}, + "id": "98617121", + "metadata": { + "editable": true + }, "source": [ "## Tossing coins\n", "\n", @@ -2000,8 +2215,10 @@ }, { "cell_type": "markdown", - "id": "42892d97", - "metadata": {}, + "id": "22b6b2a6", + "metadata": { + "editable": true + }, "source": [ "## Standard imports first" ] @@ -2009,8 +2226,11 @@ { "cell_type": "code", "execution_count": 17, - "id": "231bdf38", - "metadata": {}, + "id": "8780a315", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "# Common imports\n", @@ -2054,8 +2274,10 @@ }, { "cell_type": "markdown", - "id": "094cf1cb", - "metadata": {}, + "id": "53df0b60", + "metadata": { + "editable": true + }, "source": [ "## Simple Voting Example, head or tail" ] @@ -2063,8 +2285,11 @@ { "cell_type": "code", "execution_count": 18, - "id": "48790785", - "metadata": {}, + "id": "3c252ef9", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "\n", @@ -2094,8 +2319,10 @@ }, { "cell_type": "markdown", - "id": "d5339f7b", - "metadata": {}, + "id": "0fdfbb1c", + "metadata": { + "editable": true + }, "source": [ "## Using the Voting Classifier\n", "\n", @@ -2105,8 +2332,11 @@ { "cell_type": "code", "execution_count": 19, - "id": "6a1080ec", - "metadata": {}, + "id": "65ae1dde", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "from sklearn.model_selection import train_test_split\n", @@ -2155,8 +2385,10 @@ }, { "cell_type": "markdown", - "id": "47d98581", - "metadata": {}, + "id": "ca1f2e17", + "metadata": { + "editable": true + }, "source": [ "## Voting and Bagging" ] @@ -2164,8 +2396,11 @@ { "cell_type": "code", "execution_count": 20, - "id": "c7fd3f00", - "metadata": {}, + "id": "a20648a3", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "from sklearn.model_selection import train_test_split\n", @@ -2191,8 +2426,11 @@ { "cell_type": "code", "execution_count": 21, - "id": "c9f7b269", - "metadata": {}, + "id": "bb049c2c", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "from sklearn.metrics import accuracy_score\n", @@ -2206,8 +2444,11 @@ { "cell_type": "code", "execution_count": 22, - "id": "b45c2311", - "metadata": {}, + "id": "0976fbf2", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "log_clf = LogisticRegression(random_state=42)\n", @@ -2223,8 +2464,11 @@ { "cell_type": "code", "execution_count": 23, - "id": "f16cc6d0", - "metadata": {}, + "id": "f9fe3c33", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "from sklearn.metrics import accuracy_score\n", @@ -2237,8 +2481,10 @@ }, { "cell_type": "markdown", - "id": "4018fbab", - "metadata": {}, + "id": "9a7148c8", + "metadata": { + "editable": true + }, "source": [ "## Random forests\n", "\n", @@ -2258,8 +2504,10 @@ }, { "cell_type": "markdown", - "id": "d2e3facd", - "metadata": {}, + "id": "55f61a8d", + "metadata": { + "editable": true + }, "source": [ "$$\n", "m\\approx \\sqrt{p}.\n", @@ -2268,8 +2516,10 @@ }, { "cell_type": "markdown", - "id": "7a73c7de", - "metadata": {}, + "id": "cf370519", + "metadata": { + "editable": true + }, "source": [ "In building a random forest, at\n", "each split in the tree, the algorithm is not even allowed to consider\n", @@ -2291,8 +2541,10 @@ }, { "cell_type": "markdown", - "id": "761888c6", - "metadata": {}, + "id": "bb7388ae", + "metadata": { + "editable": true + }, "source": [ "## Random Forest Algorithm\n", "The algorithm described here can be applied to both classification and regression problems.\n", @@ -2315,8 +2567,10 @@ }, { "cell_type": "markdown", - "id": "4a3c676f", - "metadata": {}, + "id": "e3c86a9f", + "metadata": { + "editable": true + }, "source": [ "## Random Forests Compared with other Methods on the Cancer Data" ] @@ -2324,8 +2578,11 @@ { "cell_type": "code", "execution_count": 24, - "id": "0839a696", - "metadata": {}, + "id": "7f5ad325", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "import matplotlib.pyplot as plt\n", @@ -2398,8 +2655,10 @@ }, { "cell_type": "markdown", - "id": "57e88525", - "metadata": {}, + "id": "d813ed8b", + "metadata": { + "editable": true + }, "source": [ "Recall that the cumulative gains curve shows the percentage of the\n", "overall number of cases in a given category *gained* by targeting a\n", @@ -2412,8 +2671,10 @@ }, { "cell_type": "markdown", - "id": "4515344d", - "metadata": {}, + "id": "736991de", + "metadata": { + "editable": true + }, "source": [ "## Compare Bagging on Trees with Random Forests" ] @@ -2421,8 +2682,11 @@ { "cell_type": "code", "execution_count": 25, - "id": "d80e2f55", - "metadata": {}, + "id": "fa1fc990", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "bag_clf = BaggingClassifier(\n", @@ -2433,8 +2697,11 @@ { "cell_type": "code", "execution_count": 26, - "id": "27457485", - "metadata": {}, + "id": "048d511a", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "bag_clf.fit(X_train, y_train)\n", @@ -2448,8 +2715,10 @@ }, { "cell_type": "markdown", - "id": "e25dd4ec", - "metadata": {}, + "id": "da6b5e13", + "metadata": { + "editable": true + }, "source": [ "## Boosting, a Bird's Eye View\n", "\n", @@ -2466,8 +2735,10 @@ }, { "cell_type": "markdown", - "id": "92dafde6", - "metadata": {}, + "id": "9257bbbb", + "metadata": { + "editable": true + }, "source": [ "## What is boosting? Additive Modelling/Iterative Fitting\n", "\n", @@ -2478,8 +2749,10 @@ }, { "cell_type": "markdown", - "id": "bc20c85e", - "metadata": {}, + "id": "4762d537", + "metadata": { + "editable": true + }, "source": [ "$$\n", "f_M(x) = \\sum_{i=1}^M \\beta_m b(x;\\gamma_m),\n", @@ -2488,8 +2761,10 @@ }, { "cell_type": "markdown", - "id": "4ba594a4", - "metadata": {}, + "id": "ab36a813", + "metadata": { + "editable": true + }, "source": [ "where $\\beta_m$ are the expansion parameters to be determined in a\n", "minimization process and $b(x;\\gamma_m)$ are some simple functions of\n", @@ -2503,8 +2778,10 @@ }, { "cell_type": "markdown", - "id": "8593117f", - "metadata": {}, + "id": "40b63f0f", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\sigma(t) = \\frac{1}{1+\\exp{(-t)}},\n", @@ -2513,8 +2790,10 @@ }, { "cell_type": "markdown", - "id": "cc0781ac", - "metadata": {}, + "id": "d5e0cdad", + "metadata": { + "editable": true + }, "source": [ "where $t=\\gamma_0+\\gamma_1 x$ and the parameters $\\gamma_0$ and\n", "$\\gamma_1$ were determined by the Logistic Regression fitting\n", @@ -2525,8 +2804,10 @@ }, { "cell_type": "markdown", - "id": "ce1a2a56", - "metadata": {}, + "id": "dd3a061c", + "metadata": { + "editable": true + }, "source": [ "$$\n", "C(\\boldsymbol{y},\\boldsymbol{f}) = \\frac{1}{n} \\sum_{i=0}^{n-1}(y_i-f(x_i))^2.\n", @@ -2535,8 +2816,10 @@ }, { "cell_type": "markdown", - "id": "93ab835c", - "metadata": {}, + "id": "6d53d024", + "metadata": { + "editable": true + }, "source": [ "In this case the function $f(x)$ was replaced by the design matrix\n", "$\\boldsymbol{X}$ and the unknown linear regression parameters $\\boldsymbol{\\beta}$,\n", @@ -2546,8 +2829,10 @@ }, { "cell_type": "markdown", - "id": "d9a0cc62", - "metadata": {}, + "id": "3242ea1d", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{\\beta}=\\left(\\boldsymbol{X}^T\\boldsymbol{X}\\right)^{-1}\\boldsymbol{X}^T\\boldsymbol{y}.\n", @@ -2556,16 +2841,20 @@ }, { "cell_type": "markdown", - "id": "a4e87a0b", - "metadata": {}, + "id": "abcb204c", + "metadata": { + "editable": true + }, "source": [ "In iterative fitting or additive modeling, we minimize the cost function with respect to the parameters $\\beta_m$ and $\\gamma_m$." ] }, { "cell_type": "markdown", - "id": "4cd671b2", - "metadata": {}, + "id": "d7c5c454", + "metadata": { + "editable": true + }, "source": [ "## Iterative Fitting, Regression and Squared-error Cost Function\n", "\n", @@ -2590,8 +2879,10 @@ }, { "cell_type": "markdown", - "id": "f9e4e4c5", - "metadata": {}, + "id": "ed7d9340", + "metadata": { + "editable": true + }, "source": [ "## Squared-Error Example and Iterative Fitting\n", "\n", @@ -2604,8 +2895,10 @@ }, { "cell_type": "markdown", - "id": "98051368", - "metadata": {}, + "id": "e8ba9f4b", + "metadata": { + "editable": true + }, "source": [ "$$\n", "(\\beta_m,\\gamma_m) = \\mathrm{argmin}_{\\beta,\\lambda}\\hspace{0.1cm} \\sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\\beta b(x;\\gamma))^2=\\sum_{i=0}^{n-1}(y_i-f_{m-1}(x_i)-\\beta(1+\\gamma x_i))^2.\n", @@ -2614,8 +2907,10 @@ }, { "cell_type": "markdown", - "id": "b89afedd", - "metadata": {}, + "id": "4681250b", + "metadata": { + "editable": true + }, "source": [ "We start our iteration by simply setting $f_0(x)=0$. \n", "Taking the derivatives with respect to $\\beta$ and $\\gamma$ we obtain" @@ -2623,8 +2918,10 @@ }, { "cell_type": "markdown", - "id": "4ce53503", - "metadata": {}, + "id": "bd8519d8", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\frac{\\partial {\\cal C}}{\\partial \\beta} = -2\\sum_{i}(1+\\gamma x_i)(y_i-\\beta(1+\\gamma x_i))=0,\n", @@ -2633,16 +2930,20 @@ }, { "cell_type": "markdown", - "id": "bfd354cd", - "metadata": {}, + "id": "ba583d71", + "metadata": { + "editable": true + }, "source": [ "and" ] }, { "cell_type": "markdown", - "id": "1cdd2ab0", - "metadata": {}, + "id": "637356c2", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\frac{\\partial {\\cal C}}{\\partial \\gamma} =-2\\sum_{i}\\beta x_i(y_i-\\beta(1+\\gamma x_i))=0.\n", @@ -2651,16 +2952,20 @@ }, { "cell_type": "markdown", - "id": "abc6bca0", - "metadata": {}, + "id": "8c185c05", + "metadata": { + "editable": true + }, "source": [ "We can then rewrite these equations as (defining $\\boldsymbol{w}=\\boldsymbol{e}+\\gamma \\boldsymbol{x})$ with $\\boldsymbol{e}$ being the unit vector)" ] }, { "cell_type": "markdown", - "id": "15ab72b0", - "metadata": {}, + "id": "9460a8fa", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\gamma \\boldsymbol{w}^T(\\boldsymbol{y}-\\beta\\gamma \\boldsymbol{w})=0,\n", @@ -2669,16 +2974,20 @@ }, { "cell_type": "markdown", - "id": "30076526", - "metadata": {}, + "id": "0b07afc4", + "metadata": { + "editable": true + }, "source": [ "which gives us $\\beta = \\boldsymbol{w}^T\\boldsymbol{y}/(\\boldsymbol{w}^T\\boldsymbol{w})$. Similarly we have" ] }, { "cell_type": "markdown", - "id": "036983c0", - "metadata": {}, + "id": "2eca4e12", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\beta\\gamma \\boldsymbol{x}^T(\\boldsymbol{y}-\\beta(1+\\gamma \\boldsymbol{x}))=0,\n", @@ -2687,8 +2996,10 @@ }, { "cell_type": "markdown", - "id": "01855f77", - "metadata": {}, + "id": "4e66ed95", + "metadata": { + "editable": true + }, "source": [ "which leads to $\\gamma =(\\boldsymbol{x}^T\\boldsymbol{y}-\\beta\\boldsymbol{x}^T\\boldsymbol{e})/(\\beta\\boldsymbol{x}^T\\boldsymbol{x})$. Inserting\n", "for $\\beta$ gives us an equation for $\\gamma$. This is a non-linear equation in the unknown $\\gamma$ and has to be solved numerically. \n", @@ -2699,8 +3010,10 @@ }, { "cell_type": "markdown", - "id": "ea3b23fd", - "metadata": {}, + "id": "3886e3cd", + "metadata": { + "editable": true + }, "source": [ "## Iterative Fitting, Classification and AdaBoost\n", "\n", @@ -2713,8 +3026,10 @@ }, { "cell_type": "markdown", - "id": "785ad3fb", - "metadata": {}, + "id": "9340d546", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\mathrm{\\overline{err}}=\\frac{1}{n} \\sum_{i=0}^{n-1} I(y_i\\ne G(x_i)).\n", @@ -2723,8 +3038,10 @@ }, { "cell_type": "markdown", - "id": "bcdd75ca", - "metadata": {}, + "id": "4a811fe2", + "metadata": { + "editable": true + }, "source": [ "The iterative procedure starts with defining a weak classifier whose\n", "error rate is barely better than random guessing. The iterative\n", @@ -2737,8 +3054,10 @@ }, { "cell_type": "markdown", - "id": "4066ea94", - "metadata": {}, + "id": "403c01f1", + "metadata": { + "editable": true + }, "source": [ "$$\n", "f_M(x) = \\sum_{i=1}^M \\beta_m b(x;\\gamma_m),\n", @@ -2747,16 +3066,20 @@ }, { "cell_type": "markdown", - "id": "2bd9f2bd", - "metadata": {}, + "id": "a700a98e", + "metadata": { + "editable": true + }, "source": [ "will be a function of" ] }, { "cell_type": "markdown", - "id": "4e0d1bcd", - "metadata": {}, + "id": "08113929", + "metadata": { + "editable": true + }, "source": [ "$$\n", "G_M(x) = \\mathrm{sign} \\sum_{i=1}^M \\alpha_m G_m(x).\n", @@ -2765,8 +3088,10 @@ }, { "cell_type": "markdown", - "id": "c843142c", - "metadata": {}, + "id": "85f281cc", + "metadata": { + "editable": true + }, "source": [ "## Adaptive Boosting, AdaBoost\n", "\n", @@ -2775,8 +3100,10 @@ }, { "cell_type": "markdown", - "id": "fa9764ef", - "metadata": {}, + "id": "54ffa37f", + "metadata": { + "editable": true + }, "source": [ "$$\n", "f_m(x) = f_{m-1}(x)+\\beta_mG_m(x).\n", @@ -2785,8 +3112,10 @@ }, { "cell_type": "markdown", - "id": "08271d96", - "metadata": {}, + "id": "6874f147", + "metadata": { + "editable": true + }, "source": [ "The simplest possible cost function which leads (also simple from a computational point of view) to the AdaBoost algorithm is the\n", "exponential cost/loss function defined as" @@ -2794,8 +3123,10 @@ }, { "cell_type": "markdown", - "id": "730500b4", - "metadata": {}, + "id": "2f7992b0", + "metadata": { + "editable": true + }, "source": [ "$$\n", "C(\\boldsymbol{y},\\boldsymbol{f}) = \\sum_{i=0}^{n-1}\\exp{(-y_i(f_{m-1}(x_i)+\\beta G(x_i))}.\n", @@ -2804,8 +3135,10 @@ }, { "cell_type": "markdown", - "id": "a5cfcea5", - "metadata": {}, + "id": "66695c48", + "metadata": { + "editable": true + }, "source": [ "We optimize $\\beta$ and $G$ for each value of $m=1:M$ as we did in the regression case.\n", "This is normally done in two steps. Let us however first rewrite the cost function as" @@ -2813,8 +3146,10 @@ }, { "cell_type": "markdown", - "id": "f120a894", - "metadata": {}, + "id": "28b55d9c", + "metadata": { + "editable": true + }, "source": [ "$$\n", "C(\\boldsymbol{y},\\boldsymbol{f}) = \\sum_{i=0}^{n-1}w_i^{m}\\exp{(-y_i\\beta G(x_i))},\n", @@ -2823,16 +3158,20 @@ }, { "cell_type": "markdown", - "id": "b9b9773e", - "metadata": {}, + "id": "e1425728", + "metadata": { + "editable": true + }, "source": [ "where we have defined $w_i^m= \\exp{(-y_if_{m-1}(x_i))}$." ] }, { "cell_type": "markdown", - "id": "945e7c76", - "metadata": {}, + "id": "06cde447", + "metadata": { + "editable": true + }, "source": [ "## Building up AdaBoost\n", "\n", @@ -2841,8 +3180,10 @@ }, { "cell_type": "markdown", - "id": "02655c91", - "metadata": {}, + "id": "ef0b1ae2", + "metadata": { + "editable": true + }, "source": [ "$$\n", "G_m(x) = \\mathrm{sign} \\sum_{i=0}^{n-1} w_i^m I(y_i \\ne G_(x_i)),\n", @@ -2851,8 +3192,10 @@ }, { "cell_type": "markdown", - "id": "a75a0f9b", - "metadata": {}, + "id": "ccf8cbf3", + "metadata": { + "editable": true + }, "source": [ "which is the classifier that minimizes the weighted error rate in predicting $y$.\n", "\n", @@ -2861,8 +3204,10 @@ }, { "cell_type": "markdown", - "id": "ae35403a", - "metadata": {}, + "id": "4234e666", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\exp{-(\\beta)}\\sum_{y_i=G(x_i)}w_i^m+\\exp{(\\beta)}\\sum_{y_i\\ne G(x_i)}w_i^m,\n", @@ -2871,16 +3216,20 @@ }, { "cell_type": "markdown", - "id": "091c1c6f", - "metadata": {}, + "id": "178d03b7", + "metadata": { + "editable": true + }, "source": [ "which can be rewritten as" ] }, { "cell_type": "markdown", - "id": "30eb3053", - "metadata": {}, + "id": "5fa4d7ad", + "metadata": { + "editable": true + }, "source": [ "$$\n", "(\\exp{(\\beta)}-\\exp{-(\\beta)})\\sum_{i=0}^{n-1}w_i^mI(y_i\\ne G(x_i))+\\exp{(-\\beta)}\\sum_{i=0}^{n-1}w_i^m=0,\n", @@ -2889,16 +3238,20 @@ }, { "cell_type": "markdown", - "id": "f6a6d37d", - "metadata": {}, + "id": "e7070480", + "metadata": { + "editable": true + }, "source": [ "which leads to" ] }, { "cell_type": "markdown", - "id": "37e33765", - "metadata": {}, + "id": "fda49c9c", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\beta_m = \\frac{1}{2}\\log{\\frac{1-\\mathrm{\\overline{err}}}{\\mathrm{\\overline{err}}}},\n", @@ -2907,16 +3260,20 @@ }, { "cell_type": "markdown", - "id": "fffc2eed", - "metadata": {}, + "id": "d1196c44", + "metadata": { + "editable": true + }, "source": [ "where we have redefined the error as" ] }, { "cell_type": "markdown", - "id": "f5a1e2cc", - "metadata": {}, + "id": "7e9e1a54", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\mathrm{\\overline{err}}_m=\\frac{1}{n}\\frac{\\sum_{i=0}^{n-1}w_i^mI(y_i\\ne G(x_i)}{\\sum_{i=0}^{n-1}w_i^m},\n", @@ -2925,16 +3282,20 @@ }, { "cell_type": "markdown", - "id": "922eb174", - "metadata": {}, + "id": "8606b09a", + "metadata": { + "editable": true + }, "source": [ "which leads to an update of" ] }, { "cell_type": "markdown", - "id": "e20016de", - "metadata": {}, + "id": "7befd0eb", + "metadata": { + "editable": true + }, "source": [ "$$\n", "f_m(x) = f_{m-1}(x) +\\beta_m G_m(x).\n", @@ -2943,16 +3304,20 @@ }, { "cell_type": "markdown", - "id": "2c6ddb1a", - "metadata": {}, + "id": "316aaa41", + "metadata": { + "editable": true + }, "source": [ "This leads to the new weights" ] }, { "cell_type": "markdown", - "id": "d10fc0fe", - "metadata": {}, + "id": "a6e517c8", + "metadata": { + "editable": true + }, "source": [ "$$\n", "w_i^{m+1} = w_i^m \\exp{(-y_i\\beta_m G_m(x_i))}\n", @@ -2961,8 +3326,10 @@ }, { "cell_type": "markdown", - "id": "da5a926c", - "metadata": {}, + "id": "8c964d68", + "metadata": { + "editable": true + }, "source": [ "## Adaptive boosting: AdaBoost, Basic Algorithm\n", "\n", @@ -2979,8 +3346,10 @@ }, { "cell_type": "markdown", - "id": "d5985efa", - "metadata": {}, + "id": "c8cca737", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\mathrm{err}=\\frac{1}{n}\\sum_{i=0}^{n-1}I(y_i\\ne G(x_i)),\n", @@ -2989,16 +3358,20 @@ }, { "cell_type": "markdown", - "id": "19bb8280", - "metadata": {}, + "id": "01ea3b3c", + "metadata": { + "editable": true + }, "source": [ "where the function $I()$ is one if we misclassify and zero if we classify correctly." ] }, { "cell_type": "markdown", - "id": "7608b386", - "metadata": {}, + "id": "49af99b4", + "metadata": { + "editable": true + }, "source": [ "## Basic Steps of AdaBoost\n", "\n", @@ -3011,8 +3384,10 @@ }, { "cell_type": "markdown", - "id": "0ae121e3", - "metadata": {}, + "id": "13f3c995", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\mathrm{\\overline{err}}_m=\\frac{\\sum_{i=0}^{n-1}w_i^m I(y_i\\ne G(x_i))}{\\sum_{i=0}^{n-1}w_i},\n", @@ -3021,8 +3396,10 @@ }, { "cell_type": "markdown", - "id": "6a21a16e", - "metadata": {}, + "id": "066cc378", + "metadata": { + "editable": true + }, "source": [ "1. Then we start looping over all attempts at classifying, namely we start an iterative process for $m=1:M$, where $M$ is the final number of classifications. Our given classifier could for example be a plain decision tree.\n", "\n", @@ -3047,8 +3424,10 @@ }, { "cell_type": "markdown", - "id": "5a06c2c0", - "metadata": {}, + "id": "31e8b167", + "metadata": { + "editable": true + }, "source": [ "## AdaBoost Examples\n", "\n", @@ -3058,8 +3437,11 @@ { "cell_type": "code", "execution_count": 27, - "id": "5879f377", - "metadata": {}, + "id": "d21b6e38", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "from sklearn.ensemble import AdaBoostClassifier\n", @@ -3087,8 +3469,10 @@ }, { "cell_type": "markdown", - "id": "e9279b9f", - "metadata": {}, + "id": "bd73f19c", + "metadata": { + "editable": true + }, "source": [ "## Gradient boosting: Basics with Steepest Descent/Functional Gradient Descent\n", "\n", @@ -3103,8 +3487,10 @@ }, { "cell_type": "markdown", - "id": "89199bb6", - "metadata": {}, + "id": "91f98ebf", + "metadata": { + "editable": true + }, "source": [ "## The Squared-Error again! Steepest Descent\n", "\n", @@ -3114,8 +3500,10 @@ }, { "cell_type": "markdown", - "id": "d1d4dff1", - "metadata": {}, + "id": "61ecdf5b", + "metadata": { + "editable": true + }, "source": [ "$$\n", "(\\hat{\\boldsymbol{f}}) = \\mathrm{argmin}_{\\boldsymbol{f}}\\hspace{0.1cm} \\sum_{i=0}^{n-1}(y_i-f(x_i))^2.\n", @@ -3124,16 +3512,20 @@ }, { "cell_type": "markdown", - "id": "15d22a20", - "metadata": {}, + "id": "ce82798c", + "metadata": { + "editable": true + }, "source": [ "We define a real function $h_m(x)$ that defines our final function $f_M(x)$ as" ] }, { "cell_type": "markdown", - "id": "0a210fee", - "metadata": {}, + "id": "f4671edf", + "metadata": { + "editable": true + }, "source": [ "$$\n", "f_M(x) = \\sum_{m=0}^M h_m(x).\n", @@ -3142,16 +3534,20 @@ }, { "cell_type": "markdown", - "id": "5cf2a6a3", - "metadata": {}, + "id": "caa41736", + "metadata": { + "editable": true + }, "source": [ "In the steepest decent approach we approximate $h_m(x) = -\\rho_m g_m(x)$, where $\\rho_m$ is a scalar and $g_m(x)$ the gradient defined as" ] }, { "cell_type": "markdown", - "id": "ace744f9", - "metadata": {}, + "id": "e3b64ac5", + "metadata": { + "editable": true + }, "source": [ "$$\n", "g_m(x_i) = \\left[ \\frac{\\partial {\\cal L}(y_i, f(x_i))}{\\partial f(x_i)}\\right]_{f(x_i)=f_{m-1}(x_i)}.\n", @@ -3160,8 +3556,10 @@ }, { "cell_type": "markdown", - "id": "5b5c897f", - "metadata": {}, + "id": "ae07957e", + "metadata": { + "editable": true + }, "source": [ "With the new gradient we can update $f_m(x) = f_{m-1}(x) -\\rho_m g_m(x)$. Using the above squared-error function we see that\n", "the gradient is $g_m(x_i) = -2(y_i-f(x_i))$.\n", @@ -3171,8 +3569,10 @@ }, { "cell_type": "markdown", - "id": "5562a17c", - "metadata": {}, + "id": "d47eae0d", + "metadata": { + "editable": true + }, "source": [ "$$\n", "(\\rho_1) = \\mathrm{argmin}_{\\rho}\\hspace{0.1cm} \\sum_{i=0}^{n-1}(y_i+2\\rho y_i)^2.\n", @@ -3181,8 +3581,10 @@ }, { "cell_type": "markdown", - "id": "a37be653", - "metadata": {}, + "id": "df3a4e40", + "metadata": { + "editable": true + }, "source": [ "## Steepest Descent Example\n", "\n", @@ -3191,8 +3593,10 @@ }, { "cell_type": "markdown", - "id": "ad73dbb2", - "metadata": {}, + "id": "ee330688", + "metadata": { + "editable": true + }, "source": [ "$$\n", "f_1(x) = f_{0}(x) -\\rho_1 g_1(x)=-y_i.\n", @@ -3201,16 +3605,20 @@ }, { "cell_type": "markdown", - "id": "126d482b", - "metadata": {}, + "id": "32fbddf9", + "metadata": { + "editable": true + }, "source": [ "We can then proceed and compute" ] }, { "cell_type": "markdown", - "id": "4d415cc8", - "metadata": {}, + "id": "36040e0a", + "metadata": { + "editable": true + }, "source": [ "$$\n", "g_2(x_i) = \\left[ \\frac{\\partial {\\cal L}(y_i, f(x_i))}{\\partial f(x_i)}\\right]_{f(x_i)=f_{1}(x_i)=y_i}=-4y_i,\n", @@ -3219,16 +3627,20 @@ }, { "cell_type": "markdown", - "id": "a1ef6ad9", - "metadata": {}, + "id": "22c0ffd0", + "metadata": { + "editable": true + }, "source": [ "and find a new value for $\\rho_2=-1/2$ and continue till we have reached $m=M$. We can modify the steepest descent method, or steepest boosting, by introducing what is called **gradient boosting**." ] }, { "cell_type": "markdown", - "id": "8961dc18", - "metadata": {}, + "id": "ac371de8", + "metadata": { + "editable": true + }, "source": [ "## Gradient Boosting, algorithm\n", "\n", @@ -3241,8 +3653,10 @@ }, { "cell_type": "markdown", - "id": "769a885a", - "metadata": {}, + "id": "a266ee8b", + "metadata": { + "editable": true + }, "source": [ "$$\n", "C(\\boldsymbol{y},\\boldsymbol{f})=\\sum_{i=0}^{n-1}(y_i-f(x_i))^2.\n", @@ -3251,8 +3665,10 @@ }, { "cell_type": "markdown", - "id": "94f43097", - "metadata": {}, + "id": "c516339a", + "metadata": { + "editable": true + }, "source": [ "The way we proceed in an iterative fashion is to\n", "1. Initialize our estimate $f_0(x)$.\n", @@ -3270,8 +3686,10 @@ }, { "cell_type": "markdown", - "id": "f7fb4f86", - "metadata": {}, + "id": "6ffa2c59", + "metadata": { + "editable": true + }, "source": [ "## Gradient Boosting, Examples of Regression" ] @@ -3279,15 +3697,17 @@ { "cell_type": "code", "execution_count": 28, - "id": "8b3f2c0c", - "metadata": {}, + "id": "a5317ca8", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "import matplotlib.pyplot as plt\n", "import numpy as np\n", "from sklearn.model_selection import train_test_split\n", "from sklearn.ensemble import GradientBoostingRegressor\n", - "from sklearn.preprocessing import StandardScaler\n", "import scikitplot as skplt\n", "from sklearn.metrics import mean_squared_error\n", "\n", @@ -3303,15 +3723,11 @@ "variance = np.zeros(maxdegree)\n", "polydegree = np.zeros(maxdegree)\n", "X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)\n", - "scaler = StandardScaler()\n", - "scaler.fit(X_train)\n", - "X_train_scaled = scaler.transform(X_train)\n", - "X_test_scaled = scaler.transform(X_test)\n", "\n", "for degree in range(1,maxdegree):\n", " model = GradientBoostingRegressor(max_depth=degree, n_estimators=100, learning_rate=1.0) \n", - " model.fit(X_train_scaled,y_train)\n", - " y_pred = model.predict(X_test_scaled)\n", + " model.fit(X_train,y_train)\n", + " y_pred = model.predict(X_test)\n", " polydegree[degree] = degree\n", " error[degree] = np.mean( np.mean((y_test - y_pred)**2) )\n", " bias[degree] = np.mean( (y_test - np.mean(y_pred))**2 )\n", @@ -3333,8 +3749,10 @@ }, { "cell_type": "markdown", - "id": "bf4be4e9", - "metadata": {}, + "id": "20d58df1", + "metadata": { + "editable": true + }, "source": [ "## Gradient Boosting, Classification Example" ] @@ -3342,8 +3760,11 @@ { "cell_type": "code", "execution_count": 29, - "id": "bee1829a", - "metadata": {}, + "id": "b1a36e5e", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "import matplotlib.pyplot as plt\n", @@ -3390,8 +3811,10 @@ }, { "cell_type": "markdown", - "id": "ac9eb4bb", - "metadata": {}, + "id": "a2155c49", + "metadata": { + "editable": true + }, "source": [ "## XGBoost: Extreme Gradient Boosting\n", "\n", @@ -3411,8 +3834,10 @@ }, { "cell_type": "markdown", - "id": "fbe2011a", - "metadata": {}, + "id": "7856d681", + "metadata": { + "editable": true + }, "source": [ "## Regression Case" ] @@ -3420,15 +3845,17 @@ { "cell_type": "code", "execution_count": 30, - "id": "878c0380", - "metadata": {}, + "id": "653c1936", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "import matplotlib.pyplot as plt\n", "import numpy as np\n", "from sklearn.model_selection import train_test_split\n", "import xgboost as xgb\n", - "from sklearn.preprocessing import StandardScaler\n", "import scikitplot as skplt\n", "from sklearn.metrics import mean_squared_error\n", "\n", @@ -3444,16 +3871,12 @@ "variance = np.zeros(maxdegree)\n", "polydegree = np.zeros(maxdegree)\n", "X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)\n", - "scaler = StandardScaler()\n", - "scaler.fit(X_train)\n", - "X_train_scaled = scaler.transform(X_train)\n", - "X_test_scaled = scaler.transform(X_test)\n", "\n", "for degree in range(maxdegree):\n", " model = xgb.XGBRegressor(objective ='reg:squarederror', colsaobjective ='reg:squarederror', colsample_bytree = 0.3, learning_rate = 0.1,max_depth = degree, alpha = 10, n_estimators = 200)\n", "\n", - " model.fit(X_train_scaled,y_train)\n", - " y_pred = model.predict(X_test_scaled)\n", + " model.fit(X_train,y_train)\n", + " y_pred = model.predict(X_test)\n", " polydegree[degree] = degree\n", " error[degree] = np.mean( np.mean((y_test - y_pred)**2) )\n", " bias[degree] = np.mean( (y_test - np.mean(y_pred))**2 )\n", @@ -3474,8 +3897,10 @@ }, { "cell_type": "markdown", - "id": "7cf64b38", - "metadata": {}, + "id": "f987405e", + "metadata": { + "editable": true + }, "source": [ "## Xgboost on the Cancer Data\n", "\n", @@ -3485,8 +3910,11 @@ { "cell_type": "code", "execution_count": 31, - "id": "65a3e655", - "metadata": {}, + "id": "667744e1", + "metadata": { + "collapsed": false, + "editable": true + }, "outputs": [], "source": [ "\n", @@ -3544,6 +3972,7 @@ ] } ], +<<<<<<< HEAD "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", @@ -3563,6 +3992,9 @@ "version": "3.8.12" } }, +======= + "metadata": {}, +>>>>>>> 6e6a5c152c3f30dc18b12384198cdca878013a84 "nbformat": 4, "nbformat_minor": 5 } diff --git a/doc/pub/week46/html/._week46-bs000.html b/doc/pub/week46/html/._week46-bs000.html new file mode 100644 index 000000000..7ec107313 --- /dev/null +++ b/doc/pub/week46/html/._week46-bs000.html @@ -0,0 +1,233 @@ + + + + + + + +Week 46: Support Vector Machines and Project 3 + + + + + + + + + + + + + + + + + + + +
    +
    +

     

     

     

    + + +
    +
    +

    Week 46: Support Vector Machines and Project 3

    +
    + + +
    +Morten Hjorth-Jensen [1, 2] +
    + +
    +[1] Department of Physics, University of Oslo +
    +
    +[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University +
    +
    +
    +

    Nov 14, 2021

    +
    +
    + + + +

    Read »

    + + +
    + +

    + +

    + +
    + + + + +
    + © 1999-2021, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license +
    + + + diff --git a/doc/pub/week46/html/._week46-bs001.html b/doc/pub/week46/html/._week46-bs001.html new file mode 100644 index 000000000..88b474104 --- /dev/null +++ b/doc/pub/week46/html/._week46-bs001.html @@ -0,0 +1,239 @@ + + + + + + + +Week 46: Support Vector Machines and Project 3 + + + + + + + + + + + + + + + + + + + +
    +
    +

     

     

     

    + + +

    Overview of week 46

    + +
      +
    • Thursday: Summary of Gradient Boosting with selected examples. Start support Vector Machines
    • +
    • Friday: Eventual Workshop on project 3. Discussion of project 3.
    • +
    +Note that on Thursday we will have only one lecture, from 1215pm to 1pm. There is no session 115pm-2pm. + +
    +
    + +

    Reading recommendations:

    +
      +
    1. See lecture notes for week 46 at https://compphysics.github.io/MachineLearning/doc/web/course.html.
    2. +
    3. Hastie et al chapter 12
    4. +
    5. Bishop chapter 7.1 and 7.2
    6. +
    +
    +
    + + + + + +

    + +

    + +
    + + + + +
    + +
    + + + diff --git a/doc/pub/week46/html/._week46-bs002.html b/doc/pub/week46/html/._week46-bs002.html new file mode 100644 index 000000000..da878a229 --- /dev/null +++ b/doc/pub/week46/html/._week46-bs002.html @@ -0,0 +1,227 @@ + + + + + + + +Week 46: Support Vector Machines and Project 3 + + + + + + + + + + + + + + + + + + + +
    +
    +

     

     

     

    + + +

    Friday

    + +

    Last year we had a very interesting workshop with many presentations. These were (program 2020)

    + +
      +
    • Maria Emine Nylund: Lego Bricks Classifier
    • +
    • Fabio Rodrigues Pereira: Financial Machine Learning
    • +
    • Markus Borud Pettersen: Machine Learning and Brain Grid Cells
    • +
    • Jing Sun and Endrias Getachew Asgedom: Machine learning-based approaches to denoising microseismic data
    • +
    • Felicia Jacobsen: Analysis of Breast Cancer Data
    • +
    • Simon Elias Schrader: Predicting atomization energies of molecules
    • +
    • Varvara Bazilova and Sergio Andres Diaz Mesa: Glacier Mapping and Machine Learning
    • +
    • Gert Werner Kluge, Hanna Alida Fossen Hardersen and Sushma Sharma Adhikari: Gamma ray signals stemming from dark matter in the galactic center
    • +
    +

    We wish to organize something similar this coming Friday. The presentation last typically 5-10 minutes (some 3-5 slides) with time for questions afterwards. +Feel free to suggest topics. +

    + +

    The program will be available asap. It depends on input from you!

    + +

    + +

    + +
    + + + + +
    + +
    + + + diff --git a/doc/pub/week46/html/._week46-bs003.html b/doc/pub/week46/html/._week46-bs003.html new file mode 100644 index 000000000..f8f9ae8c8 --- /dev/null +++ b/doc/pub/week46/html/._week46-bs003.html @@ -0,0 +1,238 @@ + + + + + + + +Week 46: Support Vector Machines and Project 3 + + + + + + + + + + + + + + + + + + + +
    +
    +

     

     

     

    + + +

    Support Vector Machines, overarching aims

    + +

    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 (see figure below). +

    + +

    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. +

    + +

    With SVMs we distinguish between hard margin and soft margins. The +latter introduces a so-called softening parameter to be discussed +below. We distinguish also between linear and non-linear +approaches. The latter are the most frequent ones since it is rather +unlikely that we can separate classes easily by say straight lines. +

    + +

    + +

    + +
    + + + + +
    + +
    + + + diff --git a/doc/pub/week46/html/._week46-bs004.html b/doc/pub/week46/html/._week46-bs004.html new file mode 100644 index 000000000..dc8633f90 --- /dev/null +++ b/doc/pub/week46/html/._week46-bs004.html @@ -0,0 +1,312 @@ + + + + + + + +Week 46: Support Vector Machines and Project 3 + + + + + + + + + + + + + + + + + + + +
    +
    +

     

     

     

    + + +

    Hyperplanes and all that

    + +

    The theory behind support vector machines (SVM hereafter) is based on +the mathematical description of so-called hyperplanes. Let us start +with a two-dimensional case. This will also allow us to introduce our +first SVM examples. These will be tailored to the case of two specific +classes, as displayed in the figure here based on the usage of the petal data. +

    + +

    We assume here that our data set can be well separated into two +domains, where a straight line does the job in the separating the two +classes. Here the two classes are represented by either squares or +circles. +

    + + +
    +
    +
    +
    +
    +
    from sklearn import datasets
    +from sklearn.svm import SVC, LinearSVC
    +from sklearn.linear_model import SGDClassifier
    +from sklearn.preprocessing import StandardScaler
    +import matplotlib
    +import matplotlib.pyplot as plt
    +plt.rcParams['axes.labelsize'] = 14
    +plt.rcParams['xtick.labelsize'] = 12
    +plt.rcParams['ytick.labelsize'] = 12
    +
    +
    +iris = datasets.load_iris()
    +X = iris["data"][:, (2, 3)]  # petal length, petal width
    +y = iris["target"]
    +
    +setosa_or_versicolor = (y == 0) | (y == 1)
    +X = X[setosa_or_versicolor]
    +y = y[setosa_or_versicolor]
    +
    +
    +
    +C = 5
    +alpha = 1 / (C * len(X))
    +
    +lin_clf = LinearSVC(loss="hinge", C=C, random_state=42)
    +svm_clf = SVC(kernel="linear", C=C)
    +sgd_clf = SGDClassifier(loss="hinge", learning_rate="constant", eta0=0.001, alpha=alpha,
    +                        max_iter=100000, random_state=42)
    +
    +scaler = StandardScaler()
    +X_scaled = scaler.fit_transform(X)
    +
    +lin_clf.fit(X_scaled, y)
    +svm_clf.fit(X_scaled, y)
    +sgd_clf.fit(X_scaled, y)
    +
    +print("LinearSVC:                   ", lin_clf.intercept_, lin_clf.coef_)
    +print("SVC:                         ", svm_clf.intercept_, svm_clf.coef_)
    +print("SGDClassifier(alpha={:.5f}):".format(sgd_clf.alpha), sgd_clf.intercept_, sgd_clf.coef_)
    +
    +# Compute the slope and bias of each decision boundary
    +w1 = -lin_clf.coef_[0, 0]/lin_clf.coef_[0, 1]
    +b1 = -lin_clf.intercept_[0]/lin_clf.coef_[0, 1]
    +w2 = -svm_clf.coef_[0, 0]/svm_clf.coef_[0, 1]
    +b2 = -svm_clf.intercept_[0]/svm_clf.coef_[0, 1]
    +w3 = -sgd_clf.coef_[0, 0]/sgd_clf.coef_[0, 1]
    +b3 = -sgd_clf.intercept_[0]/sgd_clf.coef_[0, 1]
    +
    +# Transform the decision boundary lines back to the original scale
    +line1 = scaler.inverse_transform([[-10, -10 * w1 + b1], [10, 10 * w1 + b1]])
    +line2 = scaler.inverse_transform([[-10, -10 * w2 + b2], [10, 10 * w2 + b2]])
    +line3 = scaler.inverse_transform([[-10, -10 * w3 + b3], [10, 10 * w3 + b3]])
    +
    +# Plot all three decision boundaries
    +plt.figure(figsize=(11, 4))
    +plt.plot(line1[:, 0], line1[:, 1], "k:", label="LinearSVC")
    +plt.plot(line2[:, 0], line2[:, 1], "b--", linewidth=2, label="SVC")
    +plt.plot(line3[:, 0], line3[:, 1], "r-", label="SGDClassifier")
    +plt.plot(X[:, 0][y==1], X[:, 1][y==1], "bs") # label="Iris-Versicolor"
    +plt.plot(X[:, 0][y==0], X[:, 1][y==0], "yo") # label="Iris-Setosa"
    +plt.xlabel("Petal length", fontsize=14)
    +plt.ylabel("Petal width", fontsize=14)
    +plt.legend(loc="upper center", fontsize=14)
    +plt.axis([0, 5.5, 0, 2])
    +
    +plt.show()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +

    + +

    + +
    + + + + +
    + +
    + + + diff --git a/doc/pub/week46/html/._week46-bs005.html b/doc/pub/week46/html/._week46-bs005.html new file mode 100644 index 000000000..eb0008270 --- /dev/null +++ b/doc/pub/week46/html/._week46-bs005.html @@ -0,0 +1,238 @@ + + + + + + + +Week 46: Support Vector Machines and Project 3 + + + + + + + + + + + + + + + + + + + + +
    +

     

     

     

    + + +

    What is a hyperplane?

    + +

    The aim of the SVM algorithm is to find a hyperplane in a +\( p \)-dimensional space, where \( p \) is the number of features that +distinctly classifies the data points. +

    + +

    In a \( p \)-dimensional space, a hyperplane is what we call an affine subspace of dimension of \( p-1 \). +As an example, in two dimension, a hyperplane is simply as straight line while in three dimensions it is +a two-dimensional subspace, or stated simply, a plane. +

    + +

    In two dimensions, with the variables \( x_1 \) and \( x_2 \), the hyperplane is defined as

    +$$ +b+w_1x_1+w_2x_2=0, +$$ + +

    where \( b \) is the intercept and \( w_1 \) and \( w_2 \) define the elements of a vector orthogonal to the line +\( b+w_1x_1+w_2x_2=0 \). +In two dimensions we define the vectors \( \boldsymbol{x} =[x1,x2] \) and \( \boldsymbol{w}=[w1,w2] \). +We can then rewrite the above equation as +

    + +$$ +\boldsymbol{x}^T\boldsymbol{w}+b=0. +$$ + + +

    + +

    + +
    + + + + +
    + +
    + + + diff --git a/doc/pub/week46/html/._week46-bs006.html b/doc/pub/week46/html/._week46-bs006.html new file mode 100644 index 000000000..12cb78e12 --- /dev/null +++ b/doc/pub/week46/html/._week46-bs006.html @@ -0,0 +1,251 @@ + + + + + + + +Week 46: Support Vector Machines and Project 3 + + + + + + + + + + + + + + + + + + + + +
    +

     

     

     

    + + +

    A \( p \)-dimensional space of features

    + +

    We limit ourselves to two classes of outputs \( y_i \) and assign these classes the values \( y_i = \pm 1 \). +In a \( p \)-dimensional space of say \( p \) features we have a hyperplane defines as +

    +$$ +b+wx_1+w_2x_2+\dots +w_px_p=0. +$$ + +

    If we define a +matrix \( \boldsymbol{X}=\left[\boldsymbol{x}_1,\boldsymbol{x}_2,\dots, \boldsymbol{x}_p\right] \) +of dimension \( n\times p \), where \( n \) represents the observations for each feature and each vector \( x_i \) is a column vector of the matrix \( \boldsymbol{X} \), +

    +$$ +\boldsymbol{x}_i = \begin{bmatrix} x_{i1} \\ x_{i2} \\ \dots \\ \dots \\ x_{ip} \end{bmatrix}. +$$ + +

    If the above condition is not met for a given vector \( \boldsymbol{x}_i \) we have

    +$$ +b+w_1x_{i1}+w_2x_{i2}+\dots +w_px_{ip} >0, +$$ + +

    if our output \( y_i=1 \). +In this case we say that \( \boldsymbol{x}_i \) lies on one of the sides of the hyperplane and if +

    +$$ +b+w_1x_{i1}+w_2x_{i2}+\dots +w_px_{ip} < 0, +$$ + +

    for the class of observations \( y_i=-1 \), +then \( \boldsymbol{x}_i \) lies on the other side. +

    + +

    Equivalently, for the two classes of observations we have

    +$$ +y_i\left(b+w_1x_{i1}+w_2x_{i2}+\dots +w_px_{ip}\right) > 0. +$$ + +

    When we try to separate hyperplanes, if it exists, we can use it to construct a natural classifier: a test observation is assigned a given class depending on which side of the hyperplane it is located.

    + +

    + +

    + +
    + + + + +
    + +
    + + + diff --git a/doc/pub/week46/html/._week46-bs007.html b/doc/pub/week46/html/._week46-bs007.html new file mode 100644 index 000000000..bac666519 --- /dev/null +++ b/doc/pub/week46/html/._week46-bs007.html @@ -0,0 +1,236 @@ + + + + + + + +Week 46: Support Vector Machines and Project 3 + + + + + + + + + + + + + + + + + + + + +
    +

     

     

     

    + + +

    The two-dimensional case

    + +

    Let us try to develop our intuition about SVMs by limiting ourselves to a two-dimensional +plane. To separate the two classes of data points, there are many +possible lines (hyperplanes if you prefer a more strict naming) +that could be chosen. Our objective is to find a +plane that has the maximum margin, i.e the maximum distance between +data points of both classes. Maximizing the margin distance provides +some reinforcement so that future data points can be classified with +more confidence. +

    + +

    What a linear classifier attempts to accomplish is to split the +feature space into two half spaces by placing a hyperplane between the +data points. This hyperplane will be our decision boundary. All +points on one side of the plane will belong to class one and all points +on the other side of the plane will belong to the second class two. +

    + +

    Unfortunately there are many ways in which we can place a hyperplane +to divide the data. Below is an example of two candidate hyperplanes +for our data sample. +

    + +

    + +

    + +
    + + + + +
    + +
    + + + diff --git a/doc/pub/week46/html/._week46-bs008.html b/doc/pub/week46/html/._week46-bs008.html new file mode 100644 index 000000000..af1b460a8 --- /dev/null +++ b/doc/pub/week46/html/._week46-bs008.html @@ -0,0 +1,230 @@ + + + + + + + +Week 46: Support Vector Machines and Project 3 + + + + + + + + + + + + + + + + + + + + +
    +

     

     

     

    + + +

    Getting into the details

    + +

    Let us define the function

    +$$ +f(x) = \boldsymbol{w}^T\boldsymbol{x}+b = 0, +$$ + +

    as the function that determines the line \( L \) that separates two classes (our two features), see the figure here.

    + +

    Any point defined by \( \boldsymbol{x}_i \) and \( \boldsymbol{x}_2 \) on the line \( L \) will satisfy \( \boldsymbol{w}^T(\boldsymbol{x}_1-\boldsymbol{x}_2)=0 \).

    + +

    The signed distance \( \delta \) from any point defined by a vector \( \boldsymbol{x} \) and a point \( \boldsymbol{x}_0 \) on the line \( L \) is then

    +$$ +\delta = \frac{1}{\vert\vert \boldsymbol{w}\vert\vert}(\boldsymbol{w}^T\boldsymbol{x}+b). +$$ + + +

    + +

    + +
    + + + + +
    + +
    + + + diff --git a/doc/pub/week46/html/._week46-bs009.html b/doc/pub/week46/html/._week46-bs009.html new file mode 100644 index 000000000..0999dc24f --- /dev/null +++ b/doc/pub/week46/html/._week46-bs009.html @@ -0,0 +1,236 @@ + + + + + + + +Week 46: Support Vector Machines and Project 3 + + + + + + + + + + + + + + + + + + + + +
    +

     

     

     

    + + +

    First attempt at a minimization approach

    + +

    How do we find the parameter \( b \) and the vector \( \boldsymbol{w} \)? What we could +do is to define a cost function which now contains the set of all +misclassified points \( M \) and attempt to minimize this function +

    + +$$ +C(\boldsymbol{w},b) = -\sum_{i\in M} y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b). +$$ + +

    We could now for example define all values \( y_i =1 \) as misclassified in case we have \( \boldsymbol{w}^T\boldsymbol{x}_i+b < 0 \) and the opposite if we have \( y_i=-1 \). Taking the derivatives gives us

    +$$ +\frac{\partial C}{\partial b} = -\sum_{i\in M} y_i, +$$ + +

    and

    +$$ +\frac{\partial C}{\partial \boldsymbol{w}} = -\sum_{i\in M} y_ix_i. +$$ + + +

    + +

    + +
    + + + + +
    + +
    + + + diff --git a/doc/pub/week46/html/._week46-bs010.html b/doc/pub/week46/html/._week46-bs010.html new file mode 100644 index 000000000..99dfadce0 --- /dev/null +++ b/doc/pub/week46/html/._week46-bs010.html @@ -0,0 +1,229 @@ + + + + + + + +Week 46: Support Vector Machines and Project 3 + + + + + + + + + + + + + + + + + + + + +
    +

     

     

     

    + + +

    Solving the equations

    + +

    We can now use the Newton-Raphson method or different variants of the gradient descent family (from plain gradient descent to various stochastic gradient descent approaches) to solve the equations

    +$$ +b \leftarrow b +\eta \frac{\partial C}{\partial b}, +$$ + +

    and

    +$$ +\boldsymbol{w} \leftarrow \boldsymbol{w} +\eta \frac{\partial C}{\partial \boldsymbol{w}}, +$$ + +

    where \( \eta \) is our by now well-known learning rate.

    + +

    + +

    + +
    + + + + +
    + +
    + + + diff --git a/doc/pub/week46/html/._week46-bs011.html b/doc/pub/week46/html/._week46-bs011.html new file mode 100644 index 000000000..fc7df67aa --- /dev/null +++ b/doc/pub/week46/html/._week46-bs011.html @@ -0,0 +1,245 @@ + + + + + + + +Week 46: Support Vector Machines and Project 3 + + + + + + + + + + + + + + + + + + + + +
    +

     

     

     

    + + +

    Code Example

    + +

    The equations we discussed above can be coded rather easily (the +framework is similar to what we developed for logistic +regression). We are going to set up a simple case with two classes only and we want to find a line which separates them the best possible way. +

    + + +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +

    + +

    + +
    + + + + +
    + +
    + + + diff --git a/doc/pub/week46/html/._week46-bs012.html b/doc/pub/week46/html/._week46-bs012.html new file mode 100644 index 000000000..45cd4b4af --- /dev/null +++ b/doc/pub/week46/html/._week46-bs012.html @@ -0,0 +1,228 @@ + + + + + + + +Week 46: Support Vector Machines and Project 3 + + + + + + + + + + + + + + + + + + + + +
    +

     

     

     

    + + +

    Problems with the Simpler Approach

    + +

    There are however problems with this approach, although it looks +pretty straightforward to implement. When running the above code, we see that we can easily end up with many diffeent lines which separate the two classes. +

    + +

    For small +gaps between the entries, we may also end up needing many iterations +before the solutions converge and if the data cannot be separated +properly into two distinct classes, we may not experience a converge +at all. +

    + +

    + +

    + +
    + + + + +
    + +
    + + + diff --git a/doc/pub/week46/html/._week46-bs013.html b/doc/pub/week46/html/._week46-bs013.html new file mode 100644 index 000000000..d170402b3 --- /dev/null +++ b/doc/pub/week46/html/._week46-bs013.html @@ -0,0 +1,254 @@ + + + + + + + +Week 46: Support Vector Machines and Project 3 + + + + + + + + + + + + + + + + + + + + +
    +

     

     

     

    + + +

    A better approach

    + +

    A better approach is rather to try to define a large margin between +the two classes (if they are well separated from the beginning). +

    + +

    Thus, we wish to find a margin \( M \) with \( \boldsymbol{w} \) normalized to +\( \vert\vert \boldsymbol{w}\vert\vert =1 \) subject to the condition +

    + +$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) \geq M \hspace{0.1cm}\forall i=1,2,\dots, p. +$$ + +

    All points are thus at a signed distance from the decision boundary defined by the line \( L \). The parameters \( b \) and \( w_1 \) and \( w_2 \) define this line.

    + +

    We seek thus the largest value \( M \) defined by

    +$$ +\frac{1}{\vert \vert \boldsymbol{w}\vert\vert}y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) \geq M \hspace{0.1cm}\forall i=1,2,\dots, n, +$$ + +

    or just

    +$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) \geq M\vert \vert \boldsymbol{w}\vert\vert \hspace{0.1cm}\forall i. +$$ + +

    If we scale the equation so that \( \vert \vert \boldsymbol{w}\vert\vert = 1/M \), we have to find the minimum of +\( \boldsymbol{w}^T\boldsymbol{w}=\vert \vert \boldsymbol{w}\vert\vert \) (the norm) subject to the condition +

    +$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) \geq 1 \hspace{0.1cm}\forall i. +$$ + +

    We have thus defined our margin as the invers of the norm of +\( \boldsymbol{w} \). We want to minimize the norm in order to have a as large as +possible margin \( M \). Before we proceed, we need to remind ourselves +about Lagrangian multipliers. +

    + +

    + +

    + +
    + + + + +
    + +
    + + + diff --git a/doc/pub/week46/html/._week46-bs014.html b/doc/pub/week46/html/._week46-bs014.html new file mode 100644 index 000000000..81625e9ed --- /dev/null +++ b/doc/pub/week46/html/._week46-bs014.html @@ -0,0 +1,264 @@ + + + + + + + +Week 46: Support Vector Machines and Project 3 + + + + + + + + + + + + + + + + + + + + +
    +

     

     

     

    + + +

    A quick Reminder on Lagrangian Multipliers

    + +

    Consider a function of three independent variables \( f(x,y,z) \) . For the function \( f \) to be an +extreme we have +

    +$$ +df=0. +$$ + +

    A necessary and sufficient condition is

    +$$ +\frac{\partial f}{\partial x} =\frac{\partial f}{\partial y}=\frac{\partial f}{\partial z}=0, +$$ + +

    due to

    +$$ +df = \frac{\partial f}{\partial x}dx+\frac{\partial f}{\partial y}dy+\frac{\partial f}{\partial z}dz. +$$ + +

    In many problems the variables \( x,y,z \) are often subject to constraints (such as those above for the margin) +so that they are no longer all independent. It is possible at least in principle to use each +constraint to eliminate one variable +and to proceed with a new and smaller set of independent varables. +

    + +

    The use of so-called Lagrangian multipliers is an alternative technique when the elimination +of variables is incovenient or undesirable. Assume that we have an equation of constraint on +the variables \( x,y,z \) +

    +$$ +\phi(x,y,z) = 0, +$$ + +

    resulting in

    +$$ +d\phi = \frac{\partial \phi}{\partial x}dx+\frac{\partial \phi}{\partial y}dy+\frac{\partial \phi}{\partial z}dz =0. +$$ + +

    Now we cannot set anymore

    +$$ +\frac{\partial f}{\partial x} =\frac{\partial f}{\partial y}=\frac{\partial f}{\partial z}=0, +$$ + +

    if \( df=0 \) is wanted +because there are now only two independent variables! Assume \( x \) and \( y \) are the independent +variables. +Then \( dz \) is no longer arbitrary. +

    + +

    + +

    + +
    + + + + +
    + +
    + + + diff --git a/doc/pub/week46/html/._week46-bs015.html b/doc/pub/week46/html/._week46-bs015.html new file mode 100644 index 000000000..cb264dab7 --- /dev/null +++ b/doc/pub/week46/html/._week46-bs015.html @@ -0,0 +1,255 @@ + + + + + + + +Week 46: Support Vector Machines and Project 3 + + + + + + + + + + + + + + + + + + + + +
    +

     

     

     

    + + +

    Adding the Multiplier

    + +

    However, we can add to

    +$$ +df = \frac{\partial f}{\partial x}dx+\frac{\partial f}{\partial y}dy+\frac{\partial f}{\partial z}dz, +$$ + +

    a multiplum of \( d\phi \), viz. \( \lambda d\phi \), resulting in

    +$$ +df+\lambda d\phi = (\frac{\partial f}{\partial z}+\lambda +\frac{\partial \phi}{\partial x})dx+(\frac{\partial f}{\partial y}+\lambda\frac{\partial \phi}{\partial y})dy+ +(\frac{\partial f}{\partial z}+\lambda\frac{\partial \phi}{\partial z})dz =0. +$$ + +

    Our multiplier is chosen so that

    +$$ +\frac{\partial f}{\partial z}+\lambda\frac{\partial \phi}{\partial z} =0. +$$ + +

    We need to remember that we took \( dx \) and \( dy \) to be arbitrary and thus we must have

    +$$ +\frac{\partial f}{\partial x}+\lambda\frac{\partial \phi}{\partial x} =0, +$$ + +

    and

    +$$ +\frac{\partial f}{\partial y}+\lambda\frac{\partial \phi}{\partial y} =0. +$$ + +

    When all these equations are satisfied, \( df=0 \). We have four unknowns, \( x,y,z \) and +\( \lambda \). Actually we want only \( x,y,z \), \( \lambda \) needs not to be determined, +it is therefore often called +Lagrange's undetermined multiplier. +If we have a set of constraints \( \phi_k \) we have the equations +

    +$$ +\frac{\partial f}{\partial x_i}+\sum_k\lambda_k\frac{\partial \phi_k}{\partial x_i} =0. +$$ + + +

    + +

    + +
    + + + + +
    + +
    + + + diff --git a/doc/pub/week46/html/._week46-bs016.html b/doc/pub/week46/html/._week46-bs016.html new file mode 100644 index 000000000..fa58a569f --- /dev/null +++ b/doc/pub/week46/html/._week46-bs016.html @@ -0,0 +1,251 @@ + + + + + + + +Week 46: Support Vector Machines and Project 3 + + + + + + + + + + + + + + + + + + + + +
    +

     

     

     

    + + +

    Setting up the Problem

    +

    In order to solve the above problem, we define the following Lagrangian function to be minimized

    +$$ +{\cal L}(\lambda,b,\boldsymbol{w})=\frac{1}{2}\boldsymbol{w}^T\boldsymbol{w}-\sum_{i=1}^n\lambda_i\left[y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)-1\right], +$$ + +

    where \( \lambda_i \) is a so-called Lagrange multiplier subject to the condition \( \lambda_i \geq 0 \).

    + +

    Taking the derivatives with respect to \( b \) and \( \boldsymbol{w} \) we obtain

    +$$ +\frac{\partial {\cal L}}{\partial b} = -\sum_{i} \lambda_iy_i=0, +$$ + +

    and

    +$$ +\frac{\partial {\cal L}}{\partial \boldsymbol{w}} = 0 = \boldsymbol{w}-\sum_{i} \lambda_iy_i\boldsymbol{x}_i. +$$ + +

    Inserting these constraints into the equation for \( {\cal L} \) we obtain

    +$$ +{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\boldsymbol{x}_i^T\boldsymbol{x}_j, +$$ + +

    subject to the constraints \( \lambda_i\geq 0 \) and \( \sum_i\lambda_iy_i=0 \). +We must in addition satisfy the Karush-Kuhn-Tucker (KKT) condition +

    +$$ +\lambda_i\left[y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) -1\right] \hspace{0.1cm}\forall i. +$$ + +
      +
    1. If \( \lambda_i > 0 \), then \( y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1 \) and we say that \( x_i \) is on the boundary.
    2. +
    3. If \( y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)> 1 \), we say \( x_i \) is not on the boundary and we set \( \lambda_i=0 \).
    4. +
    +

    When \( \lambda_i > 0 \), the vectors \( \boldsymbol{x}_i \) are called support vectors. They are the vectors closest to the line (or hyperplane) and define the margin \( M \).

    + +

    + +

    + +
    + + + + +
    + +
    + + + diff --git a/doc/pub/week46/html/._week46-bs017.html b/doc/pub/week46/html/._week46-bs017.html new file mode 100644 index 000000000..9829adefe --- /dev/null +++ b/doc/pub/week46/html/._week46-bs017.html @@ -0,0 +1,236 @@ + + + + + + + +Week 46: Support Vector Machines and Project 3 + + + + + + + + + + + + + + + + + + + + +
    +

     

     

     

    + + +

    The problem to solve

    + +

    We can rewrite

    +$$ +{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\boldsymbol{x}_i^T\boldsymbol{x}_j, +$$ + +

    and its constraints in terms of a matrix-vector problem where we minimize w.r.t. \( \lambda \) the following problem

    +$$ +\frac{1}{2} \boldsymbol{\lambda}^T\begin{bmatrix} y_1y_1\boldsymbol{x}_1^T\boldsymbol{x}_1 & y_1y_2\boldsymbol{x}_1^T\boldsymbol{x}_2 & \dots & \dots & y_1y_n\boldsymbol{x}_1^T\boldsymbol{x}_n \\ +y_2y_1\boldsymbol{x}_2^T\boldsymbol{x}_1 & y_2y_2\boldsymbol{x}_2^T\boldsymbol{x}_2 & \dots & \dots & y_1y_n\boldsymbol{x}_2^T\boldsymbol{x}_n \\ +\dots & \dots & \dots & \dots & \dots \\ +\dots & \dots & \dots & \dots & \dots \\ +y_ny_1\boldsymbol{x}_n^T\boldsymbol{x}_1 & y_ny_2\boldsymbol{x}_n^T\boldsymbol{x}_2 & \dots & \dots & y_ny_n\boldsymbol{x}_n^T\boldsymbol{x}_n \\ +\end{bmatrix}\boldsymbol{\lambda}-\mathbb{1}\boldsymbol{\lambda}, +$$ + +

    subject to \( \boldsymbol{y}^T\boldsymbol{\lambda}=0 \). Here we defined the vectors \( \boldsymbol{\lambda} =[\lambda_1,\lambda_2,\dots,\lambda_n] \) and +\( \boldsymbol{y}=[y_1,y_2,\dots,y_n] \). +

    + +

    + +

    + +
    + + + + +
    + +
    + + + diff --git a/doc/pub/week46/html/._week46-bs018.html b/doc/pub/week46/html/._week46-bs018.html new file mode 100644 index 000000000..39c0c924a --- /dev/null +++ b/doc/pub/week46/html/._week46-bs018.html @@ -0,0 +1,246 @@ + + + + + + + +Week 46: Support Vector Machines and Project 3 + + + + + + + + + + + + + + + + + + + + +
    +

     

     

     

    + + +

    The last steps

    + +

    Solving the above problem, yields the values of \( \lambda_i \). +To find the coefficients of your hyperplane we need simply to compute +

    +$$ +\boldsymbol{w}=\sum_{i} \lambda_iy_i\boldsymbol{x}_i. +$$ + +

    With our vector \( \boldsymbol{w} \) we can in turn find the value of the intercept \( b \) (here in two dimensions) via

    +$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1, +$$ + +

    resulting in

    +$$ +b = \frac{1}{y_i}-\boldsymbol{w}^T\boldsymbol{x}_i, +$$ + +

    or if we write it out in terms of the support vectors only, with \( N_s \) being their number, we have

    +$$ +b = \frac{1}{N_s}\sum_{j\in N_s}\left(y_j-\sum_{i=1}^n\lambda_iy_i\boldsymbol{x}_i^T\boldsymbol{x}_j\right). +$$ + +

    With our hyperplane coefficients we can use our classifier to assign any observation by simply using

    +$$ +y_i = \mathrm{sign}(\boldsymbol{w}^T\boldsymbol{x}_i+b). +$$ + +

    Below we discuss how to find the optimal values of \( \lambda_i \). Before we proceed however, we discuss now the so-called soft classifier.

    + +

    + +

    + +
    + + + + +
    + +
    + + + diff --git a/doc/pub/week46/html/._week46-bs019.html b/doc/pub/week46/html/._week46-bs019.html new file mode 100644 index 000000000..40dcea620 --- /dev/null +++ b/doc/pub/week46/html/._week46-bs019.html @@ -0,0 +1,247 @@ + + + + + + + +Week 46: Support Vector Machines and Project 3 + + + + + + + + + + + + + + + + + + + + +
    +

     

     

     

    + + +

    A soft classifier

    + +

    Till now, the margin is strictly defined by the support vectors. This defines what is called a hard classifier, that is the margins are well defined.

    + +

    Suppose now that classes overlap in feature space, as shown in the +figure here. One way to deal with this problem before we define the +so-called kernel approach, is to allow a kind of slack in the sense +that we allow some points to be on the wrong side of the margin. +

    + +

    We introduce thus the so-called slack variables \( \boldsymbol{\xi} =[\xi_1,x_2,\dots,x_n] \) and +modify our previous equation +

    +$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1, +$$ + +

    to

    +$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1-\xi_i, +$$ + +

    with the requirement \( \xi_i\geq 0 \). The total violation is now \( \sum_i\xi \). +The value \( \xi_i \) in the constraint the last constraint corresponds to the amount by which the prediction +\( y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1 \) is on the wrong side of its margin. Hence by bounding the sum \( \sum_i \xi_i \), +we bound the total amount by which predictions fall on the wrong side of their margins. +

    + +

    Misclassifications occur when \( \xi_i > 1 \). Thus bounding the total sum by some value \( C \) bounds in turn the total number of +misclassifications. +

    + +

    + +

    + +
    + + + + +
    + +
    + + + diff --git a/doc/pub/week46/html/._week46-bs020.html b/doc/pub/week46/html/._week46-bs020.html new file mode 100644 index 000000000..fc0960e18 --- /dev/null +++ b/doc/pub/week46/html/._week46-bs020.html @@ -0,0 +1,264 @@ + + + + + + + +Week 46: Support Vector Machines and Project 3 + + + + + + + + + + + + + + + + + + + + +
    +

     

     

     

    + + +

    Soft optmization problem

    + +

    This has in turn the consequences that we change our optmization problem to finding the minimum of

    +$$ +{\cal L}=\frac{1}{2}\boldsymbol{w}^T\boldsymbol{w}-\sum_{i=1}^n\lambda_i\left[y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)-(1-\xi_)\right]+C\sum_{i=1}^n\xi_i-\sum_{i=1}^n\gamma_i\xi_i, +$$ + +

    subject to

    +$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1-\xi_i \hspace{0.1cm}\forall i, +$$ + +

    with the requirement \( \xi_i\geq 0 \).

    + +

    Taking the derivatives with respect to \( b \) and \( \boldsymbol{w} \) we obtain

    +$$ +\frac{\partial {\cal L}}{\partial b} = -\sum_{i} \lambda_iy_i=0, +$$ + +

    and

    +$$ +\frac{\partial {\cal L}}{\partial \boldsymbol{w}} = 0 = \boldsymbol{w}-\sum_{i} \lambda_iy_i\boldsymbol{x}_i, +$$ + +

    and

    +$$ +\lambda_i = C-\gamma_i \hspace{0.1cm}\forall i. +$$ + +

    Inserting these constraints into the equation for \( {\cal L} \) we obtain the same equation as before

    +$$ +{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\boldsymbol{x}_i^T\boldsymbol{x}_j, +$$ + +

    but now subject to the constraints \( \lambda_i\geq 0 \), \( \sum_i\lambda_iy_i=0 \) and \( 0\leq\lambda_i \leq C \). +We must in addition satisfy the Karush-Kuhn-Tucker condition which now reads +

    +$$ +\lambda_i\left[y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) -(1-\xi_)\right]=0 \hspace{0.1cm}\forall i, +$$ + +$$ +\gamma_i\xi_i = 0, +$$ + +

    and

    +$$ +y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) -(1-\xi_) \geq 0 \hspace{0.1cm}\forall i. +$$ + + +

    + +

    + +
    + + + + +
    + +
    + + + diff --git a/doc/pub/week46/html/._week46-bs021.html b/doc/pub/week46/html/._week46-bs021.html new file mode 100644 index 000000000..96aad1691 --- /dev/null +++ b/doc/pub/week46/html/._week46-bs021.html @@ -0,0 +1,301 @@ + + + + + + + +Week 46: Support Vector Machines and Project 3 + + + + + + + + + + + + + + + + + + + + +
    +

     

     

     

    + + +

    Kernels and non-linearity

    + +

    The cases we have studied till now, 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. +

    + + + +
    +
    +
    +
    +
    +
    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()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +

    + +

    + +
    + + + + +
    + +
    + + + diff --git a/doc/pub/week46/html/._week46-bs022.html b/doc/pub/week46/html/._week46-bs022.html new file mode 100644 index 000000000..99fa9d815 --- /dev/null +++ b/doc/pub/week46/html/._week46-bs022.html @@ -0,0 +1,252 @@ + + + + + + + +Week 46: Support Vector Machines and Project 3 + + + + + + + + + + + + + + + + + + + + +
    +

     

     

     

    + + +

    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)

    +$$ +z = \phi(x_i) =\left(x_i^2, y_i^2, \sqrt{2}x_iy_i\right). +$$ + +

    With our new basis, the equations we solved earlier are basically the same, that is we have now (without the slack option for simplicity)

    +$$ +{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\boldsymbol{z}_i^T\boldsymbol{z}_j, +$$ + +

    subject to the constraints \( \lambda_i\geq 0 \), \( \sum_i\lambda_iy_i=0 \), and for the support vectors

    +$$ +y_i(\boldsymbol{w}^T\boldsymbol{z}_i+b)= 1 \hspace{0.1cm}\forall i, +$$ + +

    from which we also find \( b \). +To compute \( \boldsymbol{z}_i^T\boldsymbol{z}_j \) we define the kernel \( K(\boldsymbol{x}_i,\boldsymbol{x}_j) \) as +

    +$$ +K(\boldsymbol{x}_i,\boldsymbol{x}_j)=\boldsymbol{z}_i^T\boldsymbol{z}_j= \phi(\boldsymbol{x}_i)^T\phi(\boldsymbol{x}_j). +$$ + +

    For the above example, the kernel reads

    +$$ +K(\boldsymbol{x}_i,\boldsymbol{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. +$$ + +

    We note that this is nothing but the dot product of the two original +vectors \( (\boldsymbol{x}_i^T\boldsymbol{x}_j)^2 \). Instead of thus computing the +product in the Lagrangian of \( \boldsymbol{z}_i^T\boldsymbol{z}_j \) we simply compute +the dot product \( (\boldsymbol{x}_i^T\boldsymbol{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(\boldsymbol{x}_i)^T\phi(\boldsymbol{x}_j) \) during the SVM calculations. +

    + +

    + +

    + +
    + + + + +
    + +
    + + + diff --git a/doc/pub/week46/html/._week46-bs023.html b/doc/pub/week46/html/._week46-bs023.html new file mode 100644 index 000000000..3a9551131 --- /dev/null +++ b/doc/pub/week46/html/._week46-bs023.html @@ -0,0 +1,244 @@ + + + + + + + +Week 46: Support Vector Machines and Project 3 + + + + + + + + + + + + + + + + + + + + +
    +

     

     

     

    + + +

    The problem to solve

    +

    Using our definition of the kernel We can rewrite again the Lagrangian

    +$$ +{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\boldsymbol{x}_i^T\boldsymbol{z}_j, +$$ + +

    subject to the constraints \( \lambda_i\geq 0 \), \( \sum_i\lambda_iy_i=0 \) in terms of a convex optimization problem

    +$$ +\frac{1}{2} \boldsymbol{\lambda}^T\begin{bmatrix} y_1y_1K(\boldsymbol{x}_1,\boldsymbol{x}_1) & y_1y_2K(\boldsymbol{x}_1,\boldsymbol{x}_2) & \dots & \dots & y_1y_nK(\boldsymbol{x}_1,\boldsymbol{x}_n) \\ +y_2y_1K(\boldsymbol{x}_2,\boldsymbol{x}_1) & y_2y_2(\boldsymbol{x}_2,\boldsymbol{x}_2) & \dots & \dots & y_1y_nK(\boldsymbol{x}_2,\boldsymbol{x}_n) \\ +\dots & \dots & \dots & \dots & \dots \\ +\dots & \dots & \dots & \dots & \dots \\ +y_ny_1K(\boldsymbol{x}_n,\boldsymbol{x}_1) & y_ny_2K(\boldsymbol{x}_n\boldsymbol{x}_2) & \dots & \dots & y_ny_nK(\boldsymbol{x}_n,\boldsymbol{x}_n) \\ +\end{bmatrix}\boldsymbol{\lambda}-\mathbb{1}\boldsymbol{\lambda}, +$$ + +

    subject to \( \boldsymbol{y}^T\boldsymbol{\lambda}=0 \). Here we defined the vectors \( \boldsymbol{\lambda} =[\lambda_1,\lambda_2,\dots,\lambda_n] \) and +\( \boldsymbol{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

    +$$ +\begin{align*} + &\mathrm{min}_{\lambda}\hspace{0.2cm} \frac{1}{2}\boldsymbol{\lambda}^T\boldsymbol{P}\boldsymbol{\lambda}+\boldsymbol{q}^T\boldsymbol{\lambda},\\ \nonumber + &\mathrm{subject\hspace{0.1cm}to} \hspace{0.2cm} \boldsymbol{G}\boldsymbol{\lambda} \preceq \boldsymbol{h} \hspace{0.2cm} \wedge \boldsymbol{A}\boldsymbol{\lambda}=f. +\end{align*} +$$ + +

    Below we discuss how to solve these equations. Here we note that the matrix \( \boldsymbol{P} \) has matrix elements \( p_{ij}=y_iy_jK(\boldsymbol{x}_i,\boldsymbol{x}_j) \). +Given a kernel \( K \) and the targets \( y_i \) this matrix is easy to set up. The constraint \( \boldsymbol{y}^T\boldsymbol{\lambda}=0 \) leads to \( f=0 \) and \( \boldsymbol{A}=\boldsymbol{y} \). How to set up the matrix \( \boldsymbol{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 \( \boldsymbol{G} \) and the vector \( \boldsymbol{h} \). +

    + +

    + +

    + +
    + + + + +
    + +
    + + + diff --git a/doc/pub/week46/html/._week46-bs024.html b/doc/pub/week46/html/._week46-bs024.html new file mode 100644 index 000000000..ce78f31f4 --- /dev/null +++ b/doc/pub/week46/html/._week46-bs024.html @@ -0,0 +1,241 @@ + + + + + + + +Week 46: Support Vector Machines and Project 3 + + + + + + + + + + + + + + + + + + + + +
    +

     

     

     

    + + +

    Different kernels and Mercer's theorem

    + +

    There are several popular kernels being used. These are

    +
      +
    1. Linear: \( K(\boldsymbol{x},\boldsymbol{y})=\boldsymbol{x}^T\boldsymbol{y} \),
    2. +
    3. Polynomial: \( K(\boldsymbol{x},\boldsymbol{y})=(\boldsymbol{x}^T\boldsymbol{y}+\gamma)^d \),
    4. +
    5. Gaussian Radial Basis Function: \( K(\boldsymbol{x},\boldsymbol{y})=\exp{\left(-\gamma\vert\vert\boldsymbol{x}-\boldsymbol{y}\vert\vert^2\right)} \),
    6. +
    7. Tanh: \( K(\boldsymbol{x},\boldsymbol{y})=\tanh{(\boldsymbol{x}^T\boldsymbol{y}+\gamma)} \),
    8. +
    +

    and many other ones.

    + +

    An important theorem for us is Mercer's +theorem. The +theorem states that if a kernel function \( K \) is symmetric, continuous +and leads to a positive semi-definite matrix \( \boldsymbol{P} \) then there +exists a function \( \phi \) that maps \( \boldsymbol{x}_i \) and \( \boldsymbol{x}_j \) into +another space (possibly with much higher dimensions) such that +

    + +$$ +K(\boldsymbol{x}_i,\boldsymbol{x}_j)=\phi(\boldsymbol{x}_i)^T\phi(\boldsymbol{x}_j). +$$ + +

    So you can use \( K \) as a kernel since you know \( \phi \) exists, even if +you don’t know what \( \phi \) is. +

    + +

    Note that some frequently used kernels (such as the Sigmoid kernel) +don’t respect all of Mercer’s conditions, yet they generally work well +in practice. +

    + +

    + +

    + +
    + + + + +
    + +
    + + + diff --git a/doc/pub/week46/html/._week46-bs025.html b/doc/pub/week46/html/._week46-bs025.html new file mode 100644 index 000000000..a29620c79 --- /dev/null +++ b/doc/pub/week46/html/._week46-bs025.html @@ -0,0 +1,420 @@ + + + + + + + +Week 46: Support Vector Machines and Project 3 + + + + + + + + + + + + + + + + + + + + +
    +

     

     

     

    + + +

    The moons example

    + + +
    +
    +
    +
    +
    +
    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()
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +

    + +

    + +
    + + + + +
    + +
    + + + diff --git a/doc/pub/week46/html/._week46-bs026.html b/doc/pub/week46/html/._week46-bs026.html new file mode 100644 index 000000000..26d44604d --- /dev/null +++ b/doc/pub/week46/html/._week46-bs026.html @@ -0,0 +1,228 @@ + + + + + + + +Week 46: Support Vector Machines and Project 3 + + + + + + + + + + + + + + + + + + + + +
    +

     

     

     

    + + +

    Mathematical optimization of convex functions

    + +

    A mathematical (quadratic) optimization problem, or just optimization problem, has the form

    +$$ +\begin{align*} + &\mathrm{min}_{\lambda}\hspace{0.2cm} \frac{1}{2}\boldsymbol{\lambda}^T\boldsymbol{P}\boldsymbol{\lambda}+\boldsymbol{q}^T\boldsymbol{\lambda},\\ \nonumber + &\mathrm{subject\hspace{0.1cm}to} \hspace{0.2cm} \boldsymbol{G}\boldsymbol{\lambda} \preceq \boldsymbol{h} \wedge \boldsymbol{A}\boldsymbol{\lambda}=f. +\end{align*} +$$ + +

    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 \( \boldsymbol{\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.

    + +

    + +

    + +
    + + + + +
    + +
    + + + diff --git a/doc/pub/week46/html/._week46-bs027.html b/doc/pub/week46/html/._week46-bs027.html new file mode 100644 index 000000000..6660e728f --- /dev/null +++ b/doc/pub/week46/html/._week46-bs027.html @@ -0,0 +1,245 @@ + + + + + + + +Week 46: Support Vector Machines and Project 3 + + + + + + + + + + + + + + + + + + + + +
    +

     

     

     

    + + +

    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

    + + + +
    +
    +
    +
    +
    +
    import numpy
    +import cvxopt
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +

    This will make our life much easier. You don't need t write your own optimizer.

    + +

    + +

    + +
    + + + + +
    + +
    + + + diff --git a/doc/pub/week46/html/._week46-bs028.html b/doc/pub/week46/html/._week46-bs028.html new file mode 100644 index 000000000..5e81fc122 --- /dev/null +++ b/doc/pub/week46/html/._week46-bs028.html @@ -0,0 +1,288 @@ + + + + + + + +Week 46: Support Vector Machines and Project 3 + + + + + + + + + + + + + + + + + + + + +
    +

     

     

     

    + + +

    A simple example

    + +

    We remind ourselves about the general problem we want to solve

    +$$ +\begin{align*} + &\mathrm{min}_{x}\hspace{0.2cm} \frac{1}{2}\boldsymbol{x}^T\boldsymbol{P}\boldsymbol{x}+\boldsymbol{q}^T\boldsymbol{x},\\ \nonumber + &\mathrm{subject\hspace{0.1cm} to} \hspace{0.2cm} \boldsymbol{G}\boldsymbol{x} \preceq \boldsymbol{h} \wedge \boldsymbol{A}\boldsymbol{x}=f. +\end{align*} +$$ + +

    Let us show how to perform the optmization using a simple case. Assume we want to optimize the following problem

    +$$ +\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*} +$$ + +

    The minimization problem can be rewritten in terms of vectors and matrices as (with \( x \) and \( y \) being the unknowns)

    +$$ +\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}. +$$ + +

    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

    +$$ +\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}. +$$ + +

    We have collapsed all the inequalities into a single matrix \( \boldsymbol{G} \). We see also that our matrix

    +$$ +\boldsymbol{P} =\begin{bmatrix} 1 & 0\\ 0 & 0 \end{bmatrix} +$$ + +

    is clearly positive semi-definite (all eigenvalues larger or equal zero). +Finally, the vector \( \boldsymbol{h} \) is defined as +

    +$$ +\boldsymbol{h} = \begin{bmatrix}0 \\ 0\\ -15 \\ 100 \\ 80\end{bmatrix}. +$$ + +

    Since we don't have any equalities the matrix \( \boldsymbol{A} \) is set to zero +The following code solves the equations for us +

    + + +
    +
    +
    +
    +
    +
    # 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’]
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + +

    + +

    + +
    + + + + +
    + +
    + + + diff --git a/doc/pub/week46/html/._week46-bs029.html b/doc/pub/week46/html/._week46-bs029.html new file mode 100644 index 000000000..f1bde7d95 --- /dev/null +++ b/doc/pub/week46/html/._week46-bs029.html @@ -0,0 +1,222 @@ + + + + + + + +Week 46: Support Vector Machines and Project 3 + + + + + + + + + + + + + + + + + + + + +
    +

     

     

     

    + + +

    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

    +$$ +\frac{1}{2} \boldsymbol{\lambda}^T\begin{bmatrix} y_1y_1K(\boldsymbol{x}_1,\boldsymbol{x}_1) & y_1y_2K(\boldsymbol{x}_1,\boldsymbol{x}_2) & \dots & \dots & y_1y_nK(\boldsymbol{x}_1,\boldsymbol{x}_n) \\ +y_2y_1K(\boldsymbol{x}_2,\boldsymbol{x}_1) & y_2y_2K(\boldsymbol{x}_2,\boldsymbol{x}_2) & \dots & \dots & y_1y_nK(\boldsymbol{x}_2,\boldsymbol{x}_n) \\ +\dots & \dots & \dots & \dots & \dots \\ +\dots & \dots & \dots & \dots & \dots \\ +y_ny_1K(\boldsymbol{x}_n,\boldsymbol{x}_1) & y_ny_2K(\boldsymbol{x}_n\boldsymbol{x}_2) & \dots & \dots & y_ny_nK(\boldsymbol{x}_n,\boldsymbol{x}_n) \\ +\end{bmatrix}\boldsymbol{\lambda}-\mathbb{I}\boldsymbol{\lambda}, +$$ + +

    subject to \( \boldsymbol{y}^T\boldsymbol{\lambda}=0 \). Here we defined the vectors \( \boldsymbol{\lambda} =[\lambda_1,\lambda_2,\dots,\lambda_n] \) and +\( \boldsymbol{y}=[y_1,y_2,\dots,y_n] \). +With the slack constants this leads to the additional constraint \( 0\leq \lambda_i \leq C \). +

    + +code will be added + +

    + +

    + +
    + + + + +
    + +
    + + + diff --git a/doc/pub/week46/html/week46-bs.html b/doc/pub/week46/html/week46-bs.html index 2cf13cca3..7ec107313 100644 --- a/doc/pub/week46/html/week46-bs.html +++ b/doc/pub/week46/html/week46-bs.html @@ -1,31 +1,28 @@ - + - - -Week 46: Gradient Boosting Summary and Support Vector Machines - + +Week 46: Support Vector Machines and Project 3 + - - - @@ -96,8 +114,6 @@ MathJax.Hub.Config({ - - -
    -

     

     

     

    - - - -
    -

    Week 46: Gradient Boosting Summary and Support Vector Machines

    +
    +

    Week 46: Support Vector Machines and Project 3

    +
    -

    -

    Morten Hjorth-Jensen [1, 2]
    - -

    +

    +[1] Department of Physics, University of Oslo +
    +
    +[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University +
    +
    +
    +

    Nov 14, 2021

    +
    +
    -
    [1] Department of Physics, University of Oslo
    -
    [2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
    -
    -

    -

    Nov 12, 2020

    -
    -

    Read »

    @@ -202,29 +212,22 @@ MathJax.Hub.Config({
  • 9
  • 10
  • ...
  • -
  • 31
  • +
  • 30
  • »
  • -
    - - -
    - © 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license + © 1999-2021, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
    - - - diff --git a/doc/pub/week46/html/week46-reveal.html b/doc/pub/week46/html/week46-reveal.html index 5a822c55f..9cc5480e1 100644 --- a/doc/pub/week46/html/week46-reveal.html +++ b/doc/pub/week46/html/week46-reveal.html @@ -1,19 +1,18 @@ + - + + - + - + +Week 46: Support Vector Machines and Project 3 -Week 46: Gradient Boosting Summary and Support Vector Machines - - - - - - - - + @@ -55,36 +54,81 @@ document.getElementsByTagName( 'head' )[0].appendChild( link ); - - - @@ -90,118 +141,135 @@ MathJax.Hub.Config({ - - +
    +

    Week 46: Support Vector Machines and Project 3

    +
    - - -

    Week 46: Gradient Boosting Summary and Support Vector Machines

    - -

    -

    Morten Hjorth-Jensen [1, 2]
    - -

    +

    +[1] Department of Physics, University of Oslo +
    +
    +[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University +
    +
    +
    +

    Nov 14, 2021

    +
    +
    -
    [1] Department of Physics, University of Oslo
    -
    [2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
    -
    -

    -

    Nov 12, 2020

    -
    -











    - -

    Overview of week 46

    +

    Overview of week 46

      -
    • Thursday: Summary of Gradient Boosting and further examples of applications, from the physical sciences to the social sciences. Guest lecture by John M. Aiken on Gradient Boosting and XGboost.
    • -
    • Friday: Support Vector Machines, classification and regression.
    • +
    • Thursday: Summary of Gradient Boosting with selected examples. Start support Vector Machines
    • +
    • Friday: Eventual Workshop on project 3. Discussion of project 3.
    +Note that on Thursday we will have only one lecture, from 1215pm to 1pm. There is no session 115pm-2pm. -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. - +
    +Reading

    -See overview video on Support Vector Machines. See also this video. +

    Reading recommendations:

    +
      +
    1. See lecture notes for week 46 at https://compphysics.github.io/MachineLearning/doc/web/course.html.
    2. +
    3. Hastie et al chapter 12
    4. +
    5. Bishop chapter 7.1 and 7.2
    6. +
    +
    + + + +









    +

    Friday

    -

    Thursday

    +

    Last year we had a very interesting workshop with many presentations. These were (program 2020)

    -

    -The first lecture on Thursday is devoted to a summary from last week, with additional examples. This material is included in the lectures from week 45, see also Hastie et al. chapter 10.1-10.10. +

      +
    • Maria Emine Nylund: Lego Bricks Classifier
    • +
    • Fabio Rodrigues Pereira: Financial Machine Learning
    • +
    • Markus Borud Pettersen: Machine Learning and Brain Grid Cells
    • +
    • Jing Sun and Endrias Getachew Asgedom: Machine learning-based approaches to denoising microseismic data
    • +
    • Felicia Jacobsen: Analysis of Breast Cancer Data
    • +
    • Simon Elias Schrader: Predicting atomization energies of molecules
    • +
    • Varvara Bazilova and Sergio Andres Diaz Mesa: Glacier Mapping and Machine Learning
    • +
    • Gert Werner Kluge, Hanna Alida Fossen Hardersen and Sushma Sharma Adhikari: Gamma ray signals stemming from dark matter in the galactic center
    • +
    +

    We wish to organize something similar this coming Friday. The presentation last typically 5-10 minutes (some 3-5 slides) with time for questions afterwards. +Feel free to suggest topics. +

    -

    -The second letter will be given by John M. Aiken, who recently defended his thesis on machine learning, and in particular using boosting methods, to data from the social sciences and science education. +

    The program will be available asap. It depends on input from you!

    -











    +

    Support Vector Machines, overarching aims

    -

    Friday

    - -

    -We start with a new topic and second-last topic covered in this course, support vector machines (SVM). - -

    -









    - -

    Support Vector Machines, overarching aims

    - -

    -A Support Vector Machine (SVM) is a very powerful and versatile +

    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. +medium-sized datasets. +

    -

    -The case with two well-separated classes only can be understood in an +

    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 (see figure below). +

    -

    -The basic mathematics behind the SVM is however less familiar to most of us. +

    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. +

    -

    -With SVMs we distinguish between hard margin and soft margins. The +

    With SVMs we distinguish between hard margin and soft margins. The latter introduces a so-called softening parameter to be discussed below. We distinguish also between linear and non-linear approaches. The latter are the most frequent ones since it is rather unlikely that we can separate classes easily by say straight lines. +

    -











    +

    Hyperplanes and all that

    -

    Hyperplanes and all that

    - -

    -The theory behind support vector machines (SVM hereafter) is based on +

    The theory behind support vector machines (SVM hereafter) is based on the mathematical description of so-called hyperplanes. Let us start with a two-dimensional case. This will also allow us to introduce our first SVM examples. These will be tailored to the case of two specific classes, as displayed in the figure here based on the usage of the petal data. +

    -

    -We assume here that our data set can be well separated into two +

    We assume here that our data set can be well separated into two domains, where a straight line does the job in the separating the two classes. Here the two classes are represented by either squares or circles. -

    +

    -
    from sklearn import datasets
    +
    +
    +
    +
    +
    +
    from sklearn import datasets
     from sklearn.svm import SVC, LinearSVC
     from sklearn.linear_model import SGDClassifier
     from sklearn.preprocessing import StandardScaler
    @@ -267,87 +335,96 @@ plt.legend(loc="upper center", fon
     plt.axis([0, 5.5, 0, 2])
     
     plt.show()
    -
    -

    +

    +
    +
    + + +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    What is a hyperplane?

    -

    What is a hyperplane?

    - -

    -The aim of the SVM algorithm is to find a hyperplane in a +

    The aim of the SVM algorithm is to find a hyperplane in a \( p \)-dimensional space, where \( p \) is the number of features that distinctly classifies the data points. +

    -

    -In a \( p \)-dimensional space, a hyperplane is what we call an affine subspace of dimension of \( p-1 \). +

    In a \( p \)-dimensional space, a hyperplane is what we call an affine subspace of dimension of \( p-1 \). As an example, in two dimension, a hyperplane is simply as straight line while in three dimensions it is -a two-dimensional subspace, or stated simply, a plane. +a two-dimensional subspace, or stated simply, a plane. +

    -

    -In two dimensions, with the variables \( x_1 \) and \( x_2 \), the hyperplane is defined as +

    In two dimensions, with the variables \( x_1 \) and \( x_2 \), the hyperplane is defined as

    $$ b+w_1x_1+w_2x_2=0, $$ -

    -where \( b \) is the intercept and \( w_1 \) and \( w_2 \) define the elements of a vector orthogonal to the line +

    where \( b \) is the intercept and \( w_1 \) and \( w_2 \) define the elements of a vector orthogonal to the line \( b+w_1x_1+w_2x_2=0 \). In two dimensions we define the vectors \( \boldsymbol{x} =[x1,x2] \) and \( \boldsymbol{w}=[w1,w2] \). We can then rewrite the above equation as +

    $$ \boldsymbol{x}^T\boldsymbol{w}+b=0. $$ -

    +









    +

    A \( p \)-dimensional space of features

    -

    A \( p \)-dimensional space of features

    - -

    -We limit ourselves to two classes of outputs \( y_i \) and assign these classes the values \( y_i = \pm 1 \). +

    We limit ourselves to two classes of outputs \( y_i \) and assign these classes the values \( y_i = \pm 1 \). In a \( p \)-dimensional space of say \( p \) features we have a hyperplane defines as +

    $$ b+wx_1+w_2x_2+\dots +w_px_p=0. $$ -If we define a +

    If we define a matrix \( \boldsymbol{X}=\left[\boldsymbol{x}_1,\boldsymbol{x}_2,\dots, \boldsymbol{x}_p\right] \) of dimension \( n\times p \), where \( n \) represents the observations for each feature and each vector \( x_i \) is a column vector of the matrix \( \boldsymbol{X} \), +

    $$ \boldsymbol{x}_i = \begin{bmatrix} x_{i1} \\ x_{i2} \\ \dots \\ \dots \\ x_{ip} \end{bmatrix}. $$ -If the above condition is not met for a given vector \( \boldsymbol{x}_i \) we have +

    If the above condition is not met for a given vector \( \boldsymbol{x}_i \) we have

    $$ b+w_1x_{i1}+w_2x_{i2}+\dots +w_px_{ip} >0, $$ -if our output \( y_i=1 \). +

    if our output \( y_i=1 \). In this case we say that \( \boldsymbol{x}_i \) lies on one of the sides of the hyperplane and if +

    $$ b+w_1x_{i1}+w_2x_{i2}+\dots +w_px_{ip} < 0, $$ -for the class of observations \( y_i=-1 \), -then \( \boldsymbol{x}_i \) lies on the other side. +

    for the class of observations \( y_i=-1 \), +then \( \boldsymbol{x}_i \) lies on the other side. +

    -

    -Equivalently, for the two classes of observations we have +

    Equivalently, for the two classes of observations we have

    $$ y_i\left(b+w_1x_{i1}+w_2x_{i2}+\dots +w_px_{ip}\right) > 0. $$ -

    -When we try to separate hyperplanes, if it exists, we can use it to construct a natural classifier: a test observation is assigned a given class depending on which side of the hyperplane it is located. +

    When we try to separate hyperplanes, if it exists, we can use it to construct a natural classifier: a test observation is assigned a given class depending on which side of the hyperplane it is located.

    -

    +

    The two-dimensional case

    -

    The two-dimensional case

    - -

    -Let us try to develop our intuition about SVMs by limiting ourselves to a two-dimensional +

    Let us try to develop our intuition about SVMs by limiting ourselves to a two-dimensional plane. To separate the two classes of data points, there are many possible lines (hyperplanes if you prefer a more strict naming) that could be chosen. Our objective is to find a @@ -355,302 +432,298 @@ plane that has the maximum margin, i.e the maximum distance between data points of both classes. Maximizing the margin distance provides some reinforcement so that future data points can be classified with more confidence. +

    -

    -What a linear classifier attempts to accomplish is to split the +

    What a linear classifier attempts to accomplish is to split the feature space into two half spaces by placing a hyperplane between the data points. This hyperplane will be our decision boundary. All points on one side of the plane will belong to class one and all points on the other side of the plane will belong to the second class two. +

    -

    -Unfortunately there are many ways in which we can place a hyperplane +

    Unfortunately there are many ways in which we can place a hyperplane to divide the data. Below is an example of two candidate hyperplanes for our data sample. +

    -











    +

    Getting into the details

    -

    Getting into the details

    - -

    -Let us define the function +

    Let us define the function

    $$ f(x) = \boldsymbol{w}^T\boldsymbol{x}+b = 0, $$ -as the function that determines the line \( L \) that separates two classes (our two features), see the figure here. +

    as the function that determines the line \( L \) that separates two classes (our two features), see the figure here.

    -

    -Any point defined by \( \boldsymbol{x}_i \) and \( \boldsymbol{x}_2 \) on the line \( L \) will satisfy \( \boldsymbol{w}^T(\boldsymbol{x}_1-\boldsymbol{x}_2)=0 \). +

    Any point defined by \( \boldsymbol{x}_i \) and \( \boldsymbol{x}_2 \) on the line \( L \) will satisfy \( \boldsymbol{w}^T(\boldsymbol{x}_1-\boldsymbol{x}_2)=0 \).

    -

    -The signed distance \( \delta \) from any point defined by a vector \( \boldsymbol{x} \) and a point \( \boldsymbol{x}_0 \) on the line \( L \) is then +

    The signed distance \( \delta \) from any point defined by a vector \( \boldsymbol{x} \) and a point \( \boldsymbol{x}_0 \) on the line \( L \) is then

    $$ \delta = \frac{1}{\vert\vert \boldsymbol{w}\vert\vert}(\boldsymbol{w}^T\boldsymbol{x}+b). $$ -

    +









    +

    First attempt at a minimization approach

    -

    First attempt at a minimization approach

    - -

    -How do we find the parameter \( b \) and the vector \( \boldsymbol{w} \)? What we could +

    How do we find the parameter \( b \) and the vector \( \boldsymbol{w} \)? What we could do is to define a cost function which now contains the set of all misclassified points \( M \) and attempt to minimize this function +

    $$ C(\boldsymbol{w},b) = -\sum_{i\in M} y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b). $$ -

    -We could now for example define all values \( y_i =1 \) as misclassified in case we have \( \boldsymbol{w}^T\boldsymbol{x}_i+b < 0 \) and the opposite if we have \( y_i=-1 \). Taking the derivatives gives us +

    We could now for example define all values \( y_i =1 \) as misclassified in case we have \( \boldsymbol{w}^T\boldsymbol{x}_i+b < 0 \) and the opposite if we have \( y_i=-1 \). Taking the derivatives gives us

    $$ \frac{\partial C}{\partial b} = -\sum_{i\in M} y_i, $$ -and +

    and

    $$ \frac{\partial C}{\partial \boldsymbol{w}} = -\sum_{i\in M} y_ix_i. $$ -

    +









    +

    Solving the equations

    -

    Solving the equations

    - -

    -We can now use the Newton-Raphson method or different variants of the gradient descent family (from plain gradient descent to various stochastic gradient descent approaches) to solve the equations +

    We can now use the Newton-Raphson method or different variants of the gradient descent family (from plain gradient descent to various stochastic gradient descent approaches) to solve the equations

    $$ b \leftarrow b +\eta \frac{\partial C}{\partial b}, $$ -and +

    and

    $$ \boldsymbol{w} \leftarrow \boldsymbol{w} +\eta \frac{\partial C}{\partial \boldsymbol{w}}, $$ -where \( \eta \) is our by now well-known learning rate. +

    where \( \eta \) is our by now well-known learning rate.

    -











    +

    Code Example

    -

    Code Example

    - -

    -The equations we discussed above can be coded rather easily (the +

    The equations we discussed above can be coded rather easily (the framework is similar to what we developed for logistic regression). We are going to set up a simple case with two classes only and we want to find a line which separates them the best possible way. -

    +

    -
    
    -
    -

    +

    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +









    +

    Problems with the Simpler Approach

    -

    Problems with the Simpler Approach

    - -

    -There are however problems with this approach, although it looks +

    There are however problems with this approach, although it looks pretty straightforward to implement. When running the above code, we see that we can easily end up with many diffeent lines which separate the two classes. +

    -

    -For small +

    For small gaps between the entries, we may also end up needing many iterations before the solutions converge and if the data cannot be separated properly into two distinct classes, we may not experience a converge at all. +

    -











    +

    A better approach

    -

    A better approach

    - -

    -A better approach is rather to try to define a large margin between +

    A better approach is rather to try to define a large margin between the two classes (if they are well separated from the beginning). +

    -

    -Thus, we wish to find a margin \( M \) with \( \boldsymbol{w} \) normalized to +

    Thus, we wish to find a margin \( M \) with \( \boldsymbol{w} \) normalized to \( \vert\vert \boldsymbol{w}\vert\vert =1 \) subject to the condition +

    $$ y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) \geq M \hspace{0.1cm}\forall i=1,2,\dots, p. $$ -All points are thus at a signed distance from the decision boundary defined by the line \( L \). The parameters \( b \) and \( w_1 \) and \( w_2 \) define this line. +

    All points are thus at a signed distance from the decision boundary defined by the line \( L \). The parameters \( b \) and \( w_1 \) and \( w_2 \) define this line.

    -

    -We seek thus the largest value \( M \) defined by +

    We seek thus the largest value \( M \) defined by

    $$ \frac{1}{\vert \vert \boldsymbol{w}\vert\vert}y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) \geq M \hspace{0.1cm}\forall i=1,2,\dots, n, $$ -or just +

    or just

    $$ y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) \geq M\vert \vert \boldsymbol{w}\vert\vert \hspace{0.1cm}\forall i. $$ -If we scale the equation so that \( \vert \vert \boldsymbol{w}\vert\vert = 1/M \), we have to find the minimum of +

    If we scale the equation so that \( \vert \vert \boldsymbol{w}\vert\vert = 1/M \), we have to find the minimum of \( \boldsymbol{w}^T\boldsymbol{w}=\vert \vert \boldsymbol{w}\vert\vert \) (the norm) subject to the condition +

    $$ y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) \geq 1 \hspace{0.1cm}\forall i. $$ -

    -We have thus defined our margin as the invers of the norm of +

    We have thus defined our margin as the invers of the norm of \( \boldsymbol{w} \). We want to minimize the norm in order to have a as large as possible margin \( M \). Before we proceed, we need to remind ourselves about Lagrangian multipliers. +

    -











    +

    A quick Reminder on Lagrangian Multipliers

    -

    A quick Reminder on Lagrangian Multipliers

    - -

    -Consider a function of three independent variables \( f(x,y,z) \) . For the function \( f \) to be an +

    Consider a function of three independent variables \( f(x,y,z) \) . For the function \( f \) to be an extreme we have +

    $$ df=0. $$ -A necessary and sufficient condition is +

    A necessary and sufficient condition is

    $$ \frac{\partial f}{\partial x} =\frac{\partial f}{\partial y}=\frac{\partial f}{\partial z}=0, $$ -due to +

    due to

    $$ df = \frac{\partial f}{\partial x}dx+\frac{\partial f}{\partial y}dy+\frac{\partial f}{\partial z}dz. $$ -In many problems the variables \( x,y,z \) are often subject to constraints (such as those above for the margin) +

    In many problems the variables \( x,y,z \) are often subject to constraints (such as those above for the margin) so that they are no longer all independent. It is possible at least in principle to use each constraint to eliminate one variable and to proceed with a new and smaller set of independent varables. +

    -

    -The use of so-called Lagrangian multipliers is an alternative technique when the elimination +

    The use of so-called Lagrangian multipliers is an alternative technique when the elimination of variables is incovenient or undesirable. Assume that we have an equation of constraint on the variables \( x,y,z \) +

    $$ \phi(x,y,z) = 0, $$ - resulting in +

    resulting in

    $$ d\phi = \frac{\partial \phi}{\partial x}dx+\frac{\partial \phi}{\partial y}dy+\frac{\partial \phi}{\partial z}dz =0. $$ -Now we cannot set anymore +

    Now we cannot set anymore

    $$ \frac{\partial f}{\partial x} =\frac{\partial f}{\partial y}=\frac{\partial f}{\partial z}=0, $$ -if \( df=0 \) is wanted +

    if \( df=0 \) is wanted because there are now only two independent variables! Assume \( x \) and \( y \) are the independent variables. Then \( dz \) is no longer arbitrary. +

    -











    +

    Adding the Multiplier

    -

    Adding the Multiplier

    - -

    -However, we can add to +

    However, we can add to

    $$ df = \frac{\partial f}{\partial x}dx+\frac{\partial f}{\partial y}dy+\frac{\partial f}{\partial z}dz, $$ -a multiplum of \( d\phi \), viz. \( \lambda d\phi \), resulting in +

    a multiplum of \( d\phi \), viz. \( \lambda d\phi \), resulting in

    $$ df+\lambda d\phi = (\frac{\partial f}{\partial z}+\lambda \frac{\partial \phi}{\partial x})dx+(\frac{\partial f}{\partial y}+\lambda\frac{\partial \phi}{\partial y})dy+ (\frac{\partial f}{\partial z}+\lambda\frac{\partial \phi}{\partial z})dz =0. $$ -Our multiplier is chosen so that +

    Our multiplier is chosen so that

    $$ \frac{\partial f}{\partial z}+\lambda\frac{\partial \phi}{\partial z} =0. $$ -

    -We need to remember that we took \( dx \) and \( dy \) to be arbitrary and thus we must have +

    We need to remember that we took \( dx \) and \( dy \) to be arbitrary and thus we must have

    $$ \frac{\partial f}{\partial x}+\lambda\frac{\partial \phi}{\partial x} =0, $$ -and +

    and

    $$ \frac{\partial f}{\partial y}+\lambda\frac{\partial \phi}{\partial y} =0. $$ -When all these equations are satisfied, \( df=0 \). We have four unknowns, \( x,y,z \) and +

    When all these equations are satisfied, \( df=0 \). We have four unknowns, \( x,y,z \) and \( \lambda \). Actually we want only \( x,y,z \), \( \lambda \) needs not to be determined, it is therefore often called Lagrange's undetermined multiplier. If we have a set of constraints \( \phi_k \) we have the equations +

    $$ \frac{\partial f}{\partial x_i}+\sum_k\lambda_k\frac{\partial \phi_k}{\partial x_i} =0. $$ -

    -









    -

    Setting up the Problem

    -In order to solve the above problem, we define the following Lagrangian function to be minimized +









    +

    Setting up the Problem

    +

    In order to solve the above problem, we define the following Lagrangian function to be minimized

    $$ {\cal L}(\lambda,b,\boldsymbol{w})=\frac{1}{2}\boldsymbol{w}^T\boldsymbol{w}-\sum_{i=1}^n\lambda_i\left[y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)-1\right], $$ -where \( \lambda_i \) is a so-called Lagrange multiplier subject to the condition \( \lambda_i \geq 0 \). +

    where \( \lambda_i \) is a so-called Lagrange multiplier subject to the condition \( \lambda_i \geq 0 \).

    -

    -Taking the derivatives with respect to \( b \) and \( \boldsymbol{w} \) we obtain +

    Taking the derivatives with respect to \( b \) and \( \boldsymbol{w} \) we obtain

    $$ \frac{\partial {\cal L}}{\partial b} = -\sum_{i} \lambda_iy_i=0, $$ -and +

    and

    $$ \frac{\partial {\cal L}}{\partial \boldsymbol{w}} = 0 = \boldsymbol{w}-\sum_{i} \lambda_iy_i\boldsymbol{x}_i. $$ -Inserting these constraints into the equation for \( {\cal L} \) we obtain +

    Inserting these constraints into the equation for \( {\cal L} \) we obtain

    $$ {\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\boldsymbol{x}_i^T\boldsymbol{x}_j, $$ -subject to the constraints \( \lambda_i\geq 0 \) and \( \sum_i\lambda_iy_i=0 \). +

    subject to the constraints \( \lambda_i\geq 0 \) and \( \sum_i\lambda_iy_i=0 \). We must in addition satisfy the Karush-Kuhn-Tucker (KKT) condition +

    $$ \lambda_i\left[y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) -1\right] \hspace{0.1cm}\forall i. $$ -
    1. If \( \lambda_i > 0 \), then \( y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1 \) and we say that \( x_i \) is on the boundary.
    2. If \( y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)> 1 \), we say \( x_i \) is not on the boundary and we set \( \lambda_i=0 \).
    +

    When \( \lambda_i > 0 \), the vectors \( \boldsymbol{x}_i \) are called support vectors. They are the vectors closest to the line (or hyperplane) and define the margin \( M \).

    -When \( \lambda_i > 0 \), the vectors \( \boldsymbol{x}_i \) are called support vectors. They are the vectors closest to the line (or hyperplane) and define the margin \( M \). - -











    +

    The problem to solve

    -

    The problem to solve

    - -

    -We can rewrite +

    We can rewrite

    $$ {\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\boldsymbol{x}_i^T\boldsymbol{x}_j, $$ -and its constraints in terms of a matrix-vector problem where we minimize w.r.t. \( \lambda \) the following problem +

    and its constraints in terms of a matrix-vector problem where we minimize w.r.t. \( \lambda \) the following problem

    $$ \frac{1}{2} \boldsymbol{\lambda}^T\begin{bmatrix} y_1y_1\boldsymbol{x}_1^T\boldsymbol{x}_1 & y_1y_2\boldsymbol{x}_1^T\boldsymbol{x}_2 & \dots & \dots & y_1y_n\boldsymbol{x}_1^T\boldsymbol{x}_n \\ y_2y_1\boldsymbol{x}_2^T\boldsymbol{x}_1 & y_2y_2\boldsymbol{x}_2^T\boldsymbol{x}_2 & \dots & \dots & y_1y_n\boldsymbol{x}_2^T\boldsymbol{x}_n \\ @@ -660,119 +733,113 @@ y_ny_1\boldsymbol{x}_n^T\boldsymbol{x}_1 & y_ny_2\boldsymbol{x}_n^T\boldsymbol{x \end{bmatrix}\boldsymbol{\lambda}-\mathbb{1}\boldsymbol{\lambda}, $$ -subject to \( \boldsymbol{y}^T\boldsymbol{\lambda}=0 \). Here we defined the vectors \( \boldsymbol{\lambda} =[\lambda_1,\lambda_2,\dots,\lambda_n] \) and -\( \boldsymbol{y}=[y_1,y_2,\dots,y_n] \). +

    subject to \( \boldsymbol{y}^T\boldsymbol{\lambda}=0 \). Here we defined the vectors \( \boldsymbol{\lambda} =[\lambda_1,\lambda_2,\dots,\lambda_n] \) and +\( \boldsymbol{y}=[y_1,y_2,\dots,y_n] \). +

    -











    +

    The last steps

    -

    The last steps

    - -

    -Solving the above problem, yields the values of \( \lambda_i \). +

    Solving the above problem, yields the values of \( \lambda_i \). To find the coefficients of your hyperplane we need simply to compute +

    $$ \boldsymbol{w}=\sum_{i} \lambda_iy_i\boldsymbol{x}_i. $$ -With our vector \( \boldsymbol{w} \) we can in turn find the value of the intercept \( b \) (here in two dimensions) via +

    With our vector \( \boldsymbol{w} \) we can in turn find the value of the intercept \( b \) (here in two dimensions) via

    $$ y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1, $$ -resulting in +

    resulting in

    $$ b = \frac{1}{y_i}-\boldsymbol{w}^T\boldsymbol{x}_i, $$ -or if we write it out in terms of the support vectors only, with \( N_s \) being their number, we have +

    or if we write it out in terms of the support vectors only, with \( N_s \) being their number, we have

    $$ b = \frac{1}{N_s}\sum_{j\in N_s}\left(y_j-\sum_{i=1}^n\lambda_iy_i\boldsymbol{x}_i^T\boldsymbol{x}_j\right). $$ -With our hyperplane coefficients we can use our classifier to assign any observation by simply using +

    With our hyperplane coefficients we can use our classifier to assign any observation by simply using

    $$ y_i = \mathrm{sign}(\boldsymbol{w}^T\boldsymbol{x}_i+b). $$ -Below we discuss how to find the optimal values of \( \lambda_i \). Before we proceed however, we discuss now the so-called soft classifier. +

    Below we discuss how to find the optimal values of \( \lambda_i \). Before we proceed however, we discuss now the so-called soft classifier.

    -











    +

    A soft classifier

    -

    A soft classifier

    +

    Till now, the margin is strictly defined by the support vectors. This defines what is called a hard classifier, that is the margins are well defined.

    -

    -Till now, the margin is strictly defined by the support vectors. This defines what is called a hard classifier, that is the margins are well defined. - -

    -Suppose now that classes overlap in feature space, as shown in the +

    Suppose now that classes overlap in feature space, as shown in the figure here. One way to deal with this problem before we define the so-called kernel approach, is to allow a kind of slack in the sense that we allow some points to be on the wrong side of the margin. +

    -

    -We introduce thus the so-called slack variables \( \boldsymbol{\xi} =[\xi_1,x_2,\dots,x_n] \) and +

    We introduce thus the so-called slack variables \( \boldsymbol{\xi} =[\xi_1,x_2,\dots,x_n] \) and modify our previous equation +

    $$ y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1, $$ -to +

    to

    $$ y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1-\xi_i, $$ -with the requirement \( \xi_i\geq 0 \). The total violation is now \( \sum_i\xi \). +

    with the requirement \( \xi_i\geq 0 \). The total violation is now \( \sum_i\xi \). The value \( \xi_i \) in the constraint the last constraint corresponds to the amount by which the prediction \( y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1 \) is on the wrong side of its margin. Hence by bounding the sum \( \sum_i \xi_i \), we bound the total amount by which predictions fall on the wrong side of their margins. +

    -

    -Misclassifications occur when \( \xi_i > 1 \). Thus bounding the total sum by some value \( C \) bounds in turn the total number of +

    Misclassifications occur when \( \xi_i > 1 \). Thus bounding the total sum by some value \( C \) bounds in turn the total number of misclassifications. +

    -











    +

    Soft optmization problem

    -

    Soft optmization problem

    - -

    -This has in turn the consequences that we change our optmization problem to finding the minimum of +

    This has in turn the consequences that we change our optmization problem to finding the minimum of

    $$ {\cal L}=\frac{1}{2}\boldsymbol{w}^T\boldsymbol{w}-\sum_{i=1}^n\lambda_i\left[y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)-(1-\xi_)\right]+C\sum_{i=1}^n\xi_i-\sum_{i=1}^n\gamma_i\xi_i, $$ -subject to +

    subject to

    $$ y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1-\xi_i \hspace{0.1cm}\forall i, $$ -with the requirement \( \xi_i\geq 0 \). +

    with the requirement \( \xi_i\geq 0 \).

    -

    -Taking the derivatives with respect to \( b \) and \( \boldsymbol{w} \) we obtain +

    Taking the derivatives with respect to \( b \) and \( \boldsymbol{w} \) we obtain

    $$ \frac{\partial {\cal L}}{\partial b} = -\sum_{i} \lambda_iy_i=0, $$ -and +

    and

    $$ \frac{\partial {\cal L}}{\partial \boldsymbol{w}} = 0 = \boldsymbol{w}-\sum_{i} \lambda_iy_i\boldsymbol{x}_i, $$ -and +

    and

    $$ \lambda_i = C-\gamma_i \hspace{0.1cm}\forall i. $$ -Inserting these constraints into the equation for \( {\cal L} \) we obtain the same equation as before +

    Inserting these constraints into the equation for \( {\cal L} \) we obtain the same equation as before

    $$ {\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\boldsymbol{x}_i^T\boldsymbol{x}_j, $$ -but now subject to the constraints \( \lambda_i\geq 0 \), \( \sum_i\lambda_iy_i=0 \) and \( 0\leq\lambda_i \leq C \). +

    but now subject to the constraints \( \lambda_i\geq 0 \), \( \sum_i\lambda_iy_i=0 \) and \( 0\leq\lambda_i \leq C \). We must in addition satisfy the Karush-Kuhn-Tucker condition which now reads +

    $$ \lambda_i\left[y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) -(1-\xi_)\right]=0 \hspace{0.1cm}\forall i, $$ @@ -781,38 +848,41 @@ $$ \gamma_i\xi_i = 0, $$ -and +

    and

    $$ y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) -(1-\xi_) \geq 0 \hspace{0.1cm}\forall i. $$ -

    +









    +

    Kernels and non-linearity

    -

    Kernels and non-linearity

    - -

    -The cases we have studied till now, were all characterized by two classes +

    The cases we have studied till now, 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 +

    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. +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 +

    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. +

    -

    -

    import numpy as np
    +
    +
    +
    +
    +
    +
    import numpy as np
     import os
     
     np.random.seed(42)
    @@ -858,62 +928,72 @@ plt.plot([-4.5, 4.5, 4.5, -1, 17])
     plt.subplots_adjust(right=1)
     plt.show()
    -
    -

    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    The equations

    -

    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) +

    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)

    $$ z = \phi(x_i) =\left(x_i^2, y_i^2, \sqrt{2}x_iy_i\right). $$ -

    -With our new basis, the equations we solved earlier are basically the same, that is we have now (without the slack option for simplicity) +

    With our new basis, the equations we solved earlier are basically the same, that is we have now (without the slack option for simplicity)

    $$ {\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\boldsymbol{z}_i^T\boldsymbol{z}_j, $$ -subject to the constraints \( \lambda_i\geq 0 \), \( \sum_i\lambda_iy_i=0 \), and for the support vectors +

    subject to the constraints \( \lambda_i\geq 0 \), \( \sum_i\lambda_iy_i=0 \), and for the support vectors

    $$ y_i(\boldsymbol{w}^T\boldsymbol{z}_i+b)= 1 \hspace{0.1cm}\forall i, $$ -from which we also find \( b \). +

    from which we also find \( b \). To compute \( \boldsymbol{z}_i^T\boldsymbol{z}_j \) we define the kernel \( K(\boldsymbol{x}_i,\boldsymbol{x}_j) \) as +

    $$ K(\boldsymbol{x}_i,\boldsymbol{x}_j)=\boldsymbol{z}_i^T\boldsymbol{z}_j= \phi(\boldsymbol{x}_i)^T\phi(\boldsymbol{x}_j). $$ -For the above example, the kernel reads +

    For the above example, the kernel reads

    $$ K(\boldsymbol{x}_i,\boldsymbol{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. $$ -

    -We note that this is nothing but the dot product of the two original +

    We note that this is nothing but the dot product of the two original vectors \( (\boldsymbol{x}_i^T\boldsymbol{x}_j)^2 \). Instead of thus computing the product in the Lagrangian of \( \boldsymbol{z}_i^T\boldsymbol{z}_j \) we simply compute the dot product \( (\boldsymbol{x}_i^T\boldsymbol{x}_j)^2 \). +

    -

    -This leads to the so-called +

    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(\boldsymbol{x}_i)^T\phi(\boldsymbol{x}_j) \) during the SVM calculations. +

    -











    - -

    The problem to solve

    -Using our definition of the kernel We can rewrite again the Lagrangian +

    The problem to solve

    +

    Using our definition of the kernel We can rewrite again the Lagrangian

    $$ {\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\boldsymbol{x}_i^T\boldsymbol{z}_j, $$ -subject to the constraints \( \lambda_i\geq 0 \), \( \sum_i\lambda_iy_i=0 \) in terms of a convex optimization problem +

    subject to the constraints \( \lambda_i\geq 0 \), \( \sum_i\lambda_iy_i=0 \) in terms of a convex optimization problem

    $$ \frac{1}{2} \boldsymbol{\lambda}^T\begin{bmatrix} y_1y_1K(\boldsymbol{x}_1,\boldsymbol{x}_1) & y_1y_2K(\boldsymbol{x}_1,\boldsymbol{x}_2) & \dots & \dots & y_1y_nK(\boldsymbol{x}_1,\boldsymbol{x}_n) \\ y_2y_1K(\boldsymbol{x}_2,\boldsymbol{x}_1) & y_2y_2(\boldsymbol{x}_2,\boldsymbol{x}_2) & \dots & \dots & y_1y_nK(\boldsymbol{x}_2,\boldsymbol{x}_n) \\ @@ -923,12 +1003,12 @@ y_ny_1K(\boldsymbol{x}_n,\boldsymbol{x}_1) & y_ny_2K(\boldsymbol{x}_n\boldsymbol \end{bmatrix}\boldsymbol{\lambda}-\mathbb{1}\boldsymbol{\lambda}, $$ -subject to \( \boldsymbol{y}^T\boldsymbol{\lambda}=0 \). Here we defined the vectors \( \boldsymbol{\lambda} =[\lambda_1,\lambda_2,\dots,\lambda_n] \) and +

    subject to \( \boldsymbol{y}^T\boldsymbol{\lambda}=0 \). Here we defined the vectors \( \boldsymbol{\lambda} =[\lambda_1,\lambda_2,\dots,\lambda_n] \) and \( \boldsymbol{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 +

    We can rewrite this (see the solutions below) in terms of a convex optimization problem of the type

    $$ \begin{align*} &\mathrm{min}_{\lambda}\hspace{0.2cm} \frac{1}{2}\boldsymbol{\lambda}^T\boldsymbol{P}\boldsymbol{\lambda}+\boldsymbol{q}^T\boldsymbol{\lambda},\\ \nonumber @@ -936,56 +1016,54 @@ $$ \end{align*} $$ -Below we discuss how to solve these equations. Here we note that the matrix \( \boldsymbol{P} \) has matrix elements \( p_{ij}=y_iy_jK(\boldsymbol{x}_i,\boldsymbol{x}_j) \). +

    Below we discuss how to solve these equations. Here we note that the matrix \( \boldsymbol{P} \) has matrix elements \( p_{ij}=y_iy_jK(\boldsymbol{x}_i,\boldsymbol{x}_j) \). Given a kernel \( K \) and the targets \( y_i \) this matrix is easy to set up. The constraint \( \boldsymbol{y}^T\boldsymbol{\lambda}=0 \) leads to \( f=0 \) and \( \boldsymbol{A}=\boldsymbol{y} \). How to set up the matrix \( \boldsymbol{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 \( \boldsymbol{G} \) and the vector \( \boldsymbol{h} \). +

    -











    +

    Different kernels and Mercer's theorem

    -

    Different kernels and Mercer's theorem

    - -

    -There are several popular kernels being used. These are - +

    There are several popular kernels being used. These are

    1. Linear: \( K(\boldsymbol{x},\boldsymbol{y})=\boldsymbol{x}^T\boldsymbol{y} \),
    2. Polynomial: \( K(\boldsymbol{x},\boldsymbol{y})=(\boldsymbol{x}^T\boldsymbol{y}+\gamma)^d \),
    3. Gaussian Radial Basis Function: \( K(\boldsymbol{x},\boldsymbol{y})=\exp{\left(-\gamma\vert\vert\boldsymbol{x}-\boldsymbol{y}\vert\vert^2\right)} \),
    4. Tanh: \( K(\boldsymbol{x},\boldsymbol{y})=\tanh{(\boldsymbol{x}^T\boldsymbol{y}+\gamma)} \),
    +

    and many other ones.

    -and many other ones. - -

    -An important theorem for us is Mercer's +

    An important theorem for us is Mercer's theorem. The theorem states that if a kernel function \( K \) is symmetric, continuous and leads to a positive semi-definite matrix \( \boldsymbol{P} \) then there exists a function \( \phi \) that maps \( \boldsymbol{x}_i \) and \( \boldsymbol{x}_j \) into another space (possibly with much higher dimensions) such that +

    $$ K(\boldsymbol{x}_i,\boldsymbol{x}_j)=\phi(\boldsymbol{x}_i)^T\phi(\boldsymbol{x}_j). $$ -

    -So you can use \( K \) as a kernel since you know \( \phi \) exists, even if -you don’t know what \( \phi \) is. +

    So you can use \( K \) as a kernel since you know \( \phi \) exists, even if +you don’t know what \( \phi \) is. +

    -

    -Note that some frequently used kernels (such as the Sigmoid kernel) +

    Note that some frequently used kernels (such as the Sigmoid kernel) don’t respect all of Mercer’s conditions, yet they generally work well in practice. +

    -











    - -

    The moons example

    -

    +

    The moons example

    -
    from __future__ import division, print_function, unicode_literals
    +
    +
    +
    +
    +
    +
    from __future__ import division, print_function, unicode_literals
     
     import numpy as np
     np.random.seed(42)
    @@ -1173,14 +1251,26 @@ plt.figure(figsize=(11, r"$\gamma = {}, C = {}$".format(gamma, C), fontsize=16)
     
     plt.show()
    -
    -

    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    Mathematical optimization of convex functions

    -

    Mathematical optimization of convex functions

    - -

    -A mathematical (quadratic) optimization problem, or just optimization problem, has the form +

    A mathematical (quadratic) optimization problem, or just optimization problem, has the form

    $$ \begin{align*} &\mathrm{min}_{\lambda}\hspace{0.2cm} \frac{1}{2}\boldsymbol{\lambda}^T\boldsymbol{P}\boldsymbol{\lambda}+\boldsymbol{q}^T\boldsymbol{\lambda},\\ \nonumber @@ -1188,50 +1278,61 @@ $$ \end{align*} $$ -subject to some constraints for say a selected set \( i=1,2,\dots, n \). +

    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 \( \boldsymbol{\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. +

    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. +

    Convex optimization problems play a central role in applied mathematics and we recommend strongly Boyd and Vandenberghe's text on the topics.

    -











    +

    How do we solve these problems?

    -

    How do we solve these problems?

    - -

    -If we use Python as programming language and wish to venture beyond +

    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 +

    The functions we need are contained in the quadratic programming package CVXOPT and we need to import it together with numpy as

    -

    -

    import numpy
    +
    +
    +
    +
    +
    +
    import numpy
     import cvxopt
    -
    -

    -This will make our life much easier. You don't need t write your own optimizer. +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    This will make our life much easier. You don't need t write your own optimizer.

    -











    +

    A simple example

    -

    A simple example

    - -

    -We remind ourselves about the general problem we want to solve +

    We remind ourselves about the general problem we want to solve

    $$ \begin{align*} &\mathrm{min}_{x}\hspace{0.2cm} \frac{1}{2}\boldsymbol{x}^T\boldsymbol{P}\boldsymbol{x}+\boldsymbol{q}^T\boldsymbol{x},\\ \nonumber @@ -1239,8 +1340,7 @@ $$ \end{align*} $$ -

    -Let us show how to perform the optmization using a simple case. Assume we want to optimize the following problem +

    Let us show how to perform the optmization using a simple case. Assume we want to optimize the following problem

    $$ \begin{align*} &\mathrm{min}_{x}\hspace{0.2cm} \frac{1}{2}x^2+5x+3y \\ \nonumber @@ -1252,34 +1352,39 @@ $$ \end{align*} $$ -The minimization problem can be rewritten in terms of vectors and matrices as (with \( x \) and \( y \) being the unknowns) +

    The minimization problem can be rewritten in terms of vectors and matrices as (with \( x \) and \( y \) being the unknowns)

    $$ \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}. $$ -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 +

    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

    $$ \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}. $$ -We have collapsed all the inequalities into a single matrix \( \boldsymbol{G} \). We see also that our matrix +

    We have collapsed all the inequalities into a single matrix \( \boldsymbol{G} \). We see also that our matrix

    $$ \boldsymbol{P} =\begin{bmatrix} 1 & 0\\ 0 & 0 \end{bmatrix} $$ -is clearly positive semi-definite (all eigenvalues larger or equal zero). +

    is clearly positive semi-definite (all eigenvalues larger or equal zero). Finally, the vector \( \boldsymbol{h} \) is defined as +

    $$ \boldsymbol{h} = \begin{bmatrix}0 \\ 0\\ -15 \\ 100 \\ 80\end{bmatrix}. $$ -

    -Since we don't have any equalities the matrix \( \boldsymbol{A} \) is set to zero +

    Since we don't have any equalities the matrix \( \boldsymbol{A} \) is set to zero The following code solves the equations for us -

    +

    -
    # Import the necessary packages
    +
    +
    +
    +
    +
    +
    # Import the necessary packages
     import numpy
     from cvxopt import matrix
     from cvxopt import solvers
    @@ -1292,14 +1397,26 @@ sol = solvers.qp(P,q,G,h)
     # Extract optimal value and solution
     sol[x] 
     sol[primal objective]
    -
    -

    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    Back to the more realistic cases

    -

    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 +

    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

    $$ \frac{1}{2} \boldsymbol{\lambda}^T\begin{bmatrix} y_1y_1K(\boldsymbol{x}_1,\boldsymbol{x}_1) & y_1y_2K(\boldsymbol{x}_1,\boldsymbol{x}_2) & \dots & \dots & y_1y_nK(\boldsymbol{x}_1,\boldsymbol{x}_n) \\ y_2y_1K(\boldsymbol{x}_2,\boldsymbol{x}_1) & y_2y_2K(\boldsymbol{x}_2,\boldsymbol{x}_2) & \dots & \dots & y_1y_nK(\boldsymbol{x}_2,\boldsymbol{x}_n) \\ @@ -1309,24 +1426,17 @@ y_ny_1K(\boldsymbol{x}_n,\boldsymbol{x}_1) & y_ny_2K(\boldsymbol{x}_n\boldsymbol \end{bmatrix}\boldsymbol{\lambda}-\mathbb{I}\boldsymbol{\lambda}, $$ -subject to \( \boldsymbol{y}^T\boldsymbol{\lambda}=0 \). Here we defined the vectors \( \boldsymbol{\lambda} =[\lambda_1,\lambda_2,\dots,\lambda_n] \) and +

    subject to \( \boldsymbol{y}^T\boldsymbol{\lambda}=0 \). Here we defined the vectors \( \boldsymbol{\lambda} =[\lambda_1,\lambda_2,\dots,\lambda_n] \) and \( \boldsymbol{y}=[y_1,y_2,\dots,y_n] \). With the slack constants this leads to the additional constraint \( 0\leq \lambda_i \leq C \). +

    -

    code will be added -

    - - -

    - © 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license + © 1999-2021, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
    - - - diff --git a/doc/pub/week46/html/week46.html b/doc/pub/week46/html/week46.html index 0110087bd..96ed4fddf 100644 --- a/doc/pub/week46/html/week46.html +++ b/doc/pub/week46/html/week46.html @@ -1,81 +1,204 @@ - + - - -Week 46: Gradient Boosting Summary and Support Vector Machines - - + +Week 46: Support Vector Machines and Project 3 - - @@ -95,118 +218,135 @@ MathJax.Hub.Config({ - - +
    +

    Week 46: Support Vector Machines and Project 3

    +
    - - -

    Week 46: Gradient Boosting Summary and Support Vector Machines

    - -

    -

    Morten Hjorth-Jensen [1, 2]
    - -

    +

    +[1] Department of Physics, University of Oslo +
    +
    +[2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University +
    +
    +
    +

    Nov 14, 2021

    +
    +
    -
    [1] Department of Physics, University of Oslo
    -
    [2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University
    -
    -

    -

    Nov 12, 2020

    -
    -











    - -

    Overview of week 46

    +

    Overview of week 46

      -
    • Thursday: Summary of Gradient Boosting and further examples of applications, from the physical sciences to the social sciences. Guest lecture by John M. Aiken on Gradient Boosting and XGboost.
    • -
    • Friday: Support Vector Machines, classification and regression.
    • +
    • Thursday: Summary of Gradient Boosting with selected examples. Start support Vector Machines
    • +
    • Friday: Eventual Workshop on project 3. Discussion of project 3.
    +Note that on Thursday we will have only one lecture, from 1215pm to 1pm. There is no session 115pm-2pm. -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. - +
    +Reading

    -See overview video on Support Vector Machines. See also this video. +

    Reading recommendations:

    +
      +
    1. See lecture notes for week 46 at https://compphysics.github.io/MachineLearning/doc/web/course.html.
    2. +
    3. Hastie et al chapter 12
    4. +
    5. Bishop chapter 7.1 and 7.2
    6. +
    +
    + + + +









    +

    Friday

    -

    Thursday

    +

    Last year we had a very interesting workshop with many presentations. These were (program 2020)

    -

    -The first lecture on Thursday is devoted to a summary from last week, with additional examples. This material is included in the lectures from week 45, see also Hastie et al. chapter 10.1-10.10. +

      +
    • Maria Emine Nylund: Lego Bricks Classifier
    • +
    • Fabio Rodrigues Pereira: Financial Machine Learning
    • +
    • Markus Borud Pettersen: Machine Learning and Brain Grid Cells
    • +
    • Jing Sun and Endrias Getachew Asgedom: Machine learning-based approaches to denoising microseismic data
    • +
    • Felicia Jacobsen: Analysis of Breast Cancer Data
    • +
    • Simon Elias Schrader: Predicting atomization energies of molecules
    • +
    • Varvara Bazilova and Sergio Andres Diaz Mesa: Glacier Mapping and Machine Learning
    • +
    • Gert Werner Kluge, Hanna Alida Fossen Hardersen and Sushma Sharma Adhikari: Gamma ray signals stemming from dark matter in the galactic center
    • +
    +

    We wish to organize something similar this coming Friday. The presentation last typically 5-10 minutes (some 3-5 slides) with time for questions afterwards. +Feel free to suggest topics. +

    -

    -The second letter will be given by John M. Aiken, who recently defended his thesis on machine learning, and in particular using boosting methods, to data from the social sciences and science education. +

    The program will be available asap. It depends on input from you!

    -











    +

    Support Vector Machines, overarching aims

    -

    Friday

    - -

    -We start with a new topic and second-last topic covered in this course, support vector machines (SVM). - -

    -









    - -

    Support Vector Machines, overarching aims

    - -

    -A Support Vector Machine (SVM) is a very powerful and versatile +

    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. +medium-sized datasets. +

    -

    -The case with two well-separated classes only can be understood in an +

    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 (see figure below). +

    -

    -The basic mathematics behind the SVM is however less familiar to most of us. +

    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. +

    -

    -With SVMs we distinguish between hard margin and soft margins. The +

    With SVMs we distinguish between hard margin and soft margins. The latter introduces a so-called softening parameter to be discussed below. We distinguish also between linear and non-linear approaches. The latter are the most frequent ones since it is rather unlikely that we can separate classes easily by say straight lines. +

    -











    +

    Hyperplanes and all that

    -

    Hyperplanes and all that

    - -

    -The theory behind support vector machines (SVM hereafter) is based on +

    The theory behind support vector machines (SVM hereafter) is based on the mathematical description of so-called hyperplanes. Let us start with a two-dimensional case. This will also allow us to introduce our first SVM examples. These will be tailored to the case of two specific classes, as displayed in the figure here based on the usage of the petal data. +

    -

    -We assume here that our data set can be well separated into two +

    We assume here that our data set can be well separated into two domains, where a straight line does the job in the separating the two classes. Here the two classes are represented by either squares or circles. -

    +

    -
    from sklearn import datasets
    +
    +
    +
    +
    +
    +
    from sklearn import datasets
     from sklearn.svm import SVC, LinearSVC
     from sklearn.linear_model import SGDClassifier
     from sklearn.preprocessing import StandardScaler
    @@ -272,87 +412,96 @@ plt.legend(loc=
     plt.axis([0, 5.5, 0, 2])
     
     plt.show()
    -
    -

    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    What is a hyperplane?

    -

    What is a hyperplane?

    - -

    -The aim of the SVM algorithm is to find a hyperplane in a +

    The aim of the SVM algorithm is to find a hyperplane in a \( p \)-dimensional space, where \( p \) is the number of features that distinctly classifies the data points. +

    -

    -In a \( p \)-dimensional space, a hyperplane is what we call an affine subspace of dimension of \( p-1 \). +

    In a \( p \)-dimensional space, a hyperplane is what we call an affine subspace of dimension of \( p-1 \). As an example, in two dimension, a hyperplane is simply as straight line while in three dimensions it is -a two-dimensional subspace, or stated simply, a plane. +a two-dimensional subspace, or stated simply, a plane. +

    -

    -In two dimensions, with the variables \( x_1 \) and \( x_2 \), the hyperplane is defined as +

    In two dimensions, with the variables \( x_1 \) and \( x_2 \), the hyperplane is defined as

    $$ b+w_1x_1+w_2x_2=0, $$ -

    -where \( b \) is the intercept and \( w_1 \) and \( w_2 \) define the elements of a vector orthogonal to the line +

    where \( b \) is the intercept and \( w_1 \) and \( w_2 \) define the elements of a vector orthogonal to the line \( b+w_1x_1+w_2x_2=0 \). In two dimensions we define the vectors \( \boldsymbol{x} =[x1,x2] \) and \( \boldsymbol{w}=[w1,w2] \). We can then rewrite the above equation as +

    $$ \boldsymbol{x}^T\boldsymbol{w}+b=0. $$ -

    +









    +

    A \( p \)-dimensional space of features

    -

    A \( p \)-dimensional space of features

    - -

    -We limit ourselves to two classes of outputs \( y_i \) and assign these classes the values \( y_i = \pm 1 \). +

    We limit ourselves to two classes of outputs \( y_i \) and assign these classes the values \( y_i = \pm 1 \). In a \( p \)-dimensional space of say \( p \) features we have a hyperplane defines as +

    $$ b+wx_1+w_2x_2+\dots +w_px_p=0. $$ -If we define a +

    If we define a matrix \( \boldsymbol{X}=\left[\boldsymbol{x}_1,\boldsymbol{x}_2,\dots, \boldsymbol{x}_p\right] \) of dimension \( n\times p \), where \( n \) represents the observations for each feature and each vector \( x_i \) is a column vector of the matrix \( \boldsymbol{X} \), +

    $$ \boldsymbol{x}_i = \begin{bmatrix} x_{i1} \\ x_{i2} \\ \dots \\ \dots \\ x_{ip} \end{bmatrix}. $$ -If the above condition is not met for a given vector \( \boldsymbol{x}_i \) we have +

    If the above condition is not met for a given vector \( \boldsymbol{x}_i \) we have

    $$ b+w_1x_{i1}+w_2x_{i2}+\dots +w_px_{ip} >0, $$ -if our output \( y_i=1 \). +

    if our output \( y_i=1 \). In this case we say that \( \boldsymbol{x}_i \) lies on one of the sides of the hyperplane and if +

    $$ b+w_1x_{i1}+w_2x_{i2}+\dots +w_px_{ip} < 0, $$ -for the class of observations \( y_i=-1 \), -then \( \boldsymbol{x}_i \) lies on the other side. +

    for the class of observations \( y_i=-1 \), +then \( \boldsymbol{x}_i \) lies on the other side. +

    -

    -Equivalently, for the two classes of observations we have +

    Equivalently, for the two classes of observations we have

    $$ y_i\left(b+w_1x_{i1}+w_2x_{i2}+\dots +w_px_{ip}\right) > 0. $$ -

    -When we try to separate hyperplanes, if it exists, we can use it to construct a natural classifier: a test observation is assigned a given class depending on which side of the hyperplane it is located. +

    When we try to separate hyperplanes, if it exists, we can use it to construct a natural classifier: a test observation is assigned a given class depending on which side of the hyperplane it is located.

    -

    +

    The two-dimensional case

    -

    The two-dimensional case

    - -

    -Let us try to develop our intuition about SVMs by limiting ourselves to a two-dimensional +

    Let us try to develop our intuition about SVMs by limiting ourselves to a two-dimensional plane. To separate the two classes of data points, there are many possible lines (hyperplanes if you prefer a more strict naming) that could be chosen. Our objective is to find a @@ -360,302 +509,298 @@ plane that has the maximum margin, i.e the maximum distance between data points of both classes. Maximizing the margin distance provides some reinforcement so that future data points can be classified with more confidence. +

    -

    -What a linear classifier attempts to accomplish is to split the +

    What a linear classifier attempts to accomplish is to split the feature space into two half spaces by placing a hyperplane between the data points. This hyperplane will be our decision boundary. All points on one side of the plane will belong to class one and all points on the other side of the plane will belong to the second class two. +

    -

    -Unfortunately there are many ways in which we can place a hyperplane +

    Unfortunately there are many ways in which we can place a hyperplane to divide the data. Below is an example of two candidate hyperplanes for our data sample. +

    -











    +

    Getting into the details

    -

    Getting into the details

    - -

    -Let us define the function +

    Let us define the function

    $$ f(x) = \boldsymbol{w}^T\boldsymbol{x}+b = 0, $$ -as the function that determines the line \( L \) that separates two classes (our two features), see the figure here. +

    as the function that determines the line \( L \) that separates two classes (our two features), see the figure here.

    -

    -Any point defined by \( \boldsymbol{x}_i \) and \( \boldsymbol{x}_2 \) on the line \( L \) will satisfy \( \boldsymbol{w}^T(\boldsymbol{x}_1-\boldsymbol{x}_2)=0 \). +

    Any point defined by \( \boldsymbol{x}_i \) and \( \boldsymbol{x}_2 \) on the line \( L \) will satisfy \( \boldsymbol{w}^T(\boldsymbol{x}_1-\boldsymbol{x}_2)=0 \).

    -

    -The signed distance \( \delta \) from any point defined by a vector \( \boldsymbol{x} \) and a point \( \boldsymbol{x}_0 \) on the line \( L \) is then +

    The signed distance \( \delta \) from any point defined by a vector \( \boldsymbol{x} \) and a point \( \boldsymbol{x}_0 \) on the line \( L \) is then

    $$ \delta = \frac{1}{\vert\vert \boldsymbol{w}\vert\vert}(\boldsymbol{w}^T\boldsymbol{x}+b). $$ -

    +









    +

    First attempt at a minimization approach

    -

    First attempt at a minimization approach

    - -

    -How do we find the parameter \( b \) and the vector \( \boldsymbol{w} \)? What we could +

    How do we find the parameter \( b \) and the vector \( \boldsymbol{w} \)? What we could do is to define a cost function which now contains the set of all misclassified points \( M \) and attempt to minimize this function +

    $$ C(\boldsymbol{w},b) = -\sum_{i\in M} y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b). $$ -

    -We could now for example define all values \( y_i =1 \) as misclassified in case we have \( \boldsymbol{w}^T\boldsymbol{x}_i+b < 0 \) and the opposite if we have \( y_i=-1 \). Taking the derivatives gives us +

    We could now for example define all values \( y_i =1 \) as misclassified in case we have \( \boldsymbol{w}^T\boldsymbol{x}_i+b < 0 \) and the opposite if we have \( y_i=-1 \). Taking the derivatives gives us

    $$ \frac{\partial C}{\partial b} = -\sum_{i\in M} y_i, $$ -and +

    and

    $$ \frac{\partial C}{\partial \boldsymbol{w}} = -\sum_{i\in M} y_ix_i. $$ -

    +









    +

    Solving the equations

    -

    Solving the equations

    - -

    -We can now use the Newton-Raphson method or different variants of the gradient descent family (from plain gradient descent to various stochastic gradient descent approaches) to solve the equations +

    We can now use the Newton-Raphson method or different variants of the gradient descent family (from plain gradient descent to various stochastic gradient descent approaches) to solve the equations

    $$ b \leftarrow b +\eta \frac{\partial C}{\partial b}, $$ -and +

    and

    $$ \boldsymbol{w} \leftarrow \boldsymbol{w} +\eta \frac{\partial C}{\partial \boldsymbol{w}}, $$ -where \( \eta \) is our by now well-known learning rate. +

    where \( \eta \) is our by now well-known learning rate.

    -











    +

    Code Example

    -

    Code Example

    - -

    -The equations we discussed above can be coded rather easily (the +

    The equations we discussed above can be coded rather easily (the framework is similar to what we developed for logistic regression). We are going to set up a simple case with two classes only and we want to find a line which separates them the best possible way. -

    +

    -
    
    -
    -

    +

    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +









    +

    Problems with the Simpler Approach

    -

    Problems with the Simpler Approach

    - -

    -There are however problems with this approach, although it looks +

    There are however problems with this approach, although it looks pretty straightforward to implement. When running the above code, we see that we can easily end up with many diffeent lines which separate the two classes. +

    -

    -For small +

    For small gaps between the entries, we may also end up needing many iterations before the solutions converge and if the data cannot be separated properly into two distinct classes, we may not experience a converge at all. +

    -











    +

    A better approach

    -

    A better approach

    - -

    -A better approach is rather to try to define a large margin between +

    A better approach is rather to try to define a large margin between the two classes (if they are well separated from the beginning). +

    -

    -Thus, we wish to find a margin \( M \) with \( \boldsymbol{w} \) normalized to +

    Thus, we wish to find a margin \( M \) with \( \boldsymbol{w} \) normalized to \( \vert\vert \boldsymbol{w}\vert\vert =1 \) subject to the condition +

    $$ y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) \geq M \hspace{0.1cm}\forall i=1,2,\dots, p. $$ -All points are thus at a signed distance from the decision boundary defined by the line \( L \). The parameters \( b \) and \( w_1 \) and \( w_2 \) define this line. +

    All points are thus at a signed distance from the decision boundary defined by the line \( L \). The parameters \( b \) and \( w_1 \) and \( w_2 \) define this line.

    -

    -We seek thus the largest value \( M \) defined by +

    We seek thus the largest value \( M \) defined by

    $$ \frac{1}{\vert \vert \boldsymbol{w}\vert\vert}y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) \geq M \hspace{0.1cm}\forall i=1,2,\dots, n, $$ -or just +

    or just

    $$ y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) \geq M\vert \vert \boldsymbol{w}\vert\vert \hspace{0.1cm}\forall i. $$ -If we scale the equation so that \( \vert \vert \boldsymbol{w}\vert\vert = 1/M \), we have to find the minimum of +

    If we scale the equation so that \( \vert \vert \boldsymbol{w}\vert\vert = 1/M \), we have to find the minimum of \( \boldsymbol{w}^T\boldsymbol{w}=\vert \vert \boldsymbol{w}\vert\vert \) (the norm) subject to the condition +

    $$ y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) \geq 1 \hspace{0.1cm}\forall i. $$ -

    -We have thus defined our margin as the invers of the norm of +

    We have thus defined our margin as the invers of the norm of \( \boldsymbol{w} \). We want to minimize the norm in order to have a as large as possible margin \( M \). Before we proceed, we need to remind ourselves about Lagrangian multipliers. +

    -











    +

    A quick Reminder on Lagrangian Multipliers

    -

    A quick Reminder on Lagrangian Multipliers

    - -

    -Consider a function of three independent variables \( f(x,y,z) \) . For the function \( f \) to be an +

    Consider a function of three independent variables \( f(x,y,z) \) . For the function \( f \) to be an extreme we have +

    $$ df=0. $$ -A necessary and sufficient condition is +

    A necessary and sufficient condition is

    $$ \frac{\partial f}{\partial x} =\frac{\partial f}{\partial y}=\frac{\partial f}{\partial z}=0, $$ -due to +

    due to

    $$ df = \frac{\partial f}{\partial x}dx+\frac{\partial f}{\partial y}dy+\frac{\partial f}{\partial z}dz. $$ -In many problems the variables \( x,y,z \) are often subject to constraints (such as those above for the margin) +

    In many problems the variables \( x,y,z \) are often subject to constraints (such as those above for the margin) so that they are no longer all independent. It is possible at least in principle to use each constraint to eliminate one variable and to proceed with a new and smaller set of independent varables. +

    -

    -The use of so-called Lagrangian multipliers is an alternative technique when the elimination +

    The use of so-called Lagrangian multipliers is an alternative technique when the elimination of variables is incovenient or undesirable. Assume that we have an equation of constraint on the variables \( x,y,z \) +

    $$ \phi(x,y,z) = 0, $$ - resulting in +

    resulting in

    $$ d\phi = \frac{\partial \phi}{\partial x}dx+\frac{\partial \phi}{\partial y}dy+\frac{\partial \phi}{\partial z}dz =0. $$ -Now we cannot set anymore +

    Now we cannot set anymore

    $$ \frac{\partial f}{\partial x} =\frac{\partial f}{\partial y}=\frac{\partial f}{\partial z}=0, $$ -if \( df=0 \) is wanted +

    if \( df=0 \) is wanted because there are now only two independent variables! Assume \( x \) and \( y \) are the independent variables. Then \( dz \) is no longer arbitrary. +

    -











    +

    Adding the Multiplier

    -

    Adding the Multiplier

    - -

    -However, we can add to +

    However, we can add to

    $$ df = \frac{\partial f}{\partial x}dx+\frac{\partial f}{\partial y}dy+\frac{\partial f}{\partial z}dz, $$ -a multiplum of \( d\phi \), viz. \( \lambda d\phi \), resulting in +

    a multiplum of \( d\phi \), viz. \( \lambda d\phi \), resulting in

    $$ df+\lambda d\phi = (\frac{\partial f}{\partial z}+\lambda \frac{\partial \phi}{\partial x})dx+(\frac{\partial f}{\partial y}+\lambda\frac{\partial \phi}{\partial y})dy+ (\frac{\partial f}{\partial z}+\lambda\frac{\partial \phi}{\partial z})dz =0. $$ -Our multiplier is chosen so that +

    Our multiplier is chosen so that

    $$ \frac{\partial f}{\partial z}+\lambda\frac{\partial \phi}{\partial z} =0. $$ -

    -We need to remember that we took \( dx \) and \( dy \) to be arbitrary and thus we must have +

    We need to remember that we took \( dx \) and \( dy \) to be arbitrary and thus we must have

    $$ \frac{\partial f}{\partial x}+\lambda\frac{\partial \phi}{\partial x} =0, $$ -and +

    and

    $$ \frac{\partial f}{\partial y}+\lambda\frac{\partial \phi}{\partial y} =0. $$ -When all these equations are satisfied, \( df=0 \). We have four unknowns, \( x,y,z \) and +

    When all these equations are satisfied, \( df=0 \). We have four unknowns, \( x,y,z \) and \( \lambda \). Actually we want only \( x,y,z \), \( \lambda \) needs not to be determined, it is therefore often called Lagrange's undetermined multiplier. If we have a set of constraints \( \phi_k \) we have the equations +

    $$ \frac{\partial f}{\partial x_i}+\sum_k\lambda_k\frac{\partial \phi_k}{\partial x_i} =0. $$ -

    -









    -

    Setting up the Problem

    -In order to solve the above problem, we define the following Lagrangian function to be minimized +









    +

    Setting up the Problem

    +

    In order to solve the above problem, we define the following Lagrangian function to be minimized

    $$ {\cal L}(\lambda,b,\boldsymbol{w})=\frac{1}{2}\boldsymbol{w}^T\boldsymbol{w}-\sum_{i=1}^n\lambda_i\left[y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)-1\right], $$ -where \( \lambda_i \) is a so-called Lagrange multiplier subject to the condition \( \lambda_i \geq 0 \). +

    where \( \lambda_i \) is a so-called Lagrange multiplier subject to the condition \( \lambda_i \geq 0 \).

    -

    -Taking the derivatives with respect to \( b \) and \( \boldsymbol{w} \) we obtain +

    Taking the derivatives with respect to \( b \) and \( \boldsymbol{w} \) we obtain

    $$ \frac{\partial {\cal L}}{\partial b} = -\sum_{i} \lambda_iy_i=0, $$ -and +

    and

    $$ \frac{\partial {\cal L}}{\partial \boldsymbol{w}} = 0 = \boldsymbol{w}-\sum_{i} \lambda_iy_i\boldsymbol{x}_i. $$ -Inserting these constraints into the equation for \( {\cal L} \) we obtain +

    Inserting these constraints into the equation for \( {\cal L} \) we obtain

    $$ {\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\boldsymbol{x}_i^T\boldsymbol{x}_j, $$ -subject to the constraints \( \lambda_i\geq 0 \) and \( \sum_i\lambda_iy_i=0 \). +

    subject to the constraints \( \lambda_i\geq 0 \) and \( \sum_i\lambda_iy_i=0 \). We must in addition satisfy the Karush-Kuhn-Tucker (KKT) condition +

    $$ \lambda_i\left[y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) -1\right] \hspace{0.1cm}\forall i. $$ -
    1. If \( \lambda_i > 0 \), then \( y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1 \) and we say that \( x_i \) is on the boundary.
    2. If \( y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)> 1 \), we say \( x_i \) is not on the boundary and we set \( \lambda_i=0 \).
    +

    When \( \lambda_i > 0 \), the vectors \( \boldsymbol{x}_i \) are called support vectors. They are the vectors closest to the line (or hyperplane) and define the margin \( M \).

    -When \( \lambda_i > 0 \), the vectors \( \boldsymbol{x}_i \) are called support vectors. They are the vectors closest to the line (or hyperplane) and define the margin \( M \). - -











    +

    The problem to solve

    -

    The problem to solve

    - -

    -We can rewrite +

    We can rewrite

    $$ {\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\boldsymbol{x}_i^T\boldsymbol{x}_j, $$ -and its constraints in terms of a matrix-vector problem where we minimize w.r.t. \( \lambda \) the following problem +

    and its constraints in terms of a matrix-vector problem where we minimize w.r.t. \( \lambda \) the following problem

    $$ \frac{1}{2} \boldsymbol{\lambda}^T\begin{bmatrix} y_1y_1\boldsymbol{x}_1^T\boldsymbol{x}_1 & y_1y_2\boldsymbol{x}_1^T\boldsymbol{x}_2 & \dots & \dots & y_1y_n\boldsymbol{x}_1^T\boldsymbol{x}_n \\ y_2y_1\boldsymbol{x}_2^T\boldsymbol{x}_1 & y_2y_2\boldsymbol{x}_2^T\boldsymbol{x}_2 & \dots & \dots & y_1y_n\boldsymbol{x}_2^T\boldsymbol{x}_n \\ @@ -665,119 +810,113 @@ y_ny_1\boldsymbol{x}_n^T\boldsymbol{x}_1 & y_ny_2\boldsymbol{x}_n^T\boldsymbol{x \end{bmatrix}\boldsymbol{\lambda}-\mathbb{1}\boldsymbol{\lambda}, $$ -subject to \( \boldsymbol{y}^T\boldsymbol{\lambda}=0 \). Here we defined the vectors \( \boldsymbol{\lambda} =[\lambda_1,\lambda_2,\dots,\lambda_n] \) and -\( \boldsymbol{y}=[y_1,y_2,\dots,y_n] \). +

    subject to \( \boldsymbol{y}^T\boldsymbol{\lambda}=0 \). Here we defined the vectors \( \boldsymbol{\lambda} =[\lambda_1,\lambda_2,\dots,\lambda_n] \) and +\( \boldsymbol{y}=[y_1,y_2,\dots,y_n] \). +

    -











    +

    The last steps

    -

    The last steps

    - -

    -Solving the above problem, yields the values of \( \lambda_i \). +

    Solving the above problem, yields the values of \( \lambda_i \). To find the coefficients of your hyperplane we need simply to compute +

    $$ \boldsymbol{w}=\sum_{i} \lambda_iy_i\boldsymbol{x}_i. $$ -With our vector \( \boldsymbol{w} \) we can in turn find the value of the intercept \( b \) (here in two dimensions) via +

    With our vector \( \boldsymbol{w} \) we can in turn find the value of the intercept \( b \) (here in two dimensions) via

    $$ y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1, $$ -resulting in +

    resulting in

    $$ b = \frac{1}{y_i}-\boldsymbol{w}^T\boldsymbol{x}_i, $$ -or if we write it out in terms of the support vectors only, with \( N_s \) being their number, we have +

    or if we write it out in terms of the support vectors only, with \( N_s \) being their number, we have

    $$ b = \frac{1}{N_s}\sum_{j\in N_s}\left(y_j-\sum_{i=1}^n\lambda_iy_i\boldsymbol{x}_i^T\boldsymbol{x}_j\right). $$ -With our hyperplane coefficients we can use our classifier to assign any observation by simply using +

    With our hyperplane coefficients we can use our classifier to assign any observation by simply using

    $$ y_i = \mathrm{sign}(\boldsymbol{w}^T\boldsymbol{x}_i+b). $$ -Below we discuss how to find the optimal values of \( \lambda_i \). Before we proceed however, we discuss now the so-called soft classifier. +

    Below we discuss how to find the optimal values of \( \lambda_i \). Before we proceed however, we discuss now the so-called soft classifier.

    -











    +

    A soft classifier

    -

    A soft classifier

    +

    Till now, the margin is strictly defined by the support vectors. This defines what is called a hard classifier, that is the margins are well defined.

    -

    -Till now, the margin is strictly defined by the support vectors. This defines what is called a hard classifier, that is the margins are well defined. - -

    -Suppose now that classes overlap in feature space, as shown in the +

    Suppose now that classes overlap in feature space, as shown in the figure here. One way to deal with this problem before we define the so-called kernel approach, is to allow a kind of slack in the sense that we allow some points to be on the wrong side of the margin. +

    -

    -We introduce thus the so-called slack variables \( \boldsymbol{\xi} =[\xi_1,x_2,\dots,x_n] \) and +

    We introduce thus the so-called slack variables \( \boldsymbol{\xi} =[\xi_1,x_2,\dots,x_n] \) and modify our previous equation +

    $$ y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1, $$ -to +

    to

    $$ y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1-\xi_i, $$ -with the requirement \( \xi_i\geq 0 \). The total violation is now \( \sum_i\xi \). +

    with the requirement \( \xi_i\geq 0 \). The total violation is now \( \sum_i\xi \). The value \( \xi_i \) in the constraint the last constraint corresponds to the amount by which the prediction \( y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1 \) is on the wrong side of its margin. Hence by bounding the sum \( \sum_i \xi_i \), we bound the total amount by which predictions fall on the wrong side of their margins. +

    -

    -Misclassifications occur when \( \xi_i > 1 \). Thus bounding the total sum by some value \( C \) bounds in turn the total number of +

    Misclassifications occur when \( \xi_i > 1 \). Thus bounding the total sum by some value \( C \) bounds in turn the total number of misclassifications. +

    -











    +

    Soft optmization problem

    -

    Soft optmization problem

    - -

    -This has in turn the consequences that we change our optmization problem to finding the minimum of +

    This has in turn the consequences that we change our optmization problem to finding the minimum of

    $$ {\cal L}=\frac{1}{2}\boldsymbol{w}^T\boldsymbol{w}-\sum_{i=1}^n\lambda_i\left[y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)-(1-\xi_)\right]+C\sum_{i=1}^n\xi_i-\sum_{i=1}^n\gamma_i\xi_i, $$ -subject to +

    subject to

    $$ y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b)=1-\xi_i \hspace{0.1cm}\forall i, $$ -with the requirement \( \xi_i\geq 0 \). +

    with the requirement \( \xi_i\geq 0 \).

    -

    -Taking the derivatives with respect to \( b \) and \( \boldsymbol{w} \) we obtain +

    Taking the derivatives with respect to \( b \) and \( \boldsymbol{w} \) we obtain

    $$ \frac{\partial {\cal L}}{\partial b} = -\sum_{i} \lambda_iy_i=0, $$ -and +

    and

    $$ \frac{\partial {\cal L}}{\partial \boldsymbol{w}} = 0 = \boldsymbol{w}-\sum_{i} \lambda_iy_i\boldsymbol{x}_i, $$ -and +

    and

    $$ \lambda_i = C-\gamma_i \hspace{0.1cm}\forall i. $$ -Inserting these constraints into the equation for \( {\cal L} \) we obtain the same equation as before +

    Inserting these constraints into the equation for \( {\cal L} \) we obtain the same equation as before

    $$ {\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\boldsymbol{x}_i^T\boldsymbol{x}_j, $$ -but now subject to the constraints \( \lambda_i\geq 0 \), \( \sum_i\lambda_iy_i=0 \) and \( 0\leq\lambda_i \leq C \). +

    but now subject to the constraints \( \lambda_i\geq 0 \), \( \sum_i\lambda_iy_i=0 \) and \( 0\leq\lambda_i \leq C \). We must in addition satisfy the Karush-Kuhn-Tucker condition which now reads +

    $$ \lambda_i\left[y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) -(1-\xi_)\right]=0 \hspace{0.1cm}\forall i, $$ @@ -786,38 +925,41 @@ $$ \gamma_i\xi_i = 0, $$ -and +

    and

    $$ y_i(\boldsymbol{w}^T\boldsymbol{x}_i+b) -(1-\xi_) \geq 0 \hspace{0.1cm}\forall i. $$ -

    +









    +

    Kernels and non-linearity

    -

    Kernels and non-linearity

    - -

    -The cases we have studied till now, were all characterized by two classes +

    The cases we have studied till now, 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 +

    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. +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 +

    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. +

    -

    -

    import numpy as np
    +
    +
    +
    +
    +
    +
    import numpy as np
     import os
     
     np.random.seed(42)
    @@ -863,62 +1005,72 @@ plt.plot([-4.5<
     plt.axis([-4.5, 4.5, -1, 17])
     plt.subplots_adjust(right=1)
     plt.show()
    -
    -

    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    The equations

    -

    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) +

    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)

    $$ z = \phi(x_i) =\left(x_i^2, y_i^2, \sqrt{2}x_iy_i\right). $$ -

    -With our new basis, the equations we solved earlier are basically the same, that is we have now (without the slack option for simplicity) +

    With our new basis, the equations we solved earlier are basically the same, that is we have now (without the slack option for simplicity)

    $$ {\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\boldsymbol{z}_i^T\boldsymbol{z}_j, $$ -subject to the constraints \( \lambda_i\geq 0 \), \( \sum_i\lambda_iy_i=0 \), and for the support vectors +

    subject to the constraints \( \lambda_i\geq 0 \), \( \sum_i\lambda_iy_i=0 \), and for the support vectors

    $$ y_i(\boldsymbol{w}^T\boldsymbol{z}_i+b)= 1 \hspace{0.1cm}\forall i, $$ -from which we also find \( b \). +

    from which we also find \( b \). To compute \( \boldsymbol{z}_i^T\boldsymbol{z}_j \) we define the kernel \( K(\boldsymbol{x}_i,\boldsymbol{x}_j) \) as +

    $$ K(\boldsymbol{x}_i,\boldsymbol{x}_j)=\boldsymbol{z}_i^T\boldsymbol{z}_j= \phi(\boldsymbol{x}_i)^T\phi(\boldsymbol{x}_j). $$ -For the above example, the kernel reads +

    For the above example, the kernel reads

    $$ K(\boldsymbol{x}_i,\boldsymbol{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. $$ -

    -We note that this is nothing but the dot product of the two original +

    We note that this is nothing but the dot product of the two original vectors \( (\boldsymbol{x}_i^T\boldsymbol{x}_j)^2 \). Instead of thus computing the product in the Lagrangian of \( \boldsymbol{z}_i^T\boldsymbol{z}_j \) we simply compute the dot product \( (\boldsymbol{x}_i^T\boldsymbol{x}_j)^2 \). +

    -

    -This leads to the so-called +

    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(\boldsymbol{x}_i)^T\phi(\boldsymbol{x}_j) \) during the SVM calculations. +

    -











    - -

    The problem to solve

    -Using our definition of the kernel We can rewrite again the Lagrangian +

    The problem to solve

    +

    Using our definition of the kernel We can rewrite again the Lagrangian

    $$ {\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\boldsymbol{x}_i^T\boldsymbol{z}_j, $$ -subject to the constraints \( \lambda_i\geq 0 \), \( \sum_i\lambda_iy_i=0 \) in terms of a convex optimization problem +

    subject to the constraints \( \lambda_i\geq 0 \), \( \sum_i\lambda_iy_i=0 \) in terms of a convex optimization problem

    $$ \frac{1}{2} \boldsymbol{\lambda}^T\begin{bmatrix} y_1y_1K(\boldsymbol{x}_1,\boldsymbol{x}_1) & y_1y_2K(\boldsymbol{x}_1,\boldsymbol{x}_2) & \dots & \dots & y_1y_nK(\boldsymbol{x}_1,\boldsymbol{x}_n) \\ y_2y_1K(\boldsymbol{x}_2,\boldsymbol{x}_1) & y_2y_2(\boldsymbol{x}_2,\boldsymbol{x}_2) & \dots & \dots & y_1y_nK(\boldsymbol{x}_2,\boldsymbol{x}_n) \\ @@ -928,12 +1080,12 @@ y_ny_1K(\boldsymbol{x}_n,\boldsymbol{x}_1) & y_ny_2K(\boldsymbol{x}_n\boldsymbol \end{bmatrix}\boldsymbol{\lambda}-\mathbb{1}\boldsymbol{\lambda}, $$ -subject to \( \boldsymbol{y}^T\boldsymbol{\lambda}=0 \). Here we defined the vectors \( \boldsymbol{\lambda} =[\lambda_1,\lambda_2,\dots,\lambda_n] \) and +

    subject to \( \boldsymbol{y}^T\boldsymbol{\lambda}=0 \). Here we defined the vectors \( \boldsymbol{\lambda} =[\lambda_1,\lambda_2,\dots,\lambda_n] \) and \( \boldsymbol{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 +

    We can rewrite this (see the solutions below) in terms of a convex optimization problem of the type

    $$ \begin{align*} &\mathrm{min}_{\lambda}\hspace{0.2cm} \frac{1}{2}\boldsymbol{\lambda}^T\boldsymbol{P}\boldsymbol{\lambda}+\boldsymbol{q}^T\boldsymbol{\lambda},\\ \nonumber @@ -941,56 +1093,54 @@ $$ \end{align*} $$ -Below we discuss how to solve these equations. Here we note that the matrix \( \boldsymbol{P} \) has matrix elements \( p_{ij}=y_iy_jK(\boldsymbol{x}_i,\boldsymbol{x}_j) \). +

    Below we discuss how to solve these equations. Here we note that the matrix \( \boldsymbol{P} \) has matrix elements \( p_{ij}=y_iy_jK(\boldsymbol{x}_i,\boldsymbol{x}_j) \). Given a kernel \( K \) and the targets \( y_i \) this matrix is easy to set up. The constraint \( \boldsymbol{y}^T\boldsymbol{\lambda}=0 \) leads to \( f=0 \) and \( \boldsymbol{A}=\boldsymbol{y} \). How to set up the matrix \( \boldsymbol{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 \( \boldsymbol{G} \) and the vector \( \boldsymbol{h} \). +

    -











    +

    Different kernels and Mercer's theorem

    -

    Different kernels and Mercer's theorem

    - -

    -There are several popular kernels being used. These are - +

    There are several popular kernels being used. These are

    1. Linear: \( K(\boldsymbol{x},\boldsymbol{y})=\boldsymbol{x}^T\boldsymbol{y} \),
    2. Polynomial: \( K(\boldsymbol{x},\boldsymbol{y})=(\boldsymbol{x}^T\boldsymbol{y}+\gamma)^d \),
    3. Gaussian Radial Basis Function: \( K(\boldsymbol{x},\boldsymbol{y})=\exp{\left(-\gamma\vert\vert\boldsymbol{x}-\boldsymbol{y}\vert\vert^2\right)} \),
    4. Tanh: \( K(\boldsymbol{x},\boldsymbol{y})=\tanh{(\boldsymbol{x}^T\boldsymbol{y}+\gamma)} \),
    +

    and many other ones.

    -and many other ones. - -

    -An important theorem for us is Mercer's +

    An important theorem for us is Mercer's theorem. The theorem states that if a kernel function \( K \) is symmetric, continuous and leads to a positive semi-definite matrix \( \boldsymbol{P} \) then there exists a function \( \phi \) that maps \( \boldsymbol{x}_i \) and \( \boldsymbol{x}_j \) into another space (possibly with much higher dimensions) such that +

    $$ K(\boldsymbol{x}_i,\boldsymbol{x}_j)=\phi(\boldsymbol{x}_i)^T\phi(\boldsymbol{x}_j). $$ -

    -So you can use \( K \) as a kernel since you know \( \phi \) exists, even if -you don’t know what \( \phi \) is. +

    So you can use \( K \) as a kernel since you know \( \phi \) exists, even if +you don’t know what \( \phi \) is. +

    -

    -Note that some frequently used kernels (such as the Sigmoid kernel) +

    Note that some frequently used kernels (such as the Sigmoid kernel) don’t respect all of Mercer’s conditions, yet they generally work well in practice. +

    -











    - -

    The moons example

    -

    +

    The moons example

    -
    from __future__ import division, print_function, unicode_literals
    +
    +
    +
    +
    +
    +
    from __future__ import division, print_function, unicode_literals
     
     import numpy as np
     np.random.seed(42)
    @@ -1178,14 +1328,26 @@ plt.figure(figsize.title(r"$\gamma = {}, C = {}$".format(gamma, C), fontsize=16)
     
     plt.show()
    -
    -

    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    Mathematical optimization of convex functions

    -

    Mathematical optimization of convex functions

    - -

    -A mathematical (quadratic) optimization problem, or just optimization problem, has the form +

    A mathematical (quadratic) optimization problem, or just optimization problem, has the form

    $$ \begin{align*} &\mathrm{min}_{\lambda}\hspace{0.2cm} \frac{1}{2}\boldsymbol{\lambda}^T\boldsymbol{P}\boldsymbol{\lambda}+\boldsymbol{q}^T\boldsymbol{\lambda},\\ \nonumber @@ -1193,50 +1355,61 @@ $$ \end{align*} $$ -subject to some constraints for say a selected set \( i=1,2,\dots, n \). +

    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 \( \boldsymbol{\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. +

    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. +

    Convex optimization problems play a central role in applied mathematics and we recommend strongly Boyd and Vandenberghe's text on the topics.

    -











    +

    How do we solve these problems?

    -

    How do we solve these problems?

    - -

    -If we use Python as programming language and wish to venture beyond +

    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 +

    The functions we need are contained in the quadratic programming package CVXOPT and we need to import it together with numpy as

    -

    -

    import numpy
    +
    +
    +
    +
    +
    +
    import numpy
     import cvxopt
    -
    -

    -This will make our life much easier. You don't need t write your own optimizer. +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +

    This will make our life much easier. You don't need t write your own optimizer.

    -











    +

    A simple example

    -

    A simple example

    - -

    -We remind ourselves about the general problem we want to solve +

    We remind ourselves about the general problem we want to solve

    $$ \begin{align*} &\mathrm{min}_{x}\hspace{0.2cm} \frac{1}{2}\boldsymbol{x}^T\boldsymbol{P}\boldsymbol{x}+\boldsymbol{q}^T\boldsymbol{x},\\ \nonumber @@ -1244,8 +1417,7 @@ $$ \end{align*} $$ -

    -Let us show how to perform the optmization using a simple case. Assume we want to optimize the following problem +

    Let us show how to perform the optmization using a simple case. Assume we want to optimize the following problem

    $$ \begin{align*} &\mathrm{min}_{x}\hspace{0.2cm} \frac{1}{2}x^2+5x+3y \\ \nonumber @@ -1257,34 +1429,39 @@ $$ \end{align*} $$ -The minimization problem can be rewritten in terms of vectors and matrices as (with \( x \) and \( y \) being the unknowns) +

    The minimization problem can be rewritten in terms of vectors and matrices as (with \( x \) and \( y \) being the unknowns)

    $$ \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}. $$ -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 +

    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

    $$ \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}. $$ -We have collapsed all the inequalities into a single matrix \( \boldsymbol{G} \). We see also that our matrix +

    We have collapsed all the inequalities into a single matrix \( \boldsymbol{G} \). We see also that our matrix

    $$ \boldsymbol{P} =\begin{bmatrix} 1 & 0\\ 0 & 0 \end{bmatrix} $$ -is clearly positive semi-definite (all eigenvalues larger or equal zero). +

    is clearly positive semi-definite (all eigenvalues larger or equal zero). Finally, the vector \( \boldsymbol{h} \) is defined as +

    $$ \boldsymbol{h} = \begin{bmatrix}0 \\ 0\\ -15 \\ 100 \\ 80\end{bmatrix}. $$ -

    -Since we don't have any equalities the matrix \( \boldsymbol{A} \) is set to zero +

    Since we don't have any equalities the matrix \( \boldsymbol{A} \) is set to zero The following code solves the equations for us -

    +

    -
    # Import the necessary packages
    +
    +
    +
    +
    +
    +
    # Import the necessary packages
     import numpy
     from cvxopt import matrix
     from cvxopt import solvers
    @@ -1297,14 +1474,26 @@ sol = solvers.<
     # Extract optimal value and solution
     sol[’x’] 
     sol[’primal objective’]
    -
    -

    +

    +
    + + + +
    +
    +
    +
    +
    +
    +
    +
    + + +









    +

    Back to the more realistic cases

    -

    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 +

    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

    $$ \frac{1}{2} \boldsymbol{\lambda}^T\begin{bmatrix} y_1y_1K(\boldsymbol{x}_1,\boldsymbol{x}_1) & y_1y_2K(\boldsymbol{x}_1,\boldsymbol{x}_2) & \dots & \dots & y_1y_nK(\boldsymbol{x}_1,\boldsymbol{x}_n) \\ y_2y_1K(\boldsymbol{x}_2,\boldsymbol{x}_1) & y_2y_2K(\boldsymbol{x}_2,\boldsymbol{x}_2) & \dots & \dots & y_1y_nK(\boldsymbol{x}_2,\boldsymbol{x}_n) \\ @@ -1314,24 +1503,17 @@ y_ny_1K(\boldsymbol{x}_n,\boldsymbol{x}_1) & y_ny_2K(\boldsymbol{x}_n\boldsymbol \end{bmatrix}\boldsymbol{\lambda}-\mathbb{I}\boldsymbol{\lambda}, $$ -subject to \( \boldsymbol{y}^T\boldsymbol{\lambda}=0 \). Here we defined the vectors \( \boldsymbol{\lambda} =[\lambda_1,\lambda_2,\dots,\lambda_n] \) and +

    subject to \( \boldsymbol{y}^T\boldsymbol{\lambda}=0 \). Here we defined the vectors \( \boldsymbol{\lambda} =[\lambda_1,\lambda_2,\dots,\lambda_n] \) and \( \boldsymbol{y}=[y_1,y_2,\dots,y_n] \). With the slack constants this leads to the additional constraint \( 0\leq \lambda_i \leq C \). +

    -

    code will be added -

    - - -

    - © 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license + © 1999-2021, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
    - - - diff --git a/doc/pub/week46/ipynb/ipynb-week46-src.tar.gz b/doc/pub/week46/ipynb/ipynb-week46-src.tar.gz index 2afac239a..376b07b9c 100644 Binary files a/doc/pub/week46/ipynb/ipynb-week46-src.tar.gz and b/doc/pub/week46/ipynb/ipynb-week46-src.tar.gz differ diff --git a/doc/pub/week46/ipynb/week46.ipynb b/doc/pub/week46/ipynb/week46.ipynb index a549ae9b4..9e903a6ef 100644 --- a/doc/pub/week46/ipynb/week46.ipynb +++ b/doc/pub/week46/ipynb/week46.ipynb @@ -2,41 +2,104 @@ "cells": [ { "cell_type": "markdown", - "metadata": {}, + "id": "ca41afe6", + "metadata": { + "editable": true + }, "source": [ - "\n", - "# Week 46: Gradient Boosting Summary and Support Vector Machines\n", - "\n", - " \n", + "\n", + "" + ] + }, + { + "cell_type": "markdown", + "id": "76653449", + "metadata": { + "editable": true + }, + "source": [ + "# Week 46: Support Vector Machines and Project 3\n", "**Morten Hjorth-Jensen**, Department of Physics, University of Oslo and Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University\n", "\n", - "Date: **Nov 12, 2020**\n", - "\n", - "Copyright 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license\n", - "\n", - "\n", + "Date: **Nov 14, 2021**\n", "\n", + "Copyright 1999-2021, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license" + ] + }, + { + "cell_type": "markdown", + "id": "d5ad9927", + "metadata": { + "editable": true + }, + "source": [ "## Overview of week 46\n", "\n", - "* **Thursday**: Summary of Gradient Boosting and further examples of applications, from the physical sciences to the social sciences. [Guest lecture by John M. Aiken on Gradient Boosting and XGboost](https://www.mn.uio.no/fysikk/english/people/johnmai/).\n", + "* **Thursday**: Summary of Gradient Boosting with selected examples. Start support Vector Machines\n", "\n", - "* **Friday**: Support Vector Machines, classification and regression.\n", + "* **Friday**: Eventual Workshop on project 3. Discussion of project 3.\n", "\n", - "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.\n", + "**Note that on Thursday we will have only one lecture, from 1215pm to 1pm. There is no session 115pm-2pm.**\n", "\n", - "[See overview video on Support Vector Machines](https://www.youtube.com/watch?v=efR1C6CvhmE&ab_channel=StatQuestwithJoshStarmer). See also [this video](https://www.youtube.com/watch?v=N1vOgolbjSc&ab_channel=AliceZhao).\n", + "**Reading.**\n", "\n", + "Reading recommendations:\n", + "1. See lecture notes for week 46 at \n", "\n", - "## Thursday\n", + "2. Hastie et al chapter 12\n", "\n", - "The first lecture on Thursday is devoted to a summary from last week, with additional examples. This material is included in the lectures from week 45, see also Hastie *et al.* chapter 10.1-10.10.\n", + "3. Bishop chapter 7.1 and 7.2\n", "\n", - "The second letter will be given by John M. Aiken, who recently defended his thesis on machine learning, and in particular using boosting methods, to data from the social sciences and science education.\n", + "**Videos.**\n", "\n", + "1. [Overview video on Support Vector Machines](https://www.youtube.com/watch?v=efR1C6CvhmE&ab_channel=StatQuestwithJoshStarmer)\n", + "\n", + "2. See also [this video](https://www.youtube.com/watch?v=N1vOgolbjSc&ab_channel=AliceZhao).\n", + "\n", + "3. [Excellent videos on Gradient Boosting](https://www.youtube.com/watch?v=3CC4N4z3GJc&ab_channel=StatQuestwithJoshStarmer)" + ] + }, + { + "cell_type": "markdown", + "id": "dcd53965", + "metadata": { + "editable": true + }, + "source": [ "## Friday\n", "\n", - "We start with a new topic and second-last topic covered in this course, support vector machines (SVM). \n", + "Last year we had a very interesting workshop with many presentations. These were (program 2020)\n", "\n", + "* Maria Emine Nylund: **Lego Bricks Classifier**\n", + "\n", + "* Fabio Rodrigues Pereira: **Financial Machine Learning**\n", + "\n", + "* Markus Borud Pettersen: **Machine Learning and Brain Grid Cells**\n", + "\n", + "* Jing Sun and Endrias Getachew Asgedom: **Machine learning-based approaches to denoising microseismic data**\n", + "\n", + "* Felicia Jacobsen: **Analysis of Breast Cancer Data**\n", + "\n", + "* Simon Elias Schrader: **Predicting atomization energies of molecules**\n", + "\n", + "* Varvara Bazilova and Sergio Andres Diaz Mesa: **Glacier Mapping and Machine Learning**\n", + "\n", + "* Gert Werner Kluge, Hanna Alida Fossen Hardersen and Sushma Sharma Adhikari: **Gamma ray signals stemming from dark matter in the galactic center**\n", + "\n", + "We wish to organize something similar this coming Friday. The presentation last typically 5-10 minutes (some 3-5 slides) with time for questions afterwards.\n", + "Feel free to suggest topics.\n", + "\n", + "The program will be available asap. It depends on input from you!" + ] + }, + { + "cell_type": "markdown", + "id": "3907d65e", + "metadata": { + "editable": true + }, + "source": [ "## Support Vector Machines, overarching aims\n", "\n", "A Support Vector Machine (SVM) is a very powerful and versatile\n", @@ -61,8 +124,16 @@ "latter introduces a so-called softening parameter to be discussed\n", "below. We distinguish also between linear and non-linear\n", "approaches. The latter are the most frequent ones since it is rather\n", - "unlikely that we can separate classes easily by say straight lines.\n", - "\n", + "unlikely that we can separate classes easily by say straight lines." + ] + }, + { + "cell_type": "markdown", + "id": "45cb9d11", + "metadata": { + "editable": true + }, + "source": [ "## Hyperplanes and all that\n", "\n", "The theory behind support vector machines (SVM hereafter) is based on\n", @@ -80,8 +151,10 @@ { "cell_type": "code", "execution_count": 1, + "id": "0a43c290", "metadata": { - "collapsed": false + "collapsed": false, + "editable": true }, "outputs": [], "source": [ @@ -157,7 +230,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "895a58c0", + "metadata": { + "editable": true + }, "source": [ "## What is a hyperplane?\n", "\n", @@ -174,7 +250,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "e867a95a", + "metadata": { + "editable": true + }, "source": [ "$$\n", "b+w_1x_1+w_2x_2=0,\n", @@ -183,7 +262,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "b3886486", + "metadata": { + "editable": true + }, "source": [ "where $b$ is the intercept and $w_1$ and $w_2$ define the elements of a vector orthogonal to the line \n", "$b+w_1x_1+w_2x_2=0$. \n", @@ -193,7 +275,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "1e5d6245", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{x}^T\\boldsymbol{w}+b=0.\n", @@ -202,7 +287,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "edef7b5c", + "metadata": { + "editable": true + }, "source": [ "## A $p$-dimensional space of features\n", "\n", @@ -212,7 +300,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "e8ed4acb", + "metadata": { + "editable": true + }, "source": [ "$$\n", "b+wx_1+w_2x_2+\\dots +w_px_p=0.\n", @@ -221,7 +312,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "cb26d5ed", + "metadata": { + "editable": true + }, "source": [ "If we define a \n", "matrix $\\boldsymbol{X}=\\left[\\boldsymbol{x}_1,\\boldsymbol{x}_2,\\dots, \\boldsymbol{x}_p\\right]$\n", @@ -230,7 +324,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "c33d6e36", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{x}_i = \\begin{bmatrix} x_{i1} \\\\ x_{i2} \\\\ \\dots \\\\ \\dots \\\\ x_{ip} \\end{bmatrix}.\n", @@ -239,14 +336,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "c2343029", + "metadata": { + "editable": true + }, "source": [ "If the above condition is not met for a given vector $\\boldsymbol{x}_i$ we have" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "7ebc7145", + "metadata": { + "editable": true + }, "source": [ "$$\n", "b+w_1x_{i1}+w_2x_{i2}+\\dots +w_px_{ip} >0,\n", @@ -255,7 +358,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "0a2a521a", + "metadata": { + "editable": true + }, "source": [ "if our output $y_i=1$.\n", "In this case we say that $\\boldsymbol{x}_i$ lies on one of the sides of the hyperplane and if" @@ -263,7 +369,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "0e0173dc", + "metadata": { + "editable": true + }, "source": [ "$$\n", "b+w_1x_{i1}+w_2x_{i2}+\\dots +w_px_{ip} < 0,\n", @@ -272,7 +381,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "cd85fb81", + "metadata": { + "editable": true + }, "source": [ "for the class of observations $y_i=-1$, \n", "then $\\boldsymbol{x}_i$ lies on the other side. \n", @@ -282,7 +394,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "8e1c4d91", + "metadata": { + "editable": true + }, "source": [ "$$\n", "y_i\\left(b+w_1x_{i1}+w_2x_{i2}+\\dots +w_px_{ip}\\right) > 0.\n", @@ -291,11 +406,21 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "2aad42a6", + "metadata": { + "editable": true + }, + "source": [ + "When we try to separate hyperplanes, if it exists, we can use it to construct a natural classifier: a test observation is assigned a given class depending on which side of the hyperplane it is located." + ] + }, + { + "cell_type": "markdown", + "id": "819d3711", + "metadata": { + "editable": true + }, "source": [ - "When we try to separate hyperplanes, if it exists, we can use it to construct a natural classifier: a test observation is assigned a given class depending on which side of the hyperplane it is located.\n", - "\n", - "\n", "## The two-dimensional case\n", "\n", "Let us try to develop our intuition about SVMs by limiting ourselves to a two-dimensional\n", @@ -315,8 +440,16 @@ "\n", "Unfortunately there are many ways in which we can place a hyperplane\n", "to divide the data. Below is an example of two candidate hyperplanes\n", - "for our data sample.\n", - "\n", + "for our data sample." + ] + }, + { + "cell_type": "markdown", + "id": "8b9ef6f2", + "metadata": { + "editable": true + }, + "source": [ "## Getting into the details\n", "\n", "Let us define the function" @@ -324,7 +457,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "f66d130f", + "metadata": { + "editable": true + }, "source": [ "$$\n", "f(x) = \\boldsymbol{w}^T\\boldsymbol{x}+b = 0,\n", @@ -333,11 +469,13 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "3da89dc5", + "metadata": { + "editable": true + }, "source": [ "as the function that determines the line $L$ that separates two classes (our two features), see the figure here. \n", "\n", - "\n", "Any point defined by $\\boldsymbol{x}_i$ and $\\boldsymbol{x}_2$ on the line $L$ will satisfy $\\boldsymbol{w}^T(\\boldsymbol{x}_1-\\boldsymbol{x}_2)=0$. \n", "\n", "The signed distance $\\delta$ from any point defined by a vector $\\boldsymbol{x}$ and a point $\\boldsymbol{x}_0$ on the line $L$ is then" @@ -345,7 +483,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "f87588b9", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\delta = \\frac{1}{\\vert\\vert \\boldsymbol{w}\\vert\\vert}(\\boldsymbol{w}^T\\boldsymbol{x}+b).\n", @@ -354,7 +495,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "9a097c0e", + "metadata": { + "editable": true + }, "source": [ "## First attempt at a minimization approach\n", "\n", @@ -365,7 +509,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "7d9e3e4a", + "metadata": { + "editable": true + }, "source": [ "$$\n", "C(\\boldsymbol{w},b) = -\\sum_{i\\in M} y_i(\\boldsymbol{w}^T\\boldsymbol{x}_i+b).\n", @@ -374,14 +521,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "f57a8e66", + "metadata": { + "editable": true + }, "source": [ "We could now for example define all values $y_i =1$ as misclassified in case we have $\\boldsymbol{w}^T\\boldsymbol{x}_i+b < 0$ and the opposite if we have $y_i=-1$. Taking the derivatives gives us" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "f45210a5", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\frac{\\partial C}{\\partial b} = -\\sum_{i\\in M} y_i,\n", @@ -390,14 +543,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "8ebfcdad", + "metadata": { + "editable": true + }, "source": [ "and" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "077fb0d6", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\frac{\\partial C}{\\partial \\boldsymbol{w}} = -\\sum_{i\\in M} y_ix_i.\n", @@ -406,7 +565,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "0e092b3b", + "metadata": { + "editable": true + }, "source": [ "## Solving the equations\n", "\n", @@ -415,7 +577,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "c2b2886c", + "metadata": { + "editable": true + }, "source": [ "$$\n", "b \\leftarrow b +\\eta \\frac{\\partial C}{\\partial b},\n", @@ -424,14 +589,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "9cd095ef", + "metadata": { + "editable": true + }, "source": [ "and" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "8adb2387", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{w} \\leftarrow \\boldsymbol{w} +\\eta \\frac{\\partial C}{\\partial \\boldsymbol{w}},\n", @@ -440,11 +611,21 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "9b209c51", + "metadata": { + "editable": true + }, + "source": [ + "where $\\eta$ is our by now well-known learning rate." + ] + }, + { + "cell_type": "markdown", + "id": "4daf1a65", + "metadata": { + "editable": true + }, "source": [ - "where $\\eta$ is our by now well-known learning rate. \n", - "\n", - "\n", "## Code Example\n", "\n", "The equations we discussed above can be coded rather easily (the\n", @@ -454,21 +635,30 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "b3a923b4", + "metadata": { + "editable": true + }, "source": [ "## Problems with the Simpler Approach\n", "\n", - "\n", "There are however problems with this approach, although it looks\n", "pretty straightforward to implement. When running the above code, we see that we can easily end up with many diffeent lines which separate the two classes.\n", "\n", - "\n", "For small\n", "gaps between the entries, we may also end up needing many iterations\n", "before the solutions converge and if the data cannot be separated\n", "properly into two distinct classes, we may not experience a converge\n", - "at all.\n", - "\n", + "at all." + ] + }, + { + "cell_type": "markdown", + "id": "2164baad", + "metadata": { + "editable": true + }, + "source": [ "## A better approach\n", "\n", "A better approach is rather to try to define a large margin between\n", @@ -480,7 +670,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "ddfe0bdb", + "metadata": { + "editable": true + }, "source": [ "$$\n", "y_i(\\boldsymbol{w}^T\\boldsymbol{x}_i+b) \\geq M \\hspace{0.1cm}\\forall i=1,2,\\dots, p.\n", @@ -489,7 +682,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "425f573c", + "metadata": { + "editable": true + }, "source": [ "All points are thus at a signed distance from the decision boundary defined by the line $L$. The parameters $b$ and $w_1$ and $w_2$ define this line. \n", "\n", @@ -498,7 +694,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "e70a947d", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\frac{1}{\\vert \\vert \\boldsymbol{w}\\vert\\vert}y_i(\\boldsymbol{w}^T\\boldsymbol{x}_i+b) \\geq M \\hspace{0.1cm}\\forall i=1,2,\\dots, n,\n", @@ -507,14 +706,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "0a7b2b1f", + "metadata": { + "editable": true + }, "source": [ "or just" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "b5894840", + "metadata": { + "editable": true + }, "source": [ "$$\n", "y_i(\\boldsymbol{w}^T\\boldsymbol{x}_i+b) \\geq M\\vert \\vert \\boldsymbol{w}\\vert\\vert \\hspace{0.1cm}\\forall i.\n", @@ -523,7 +728,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "433b338f", + "metadata": { + "editable": true + }, "source": [ "If we scale the equation so that $\\vert \\vert \\boldsymbol{w}\\vert\\vert = 1/M$, we have to find the minimum of \n", "$\\boldsymbol{w}^T\\boldsymbol{w}=\\vert \\vert \\boldsymbol{w}\\vert\\vert$ (the norm) subject to the condition" @@ -531,7 +739,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "13d32ff2", + "metadata": { + "editable": true + }, "source": [ "$$\n", "y_i(\\boldsymbol{w}^T\\boldsymbol{x}_i+b) \\geq 1 \\hspace{0.1cm}\\forall i.\n", @@ -540,13 +751,24 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "912b65d5", + "metadata": { + "editable": true + }, "source": [ "We have thus defined our margin as the invers of the norm of\n", "$\\boldsymbol{w}$. We want to minimize the norm in order to have a as large as\n", "possible margin $M$. Before we proceed, we need to remind ourselves\n", - "about Lagrangian multipliers.\n", - "\n", + "about Lagrangian multipliers." + ] + }, + { + "cell_type": "markdown", + "id": "63b8fac0", + "metadata": { + "editable": true + }, + "source": [ "## A quick Reminder on Lagrangian Multipliers\n", "\n", "Consider a function of three independent variables $f(x,y,z)$ . For the function $f$ to be an\n", @@ -555,7 +777,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "e71e686d", + "metadata": { + "editable": true + }, "source": [ "$$\n", "df=0.\n", @@ -564,14 +789,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "37356bff", + "metadata": { + "editable": true + }, "source": [ "A necessary and sufficient condition is" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "e82a1518", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\frac{\\partial f}{\\partial x} =\\frac{\\partial f}{\\partial y}=\\frac{\\partial f}{\\partial z}=0,\n", @@ -580,14 +811,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "dc39c058", + "metadata": { + "editable": true + }, "source": [ "due to" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "c8e9fabd", + "metadata": { + "editable": true + }, "source": [ "$$\n", "df = \\frac{\\partial f}{\\partial x}dx+\\frac{\\partial f}{\\partial y}dy+\\frac{\\partial f}{\\partial z}dz.\n", @@ -596,7 +833,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "06155d66", + "metadata": { + "editable": true + }, "source": [ "In many problems the variables $x,y,z$ are often subject to constraints (such as those above for the margin)\n", "so that they are no longer all independent. It is possible at least in principle to use each \n", @@ -610,7 +850,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "8cf223be", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\phi(x,y,z) = 0,\n", @@ -619,14 +862,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "a7a2ca1c", + "metadata": { + "editable": true + }, "source": [ "resulting in" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "4fb63460", + "metadata": { + "editable": true + }, "source": [ "$$\n", "d\\phi = \\frac{\\partial \\phi}{\\partial x}dx+\\frac{\\partial \\phi}{\\partial y}dy+\\frac{\\partial \\phi}{\\partial z}dz =0.\n", @@ -635,14 +884,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "a593f86a", + "metadata": { + "editable": true + }, "source": [ "Now we cannot set anymore" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "c89d8514", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\frac{\\partial f}{\\partial x} =\\frac{\\partial f}{\\partial y}=\\frac{\\partial f}{\\partial z}=0,\n", @@ -651,13 +906,24 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "4c533230", + "metadata": { + "editable": true + }, "source": [ "if $df=0$ is wanted\n", "because there are now only two independent variables! Assume $x$ and $y$ are the independent \n", "variables.\n", - "Then $dz$ is no longer arbitrary.\n", - "\n", + "Then $dz$ is no longer arbitrary." + ] + }, + { + "cell_type": "markdown", + "id": "3fdee740", + "metadata": { + "editable": true + }, + "source": [ "## Adding the Multiplier\n", "\n", "However, we can add to" @@ -665,7 +931,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "fbf28cd8", + "metadata": { + "editable": true + }, "source": [ "$$\n", "df = \\frac{\\partial f}{\\partial x}dx+\\frac{\\partial f}{\\partial y}dy+\\frac{\\partial f}{\\partial z}dz,\n", @@ -674,14 +943,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "8d1407a2", + "metadata": { + "editable": true + }, "source": [ "a multiplum of $d\\phi$, viz. $\\lambda d\\phi$, resulting in" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "95355989", + "metadata": { + "editable": true + }, "source": [ "$$\n", "df+\\lambda d\\phi = (\\frac{\\partial f}{\\partial z}+\\lambda\n", @@ -692,14 +967,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "39fae3a7", + "metadata": { + "editable": true + }, "source": [ "Our multiplier is chosen so that" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "dd18c177", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\frac{\\partial f}{\\partial z}+\\lambda\\frac{\\partial \\phi}{\\partial z} =0.\n", @@ -708,14 +989,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "8a7e3275", + "metadata": { + "editable": true + }, "source": [ "We need to remember that we took $dx$ and $dy$ to be arbitrary and thus we must have" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "6b7c1824", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\frac{\\partial f}{\\partial x}+\\lambda\\frac{\\partial \\phi}{\\partial x} =0,\n", @@ -724,14 +1011,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "2328ce76", + "metadata": { + "editable": true + }, "source": [ "and" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "f697d679", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\frac{\\partial f}{\\partial y}+\\lambda\\frac{\\partial \\phi}{\\partial y} =0.\n", @@ -740,7 +1033,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "f679867d", + "metadata": { + "editable": true + }, "source": [ "When all these equations are satisfied, $df=0$. We have four unknowns, $x,y,z$ and\n", "$\\lambda$. Actually we want only $x,y,z$, $\\lambda$ needs not to be determined, \n", @@ -751,7 +1047,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "0835ef08", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\frac{\\partial f}{\\partial x_i}+\\sum_k\\lambda_k\\frac{\\partial \\phi_k}{\\partial x_i} =0.\n", @@ -760,7 +1059,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "b19ddb22", + "metadata": { + "editable": true + }, "source": [ "## Setting up the Problem\n", "In order to solve the above problem, we define the following Lagrangian function to be minimized" @@ -768,7 +1070,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "89c349fa", + "metadata": { + "editable": true + }, "source": [ "$$\n", "{\\cal L}(\\lambda,b,\\boldsymbol{w})=\\frac{1}{2}\\boldsymbol{w}^T\\boldsymbol{w}-\\sum_{i=1}^n\\lambda_i\\left[y_i(\\boldsymbol{w}^T\\boldsymbol{x}_i+b)-1\\right],\n", @@ -777,7 +1082,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "fdc1c959", + "metadata": { + "editable": true + }, "source": [ "where $\\lambda_i$ is a so-called Lagrange multiplier subject to the condition $\\lambda_i \\geq 0$.\n", "\n", @@ -786,7 +1094,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "7e2a5ab1", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\frac{\\partial {\\cal L}}{\\partial b} = -\\sum_{i} \\lambda_iy_i=0,\n", @@ -795,14 +1106,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "672fb202", + "metadata": { + "editable": true + }, "source": [ "and" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "c27c399f", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\frac{\\partial {\\cal L}}{\\partial \\boldsymbol{w}} = 0 = \\boldsymbol{w}-\\sum_{i} \\lambda_iy_i\\boldsymbol{x}_i.\n", @@ -811,14 +1128,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "e520cc36", + "metadata": { + "editable": true + }, "source": [ "Inserting these constraints into the equation for ${\\cal L}$ we obtain" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "44c167ae", + "metadata": { + "editable": true + }, "source": [ "$$\n", "{\\cal L}=\\sum_i\\lambda_i-\\frac{1}{2}\\sum_{ij}^n\\lambda_i\\lambda_jy_iy_j\\boldsymbol{x}_i^T\\boldsymbol{x}_j,\n", @@ -827,7 +1150,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "549ed5b7", + "metadata": { + "editable": true + }, "source": [ "subject to the constraints $\\lambda_i\\geq 0$ and $\\sum_i\\lambda_iy_i=0$. \n", "We must in addition satisfy the [Karush-Kuhn-Tucker](https://en.wikipedia.org/wiki/Karush%E2%80%93Kuhn%E2%80%93Tucker_conditions) (KKT) condition" @@ -835,7 +1161,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "a8e62b1b", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\lambda_i\\left[y_i(\\boldsymbol{w}^T\\boldsymbol{x}_i+b) -1\\right] \\hspace{0.1cm}\\forall i.\n", @@ -844,14 +1173,25 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "a3add0b2", + "metadata": { + "editable": true + }, "source": [ "1. If $\\lambda_i > 0$, then $y_i(\\boldsymbol{w}^T\\boldsymbol{x}_i+b)=1$ and we say that $x_i$ is on the boundary.\n", "\n", "2. If $y_i(\\boldsymbol{w}^T\\boldsymbol{x}_i+b)> 1$, we say $x_i$ is not on the boundary and we set $\\lambda_i=0$. \n", "\n", - "When $\\lambda_i > 0$, the vectors $\\boldsymbol{x}_i$ are called support vectors. They are the vectors closest to the line (or hyperplane) and define the margin $M$. \n", - "\n", + "When $\\lambda_i > 0$, the vectors $\\boldsymbol{x}_i$ are called support vectors. They are the vectors closest to the line (or hyperplane) and define the margin $M$." + ] + }, + { + "cell_type": "markdown", + "id": "ead680eb", + "metadata": { + "editable": true + }, + "source": [ "## The problem to solve\n", "\n", "We can rewrite" @@ -859,7 +1199,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "f7020a4d", + "metadata": { + "editable": true + }, "source": [ "$$\n", "{\\cal L}=\\sum_i\\lambda_i-\\frac{1}{2}\\sum_{ij}^n\\lambda_i\\lambda_jy_iy_j\\boldsymbol{x}_i^T\\boldsymbol{x}_j,\n", @@ -868,14 +1211,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "0b5c51e7", + "metadata": { + "editable": true + }, "source": [ "and its constraints in terms of a matrix-vector problem where we minimize w.r.t. $\\lambda$ the following problem" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "cb605175", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\frac{1}{2} \\boldsymbol{\\lambda}^T\\begin{bmatrix} y_1y_1\\boldsymbol{x}_1^T\\boldsymbol{x}_1 & y_1y_2\\boldsymbol{x}_1^T\\boldsymbol{x}_2 & \\dots & \\dots & y_1y_n\\boldsymbol{x}_1^T\\boldsymbol{x}_n \\\\\n", @@ -889,12 +1238,22 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "33844a80", + "metadata": { + "editable": true + }, "source": [ "subject to $\\boldsymbol{y}^T\\boldsymbol{\\lambda}=0$. Here we defined the vectors $\\boldsymbol{\\lambda} =[\\lambda_1,\\lambda_2,\\dots,\\lambda_n]$ and \n", - "$\\boldsymbol{y}=[y_1,y_2,\\dots,y_n]$. \n", - "\n", - "\n", + "$\\boldsymbol{y}=[y_1,y_2,\\dots,y_n]$." + ] + }, + { + "cell_type": "markdown", + "id": "451a8c5b", + "metadata": { + "editable": true + }, + "source": [ "## The last steps\n", "\n", "Solving the above problem, yields the values of $\\lambda_i$.\n", @@ -903,7 +1262,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "25f2ac38", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{w}=\\sum_{i} \\lambda_iy_i\\boldsymbol{x}_i.\n", @@ -912,14 +1274,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "e0cf57ee", + "metadata": { + "editable": true + }, "source": [ "With our vector $\\boldsymbol{w}$ we can in turn find the value of the intercept $b$ (here in two dimensions) via" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "c43f8ca4", + "metadata": { + "editable": true + }, "source": [ "$$\n", "y_i(\\boldsymbol{w}^T\\boldsymbol{x}_i+b)=1,\n", @@ -928,14 +1296,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "588af6e2", + "metadata": { + "editable": true + }, "source": [ "resulting in" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "ba6b6192", + "metadata": { + "editable": true + }, "source": [ "$$\n", "b = \\frac{1}{y_i}-\\boldsymbol{w}^T\\boldsymbol{x}_i,\n", @@ -944,14 +1318,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "881046e1", + "metadata": { + "editable": true + }, "source": [ "or if we write it out in terms of the support vectors only, with $N_s$ being their number, we have" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "cb4d46ee", + "metadata": { + "editable": true + }, "source": [ "$$\n", "b = \\frac{1}{N_s}\\sum_{j\\in N_s}\\left(y_j-\\sum_{i=1}^n\\lambda_iy_i\\boldsymbol{x}_i^T\\boldsymbol{x}_j\\right).\n", @@ -960,14 +1340,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "78d32f35", + "metadata": { + "editable": true + }, "source": [ "With our hyperplane coefficients we can use our classifier to assign any observation by simply using" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "04214828", + "metadata": { + "editable": true + }, "source": [ "$$\n", "y_i = \\mathrm{sign}(\\boldsymbol{w}^T\\boldsymbol{x}_i+b).\n", @@ -976,10 +1362,21 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "bc8b07f9", + "metadata": { + "editable": true + }, + "source": [ + "Below we discuss how to find the optimal values of $\\lambda_i$. Before we proceed however, we discuss now the so-called soft classifier." + ] + }, + { + "cell_type": "markdown", + "id": "473f10c3", + "metadata": { + "editable": true + }, "source": [ - "Below we discuss how to find the optimal values of $\\lambda_i$. Before we proceed however, we discuss now the so-called soft classifier. \n", - "\n", "## A soft classifier\n", "\n", "Till now, the margin is strictly defined by the support vectors. This defines what is called a hard classifier, that is the margins are well defined.\n", @@ -995,7 +1392,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "7167ce20", + "metadata": { + "editable": true + }, "source": [ "$$\n", "y_i(\\boldsymbol{w}^T\\boldsymbol{x}_i+b)=1,\n", @@ -1004,14 +1404,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "60959b50", + "metadata": { + "editable": true + }, "source": [ "to" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "bc99f000", + "metadata": { + "editable": true + }, "source": [ "$$\n", "y_i(\\boldsymbol{w}^T\\boldsymbol{x}_i+b)=1-\\xi_i,\n", @@ -1020,7 +1426,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "539bcb31", + "metadata": { + "editable": true + }, "source": [ "with the requirement $\\xi_i\\geq 0$. The total violation is now $\\sum_i\\xi$. \n", "The value $\\xi_i$ in the constraint the last constraint corresponds to the amount by which the prediction\n", @@ -1028,17 +1437,27 @@ "we bound the total amount by which predictions fall on the wrong side of their margins.\n", "\n", "Misclassifications occur when $\\xi_i > 1$. Thus bounding the total sum by some value $C$ bounds in turn the total number of\n", - "misclassifications.\n", - "\n", + "misclassifications." + ] + }, + { + "cell_type": "markdown", + "id": "48c0687a", + "metadata": { + "editable": true + }, + "source": [ "## Soft optmization problem\n", "\n", - "\n", "This has in turn the consequences that we change our optmization problem to finding the minimum of" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "8b7a0d6b", + "metadata": { + "editable": true + }, "source": [ "$$\n", "{\\cal L}=\\frac{1}{2}\\boldsymbol{w}^T\\boldsymbol{w}-\\sum_{i=1}^n\\lambda_i\\left[y_i(\\boldsymbol{w}^T\\boldsymbol{x}_i+b)-(1-\\xi_)\\right]+C\\sum_{i=1}^n\\xi_i-\\sum_{i=1}^n\\gamma_i\\xi_i,\n", @@ -1047,14 +1466,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "4fd2533e", + "metadata": { + "editable": true + }, "source": [ "subject to" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "8e6e09f7", + "metadata": { + "editable": true + }, "source": [ "$$\n", "y_i(\\boldsymbol{w}^T\\boldsymbol{x}_i+b)=1-\\xi_i \\hspace{0.1cm}\\forall i,\n", @@ -1063,7 +1488,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "f01eb1a3", + "metadata": { + "editable": true + }, "source": [ "with the requirement $\\xi_i\\geq 0$.\n", "\n", @@ -1072,7 +1500,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "fd747ad1", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\frac{\\partial {\\cal L}}{\\partial b} = -\\sum_{i} \\lambda_iy_i=0,\n", @@ -1081,14 +1512,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "67d9d052", + "metadata": { + "editable": true + }, "source": [ "and" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "59ab3f2e", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\frac{\\partial {\\cal L}}{\\partial \\boldsymbol{w}} = 0 = \\boldsymbol{w}-\\sum_{i} \\lambda_iy_i\\boldsymbol{x}_i,\n", @@ -1097,14 +1534,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "47018d28", + "metadata": { + "editable": true + }, "source": [ "and" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "5abbf4ed", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\lambda_i = C-\\gamma_i \\hspace{0.1cm}\\forall i.\n", @@ -1113,14 +1556,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "9aa83777", + "metadata": { + "editable": true + }, "source": [ "Inserting these constraints into the equation for ${\\cal L}$ we obtain the same equation as before" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "0ae64fa7", + "metadata": { + "editable": true + }, "source": [ "$$\n", "{\\cal L}=\\sum_i\\lambda_i-\\frac{1}{2}\\sum_{ij}^n\\lambda_i\\lambda_jy_iy_j\\boldsymbol{x}_i^T\\boldsymbol{x}_j,\n", @@ -1129,7 +1578,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "04456e07", + "metadata": { + "editable": true + }, "source": [ "but now subject to the constraints $\\lambda_i\\geq 0$, $\\sum_i\\lambda_iy_i=0$ and $0\\leq\\lambda_i \\leq C$. \n", "We must in addition satisfy the Karush-Kuhn-Tucker condition which now reads" @@ -1137,31 +1589,22 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "7373cfc9", + "metadata": { + "editable": true + }, "source": [ - "5\n", - "0\n", - " \n", - "<\n", - "<\n", - "<\n", - "!\n", - "!\n", - "M\n", - "A\n", - "T\n", - "H\n", - "_\n", - "B\n", - "L\n", - "O\n", - "C\n", - "K" + "$$\n", + "\\lambda_i\\left[y_i(\\boldsymbol{w}^T\\boldsymbol{x}_i+b) -(1-\\xi_)\\right]=0 \\hspace{0.1cm}\\forall i,\n", + "$$" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "e372a295", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\gamma_i\\xi_i = 0,\n", @@ -1170,14 +1613,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "4d08ba31", + "metadata": { + "editable": true + }, "source": [ "and" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "1380e190", + "metadata": { + "editable": true + }, "source": [ "$$\n", "y_i(\\boldsymbol{w}^T\\boldsymbol{x}_i+b) -(1-\\xi_) \\geq 0 \\hspace{0.1cm}\\forall i.\n", @@ -1186,7 +1635,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "f641737d", + "metadata": { + "editable": true + }, "source": [ "## Kernels and non-linearity\n", "\n", @@ -1209,8 +1661,10 @@ { "cell_type": "code", "execution_count": 2, + "id": "8b69717e", "metadata": { - "collapsed": false + "collapsed": false, + "editable": true }, "outputs": [], "source": [ @@ -1264,7 +1718,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "8936ee34", + "metadata": { + "editable": true + }, "source": [ "## The equations\n", "\n", @@ -1273,7 +1730,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "4f0a7095", + "metadata": { + "editable": true + }, "source": [ "$$\n", "z = \\phi(x_i) =\\left(x_i^2, y_i^2, \\sqrt{2}x_iy_i\\right).\n", @@ -1282,14 +1742,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "86b3e715", + "metadata": { + "editable": true + }, "source": [ "With our new basis, the equations we solved earlier are basically the same, that is we have now (without the slack option for simplicity)" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "536a8b13", + "metadata": { + "editable": true + }, "source": [ "$$\n", "{\\cal L}=\\sum_i\\lambda_i-\\frac{1}{2}\\sum_{ij}^n\\lambda_i\\lambda_jy_iy_j\\boldsymbol{z}_i^T\\boldsymbol{z}_j,\n", @@ -1298,14 +1764,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "20322a0f", + "metadata": { + "editable": true + }, "source": [ "subject to the constraints $\\lambda_i\\geq 0$, $\\sum_i\\lambda_iy_i=0$, and for the support vectors" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "4ce193c6", + "metadata": { + "editable": true + }, "source": [ "$$\n", "y_i(\\boldsymbol{w}^T\\boldsymbol{z}_i+b)= 1 \\hspace{0.1cm}\\forall i,\n", @@ -1314,7 +1786,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "a2dd5169", + "metadata": { + "editable": true + }, "source": [ "from which we also find $b$.\n", "To compute $\\boldsymbol{z}_i^T\\boldsymbol{z}_j$ we define the kernel $K(\\boldsymbol{x}_i,\\boldsymbol{x}_j)$ as" @@ -1322,7 +1797,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "401ba6d9", + "metadata": { + "editable": true + }, "source": [ "$$\n", "K(\\boldsymbol{x}_i,\\boldsymbol{x}_j)=\\boldsymbol{z}_i^T\\boldsymbol{z}_j= \\phi(\\boldsymbol{x}_i)^T\\phi(\\boldsymbol{x}_j).\n", @@ -1331,14 +1809,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "c536d48f", + "metadata": { + "editable": true + }, "source": [ "For the above example, the kernel reads" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "95a4784c", + "metadata": { + "editable": true + }, "source": [ "$$\n", "K(\\boldsymbol{x}_i,\\boldsymbol{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.\n", @@ -1347,27 +1831,39 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "172682a3", + "metadata": { + "editable": true + }, "source": [ "We note that this is nothing but the dot product of the two original\n", "vectors $(\\boldsymbol{x}_i^T\\boldsymbol{x}_j)^2$. Instead of thus computing the\n", "product in the Lagrangian of $\\boldsymbol{z}_i^T\\boldsymbol{z}_j$ we simply compute\n", "the dot product $(\\boldsymbol{x}_i^T\\boldsymbol{x}_j)^2$.\n", "\n", - "\n", "This leads to the so-called\n", "kernel trick and the result leads to the same as if we went through\n", "the trouble of performing the transformation\n", - "$\\phi(\\boldsymbol{x}_i)^T\\phi(\\boldsymbol{x}_j)$ during the SVM calculations.\n", - "\n", - "\n", + "$\\phi(\\boldsymbol{x}_i)^T\\phi(\\boldsymbol{x}_j)$ during the SVM calculations." + ] + }, + { + "cell_type": "markdown", + "id": "65e8f650", + "metadata": { + "editable": true + }, + "source": [ "## The problem to solve\n", "Using our definition of the kernel We can rewrite again the Lagrangian" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "fdd71f61", + "metadata": { + "editable": true + }, "source": [ "$$\n", "{\\cal L}=\\sum_i\\lambda_i-\\frac{1}{2}\\sum_{ij}^n\\lambda_i\\lambda_jy_iy_j\\boldsymbol{x}_i^T\\boldsymbol{z}_j,\n", @@ -1376,14 +1872,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "f286f2d9", + "metadata": { + "editable": true + }, "source": [ "subject to the constraints $\\lambda_i\\geq 0$, $\\sum_i\\lambda_iy_i=0$ in terms of a convex optimization problem" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "f1a5d7e6", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\frac{1}{2} \\boldsymbol{\\lambda}^T\\begin{bmatrix} y_1y_1K(\\boldsymbol{x}_1,\\boldsymbol{x}_1) & y_1y_2K(\\boldsymbol{x}_1,\\boldsymbol{x}_2) & \\dots & \\dots & y_1y_nK(\\boldsymbol{x}_1,\\boldsymbol{x}_n) \\\\\n", @@ -1397,7 +1899,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "d32d9e3b", + "metadata": { + "editable": true + }, "source": [ "subject to $\\boldsymbol{y}^T\\boldsymbol{\\lambda}=0$. Here we defined the vectors $\\boldsymbol{\\lambda} =[\\lambda_1,\\lambda_2,\\dots,\\lambda_n]$ and \n", "$\\boldsymbol{y}=[y_1,y_2,\\dots,y_n]$. \n", @@ -1408,7 +1913,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "fd0f61b7", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\begin{align*}\n", @@ -1420,13 +1928,23 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "1f55d7a0", + "metadata": { + "editable": true + }, "source": [ "Below we discuss how to solve these equations. Here we note that the matrix $\\boldsymbol{P}$ has matrix elements $p_{ij}=y_iy_jK(\\boldsymbol{x}_i,\\boldsymbol{x}_j)$.\n", "Given a kernel $K$ and the targets $y_i$ this matrix is easy to set up. The constraint $\\boldsymbol{y}^T\\boldsymbol{\\lambda}=0$ leads to $f=0$ and $\\boldsymbol{A}=\\boldsymbol{y}$. How to set up the matrix $\\boldsymbol{G}$ is discussed later. Here note that the inequalities $0\\leq \\lambda_i \\leq C$ can be split up into\n", - "$0\\leq \\lambda_i$ and $\\lambda_i \\leq C$. These two inequalities define then the matrix $\\boldsymbol{G}$ and the vector $\\boldsymbol{h}$.\n", - "\n", - "\n", + "$0\\leq \\lambda_i$ and $\\lambda_i \\leq C$. These two inequalities define then the matrix $\\boldsymbol{G}$ and the vector $\\boldsymbol{h}$." + ] + }, + { + "cell_type": "markdown", + "id": "a50a3478", + "metadata": { + "editable": true + }, + "source": [ "## Different kernels and Mercer's theorem\n", "\n", "There are several popular kernels being used. These are\n", @@ -1450,7 +1968,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "10b2c6f8", + "metadata": { + "editable": true + }, "source": [ "$$\n", "K(\\boldsymbol{x}_i,\\boldsymbol{x}_j)=\\phi(\\boldsymbol{x}_i)^T\\phi(\\boldsymbol{x}_j).\n", @@ -1459,24 +1980,36 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "b866e8a0", + "metadata": { + "editable": true + }, "source": [ "So you can use $K$ as a kernel since you know $\\phi$ exists, even if\n", "you don’t know what $\\phi$ is. \n", "\n", "Note that some frequently used kernels (such as the Sigmoid kernel)\n", "don’t respect all of Mercer’s conditions, yet they generally work well\n", - "in practice.\n", - "\n", - "\n", + "in practice." + ] + }, + { + "cell_type": "markdown", + "id": "2e83aafb", + "metadata": { + "editable": true + }, + "source": [ "## The moons example" ] }, { "cell_type": "code", "execution_count": 3, + "id": "92363579", "metadata": { - "collapsed": false + "collapsed": false, + "editable": true }, "outputs": [], "source": [ @@ -1672,7 +2205,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "70fb0bce", + "metadata": { + "editable": true + }, "source": [ "## Mathematical optimization of convex functions\n", "\n", @@ -1681,7 +2217,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "140dc96a", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\begin{align*}\n", @@ -1693,7 +2232,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "ad0c0ee0", + "metadata": { + "editable": true + }, "source": [ "subject to some constraints for say a selected set $i=1,2,\\dots, n$.\n", "In our case we are optimizing with respect to the Lagrangian multipliers $\\lambda_i$, and the\n", @@ -1702,10 +2244,16 @@ "In our case we are particularly interested in a class of optimization problems called convex optmization problems. \n", "In our discussion on gradient descent methods we discussed at length the definition of a convex function. \n", "\n", - "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/).\n", - "\n", - "\n", - "\n", + "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/)." + ] + }, + { + "cell_type": "markdown", + "id": "8bdecd3e", + "metadata": { + "editable": true + }, + "source": [ "## How do we solve these problems?\n", "\n", "If we use Python as programming language and wish to venture beyond\n", @@ -1722,8 +2270,10 @@ { "cell_type": "code", "execution_count": 4, + "id": "1ce25f94", "metadata": { - "collapsed": false + "collapsed": false, + "editable": true }, "outputs": [], "source": [ @@ -1733,11 +2283,21 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "7ec6416c", + "metadata": { + "editable": true + }, + "source": [ + "This will make our life much easier. You don't need t write your own optimizer." + ] + }, + { + "cell_type": "markdown", + "id": "6c9e8166", + "metadata": { + "editable": true + }, "source": [ - "This will make our life much easier. You don't need t write your own optimizer.\n", - "\n", - "\n", "## A simple example\n", "\n", "We remind ourselves about the general problem we want to solve" @@ -1745,7 +2305,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "cc70c995", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\begin{align*}\n", @@ -1757,14 +2320,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "67f4203f", + "metadata": { + "editable": true + }, "source": [ "Let us show how to perform the optmization using a simple case. Assume we want to optimize the following problem" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "512e384c", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\begin{align*}\n", @@ -1780,14 +2349,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "64f068fd", + "metadata": { + "editable": true + }, "source": [ "The minimization problem can be rewritten in terms of vectors and matrices as (with $x$ and $y$ being the unknowns)" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "8ed41caf", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\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}.\n", @@ -1796,14 +2371,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "26ac4c8e", + "metadata": { + "editable": true + }, "source": [ "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" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "6f912005", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\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}.\n", @@ -1812,14 +2393,20 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "ace44062", + "metadata": { + "editable": true + }, "source": [ "We have collapsed all the inequalities into a single matrix $\\boldsymbol{G}$. We see also that our matrix" ] }, { "cell_type": "markdown", - "metadata": {}, + "id": "bec0945a", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{P} =\\begin{bmatrix} 1 & 0\\\\ 0 & 0 \\end{bmatrix}\n", @@ -1828,7 +2415,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "aea163b1", + "metadata": { + "editable": true + }, "source": [ "is clearly positive semi-definite (all eigenvalues larger or equal zero). \n", "Finally, the vector $\\boldsymbol{h}$ is defined as" @@ -1836,7 +2426,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "31d35d0f", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\boldsymbol{h} = \\begin{bmatrix}0 \\\\ 0\\\\ -15 \\\\ 100 \\\\ 80\\end{bmatrix}.\n", @@ -1845,7 +2438,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "9738a887", + "metadata": { + "editable": true + }, "source": [ "Since we don't have any equalities the matrix $\\boldsymbol{A}$ is set to zero\n", "The following code solves the equations for us" @@ -1854,8 +2450,10 @@ { "cell_type": "code", "execution_count": 5, + "id": "78e54b3b", "metadata": { - "collapsed": false + "collapsed": false, + "editable": true }, "outputs": [], "source": [ @@ -1876,7 +2474,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "16699496", + "metadata": { + "editable": true + }, "source": [ "## Back to the more realistic cases\n", "\n", @@ -1885,7 +2486,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "667e4ebd", + "metadata": { + "editable": true + }, "source": [ "$$\n", "\\frac{1}{2} \\boldsymbol{\\lambda}^T\\begin{bmatrix} y_1y_1K(\\boldsymbol{x}_1,\\boldsymbol{x}_1) & y_1y_2K(\\boldsymbol{x}_1,\\boldsymbol{x}_2) & \\dots & \\dots & y_1y_nK(\\boldsymbol{x}_1,\\boldsymbol{x}_n) \\\\\n", @@ -1899,7 +2503,10 @@ }, { "cell_type": "markdown", - "metadata": {}, + "id": "7986d8fd", + "metadata": { + "editable": true + }, "source": [ "subject to $\\boldsymbol{y}^T\\boldsymbol{\\lambda}=0$. Here we defined the vectors $\\boldsymbol{\\lambda} =[\\lambda_1,\\lambda_2,\\dots,\\lambda_n]$ and \n", "$\\boldsymbol{y}=[y_1,y_2,\\dots,y_n]$. \n", @@ -1911,5 +2518,5 @@ ], "metadata": {}, "nbformat": 4, - "nbformat_minor": 4 + "nbformat_minor": 5 } diff --git a/doc/src/Projects/2021/Project3/Project3.do.txt b/doc/src/Projects/2021/Project3/Project3.do.txt new file mode 100644 index 000000000..f4a7dfd22 --- /dev/null +++ b/doc/src/Projects/2021/Project3/Project3.do.txt @@ -0,0 +1,283 @@ +TITLE: Project 3 on Machine Learning, deadline December 17, 2021 +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":"https://archive.ics.uci.edu/ml/index.php". +o Or other sources. + +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_, _Adversarial 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. You can also study unsupervised methods, although we in this course have mainly paid attendtion to supervised learning. The methods we have explored as _Principal Component Analysis_ and _k-means Clustering_. + +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/week42/html/week42.html" and/or the textbook by "Yadav et al":"https://www.springer.com/gp/book/9789401798150". + + +_Note_: Project 3 has an additional exercise which can give you an additional score of 30 (thirty) points. These are added to the total score from all projects. See below for the additional exercise. + +===== 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. + + +===== Additonal (optional) exercise, adding 30 more points to final score ===== + +This exercise can be done independently of the other tasks. Here you +can also choose the data set you want to use. Furthermore, you can use +your codes from projects 1 and 2 as well as the codes here or simply use +libraries like _Scikit-Learn_, _Tensorflow_ or similar. + +Your task is to perform an analysis of the bias-variance tradeoff +using at least three of the main sets of algorithms we have discussed in this +course. We will limit ourselves to a regression problem (fitting). However, feel free to venture into a classification problem. + +You +are free to choose between bootstrap for resampling (recommended) or +cross-validation in order to get the best possible estimates. The +methods you could study are Linear Regression (OLS, Ridge and Lasso), +deep learning (feed forward neural networks and/or recurrent neural +networks), Ensemble methods (decision trees, bagging, random forests +and boosting) and support vector machines. + +Study the bias-variance tradeoff for at least three of these sets of +algorithms for a data set of your choice as function of the complexity +of your model. Comment and discuss the results. Discuss the pros and +cons of the various methods. Are there some methods which provide both +low variance and low bias? + +_Hint_: when you use different methods, pay attention to how you represent (and understand) the complexity of the model. For example, when using decision trees you may represent the complexity of your model by the depth of the tree. + + + + +===== 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. + + + + diff --git a/doc/src/Projects/2021/Project3/clean.sh b/doc/src/Projects/2021/Project3/clean.sh new file mode 100755 index 000000000..2e5da2c72 --- /dev/null +++ b/doc/src/Projects/2021/Project3/clean.sh @@ -0,0 +1,3 @@ +#!/bin/sh +doconce clean +rm -rf *.pdf *.tex ipynb*.tar.gz *.html ._*.html *~ reveal.js Trash README.txt diff --git a/doc/src/Projects/2021/Project3/make.sh b/doc/src/Projects/2021/Project3/make.sh new file mode 100755 index 000000000..3b48fe3c7 --- /dev/null +++ b/doc/src/Projects/2021/Project3/make.sh @@ -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/2021 +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 < @@ -455,7 +455,7 @@ end of tocinfo -->
  • ipynb file
  • -

    Project 2, Deadline November 15 (available October 12)

    +

    Project 2, Deadline November 20 (available October 12)

    • LaTeX and PDF:
      • @@ -472,7 +472,7 @@ end of tocinfo -->
      • ipynb file
    -

    Project 3, Deadline December 13 (available November 12)

    +

    Project 3, Deadline December 17 (available November 13)

    • LaTeX and PDF:
      • diff --git a/doc/web/tmp_mako__course.do.txt b/doc/web/tmp_mako__course.do.txt index c2c7edfc5..2a1238eae 100644 --- a/doc/web/tmp_mako__course.do.txt +++ b/doc/web/tmp_mako__course.do.txt @@ -209,7 +209,7 @@ The teaching material is produced in various formats for running codes (jupyter * Jupyter notebook: * "ipynb file": "http://compphysics.github.io/MachineLearning/doc/Projects/2021/Project1/ipynb/Project1.ipynb" -=== Project 2, Deadline November 15 (available October 12) === +=== Project 2, Deadline November 20 (available October 12) === * LaTeX and PDF: * "Latex file":"http://compphysics.github.io/MachineLearning/doc/Projects/2021/Project2/pdf/Project2.tex" * "PDF file":"http://compphysics.github.io/MachineLearning/doc/Projects/2021/Project2/pdf/Project2.pdf" @@ -220,7 +220,7 @@ The teaching material is produced in various formats for running codes (jupyter * "ipynb file": "http://compphysics.github.io/MachineLearning/doc/Projects/2021/Project2/ipynb/Project2.ipynb" -=== Project 3, Deadline December 13 (available November 12) === +=== Project 3, Deadline December 17 (available November 13) === * LaTeX and PDF: * "LaTex file":"http://compphysics.github.io/MachineLearning/doc/Projects/2021/Project3/pdf/Project3.tex" * "PDF file":"http://compphysics.github.io/MachineLearning/doc/Projects/2021/Project3/pdf/Project3.pdf"