Files
FYS-STK4155/doc/pub/week35/html/._week35-bs068.html
T
Morten Hjorth-Jensen 78e88f1f9a update week 35
2023-05-29 22:03:48 +02:00

1023 lines
62 KiB
HTML

<!--
HTML file automatically generated from DocOnce source
(https://github.com/doconce/doconce/)
doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=default --html_admon=bootstrap_panel --html_output=week35-bs --no_mako
-->
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="generator" content="DocOnce: https://github.com/doconce/doconce/" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="description" content="Week 35: From Ordinary Linear Regression to Ridge and Lasso Regression">
<title>Week 35: From Ordinary Linear Regression to Ridge and Lasso Regression</title>
<!-- Bootstrap style: bootstrap -->
<!-- doconce format html week35.do.txt --html_style=bootstrap --pygments_html_style=default --html_admon=bootstrap_panel --html_output=week35-bs --no_mako -->
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">
<!-- not necessary
<link href="https://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">
-->
<style type="text/css">
/* Add scrollbar to dropdown menus in bootstrap navigation bar */
.dropdown-menu {
height: auto;
max-height: 400px;
overflow-x: hidden;
}
/* Adds an invisible element before each target to offset for the navigation
bar */
.anchor::before {
content:"";
display:block;
height:50px; /* fixed header height for style bootstrap */
margin:-50px 0 0; /* negative fixed header height */
}
</style>
</head>
<!-- tocinfo
{'highest level': 2,
'sections': [('Plans for week 35', 2, None, 'plans-for-week-35'),
('Reading recommendations:', 3, None, 'reading-recommendations'),
('Topics of week 35', 2, None, 'topics-of-week-35'),
('Why Linear Regression (aka Ordinary Least Squares and family), '
'repeat from last week',
2,
None,
'why-linear-regression-aka-ordinary-least-squares-and-family-repeat-from-last-week'),
('Regression analysis, overarching aims',
2,
None,
'regression-analysis-overarching-aims'),
('Regression analysis, overarching aims II',
2,
None,
'regression-analysis-overarching-aims-ii'),
('Examples', 2, None, 'examples'),
('General linear models', 2, None, 'general-linear-models'),
('Rewriting the fitting procedure as a linear algebra problem',
2,
None,
'rewriting-the-fitting-procedure-as-a-linear-algebra-problem'),
('Rewriting the fitting procedure as a linear algebra problem, '
'more details',
2,
None,
'rewriting-the-fitting-procedure-as-a-linear-algebra-problem-more-details'),
('Generalizing the fitting procedure as a linear algebra problem',
2,
None,
'generalizing-the-fitting-procedure-as-a-linear-algebra-problem'),
('Generalizing the fitting procedure as a linear algebra problem',
2,
None,
'generalizing-the-fitting-procedure-as-a-linear-algebra-problem'),
('Optimizing our parameters',
2,
None,
'optimizing-our-parameters'),
('Our model for the nuclear binding energies',
2,
None,
'our-model-for-the-nuclear-binding-energies'),
('Optimizing our parameters, more details',
2,
None,
'optimizing-our-parameters-more-details'),
('Interpretations and optimizing our parameters',
2,
None,
'interpretations-and-optimizing-our-parameters'),
('Interpretations and optimizing our parameters',
2,
None,
'interpretations-and-optimizing-our-parameters'),
('Some useful matrix and vector expressions',
2,
None,
'some-useful-matrix-and-vector-expressions'),
('Meet the Hessian Matrix', 2, None, 'meet-the-hessian-matrix'),
('Interpretations and optimizing our parameters',
2,
None,
'interpretations-and-optimizing-our-parameters'),
('Own code for Ordinary Least Squares',
2,
None,
'own-code-for-ordinary-least-squares'),
('Adding error analysis and training set up',
2,
None,
'adding-error-analysis-and-training-set-up'),
('Splitting our Data in Training and Test data',
2,
None,
'splitting-our-data-in-training-and-test-data'),
('Examples', 2, None, 'examples'),
('Making your own test-train splitting',
2,
None,
'making-your-own-test-train-splitting'),
('The Boston housing data example',
2,
None,
'the-boston-housing-data-example'),
('Housing data, the code', 2, None, 'housing-data-the-code'),
('Reducing the number of degrees of freedom, overarching view',
2,
None,
'reducing-the-number-of-degrees-of-freedom-overarching-view'),
('Preprocessing our data', 2, None, 'preprocessing-our-data'),
('Functionality in Scikit-Learn',
2,
None,
'functionality-in-scikit-learn'),
('More preprocessing', 2, None, 'more-preprocessing'),
('Frequently used scaling functions',
2,
None,
'frequently-used-scaling-functions'),
('Example of own Standard scaling',
2,
None,
'example-of-own-standard-scaling'),
('Min-Max Scaling', 2, None, 'min-max-scaling'),
('Testing the Means Squared Error as function of Complexity',
2,
None,
'testing-the-means-squared-error-as-function-of-complexity'),
('More preprocessing examples, Franke function and regression',
2,
None,
'more-preprocessing-examples-franke-function-and-regression'),
('Mathematical Interpretation of Ordinary Least Squares',
2,
None,
'mathematical-interpretation-of-ordinary-least-squares'),
('Residual Error', 2, None, 'residual-error'),
('Simple case', 2, None, 'simple-case'),
('The singular value decomposition',
2,
None,
'the-singular-value-decomposition'),
('Linear Regression Problems',
2,
None,
'linear-regression-problems'),
('Fixing the singularity', 2, None, 'fixing-the-singularity'),
('Basic math of the SVD', 2, None, 'basic-math-of-the-svd'),
('The SVD, a Fantastic Algorithm',
2,
None,
'the-svd-a-fantastic-algorithm'),
('Economy-size SVD', 2, None, 'economy-size-svd'),
('Codes for the SVD', 2, None, 'codes-for-the-svd'),
('Note about SVD Calculations',
2,
None,
'note-about-svd-calculations'),
('Mathematics of the SVD and implications',
2,
None,
'mathematics-of-the-svd-and-implications'),
('Example Matrix', 2, None, 'example-matrix'),
('Setting up the Matrix to be inverted',
2,
None,
'setting-up-the-matrix-to-be-inverted'),
('Further properties (important for our analyses later)',
2,
None,
'further-properties-important-for-our-analyses-later'),
('Meet the Covariance Matrix',
2,
None,
'meet-the-covariance-matrix'),
('Introducing the Covariance and Correlation functions',
2,
None,
'introducing-the-covariance-and-correlation-functions'),
('Covariance and Correlation Matrix',
2,
None,
'covariance-and-correlation-matrix'),
('Correlation Function and Design/Feature Matrix',
2,
None,
'correlation-function-and-design-feature-matrix'),
('Covariance Matrix Examples',
2,
None,
'covariance-matrix-examples'),
('Correlation Matrix', 2, None, 'correlation-matrix'),
('Correlation Matrix with Pandas',
2,
None,
'correlation-matrix-with-pandas'),
('Correlation Matrix with Pandas and the Franke function',
2,
None,
'correlation-matrix-with-pandas-and-the-franke-function'),
('Rewriting the Covariance and/or Correlation Matrix',
2,
None,
'rewriting-the-covariance-and-or-correlation-matrix'),
('Linking with the SVD', 2, None, 'linking-with-the-svd'),
('What does it mean?', 2, None, 'what-does-it-mean'),
('And finally $\\boldsymbol{X}\\boldsymbol{X}^T$',
2,
None,
'and-finally-boldsymbol-x-boldsymbol-x-t'),
('Ridge and LASSO Regression',
2,
None,
'ridge-and-lasso-regression'),
('Deriving the Ridge Regression Equations',
2,
None,
'deriving-the-ridge-regression-equations'),
('Interpreting the Ridge results',
2,
None,
'interpreting-the-ridge-results'),
('More interpretations', 2, None, 'more-interpretations'),
('Deriving the Lasso Regression Equations',
2,
None,
'deriving-the-lasso-regression-equations'),
('Exercises for week 35', 2, None, 'exercises-for-week-35'),
('Exercise 1: Setting up various Python environments',
2,
None,
'exercise-1-setting-up-various-python-environments'),
('Exercise 2: making your own data and exploring scikit-learn',
2,
None,
'exercise-2-making-your-own-data-and-exploring-scikit-learn'),
('Exercise 3: Normalizing our data',
2,
None,
'exercise-3-normalizing-our-data'),
('Exercise 4: Adding Ridge Regression',
2,
None,
'exercise-4-adding-ridge-regression'),
('Exercise 5: Analytical exercises',
2,
None,
'exercise-5-analytical-exercises')]}
end of tocinfo -->
<body>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
TeX: {
equationNumbers: { autoNumber: "none" },
extensions: ["AMSmath.js", "AMSsymbols.js", "autobold.js", "color.js"]
}
});
</script>
<script type="text/javascript" async
src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>
<!-- Bootstrap navigation bar -->
<div class="navbar navbar-default navbar-fixed-top">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-responsive-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="week35-bs.html">Week 35: From Ordinary Linear Regression to Ridge and Lasso Regression</a>
</div>
<div class="navbar-collapse collapse navbar-responsive-collapse">
<ul class="nav navbar-nav navbar-right">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Contents <b class="caret"></b></a>
<ul class="dropdown-menu">
<!-- navigation toc: --> <li><a href="._week35-bs001.html#plans-for-week-35" style="font-size: 80%;"><b>Plans for week 35</b></a></li>
<!-- navigation toc: --> <li><a href="._week35-bs001.html#reading-recommendations" style="font-size: 80%;">&nbsp;&nbsp;&nbsp;Reading recommendations:</a></li>
<!-- navigation toc: --> <li><a href="._week35-bs002.html#topics-of-week-35" style="font-size: 80%;"><b>Topics of week 35</b></a></li>
<!-- navigation toc: --> <li><a href="._week35-bs003.html#why-linear-regression-aka-ordinary-least-squares-and-family-repeat-from-last-week" style="font-size: 80%;"><b>Why Linear Regression (aka Ordinary Least Squares and family), repeat from last week</b></a></li>
<!-- navigation toc: --> <li><a href="._week35-bs004.html#regression-analysis-overarching-aims" style="font-size: 80%;"><b>Regression analysis, overarching aims</b></a></li>
<!-- navigation toc: --> <li><a href="._week35-bs005.html#regression-analysis-overarching-aims-ii" style="font-size: 80%;"><b>Regression analysis, overarching aims II</b></a></li>
<!-- navigation toc: --> <li><a href="._week35-bs023.html#examples" style="font-size: 80%;"><b>Examples</b></a></li>
<!-- navigation toc: --> <li><a href="._week35-bs007.html#general-linear-models" style="font-size: 80%;"><b>General linear models</b></a></li>
<!-- navigation toc: --> <li><a href="._week35-bs008.html#rewriting-the-fitting-procedure-as-a-linear-algebra-problem" style="font-size: 80%;"><b>Rewriting the fitting procedure as a linear algebra problem</b></a></li>
<!-- navigation toc: --> <li><a href="._week35-bs009.html#rewriting-the-fitting-procedure-as-a-linear-algebra-problem-more-details" style="font-size: 80%;"><b>Rewriting the fitting procedure as a linear algebra problem, more details</b></a></li>
<!-- navigation toc: --> <li><a href="._week35-bs011.html#generalizing-the-fitting-procedure-as-a-linear-algebra-problem" style="font-size: 80%;"><b>Generalizing the fitting procedure as a linear algebra problem</b></a></li>
<!-- navigation toc: --> <li><a href="._week35-bs011.html#generalizing-the-fitting-procedure-as-a-linear-algebra-problem" style="font-size: 80%;"><b>Generalizing the fitting procedure as a linear algebra problem</b></a></li>
<!-- navigation toc: --> <li><a href="._week35-bs012.html#optimizing-our-parameters" style="font-size: 80%;"><b>Optimizing our parameters</b></a></li>
<!-- navigation toc: --> <li><a href="._week35-bs013.html#our-model-for-the-nuclear-binding-energies" style="font-size: 80%;"><b>Our model for the nuclear binding energies</b></a></li>
<!-- navigation toc: --> <li><a href="._week35-bs014.html#optimizing-our-parameters-more-details" style="font-size: 80%;"><b>Optimizing our parameters, more details</b></a></li>
<!-- navigation toc: --> <li><a href="._week35-bs019.html#interpretations-and-optimizing-our-parameters" style="font-size: 80%;"><b>Interpretations and optimizing our parameters</b></a></li>
<!-- navigation toc: --> <li><a href="._week35-bs019.html#interpretations-and-optimizing-our-parameters" style="font-size: 80%;"><b>Interpretations and optimizing our parameters</b></a></li>
<!-- navigation toc: --> <li><a href="._week35-bs017.html#some-useful-matrix-and-vector-expressions" style="font-size: 80%;"><b>Some useful matrix and vector expressions</b></a></li>
<!-- navigation toc: --> <li><a href="._week35-bs018.html#meet-the-hessian-matrix" style="font-size: 80%;"><b>Meet the Hessian Matrix</b></a></li>
<!-- navigation toc: --> <li><a href="._week35-bs019.html#interpretations-and-optimizing-our-parameters" style="font-size: 80%;"><b>Interpretations and optimizing our parameters</b></a></li>
<!-- navigation toc: --> <li><a href="._week35-bs020.html#own-code-for-ordinary-least-squares" style="font-size: 80%;"><b>Own code for Ordinary Least Squares</b></a></li>
<!-- navigation toc: --> <li><a href="._week35-bs021.html#adding-error-analysis-and-training-set-up" style="font-size: 80%;"><b>Adding error analysis and training set up</b></a></li>
<!-- navigation toc: --> <li><a href="._week35-bs022.html#splitting-our-data-in-training-and-test-data" style="font-size: 80%;"><b>Splitting our Data in Training and Test data</b></a></li>
<!-- navigation toc: --> <li><a href="._week35-bs023.html#examples" style="font-size: 80%;"><b>Examples</b></a></li>
<!-- navigation toc: --> <li><a href="._week35-bs024.html#making-your-own-test-train-splitting" style="font-size: 80%;"><b>Making your own test-train splitting</b></a></li>
<!-- navigation toc: --> <li><a href="._week35-bs025.html#the-boston-housing-data-example" style="font-size: 80%;"><b>The Boston housing data example</b></a></li>
<!-- navigation toc: --> <li><a href="._week35-bs026.html#housing-data-the-code" style="font-size: 80%;"><b>Housing data, the code</b></a></li>
<!-- navigation toc: --> <li><a href="._week35-bs027.html#reducing-the-number-of-degrees-of-freedom-overarching-view" style="font-size: 80%;"><b>Reducing the number of degrees of freedom, overarching view</b></a></li>
<!-- navigation toc: --> <li><a href="._week35-bs028.html#preprocessing-our-data" style="font-size: 80%;"><b>Preprocessing our data</b></a></li>
<!-- navigation toc: --> <li><a href="._week35-bs029.html#functionality-in-scikit-learn" style="font-size: 80%;"><b>Functionality in Scikit-Learn</b></a></li>
<!-- navigation toc: --> <li><a href="._week35-bs030.html#more-preprocessing" style="font-size: 80%;"><b>More preprocessing</b></a></li>
<!-- navigation toc: --> <li><a href="._week35-bs031.html#frequently-used-scaling-functions" style="font-size: 80%;"><b>Frequently used scaling functions</b></a></li>
<!-- navigation toc: --> <li><a href="._week35-bs032.html#example-of-own-standard-scaling" style="font-size: 80%;"><b>Example of own Standard scaling</b></a></li>
<!-- navigation toc: --> <li><a href="._week35-bs033.html#min-max-scaling" style="font-size: 80%;"><b>Min-Max Scaling</b></a></li>
<!-- navigation toc: --> <li><a href="._week35-bs034.html#testing-the-means-squared-error-as-function-of-complexity" style="font-size: 80%;"><b>Testing the Means Squared Error as function of Complexity</b></a></li>
<!-- navigation toc: --> <li><a href="._week35-bs035.html#more-preprocessing-examples-franke-function-and-regression" style="font-size: 80%;"><b>More preprocessing examples, Franke function and regression</b></a></li>
<!-- navigation toc: --> <li><a href="._week35-bs036.html#mathematical-interpretation-of-ordinary-least-squares" style="font-size: 80%;"><b>Mathematical Interpretation of Ordinary Least Squares</b></a></li>
<!-- navigation toc: --> <li><a href="._week35-bs037.html#residual-error" style="font-size: 80%;"><b>Residual Error</b></a></li>
<!-- navigation toc: --> <li><a href="._week35-bs038.html#simple-case" style="font-size: 80%;"><b>Simple case</b></a></li>
<!-- navigation toc: --> <li><a href="._week35-bs039.html#the-singular-value-decomposition" style="font-size: 80%;"><b>The singular value decomposition</b></a></li>
<!-- navigation toc: --> <li><a href="._week35-bs040.html#linear-regression-problems" style="font-size: 80%;"><b>Linear Regression Problems</b></a></li>
<!-- navigation toc: --> <li><a href="._week35-bs041.html#fixing-the-singularity" style="font-size: 80%;"><b>Fixing the singularity</b></a></li>
<!-- navigation toc: --> <li><a href="._week35-bs042.html#basic-math-of-the-svd" style="font-size: 80%;"><b>Basic math of the SVD</b></a></li>
<!-- navigation toc: --> <li><a href="._week35-bs043.html#the-svd-a-fantastic-algorithm" style="font-size: 80%;"><b>The SVD, a Fantastic Algorithm</b></a></li>
<!-- navigation toc: --> <li><a href="._week35-bs044.html#economy-size-svd" style="font-size: 80%;"><b>Economy-size SVD</b></a></li>
<!-- navigation toc: --> <li><a href="._week35-bs045.html#codes-for-the-svd" style="font-size: 80%;"><b>Codes for the SVD</b></a></li>
<!-- navigation toc: --> <li><a href="._week35-bs046.html#note-about-svd-calculations" style="font-size: 80%;"><b>Note about SVD Calculations</b></a></li>
<!-- navigation toc: --> <li><a href="._week35-bs047.html#mathematics-of-the-svd-and-implications" style="font-size: 80%;"><b>Mathematics of the SVD and implications</b></a></li>
<!-- navigation toc: --> <li><a href="._week35-bs048.html#example-matrix" style="font-size: 80%;"><b>Example Matrix</b></a></li>
<!-- navigation toc: --> <li><a href="._week35-bs049.html#setting-up-the-matrix-to-be-inverted" style="font-size: 80%;"><b>Setting up the Matrix to be inverted</b></a></li>
<!-- navigation toc: --> <li><a href="._week35-bs050.html#further-properties-important-for-our-analyses-later" style="font-size: 80%;"><b>Further properties (important for our analyses later)</b></a></li>
<!-- navigation toc: --> <li><a href="._week35-bs051.html#meet-the-covariance-matrix" style="font-size: 80%;"><b>Meet the Covariance Matrix</b></a></li>
<!-- navigation toc: --> <li><a href="._week35-bs052.html#introducing-the-covariance-and-correlation-functions" style="font-size: 80%;"><b>Introducing the Covariance and Correlation functions</b></a></li>
<!-- navigation toc: --> <li><a href="._week35-bs053.html#covariance-and-correlation-matrix" style="font-size: 80%;"><b>Covariance and Correlation Matrix</b></a></li>
<!-- navigation toc: --> <li><a href="._week35-bs054.html#correlation-function-and-design-feature-matrix" style="font-size: 80%;"><b>Correlation Function and Design/Feature Matrix</b></a></li>
<!-- navigation toc: --> <li><a href="._week35-bs055.html#covariance-matrix-examples" style="font-size: 80%;"><b>Covariance Matrix Examples</b></a></li>
<!-- navigation toc: --> <li><a href="._week35-bs056.html#correlation-matrix" style="font-size: 80%;"><b>Correlation Matrix</b></a></li>
<!-- navigation toc: --> <li><a href="._week35-bs057.html#correlation-matrix-with-pandas" style="font-size: 80%;"><b>Correlation Matrix with Pandas</b></a></li>
<!-- navigation toc: --> <li><a href="._week35-bs058.html#correlation-matrix-with-pandas-and-the-franke-function" style="font-size: 80%;"><b>Correlation Matrix with Pandas and the Franke function</b></a></li>
<!-- navigation toc: --> <li><a href="._week35-bs059.html#rewriting-the-covariance-and-or-correlation-matrix" style="font-size: 80%;"><b>Rewriting the Covariance and/or Correlation Matrix</b></a></li>
<!-- navigation toc: --> <li><a href="._week35-bs060.html#linking-with-the-svd" style="font-size: 80%;"><b>Linking with the SVD</b></a></li>
<!-- navigation toc: --> <li><a href="._week35-bs061.html#what-does-it-mean" style="font-size: 80%;"><b>What does it mean?</b></a></li>
<!-- navigation toc: --> <li><a href="._week35-bs062.html#and-finally-boldsymbol-x-boldsymbol-x-t" style="font-size: 80%;"><b>And finally \( \boldsymbol{X}\boldsymbol{X}^T \)</b></a></li>
<!-- navigation toc: --> <li><a href="._week35-bs063.html#ridge-and-lasso-regression" style="font-size: 80%;"><b>Ridge and LASSO Regression</b></a></li>
<!-- navigation toc: --> <li><a href="._week35-bs064.html#deriving-the-ridge-regression-equations" style="font-size: 80%;"><b>Deriving the Ridge Regression Equations</b></a></li>
<!-- navigation toc: --> <li><a href="._week35-bs065.html#interpreting-the-ridge-results" style="font-size: 80%;"><b>Interpreting the Ridge results</b></a></li>
<!-- navigation toc: --> <li><a href="._week35-bs066.html#more-interpretations" style="font-size: 80%;"><b>More interpretations</b></a></li>
<!-- navigation toc: --> <li><a href="._week35-bs067.html#deriving-the-lasso-regression-equations" style="font-size: 80%;"><b>Deriving the Lasso Regression Equations</b></a></li>
<!-- navigation toc: --> <li><a href="#exercises-for-week-35" style="font-size: 80%;"><b>Exercises for week 35</b></a></li>
<!-- navigation toc: --> <li><a href="#exercise-1-setting-up-various-python-environments" style="font-size: 80%;"><b>Exercise 1: Setting up various Python environments</b></a></li>
<!-- navigation toc: --> <li><a href="#exercise-2-making-your-own-data-and-exploring-scikit-learn" style="font-size: 80%;"><b>Exercise 2: making your own data and exploring scikit-learn</b></a></li>
<!-- navigation toc: --> <li><a href="#exercise-3-normalizing-our-data" style="font-size: 80%;"><b>Exercise 3: Normalizing our data</b></a></li>
<!-- navigation toc: --> <li><a href="#exercise-4-adding-ridge-regression" style="font-size: 80%;"><b>Exercise 4: Adding Ridge Regression</b></a></li>
<!-- navigation toc: --> <li><a href="#exercise-5-analytical-exercises" style="font-size: 80%;"><b>Exercise 5: Analytical exercises</b></a></li>
</ul>
</li>
</ul>
</div>
</div>
</div> <!-- end of navigation bar -->
<div class="container">
<p>&nbsp;</p><p>&nbsp;</p><p>&nbsp;</p> <!-- add vertical space -->
<a name="part0068"></a>
<!-- !split -->
<h2 id="exercises-for-week-35" class="anchor">Exercises for week 35 </h2>
<p>The exercises here are meant to prepare you for work with project 1. The first exercise is a follow-up of exercise 2 from week 35 August 30-September 3).</p>
<!-- --- begin exercise --- -->
<h2 id="exercise-1-setting-up-various-python-environments" class="anchor">Exercise 1: Setting up various Python environments </h2>
<p>The first exercise here is of a mere technical art. We want you to have </p>
<ul>
<li> 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 <a href="https://www.uio.no/tjenester/it/maskin/filer/versjonskontroll/github.html" target="_self">GitHub facilities</a>.</li>
<li> Install various Python packages</li>
</ul>
<p>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 <b>R</b>
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.
</p>
<p>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 <b>pip</b> as
</p>
<ol>
<li> pip install numpy scipy matplotlib ipython scikit-learn sympy pandas pillow</li>
</ol>
<p>For <b>Tensorflow</b>, we recommend following the instructions in the text of
<a href="http://shop.oreilly.com/product/0636920052289.do" target="_self">Aurelien Geron, Hands&#8209;On Machine Learning with Scikit&#8209;Learn and TensorFlow, O'Reilly</a>
</p>
<p>We will come back to <b>tensorflow</b> later. </p>
<p>For Python3, replace <b>pip</b> with <b>pip3</b>.</p>
<p>For OSX users we recommend, after having installed Xcode, to
install <b>brew</b>. Brew allows for a seamless installation of additional
software via for example
</p>
<ol>
<li> brew install python3</li>
</ol>
<p>For Linux users, with its variety of distributions like for example the widely popular Ubuntu distribution,
you can use <b>pip</b> as well and simply install Python as
</p>
<ol>
<li> sudo apt-get install python3 (or python for Python2.7)</li>
</ol>
<p>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
</p>
<ul>
<li> <a href="https://docs.anaconda.com/" target="_self">Anaconda</a>,</li>
</ul>
<p>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 <b>conda</b>.
</p>
<ul>
<li> <a href="https://www.enthought.com/product/canopy/" target="_self">Enthought canopy</a></li>
</ul>
<p>is a Python
distribution for scientific and analytic computing distribution and
analysis environment, available for free and under a commercial
license.
</p>
<p>We recommend using <b>Anaconda</b> if you are not too familiar with setting paths in a terminal environment.</p>
<!-- --- end exercise --- -->
<!-- --- begin exercise --- -->
<h2 id="exercise-2-making-your-own-data-and-exploring-scikit-learn" class="anchor">Exercise 2: making your own data and exploring scikit-learn </h2>
<p>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).
</p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;">x <span style="color: #666666">=</span> np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>rand(<span style="color: #666666">100</span>,<span style="color: #666666">1</span>)
y <span style="color: #666666">=</span> <span style="color: #666666">2.0+5*</span>x<span style="color: #666666">*</span>x<span style="color: #666666">+0.1*</span>np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>randn(<span style="color: #666666">100</span>,<span style="color: #666666">1</span>)
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<ol>
<li> Write your own code (following the examples under the <a href="https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/chapter1.html" target="_self">regression notes</a>) for computing the parametrization of the data set fitting a second-order polynomial.</li>
<li> Use thereafter <b>scikit-learn</b> (see again the examples in the regression slides) and compare with your own code. When compairing with _scikit_learn_, make sure you set the option for the intercept to <b>FALSE</b>, see <a href="https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html" target="_self"><tt>https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html</tt></a>. This feature will be explained in more detail during the lectures of week 35 and week 36. You can find more in <a href="https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/chapter3.html#more-on-rescaling-data" target="_self"><tt>https://compphysics.github.io/MachineLearning/doc/LectureNotes/_build/html/chapter3.html#more-on-rescaling-data</tt></a>.</li>
<li> Using scikit-learn, compute also the mean square error, a risk metric corresponding to the expected value of the squared (quadratic) error defined as</li>
</ol>
$$ MSE(\boldsymbol{y},\boldsymbol{\tilde{y}}) = \frac{1}{n}
\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2,
$$
<p>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
</p>
$$
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},
$$
<p>where we have defined the mean value of \( \boldsymbol{y} \) as</p>
$$
\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i.
$$
<p>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.
</p>
<!-- --- begin solution of exercise --- -->
<p>
<p><a class="glyphicon glyphicon-hand-right showdetails" data-toggle="collapse"
data-target="#exer_2_1" style="font-size: 80%;"></a>
</p>
<a href="#exer_2_1" data-toggle="collapse">
<p>
<b>Solution.</b>
</p>
</a>
<div class="collapse-group">
<p><div class="collapse" id="exer_2_1">
<p>The code here is an example of where we define our own design matrix and fit parameters \( \beta \).</p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">os</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">pandas</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">pd</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">matplotlib.pyplot</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">plt</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.model_selection</span> <span style="color: #008000; font-weight: bold">import</span> train_test_split
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">save_fig</span>(fig_id):
plt<span style="color: #666666">.</span>savefig(image_path(fig_id) <span style="color: #666666">+</span> <span style="color: #BA2121">&quot;.png&quot;</span>, <span style="color: #008000">format</span><span style="color: #666666">=</span><span style="color: #BA2121">&#39;png&#39;</span>)
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">R2</span>(y_data, y_model):
<span style="color: #008000; font-weight: bold">return</span> <span style="color: #666666">1</span> <span style="color: #666666">-</span> np<span style="color: #666666">.</span>sum((y_data <span style="color: #666666">-</span> y_model) <span style="color: #666666">**</span> <span style="color: #666666">2</span>) <span style="color: #666666">/</span> np<span style="color: #666666">.</span>sum((y_data <span style="color: #666666">-</span> np<span style="color: #666666">.</span>mean(y_data)) <span style="color: #666666">**</span> <span style="color: #666666">2</span>)
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">MSE</span>(y_data,y_model):
n <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(y_model)
<span style="color: #008000; font-weight: bold">return</span> np<span style="color: #666666">.</span>sum((y_data<span style="color: #666666">-</span>y_model)<span style="color: #666666">**2</span>)<span style="color: #666666">/</span>n
x <span style="color: #666666">=</span> np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>rand(<span style="color: #666666">100</span>)
y <span style="color: #666666">=</span> <span style="color: #666666">2.0+5*</span>x<span style="color: #666666">*</span>x<span style="color: #666666">+0.1*</span>np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>randn(<span style="color: #666666">100</span>)
<span style="color: #408080; font-style: italic"># The design matrix now as function of a given polynomial</span>
X <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros((<span style="color: #008000">len</span>(x),<span style="color: #666666">3</span>))
X[:,<span style="color: #666666">0</span>] <span style="color: #666666">=</span> <span style="color: #666666">1.0</span>
X[:,<span style="color: #666666">1</span>] <span style="color: #666666">=</span> x
X[:,<span style="color: #666666">2</span>] <span style="color: #666666">=</span> x<span style="color: #666666">**2</span>
<span style="color: #408080; font-style: italic"># We split the data in test and training data</span>
X_train, X_test, y_train, y_test <span style="color: #666666">=</span> train_test_split(X, y, test_size<span style="color: #666666">=0.2</span>)
<span style="color: #408080; font-style: italic"># matrix inversion to find beta</span>
beta <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linalg<span style="color: #666666">.</span>inv(X_train<span style="color: #666666">.</span>T <span style="color: #666666">@</span> X_train) <span style="color: #666666">@</span> X_train<span style="color: #666666">.</span>T <span style="color: #666666">@</span> y_train
<span style="color: #008000">print</span>(beta)
<span style="color: #408080; font-style: italic"># and then make the prediction</span>
ytilde <span style="color: #666666">=</span> X_train <span style="color: #666666">@</span> beta
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;Training R2&quot;</span>)
<span style="color: #008000">print</span>(R2(y_train,ytilde))
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;Training MSE&quot;</span>)
<span style="color: #008000">print</span>(MSE(y_train,ytilde))
ypredict <span style="color: #666666">=</span> X_test <span style="color: #666666">@</span> beta
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;Test R2&quot;</span>)
<span style="color: #008000">print</span>(R2(y_test,ypredict))
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;Test MSE&quot;</span>)
<span style="color: #008000">print</span>(MSE(y_test,ypredict))
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
</div></p>
</div>
</p>
<!-- --- end solution of exercise --- -->
<!-- --- end exercise --- -->
<!-- --- begin exercise --- -->
<h2 id="exercise-3-normalizing-our-data" class="anchor">Exercise 3: Normalizing our data </h2>
<p>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.
</p>
<p><b>Scikit-Learn</b> has several functions which allow us to rescale the
data, normally resulting in much better results in terms of various
accuracy scores. The <b>StandardScaler</b> function in <b>Scikit-Learn</b>
ensures that for each feature/predictor we study the mean value is
zero and the variance is one (every column in the design/feature
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 <b>Scikit-Learn</b> is the <b>MinMaxScaler</b> which
ensures that all features are exactly between \( 0 \) and \( 1 \). The
</p>
<p>The <b>Normalizer</b> 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&#8217;s length).
This normalization is often used when only the direction (or angle) of the data matters,
not the length of the feature vector.
</p>
<p>The <b>RobustScaler</b> 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
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.
</p>
<p>It also common to split the data in a <b>training</b> set and a <b>testing</b> 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 <b>scikit-learn</b>)
</p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;"><span style="color: #408080; font-style: italic"># split in training and test data</span>
X_train, X_test, y_train, y_test <span style="color: #666666">=</span> train_test_split(X,y,test_size<span style="color: #666666">=0.2</span>)
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<p>Then we can use the standard scaler to scale our data as</p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;">scaler <span style="color: #666666">=</span> StandardScaler()
scaler<span style="color: #666666">.</span>fit(X_train)
X_train_scaled <span style="color: #666666">=</span> scaler<span style="color: #666666">.</span>transform(X_train)
X_test_scaled <span style="color: #666666">=</span> scaler<span style="color: #666666">.</span>transform(X_test)
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<p>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.
</p>
<p>One of
the aims is to reproduce Figure 2.11 of <a href="https://github.com/CompPhysics/MLErasmus/blob/master/doc/Textbooks/elementsstat.pdf" target="_self">Hastie et al</a>.
</p>
<p>Our data is defined by \( x\in [-3,3] \) with a total of for example \( 100 \) data points.</p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;">np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>seed()
n <span style="color: #666666">=</span> <span style="color: #666666">100</span>
maxdegree <span style="color: #666666">=</span> <span style="color: #666666">14</span>
<span style="color: #408080; font-style: italic"># Make data set.</span>
x <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linspace(<span style="color: #666666">-3</span>, <span style="color: #666666">3</span>, n)<span style="color: #666666">.</span>reshape(<span style="color: #666666">-1</span>, <span style="color: #666666">1</span>)
y <span style="color: #666666">=</span> np<span style="color: #666666">.</span>exp(<span style="color: #666666">-</span>x<span style="color: #666666">**2</span>) <span style="color: #666666">+</span> <span style="color: #666666">1.5</span> <span style="color: #666666">*</span> np<span style="color: #666666">.</span>exp(<span style="color: #666666">-</span>(x<span style="color: #666666">-2</span>)<span style="color: #666666">**2</span>)<span style="color: #666666">+</span> np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>normal(<span style="color: #666666">0</span>, <span style="color: #666666">0.1</span>, x<span style="color: #666666">.</span>shape)
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<p>where \( y \) is the function we want to fit with a given polynomial.</p>
<!-- --- begin subexercise --- -->
<p>
<b>a)</b>
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.
</p>
<!-- --- end subexercise --- -->
<!-- --- begin subexercise --- -->
<p>
<b>b)</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.
</p>
<!-- --- end subexercise --- -->
<!-- --- begin subexercise --- -->
<p>
<b>c)</b>
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)?
</p>
<!-- --- end subexercise --- -->
<!-- --- end exercise --- -->
<!-- --- begin exercise --- -->
<h2 id="exercise-4-adding-ridge-regression" class="anchor">Exercise 4: Adding Ridge Regression </h2>
<p>This exercise is a continuation of exercise 2. 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 regression method.
</p>
<p>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) \).
</p>
<p>The following simple Python instructions define our \( x \) and \( y \) values (with 100 data points).</p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;">x <span style="color: #666666">=</span> np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>rand(<span style="color: #666666">100</span>)
y <span style="color: #666666">=</span> <span style="color: #666666">2.0+5*</span>x<span style="color: #666666">*</span>x<span style="color: #666666">+0.1*</span>np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>randn(<span style="color: #666666">100</span>)
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<p>Write your own code for the Ridge method (see chapter 3.4 of Hastie <em>et al.</em>, equations (3.43) and (3.44)) and compute the parametrization for different values of \( \lambda \). Compare and analyze your results with those from exercise 3. Study the dependence on \( \lambda \) while also varying the strength of the noise in your expression for \( y(x) \). </p>
<p>The code here allows you to perform your own Ridge calculation and
perform calculations for various values of the regularization
parameter \( \lambda \). This program can easily be extended upon.
</p>
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="inner_cell">
<div class="input_area">
<div class="highlight" style="background: #f8f8f8">
<pre style="line-height: 125%;"><span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">os</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">numpy</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">np</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">pandas</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">pd</span>
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">matplotlib.pyplot</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">plt</span>
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.model_selection</span> <span style="color: #008000; font-weight: bold">import</span> train_test_split
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.preprocessing</span> <span style="color: #008000; font-weight: bold">import</span> StandardScaler
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">R2</span>(y_data, y_model):
<span style="color: #008000; font-weight: bold">return</span> <span style="color: #666666">1</span> <span style="color: #666666">-</span> np<span style="color: #666666">.</span>sum((y_data <span style="color: #666666">-</span> y_model) <span style="color: #666666">**</span> <span style="color: #666666">2</span>) <span style="color: #666666">/</span> np<span style="color: #666666">.</span>sum((y_data <span style="color: #666666">-</span> np<span style="color: #666666">.</span>mean(y_data)) <span style="color: #666666">**</span> <span style="color: #666666">2</span>)
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">MSE</span>(y_data,y_model):
n <span style="color: #666666">=</span> np<span style="color: #666666">.</span>size(y_model)
<span style="color: #008000; font-weight: bold">return</span> np<span style="color: #666666">.</span>sum((y_data<span style="color: #666666">-</span>y_model)<span style="color: #666666">**2</span>)<span style="color: #666666">/</span>n
<span style="color: #408080; font-style: italic"># A seed just to ensure that the random numbers are the same for every run.</span>
<span style="color: #408080; font-style: italic"># Useful for eventual debugging.</span>
np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>seed(<span style="color: #666666">3155</span>)
x <span style="color: #666666">=</span> np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>rand(<span style="color: #666666">100</span>)
y <span style="color: #666666">=</span> <span style="color: #666666">2.0+5*</span>x<span style="color: #666666">*</span>x<span style="color: #666666">+0.1*</span>np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>randn(<span style="color: #666666">100</span>)
<span style="color: #408080; font-style: italic"># number of features p (here degree of polynomial</span>
p <span style="color: #666666">=</span> <span style="color: #666666">3</span>
<span style="color: #408080; font-style: italic"># The design matrix now as function of a given polynomial</span>
X <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros((<span style="color: #008000">len</span>(x),p))
X[:,<span style="color: #666666">0</span>] <span style="color: #666666">=</span> <span style="color: #666666">1.0</span>
X[:,<span style="color: #666666">1</span>] <span style="color: #666666">=</span> x
X[:,<span style="color: #666666">2</span>] <span style="color: #666666">=</span> x<span style="color: #666666">*</span>x
<span style="color: #408080; font-style: italic"># We split the data in test and training data</span>
X_train, X_test, y_train, y_test <span style="color: #666666">=</span> train_test_split(X, y, test_size<span style="color: #666666">=0.2</span>)
<span style="color: #408080; font-style: italic"># matrix inversion to find beta</span>
OLSbeta <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linalg<span style="color: #666666">.</span>inv(X_train<span style="color: #666666">.</span>T <span style="color: #666666">@</span> X_train) <span style="color: #666666">@</span> X_train<span style="color: #666666">.</span>T <span style="color: #666666">@</span> y_train
<span style="color: #008000">print</span>(OLSbeta)
<span style="color: #408080; font-style: italic"># and then make the prediction</span>
ytildeOLS <span style="color: #666666">=</span> X_train <span style="color: #666666">@</span> OLSbeta
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;Training R2 for OLS&quot;</span>)
<span style="color: #008000">print</span>(R2(y_train,ytildeOLS))
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;Training MSE for OLS&quot;</span>)
<span style="color: #008000">print</span>(MSE(y_train,ytildeOLS))
ypredictOLS <span style="color: #666666">=</span> X_test <span style="color: #666666">@</span> OLSbeta
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;Test R2 for OLS&quot;</span>)
<span style="color: #008000">print</span>(R2(y_test,ypredictOLS))
<span style="color: #008000">print</span>(<span style="color: #BA2121">&quot;Test MSE OLS&quot;</span>)
<span style="color: #008000">print</span>(MSE(y_test,ypredictOLS))
<span style="color: #408080; font-style: italic"># Repeat now for Ridge regression and various values of the regularization parameter</span>
I <span style="color: #666666">=</span> np<span style="color: #666666">.</span>eye(p,p)
<span style="color: #408080; font-style: italic"># Decide which values of lambda to use</span>
nlambdas <span style="color: #666666">=</span> <span style="color: #666666">20</span>
MSEPredict <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(nlambdas)
MSETrain <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(nlambdas)
lambdas <span style="color: #666666">=</span> np<span style="color: #666666">.</span>logspace(<span style="color: #666666">-4</span>, <span style="color: #666666">1</span>, nlambdas)
<span style="color: #008000; font-weight: bold">for</span> i <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(nlambdas):
lmb <span style="color: #666666">=</span> lambdas[i]
Ridgebeta <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linalg<span style="color: #666666">.</span>inv(X_train<span style="color: #666666">.</span>T <span style="color: #666666">@</span> X_train<span style="color: #666666">+</span>lmb<span style="color: #666666">*</span>I) <span style="color: #666666">@</span> X_train<span style="color: #666666">.</span>T <span style="color: #666666">@</span> y_train
<span style="color: #408080; font-style: italic"># and then make the prediction</span>
ytildeRidge <span style="color: #666666">=</span> X_train <span style="color: #666666">@</span> Ridgebeta
ypredictRidge <span style="color: #666666">=</span> X_test <span style="color: #666666">@</span> Ridgebeta
MSEPredict[i] <span style="color: #666666">=</span> MSE(y_test,ypredictRidge)
MSETrain[i] <span style="color: #666666">=</span> MSE(y_train,ytildeRidge)
<span style="color: #408080; font-style: italic"># Now plot the results</span>
plt<span style="color: #666666">.</span>figure()
plt<span style="color: #666666">.</span>plot(np<span style="color: #666666">.</span>log10(lambdas), MSETrain, label <span style="color: #666666">=</span> <span style="color: #BA2121">&#39;MSE Ridge train&#39;</span>)
plt<span style="color: #666666">.</span>plot(np<span style="color: #666666">.</span>log10(lambdas), MSEPredict, <span style="color: #BA2121">&#39;r--&#39;</span>, label <span style="color: #666666">=</span> <span style="color: #BA2121">&#39;MSE Ridge Test&#39;</span>)
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">&#39;log10(lambda)&#39;</span>)
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">&#39;MSE&#39;</span>)
plt<span style="color: #666666">.</span>legend()
plt<span style="color: #666666">.</span>show()
</pre>
</div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area">
<div class="output_subarea output_stream output_stdout output_text">
</div>
</div>
</div>
</div>
</div>
<p>Repeat the above but using the functionality of
<b>Scikit-Learn</b>. Compare your code with the results from
<b>Scikit-Learn</b>. Remember to run with the same random numbers for
generating \( x \) and \( y \). Observe also that when you compare with <b>Scikit-Learn</b>, you need to pay attention to how the intercept is dealt with.
</p>
<p>Finally, using <b>Scikit-Learn</b> 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</p>
$$ MSE(\hat{y},\hat{\tilde{y}}) = \frac{1}{n}
\sum_{i=0}^{n-1}(y_i-\tilde{y}_i)^2,
$$
<p>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
</p>
$$
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},
$$
<p>where we have defined the mean value of \( \hat{y} \) as</p>
$$
\bar{y} = \frac{1}{n} \sum_{i=0}^{n - 1} y_i.
$$
<p>Discuss these quantities as functions of the variable \( \lambda \) in Ridge regression.</p>
<!-- --- end exercise --- -->
<!-- --- begin exercise --- -->
<h2 id="exercise-5-analytical-exercises" class="anchor">Exercise 5: Analytical exercises </h2>
<p>In this exercise we derive the expressions for various derivatives of
products of vectors and matrices. Such derivatives are central to the
optimization of various cost functions. Although we will often use
automatic differentiation in actual calculations, to be able to have
analytical expressions is extremely helpful in case we have simpler
derivatives as well as when we analyze various properties (like second
derivatives) of the chosen cost functions. Vectors are always written
as boldfaced lower case letters and matrices as upper case boldfaced
letters.
</p>
<p>Show that</p>
$$
\frac{\partial (\boldsymbol{b}^T\boldsymbol{a})}{\partial \boldsymbol{a}} = \boldsymbol{b},
$$
<p>and</p>
$$
\frac{\partial (\boldsymbol{a}^T\boldsymbol{A}\boldsymbol{a})}{\partial \boldsymbol{a}} = \boldsymbol{a}^T(\boldsymbol{A}+\boldsymbol{A}^T),
$$
<p>and</p>
$$
\frac{\partial \left(\boldsymbol{x}-\boldsymbol{A}\boldsymbol{s}\right)^T\left(\boldsymbol{x}-\boldsymbol{A}\boldsymbol{s}\right)}{\partial \boldsymbol{s}} = -2\left(\boldsymbol{x}-\boldsymbol{A}\boldsymbol{s}\right)^T\boldsymbol{A},
$$
<p>and finally find the second derivative of this function with respect to the vector \( \boldsymbol{s} \).</p>
<p><b>Hint</b>: In these exercises it is always useful to write out with summation indices the various quantities.
As an example, consider the function
</p>
$$
f(\boldsymbol{x}) =\boldsymbol{A}\boldsymbol{x},
$$
<p>which reads for a specific component \( f_i \) (we define the matrix \( \boldsymbol{A} \) to have dimension \( n\times n \) and the vector $\boldsymbol{x} to have length \( n \))</p>
$$
f_i =\sum_{j=0}^{n-1}a_{ij}x_j,
$$
<p>which leads to</p>
$$
\frac{\partial f_i}{\partial x_j}= a_{ij},
$$
<p>and written out in terms of the vector \( \boldsymbol{x} \) we have</p>
$$
\frac{\partial f(\boldsymbol{x})}{\partial \boldsymbol{x}}= \boldsymbol{A}.
$$
<!-- --- end exercise --- -->
<p>
<!-- navigation buttons at the bottom of the page -->
<ul class="pagination">
<li><a href="._week35-bs067.html">&laquo;</a></li>
<li><a href="._week35-bs000.html">1</a></li>
<li><a href="">...</a></li>
<li><a href="._week35-bs060.html">61</a></li>
<li><a href="._week35-bs061.html">62</a></li>
<li><a href="._week35-bs062.html">63</a></li>
<li><a href="._week35-bs063.html">64</a></li>
<li><a href="._week35-bs064.html">65</a></li>
<li><a href="._week35-bs065.html">66</a></li>
<li><a href="._week35-bs066.html">67</a></li>
<li><a href="._week35-bs067.html">68</a></li>
<li class="active"><a href="._week35-bs068.html">69</a></li>
</ul>
<!-- ------------------- end of main content --------------- -->
</div> <!-- end container -->
<!-- include javascript, jQuery *first* -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<!-- Bootstrap footer
<footer>
<a href="https://..."><img width="250" align=right src="https://..."></a>
</footer>
-->
<center style="font-size:80%">
<!-- copyright only on the titlepage -->
</center>
</body>
</html>