diff --git a/doc/Projects/2019/Project1/html/._Project1-bs000.html b/doc/Projects/2019/Project1/html/._Project1-bs000.html new file mode 100644 index 000000000..d90fd1c30 --- /dev/null +++ b/doc/Projects/2019/Project1/html/._Project1-bs000.html @@ -0,0 +1,327 @@ + + + + + + + + +Project 1 on Machine Learning, deadline September 30, 2019 + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + + + +
+

Project 1 on Machine Learning, deadline September 30, 2019

+ +

+ + +

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

+ + +

Department of Physics, University of Oslo, Norway
+
+

+

Aug 26, 2019

+
+

+

+ +

Regression analysis and resampling methods

+ +

+The main aim of this project is to study in more detail various +regression methods, including the Ordinary Least Squares (OLS) method, +Ridge regression and finally Lasso regression. +The methods are in turn combined with resampling techniques. + +

Part a): Ordinary Least Square on the Franke function with resampling

+ +

+We will thus again generate our own dataset for a function \( \mathrm{FrankeFunction}(x,y) \) where +\( x,y \in [0,1] \) could be defined by random numbers computed with the uniform +distribution. The function \( f(x,y) \) is the Franke function. You should explore also the addition +an added stochastic noise to this function using the normal distribution \( \cal{N}(0,1) \). + +

+Write your own code (using either a matrix inversion or a singular value decomposition from e.g., numpy ) or use your code from homeworks 1 and 2 +and perform a standard least square regression analysis using polynomials in \( x \) and \( y \) up to fifth order. Find the confidence intervals of the parameters \( \beta \) by computing their variances, evaluate the Mean Squared error (MSE) +$$ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n} +\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, +$$ + +and the \( R^2 \) score function. +If \( \tilde{\hat{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(\hat{y}, \tilde{\hat{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 \( \hat{y} \) as +$$ +\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. +$$ + +

+Perform a resampling of the data where you split the data in training data and test data. Implement the \( k \)-fold cross-validation algorithm and/or the bootstrap algorithm +and evaluate again the MSE and the \( R^2 \) functions resulting from the test data. Evaluate also the bias and variance of the final models using for example equation (7.9) in the textbook of Hastie et al. + +

Part b): Ridge Regression with resampling

+ +

+Write your own code for the Ridge method, either using matrix inversion or the singular value decomposition as done in the previous exercise or howework 2 (see also chapter 3.4 of Hastie et al., equations (3.43) and (3.44)). Perform the same analysis as in the previous exercise (for the same polynomials and include resampling techniques) but now for different values of \( \lambda \). Compare and analyze your results with those obtained in part a). Study the dependence on \( \lambda \) while also varying eventually the strength of the noise in your expression for \( \mathrm{FrankeFunction}(x,y) \). + +

Part c): Lasso Regression with resampling

+ +

+This part is essentially a repeat of the previous two ones, but now with Lasso regression. Write either your own code or, in this case, you can also use the functionalities of scikit-learn. Give a critical discussion of the three methods and a judgement of which model fits the data best. + +

Part e) OLS, Ridge and Lasso regression with resampling

+ +

+At the end, you should pesent a critical evaluation of your results and discuss the applicability of these regression methods to the type of data presented here. + +

Background literature

+ +
    +
  1. For a discussion and derivation of the variances and mean squared errors using linear regression, see the Lecture notes on ridge regression by Wessel N. van Wieringen
  2. +
  3. The textbook of Trevor Hastie, Robert Tibshirani, Jerome H. Friedman, The Elements of Statistical Learning, Springer, chapters 3 and 7 are the most relevant ones for the analysis here.
  4. +
+ +

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-2019, "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/2019/Project1/html/Project1-bs.html b/doc/Projects/2019/Project1/html/Project1-bs.html new file mode 100644 index 000000000..d90fd1c30 --- /dev/null +++ b/doc/Projects/2019/Project1/html/Project1-bs.html @@ -0,0 +1,327 @@ + + + + + + + + +Project 1 on Machine Learning, deadline September 30, 2019 + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + + + +
+

Project 1 on Machine Learning, deadline September 30, 2019

+ +

+ + +

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

+ + +

Department of Physics, University of Oslo, Norway
+
+

+

Aug 26, 2019

+
+

+

+ +

Regression analysis and resampling methods

+ +

+The main aim of this project is to study in more detail various +regression methods, including the Ordinary Least Squares (OLS) method, +Ridge regression and finally Lasso regression. +The methods are in turn combined with resampling techniques. + +

Part a): Ordinary Least Square on the Franke function with resampling

+ +

+We will thus again generate our own dataset for a function \( \mathrm{FrankeFunction}(x,y) \) where +\( x,y \in [0,1] \) could be defined by random numbers computed with the uniform +distribution. The function \( f(x,y) \) is the Franke function. You should explore also the addition +an added stochastic noise to this function using the normal distribution \( \cal{N}(0,1) \). + +

+Write your own code (using either a matrix inversion or a singular value decomposition from e.g., numpy ) or use your code from homeworks 1 and 2 +and perform a standard least square regression analysis using polynomials in \( x \) and \( y \) up to fifth order. Find the confidence intervals of the parameters \( \beta \) by computing their variances, evaluate the Mean Squared error (MSE) +$$ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n} +\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, +$$ + +and the \( R^2 \) score function. +If \( \tilde{\hat{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(\hat{y}, \tilde{\hat{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 \( \hat{y} \) as +$$ +\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. +$$ + +

+Perform a resampling of the data where you split the data in training data and test data. Implement the \( k \)-fold cross-validation algorithm and/or the bootstrap algorithm +and evaluate again the MSE and the \( R^2 \) functions resulting from the test data. Evaluate also the bias and variance of the final models using for example equation (7.9) in the textbook of Hastie et al. + +

Part b): Ridge Regression with resampling

+ +

+Write your own code for the Ridge method, either using matrix inversion or the singular value decomposition as done in the previous exercise or howework 2 (see also chapter 3.4 of Hastie et al., equations (3.43) and (3.44)). Perform the same analysis as in the previous exercise (for the same polynomials and include resampling techniques) but now for different values of \( \lambda \). Compare and analyze your results with those obtained in part a). Study the dependence on \( \lambda \) while also varying eventually the strength of the noise in your expression for \( \mathrm{FrankeFunction}(x,y) \). + +

Part c): Lasso Regression with resampling

+ +

+This part is essentially a repeat of the previous two ones, but now with Lasso regression. Write either your own code or, in this case, you can also use the functionalities of scikit-learn. Give a critical discussion of the three methods and a judgement of which model fits the data best. + +

Part e) OLS, Ridge and Lasso regression with resampling

+ +

+At the end, you should pesent a critical evaluation of your results and discuss the applicability of these regression methods to the type of data presented here. + +

Background literature

+ +
    +
  1. For a discussion and derivation of the variances and mean squared errors using linear regression, see the Lecture notes on ridge regression by Wessel N. van Wieringen
  2. +
  3. The textbook of Trevor Hastie, Robert Tibshirani, Jerome H. Friedman, The Elements of Statistical Learning, Springer, chapters 3 and 7 are the most relevant ones for the analysis here.
  4. +
+ +

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-2019, "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/2019/Project1/html/Project1.html b/doc/Projects/2019/Project1/html/Project1.html new file mode 100644 index 000000000..da316d785 --- /dev/null +++ b/doc/Projects/2019/Project1/html/Project1.html @@ -0,0 +1,269 @@ + + + + + + + + +Project 1 on Machine Learning, deadline September 30, 2019 + + + + + + + + + + + + + + + + + + + + + + + +

Project 1 on Machine Learning, deadline September 30, 2019

+ +

+ + +

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

+ + +

Department of Physics, University of Oslo, Norway
+
+

+

Aug 26, 2019

+
+ +

Regression analysis and resampling methods

+ +

+The main aim of this project is to study in more detail various +regression methods, including the Ordinary Least Squares (OLS) method, +Ridge regression and finally Lasso regression. +The methods are in turn combined with resampling techniques. + +

Part a): Ordinary Least Square on the Franke function with resampling

+ +

+We will thus again generate our own dataset for a function \( \mathrm{FrankeFunction}(x,y) \) where +\( x,y \in [0,1] \) could be defined by random numbers computed with the uniform +distribution. The function \( f(x,y) \) is the Franke function. You should explore also the addition +an added stochastic noise to this function using the normal distribution \( \cal{N}(0,1) \). + +

+Write your own code (using either a matrix inversion or a singular value decomposition from e.g., numpy ) or use your code from homeworks 1 and 2 +and perform a standard least square regression analysis using polynomials in \( x \) and \( y \) up to fifth order. Find the confidence intervals of the parameters \( \beta \) by computing their variances, evaluate the Mean Squared error (MSE) +$$ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n} +\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, +$$ + +and the \( R^2 \) score function. +If \( \tilde{\hat{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(\hat{y}, \tilde{\hat{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 \( \hat{y} \) as +$$ +\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. +$$ + +

+Perform a resampling of the data where you split the data in training data and test data. Implement the \( k \)-fold cross-validation algorithm and/or the bootstrap algorithm +and evaluate again the MSE and the \( R^2 \) functions resulting from the test data. Evaluate also the bias and variance of the final models using for example equation (7.9) in the textbook of Hastie et al. + +

Part b): Ridge Regression with resampling

+ +

+Write your own code for the Ridge method, either using matrix inversion or the singular value decomposition as done in the previous exercise or howework 2 (see also chapter 3.4 of Hastie et al., equations (3.43) and (3.44)). Perform the same analysis as in the previous exercise (for the same polynomials and include resampling techniques) but now for different values of \( \lambda \). Compare and analyze your results with those obtained in part a). Study the dependence on \( \lambda \) while also varying eventually the strength of the noise in your expression for \( \mathrm{FrankeFunction}(x,y) \). + +

Part c): Lasso Regression with resampling

+ +

+This part is essentially a repeat of the previous two ones, but now with Lasso regression. Write either your own code or, in this case, you can also use the functionalities of scikit-learn. Give a critical discussion of the three methods and a judgement of which model fits the data best. + +

Part e) OLS, Ridge and Lasso regression with resampling

+ +

+At the end, you should pesent a critical evaluation of your results and discuss the applicability of these regression methods to the type of data presented here. + +

Background literature

+ +
    +
  1. For a discussion and derivation of the variances and mean squared errors using linear regression, see the Lecture notes on ridge regression by Wessel N. van Wieringen
  2. +
  3. The textbook of Trevor Hastie, Robert Tibshirani, Jerome H. Friedman, The Elements of Statistical Learning, Springer, chapters 3 and 7 are the most relevant ones for the analysis here.
  4. +
+ +

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-2019, "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/2019/Project1/ipynb/ipynb-Project1-src.tar.gz b/doc/Projects/2019/Project1/ipynb/ipynb-Project1-src.tar.gz new file mode 100644 index 000000000..02a09a19b Binary files /dev/null and b/doc/Projects/2019/Project1/ipynb/ipynb-Project1-src.tar.gz differ diff --git a/doc/Projects/2019/Project1/pdf/Project1.p.tex b/doc/Projects/2019/Project1/pdf/Project1.p.tex new file mode 100644 index 000000000..7bd7e93f0 --- /dev/null +++ b/doc/Projects/2019/Project1/pdf/Project1.p.tex @@ -0,0 +1,327 @@ +%% +%% Automatically generated file from DocOnce source +%% (https://github.com/hplgit/doconce/) +%% +%% +% #ifdef PTEX2TEX_EXPLANATION +%% +%% The file follows the ptex2tex extended LaTeX format, see +%% ptex2tex: http://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: http://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-2019, "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-2019, "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 1 on Machine Learning, deadline September 30, 2019 +\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} +Aug 26, 2019 +\end{center} +% --- end date --- + +\vspace{1cm} + + +\subsection{Regression analysis and resampling methods} + +The main aim of this project is to study in more detail various +regression methods, including the Ordinary Least Squares (OLS) method, +Ridge regression and finally Lasso regression. +The methods are in turn combined with resampling techniques. + + +\paragraph{Part a): Ordinary Least Square on the Franke function with resampling.} +We will thus again generate our own dataset for a function $\mathrm{FrankeFunction}(x,y)$ where +$x,y \in [0,1]$ could be defined by random numbers computed with the uniform +distribution. The function $f(x,y)$ is the Franke function. You should explore also the addition +an added stochastic noise to this function using the normal distribution $\cal{N}(0,1)$. + +Write your own code (using either a matrix inversion or a singular value decomposition from e.g., \textbf{numpy} ) or use your code from homeworks 1 and 2 +and perform a standard least square regression analysis using polynomials in $x$ and $y$ up to fifth order. Find the confidence intervals of the parameters $\beta$ by computing their variances, evaluate the Mean Squared error (MSE) +\[ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n} +\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, +\] +and the $R^2$ score function. +If $\tilde{\hat{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(\hat{y}, \tilde{\hat{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 $\hat{y}$ as +\[ +\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. +\] + +Perform a resampling of the data where you split the data in training data and test data. Implement the $k$-fold cross-validation algorithm and/or the bootstrap algorithm +and evaluate again the MSE and the $R^2$ functions resulting from the test data. Evaluate also the bias and variance of the final models using for example equation (7.9) in the textbook of Hastie \emph{et al.} + + + +\paragraph{Part b): Ridge Regression with resampling.} +Write your own code for the Ridge method, either using matrix inversion or the singular value decomposition as done in the previous exercise or howework 2 (see also chapter 3.4 of Hastie \emph{et al.}, equations (3.43) and (3.44)). Perform the same analysis as in the previous exercise (for the same polynomials and include resampling techniques) but now for different values of $\lambda$. Compare and analyze your results with those obtained in part a). Study the dependence on $\lambda$ while also varying eventually the strength of the noise in your expression for $\mathrm{FrankeFunction}(x,y)$. + +\paragraph{Part c): Lasso Regression with resampling.} +This part is essentially a repeat of the previous two ones, but now with Lasso regression. Write either your own code or, in this case, you can also use the functionalities of \textbf{scikit-learn}. Give a critical discussion of the three methods and a judgement of which model fits the data best. + + +\paragraph{Part e) OLS, Ridge and Lasso regression with resampling.} +At the end, you should pesent a critical evaluation of your results and discuss the applicability of these regression methods to the type of data presented here. + + + + +\subsection{Background literature} + +\begin{enumerate} +\item For a discussion and derivation of the variances and mean squared errors using linear regression, see the \href{{https://arxiv.org/abs/1509.09169}}{Lecture notes on ridge regression by Wessel N. van Wieringen} + +\item The textbook of \href{{https://www.springer.com/gp/book/9780387848570}}{Trevor Hastie, Robert Tibshirani, Jerome H. Friedman, The Elements of Statistical Learning, Springer}, chapters 3 and 7 are the most relevant ones for the analysis here. +\end{enumerate} + +\noindent +\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 Devilry to hand in your projects, log in at \href{{http://devilry.ifi.uio.no}}{\nolinkurl{http://devilry.ifi.uio.no}} with your normal UiO username and password and choose either 'fysstk3155' or 'fysstk4155'. There you can load up the files within the deadline. + + \item Upload \textbf{only} the report file! For the source code file(s) you have developed please provide us with your link to your github 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 git 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. + + \item In this and all later projects, you should include tests (for example unit tests) of your code(s). + + \item Comments from us on your projects, approval or not, corrections to be made etc can be found under your Devilry domain and are only visible to you and the teachers of the course. +\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/2019/Project1/pdf/Project1.pdf b/doc/Projects/2019/Project1/pdf/Project1.pdf new file mode 100644 index 000000000..4f3b2f826 Binary files /dev/null and b/doc/Projects/2019/Project1/pdf/Project1.pdf differ diff --git a/doc/Projects/2019/Project1/pdf/Project1.tex b/doc/Projects/2019/Project1/pdf/Project1.tex new file mode 100644 index 000000000..bc5aeab20 --- /dev/null +++ b/doc/Projects/2019/Project1/pdf/Project1.tex @@ -0,0 +1,299 @@ +%% +%% Automatically generated file from DocOnce source +%% (https://github.com/hplgit/doconce/) +%% +%% + + +%-------------------- 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-2019, "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-2019, "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 1 on Machine Learning, deadline September 30, 2019 +\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} +Aug 26, 2019 +\end{center} +% --- end date --- + +\vspace{1cm} + + +\subsection*{Regression analysis and resampling methods} + +The main aim of this project is to study in more detail various +regression methods, including the Ordinary Least Squares (OLS) method, +Ridge regression and finally Lasso regression. +The methods are in turn combined with resampling techniques. + + +\paragraph{Part a): Ordinary Least Square on the Franke function with resampling.} +We will thus again generate our own dataset for a function $\mathrm{FrankeFunction}(x,y)$ where +$x,y \in [0,1]$ could be defined by random numbers computed with the uniform +distribution. The function $f(x,y)$ is the Franke function. You should explore also the addition +an added stochastic noise to this function using the normal distribution $\cal{N}(0,1)$. + +Write your own code (using either a matrix inversion or a singular value decomposition from e.g., \textbf{numpy} ) or use your code from homeworks 1 and 2 +and perform a standard least square regression analysis using polynomials in $x$ and $y$ up to fifth order. Find the confidence intervals of the parameters $\beta$ by computing their variances, evaluate the Mean Squared error (MSE) +\[ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n} +\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, +\] +and the $R^2$ score function. +If $\tilde{\hat{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(\hat{y}, \tilde{\hat{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 $\hat{y}$ as +\[ +\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. +\] + +Perform a resampling of the data where you split the data in training data and test data. Implement the $k$-fold cross-validation algorithm and/or the bootstrap algorithm +and evaluate again the MSE and the $R^2$ functions resulting from the test data. Evaluate also the bias and variance of the final models using for example equation (7.9) in the textbook of Hastie \emph{et al.} + + + +\paragraph{Part b): Ridge Regression with resampling.} +Write your own code for the Ridge method, either using matrix inversion or the singular value decomposition as done in the previous exercise or howework 2 (see also chapter 3.4 of Hastie \emph{et al.}, equations (3.43) and (3.44)). Perform the same analysis as in the previous exercise (for the same polynomials and include resampling techniques) but now for different values of $\lambda$. Compare and analyze your results with those obtained in part a). Study the dependence on $\lambda$ while also varying eventually the strength of the noise in your expression for $\mathrm{FrankeFunction}(x,y)$. + +\paragraph{Part c): Lasso Regression with resampling.} +This part is essentially a repeat of the previous two ones, but now with Lasso regression. Write either your own code or, in this case, you can also use the functionalities of \textbf{scikit-learn}. Give a critical discussion of the three methods and a judgement of which model fits the data best. + + +\paragraph{Part e) OLS, Ridge and Lasso regression with resampling.} +At the end, you should pesent a critical evaluation of your results and discuss the applicability of these regression methods to the type of data presented here. + + + + +\subsection*{Background literature} + +\begin{enumerate} +\item For a discussion and derivation of the variances and mean squared errors using linear regression, see the \href{{https://arxiv.org/abs/1509.09169}}{Lecture notes on ridge regression by Wessel N. van Wieringen} + +\item The textbook of \href{{https://www.springer.com/gp/book/9780387848570}}{Trevor Hastie, Robert Tibshirani, Jerome H. Friedman, The Elements of Statistical Learning, Springer}, chapters 3 and 7 are the most relevant ones for the analysis here. +\end{enumerate} + +\noindent +\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 Devilry to hand in your projects, log in at \href{{http://devilry.ifi.uio.no}}{\nolinkurl{http://devilry.ifi.uio.no}} with your normal UiO username and password and choose either 'fysstk3155' or 'fysstk4155'. There you can load up the files within the deadline. + + \item Upload \textbf{only} the report file! For the source code file(s) you have developed please provide us with your link to your github 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 git 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. + + \item In this and all later projects, you should include tests (for example unit tests) of your code(s). + + \item Comments from us on your projects, approval or not, corrections to be made etc can be found under your Devilry domain and are only visible to you and the teachers of the course. +\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/Projects/2019/hw2/html/._hw2-bs000.html b/doc/Projects/2019/hw2/html/._hw2-bs000.html new file mode 100644 index 000000000..8cd53ae0f --- /dev/null +++ b/doc/Projects/2019/hw2/html/._hw2-bs000.html @@ -0,0 +1,212 @@ + + + + + + + + +Homework 2 + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + + + +
+

Homework 2

+ +

+ + +

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

+ + +

Department of Physics, University of Oslo, Norway
+
+

+

Aug 28, 2019

+
+

+

+ +

Exercise 4

+ +

+This exercise is a continuation of exercise 2 from homework 1. We will +use the same function to generate our data set, still staying with a +simple function \( y(x) \) which we want to fit using linear regression, +but now extending the analysis to include the Ridge and the Lasso +regression methods. You can use the code under the Regression as an example on how to use the Ridge and the Lasso methods, see the regression slides). + +

+We will thus again 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)
+y = 5*x*x+0.1*np.random.randn(100,1)
+
+
    +
  1. Write your own code for the Ridge method (see chapter 3.4 of Hastie et al., equations (3.43) and (3.44)) and compute the parametrization for different values of \( \lambda \). Compare and analyze your results with those from exercise 2. Study the dependence on \( \lambda \) while also varying the strength of the noise in your expression for \( y(x) \).
  2. +
  3. Repeat the above but using the functionality of scikit-learn. Compare your code with the results from scikit-learn. Remember to run with the same random numbers for generating \( x \) and \( y \).
  4. +
  5. Our next step is to study the variance of the parameters \( \beta_1 \) and \( \beta_2 \) (assuming that we are parametrizing our function with a second-order polynomial. We will use standard linear regression and the Ridge regression. You can now opt for either writing your own function that calculates the variance of these paramaters (recall that this is equal to the diagonal elements of the matrix \( (\hat{X}^T\hat{X})+\lambda\hat{I})^{-1} \)) or use the functionality of scikit-learn and compute their variances. Discuss the results of these variances as functions of \( \lambda \). In particular, try to link your discussion with the discussion in Hastie et al. and their figure 3.11.
  6. +
  7. Repeat the previous step but add now the Lasso method, see equation (3.53) of Hastie et al.. Discuss your results and compare with standard regression and the Ridge regression results. You can write your own code or use the functionality of scikit-learn. We recommend the last since we have not yet discussed how to solve the Lasso equations numerically.
  8. +
  9. Finally, using scikit-learn or your own code, compute also the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error defined as
  10. +
+ +$$ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n} +\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, +$$ + +and the \( R^2 \) score function. +If \( \tilde{\hat{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(\hat{y}, \tilde{\hat{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 \( \hat{y} \) as +$$ +\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. +$$ + +Discuss these quantities as functions of the variable \( \lambda \) in the Ridge and Lasso regression methods. + +

Exercise 5

+ +

+Using the singular value decomposition, show that the variance of the direction vector +\( \hat{z}_i=\hat{X}\hat{v}_i=\hat{u}_1d_1 \) is equal to (equation (3.49) of Hastie et al.) +$$ +\mathrm{Var}(\hat{z}_i)=\frac{d_i^2}{N}, +$$ + +where \( d_i \) are the singular values of the matrix \( \hat{X} \). In Hastie et al, the matrix elements of \( X \) are centered. The consequence is that the mean values of for example \( \hat{u}_i \) are zero. + +

+Give an interpretation of these results, in particular in connection with the variance of the coefficients you obtained in the previous exercise. + +

+ +

+ + +
+ + + + + + + +
+ © 1999-2019, "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/2019/hw2/html/hw2-bs.html b/doc/Projects/2019/hw2/html/hw2-bs.html new file mode 100644 index 000000000..8cd53ae0f --- /dev/null +++ b/doc/Projects/2019/hw2/html/hw2-bs.html @@ -0,0 +1,212 @@ + + + + + + + + +Homework 2 + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

 

 

 

+ + + + + + +
+

Homework 2

+ +

+ + +

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

+ + +

Department of Physics, University of Oslo, Norway
+
+

+

Aug 28, 2019

+
+

+

+ +

Exercise 4

+ +

+This exercise is a continuation of exercise 2 from homework 1. We will +use the same function to generate our data set, still staying with a +simple function \( y(x) \) which we want to fit using linear regression, +but now extending the analysis to include the Ridge and the Lasso +regression methods. You can use the code under the Regression as an example on how to use the Ridge and the Lasso methods, see the regression slides). + +

+We will thus again 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)
+y = 5*x*x+0.1*np.random.randn(100,1)
+
+
    +
  1. Write your own code for the Ridge method (see chapter 3.4 of Hastie et al., equations (3.43) and (3.44)) and compute the parametrization for different values of \( \lambda \). Compare and analyze your results with those from exercise 2. Study the dependence on \( \lambda \) while also varying the strength of the noise in your expression for \( y(x) \).
  2. +
  3. Repeat the above but using the functionality of scikit-learn. Compare your code with the results from scikit-learn. Remember to run with the same random numbers for generating \( x \) and \( y \).
  4. +
  5. Our next step is to study the variance of the parameters \( \beta_1 \) and \( \beta_2 \) (assuming that we are parametrizing our function with a second-order polynomial. We will use standard linear regression and the Ridge regression. You can now opt for either writing your own function that calculates the variance of these paramaters (recall that this is equal to the diagonal elements of the matrix \( (\hat{X}^T\hat{X})+\lambda\hat{I})^{-1} \)) or use the functionality of scikit-learn and compute their variances. Discuss the results of these variances as functions of \( \lambda \). In particular, try to link your discussion with the discussion in Hastie et al. and their figure 3.11.
  6. +
  7. Repeat the previous step but add now the Lasso method, see equation (3.53) of Hastie et al.. Discuss your results and compare with standard regression and the Ridge regression results. You can write your own code or use the functionality of scikit-learn. We recommend the last since we have not yet discussed how to solve the Lasso equations numerically.
  8. +
  9. Finally, using scikit-learn or your own code, compute also the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error defined as
  10. +
+ +$$ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n} +\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, +$$ + +and the \( R^2 \) score function. +If \( \tilde{\hat{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(\hat{y}, \tilde{\hat{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 \( \hat{y} \) as +$$ +\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. +$$ + +Discuss these quantities as functions of the variable \( \lambda \) in the Ridge and Lasso regression methods. + +

Exercise 5

+ +

+Using the singular value decomposition, show that the variance of the direction vector +\( \hat{z}_i=\hat{X}\hat{v}_i=\hat{u}_1d_1 \) is equal to (equation (3.49) of Hastie et al.) +$$ +\mathrm{Var}(\hat{z}_i)=\frac{d_i^2}{N}, +$$ + +where \( d_i \) are the singular values of the matrix \( \hat{X} \). In Hastie et al, the matrix elements of \( X \) are centered. The consequence is that the mean values of for example \( \hat{u}_i \) are zero. + +

+Give an interpretation of these results, in particular in connection with the variance of the coefficients you obtained in the previous exercise. + +

+ +

+ + +
+ + + + + + + +
+ © 1999-2019, "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/2019/hw2/html/hw2.html b/doc/Projects/2019/hw2/html/hw2.html new file mode 100644 index 000000000..4e4a6dfda --- /dev/null +++ b/doc/Projects/2019/hw2/html/hw2.html @@ -0,0 +1,161 @@ + + + + + + + + +Homework 2 + + + + + + + + + + + + + + + + + + + + + + + +

Homework 2

+ +

+ + +

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

+ + +

Department of Physics, University of Oslo, Norway
+
+

+

Aug 28, 2019

+
+ +

Exercise 4

+ +

+This exercise is a continuation of exercise 2 from homework 1. We will +use the same function to generate our data set, still staying with a +simple function \( y(x) \) which we want to fit using linear regression, +but now extending the analysis to include the Ridge and the Lasso +regression methods. You can use the code under the Regression as an example on how to use the Ridge and the Lasso methods, see the regression slides). + +

+We will thus again 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)
+y = 5*x*x+0.1*np.random.randn(100,1)
+
+
    +
  1. Write your own code for the Ridge method (see chapter 3.4 of Hastie et al., equations (3.43) and (3.44)) and compute the parametrization for different values of \( \lambda \). Compare and analyze your results with those from exercise 2. Study the dependence on \( \lambda \) while also varying the strength of the noise in your expression for \( y(x) \).
  2. +
  3. Repeat the above but using the functionality of scikit-learn. Compare your code with the results from scikit-learn. Remember to run with the same random numbers for generating \( x \) and \( y \).
  4. +
  5. Our next step is to study the variance of the parameters \( \beta_1 \) and \( \beta_2 \) (assuming that we are parametrizing our function with a second-order polynomial. We will use standard linear regression and the Ridge regression. You can now opt for either writing your own function that calculates the variance of these paramaters (recall that this is equal to the diagonal elements of the matrix \( (\hat{X}^T\hat{X})+\lambda\hat{I})^{-1} \)) or use the functionality of scikit-learn and compute their variances. Discuss the results of these variances as functions of \( \lambda \). In particular, try to link your discussion with the discussion in Hastie et al. and their figure 3.11.
  6. +
  7. Repeat the previous step but add now the Lasso method, see equation (3.53) of Hastie et al.. Discuss your results and compare with standard regression and the Ridge regression results. You can write your own code or use the functionality of scikit-learn. We recommend the last since we have not yet discussed how to solve the Lasso equations numerically.
  8. +
  9. Finally, using scikit-learn or your own code, compute also the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error defined as
  10. +
+ +$$ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n} +\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, +$$ + +and the \( R^2 \) score function. +If \( \tilde{\hat{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(\hat{y}, \tilde{\hat{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 \( \hat{y} \) as +$$ +\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. +$$ + +Discuss these quantities as functions of the variable \( \lambda \) in the Ridge and Lasso regression methods. + +

Exercise 5

+ +

+Using the singular value decomposition, show that the variance of the direction vector +\( \hat{z}_i=\hat{X}\hat{v}_i=\hat{u}_1d_1 \) is equal to (equation (3.49) of Hastie et al.) +$$ +\mathrm{Var}(\hat{z}_i)=\frac{d_i^2}{N}, +$$ + +where \( d_i \) are the singular values of the matrix \( \hat{X} \). In Hastie et al, the matrix elements of \( X \) are centered. The consequence is that the mean values of for example \( \hat{u}_i \) are zero. + +

+Give an interpretation of these results, in particular in connection with the variance of the coefficients you obtained in the previous exercise. + + + + +

+ © 1999-2019, "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/2019/hw2/ipynb/ipynb-hw2-src.tar.gz b/doc/Projects/2019/hw2/ipynb/ipynb-hw2-src.tar.gz new file mode 100644 index 000000000..8b0f16f77 Binary files /dev/null and b/doc/Projects/2019/hw2/ipynb/ipynb-hw2-src.tar.gz differ diff --git a/doc/Projects/2019/hw2/pdf/hw2.p.tex b/doc/Projects/2019/hw2/pdf/hw2.p.tex new file mode 100644 index 000000000..5ff4fd87e --- /dev/null +++ b/doc/Projects/2019/hw2/pdf/hw2.p.tex @@ -0,0 +1,227 @@ +%% +%% Automatically generated file from DocOnce source +%% (https://github.com/hplgit/doconce/) +%% +%% +% #ifdef PTEX2TEX_EXPLANATION +%% +%% The file follows the ptex2tex extended LaTeX format, see +%% ptex2tex: http://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: http://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{ptex2tex} +% #ifdef MINTED +\usepackage{minted} +\usemintedstyle{default} +% #endif + +\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-2019, "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-2019, "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} +Homework 2 +\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} +Aug 28, 2019 +\end{center} +% --- end date --- + +\vspace{1cm} + + +\subsection{Exercise 4} + +This exercise is a continuation of exercise 2 from homework 1. We will +use the same function to generate our data set, still staying with a +simple function $y(x)$ which we want to fit using linear regression, +but now extending the analysis to include the Ridge and the Lasso +regression methods. You can use the code under the Regression as an example on how to use the Ridge and the Lasso methods, see the \href{{https://compphysics.github.io/MachineLearning/doc/pub/Regression/html/Regression-bs.html}}{regression slides}). + +We will thus again 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). +\bpycod +x = np.random.rand(100,1) +y = 5*x*x+0.1*np.random.randn(100,1) +\epycod + +\begin{enumerate} +\item Write your own code for the Ridge method (see chapter 3.4 of Hastie \emph{et al.}, equations (3.43) and (3.44)) and compute the parametrization for different values of $\lambda$. Compare and analyze your results with those from exercise 2. Study the dependence on $\lambda$ while also varying the strength of the noise in your expression for $y(x)$. + +\item Repeat the above but using the functionality of \textbf{scikit-learn}. Compare your code with the results from \textbf{scikit-learn}. Remember to run with the same random numbers for generating $x$ and $y$. + +\item Our next step is to study the variance of the parameters $\beta_1$ and $\beta_2$ (assuming that we are parametrizing our function with a second-order polynomial. We will use standard linear regression and the Ridge regression. You can now opt for either writing your own function that calculates the variance of these paramaters (recall that this is equal to the diagonal elements of the matrix $(\hat{X}^T\hat{X})+\lambda\hat{I})^{-1}$) or use the functionality of \textbf{scikit-learn} and compute their variances. Discuss the results of these variances as functions of $\lambda$. In particular, try to link your discussion with the discussion in Hastie \emph{et al.} and their figure 3.11. + +\item Repeat the previous step but add now the Lasso method, see equation (3.53) of Hastie \emph{et al.}. Discuss your results and compare with standard regression and the Ridge regression results. You can write your own code or use the functionality of \textbf{scikit-learn}. We recommend the last since we have not yet discussed how to solve the Lasso equations numerically. + +\item Finally, using \textbf{scikit-learn} or your own code, compute also the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error defined as +\end{enumerate} + +\noindent +\[ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n} +\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, +\] +and the $R^2$ score function. +If $\tilde{\hat{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(\hat{y}, \tilde{\hat{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 $\hat{y}$ as +\[ +\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. +\] +Discuss these quantities as functions of the variable $\lambda$ in the Ridge and Lasso regression methods. + +\subsection{Exercise 5} + +Using the singular value decomposition, show that the variance of the direction vector +$\hat{z}_i=\hat{X}\hat{v}_i=\hat{u}_1d_1$ is equal to (equation (3.49) of Hastie \emph{et al.}) +\[ +\mathrm{Var}(\hat{z}_i)=\frac{d_i^2}{N}, +\] +where $d_i$ are the singular values of the matrix $\hat{X}$. In Hastie \emph{et al}, the matrix elements of $X$ are centered. The consequence is that the mean values of for example $\hat{u}_i$ are zero. + +Give an interpretation of these results, in particular in connection with the variance of the coefficients you obtained in the previous exercise. + +% ------------------- end of main content --------------- + +% #ifdef PREAMBLE +\end{document} +% #endif + diff --git a/doc/Projects/2019/hw2/pdf/hw2.pdf b/doc/Projects/2019/hw2/pdf/hw2.pdf new file mode 100644 index 000000000..1b4487db9 Binary files /dev/null and b/doc/Projects/2019/hw2/pdf/hw2.pdf differ diff --git a/doc/Projects/2019/hw2/pdf/hw2.tex b/doc/Projects/2019/hw2/pdf/hw2.tex new file mode 100644 index 000000000..1020ef780 --- /dev/null +++ b/doc/Projects/2019/hw2/pdf/hw2.tex @@ -0,0 +1,195 @@ +%% +%% Automatically generated file from DocOnce source +%% (https://github.com/hplgit/doconce/) +%% +%% + + +%-------------------- 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{fancyvrb} % packages needed for verbatim environments + +\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-2019, "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-2019, "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} +Homework 2 +\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} +Aug 28, 2019 +\end{center} +% --- end date --- + +\vspace{1cm} + + +\subsection*{Exercise 4} + +This exercise is a continuation of exercise 2 from homework 1. We will +use the same function to generate our data set, still staying with a +simple function $y(x)$ which we want to fit using linear regression, +but now extending the analysis to include the Ridge and the Lasso +regression methods. You can use the code under the Regression as an example on how to use the Ridge and the Lasso methods, see the \href{{https://compphysics.github.io/MachineLearning/doc/pub/Regression/html/Regression-bs.html}}{regression slides}). + +We will thus again 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). +\begin{verbatim} +x = np.random.rand(100,1) +y = 5*x*x+0.1*np.random.randn(100,1) +\end{verbatim} + +\begin{enumerate} +\item Write your own code for the Ridge method (see chapter 3.4 of Hastie \emph{et al.}, equations (3.43) and (3.44)) and compute the parametrization for different values of $\lambda$. Compare and analyze your results with those from exercise 2. Study the dependence on $\lambda$ while also varying the strength of the noise in your expression for $y(x)$. + +\item Repeat the above but using the functionality of \textbf{scikit-learn}. Compare your code with the results from \textbf{scikit-learn}. Remember to run with the same random numbers for generating $x$ and $y$. + +\item Our next step is to study the variance of the parameters $\beta_1$ and $\beta_2$ (assuming that we are parametrizing our function with a second-order polynomial. We will use standard linear regression and the Ridge regression. You can now opt for either writing your own function that calculates the variance of these paramaters (recall that this is equal to the diagonal elements of the matrix $(\hat{X}^T\hat{X})+\lambda\hat{I})^{-1}$) or use the functionality of \textbf{scikit-learn} and compute their variances. Discuss the results of these variances as functions of $\lambda$. In particular, try to link your discussion with the discussion in Hastie \emph{et al.} and their figure 3.11. + +\item Repeat the previous step but add now the Lasso method, see equation (3.53) of Hastie \emph{et al.}. Discuss your results and compare with standard regression and the Ridge regression results. You can write your own code or use the functionality of \textbf{scikit-learn}. We recommend the last since we have not yet discussed how to solve the Lasso equations numerically. + +\item Finally, using \textbf{scikit-learn} or your own code, compute also the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error defined as +\end{enumerate} + +\noindent +\[ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n} +\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, +\] +and the $R^2$ score function. +If $\tilde{\hat{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(\hat{y}, \tilde{\hat{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 $\hat{y}$ as +\[ +\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. +\] +Discuss these quantities as functions of the variable $\lambda$ in the Ridge and Lasso regression methods. + +\subsection*{Exercise 5} + +Using the singular value decomposition, show that the variance of the direction vector +$\hat{z}_i=\hat{X}\hat{v}_i=\hat{u}_1d_1$ is equal to (equation (3.49) of Hastie \emph{et al.}) +\[ +\mathrm{Var}(\hat{z}_i)=\frac{d_i^2}{N}, +\] +where $d_i$ are the singular values of the matrix $\hat{X}$. In Hastie \emph{et al}, the matrix elements of $X$ are centered. The consequence is that the mean values of for example $\hat{u}_i$ are zero. + +Give an interpretation of these results, in particular in connection with the variance of the coefficients you obtained in the previous exercise. + +% ------------------- end of main content --------------- + +\end{document} + diff --git a/doc/Projects/2019/hw2/pdf/hw2.tex~ b/doc/Projects/2019/hw2/pdf/hw2.tex~ new file mode 100644 index 000000000..67d2d70be --- /dev/null +++ b/doc/Projects/2019/hw2/pdf/hw2.tex~ @@ -0,0 +1,195 @@ +%% +%% Automatically generated file from DocOnce source +%% (https://github.com/hplgit/doconce/) +%% +%% + + +%-------------------- 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{fancyvrb} % packages needed for verbatim environments + +\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-2019, "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-2019, "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} +Homework 2 +\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} +Aug 28, 2019 +\end{center} +% --- end date --- + +\vspace{1cm} + + +\subsection*{Exercise 4} + +This exercise is a continuation of exercise 2 from homework 1. We will +use the same function to generate our data set, still staying with a +simple function $y(x)$ which we want to fit using linear regression, +but now extending the analysis to include the Ridge and the Lasso +regression methods. You can use the code under the Regression as an example on how to use the Ridge and the Lasso methods, see the \href{{https://compphysics.github.io/MachineLearning/doc/pub/Regression/html/Regression-bs.html}}{regression slides}). + +We will thus again 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). +\begin{print} +x = np.random.rand(100,1) +y = 5*x*x+0.1*np.random.randn(100,1) +\end{print} + +\begin{enumerate} +\item Write your own code for the Ridge method (see chapter 3.4 of Hastie \emph{et al.}, equations (3.43) and (3.44)) and compute the parametrization for different values of $\lambda$. Compare and analyze your results with those from exercise 2. Study the dependence on $\lambda$ while also varying the strength of the noise in your expression for $y(x)$. + +\item Repeat the above but using the functionality of \textbf{scikit-learn}. Compare your code with the results from \textbf{scikit-learn}. Remember to run with the same random numbers for generating $x$ and $y$. + +\item Our next step is to study the variance of the parameters $\beta_1$ and $\beta_2$ (assuming that we are parametrizing our function with a second-order polynomial. We will use standard linear regression and the Ridge regression. You can now opt for either writing your own function that calculates the variance of these paramaters (recall that this is equal to the diagonal elements of the matrix $(\hat{X}^T\hat{X})+\lambda\hat{I})^{-1}$) or use the functionality of \textbf{scikit-learn} and compute their variances. Discuss the results of these variances as functions of $\lambda$. In particular, try to link your discussion with the discussion in Hastie \emph{et al.} and their figure 3.11. + +\item Repeat the previous step but add now the Lasso method, see equation (3.53) of Hastie \emph{et al.}. Discuss your results and compare with standard regression and the Ridge regression results. You can write your own code or use the functionality of \textbf{scikit-learn}. We recommend the last since we have not yet discussed how to solve the Lasso equations numerically. + +\item Finally, using \textbf{scikit-learn} or your own code, compute also the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error defined as +\end{enumerate} + +\noindent +\[ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n} +\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2, +\] +and the $R^2$ score function. +If $\tilde{\hat{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(\hat{y}, \tilde{\hat{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 $\hat{y}$ as +\[ +\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i. +\] +Discuss these quantities as functions of the variable $\lambda$ in the Ridge and Lasso regression methods. + +\subsection*{Exercise 5} + +Using the singular value decomposition, show that the variance of the direction vector +$\hat{z}_i=\hat{X}\hat{v}_i=\hat{u}_1d_1$ is equal to (equation (3.49) of Hastie \emph{et al.}) +\[ +\mathrm{Var}(\hat{z}_i)=\frac{d_i^2}{N}, +\] +where $d_i$ are the singular values of the matrix $\hat{X}$. In Hastie \emph{et al}, the matrix elements of $X$ are centered. The consequence is that the mean values of for example $\hat{u}_i$ are zero. + +Give an interpretation of these results, in particular in connection with the variance of the coefficients you obtained in the previous exercise. + +% ------------------- end of main content --------------- + +\end{document} +