2603 lines
158 KiB
HTML
2603 lines
158 KiB
HTML
<!--
|
|
Automatically generated HTML file from DocOnce source
|
|
(https://github.com/doconce/doconce/)
|
|
-->
|
|
<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="Data Analysis and Machine Learning: Logistic Regression">
|
|
|
|
<title>Data Analysis and Machine Learning: Logistic Regression</title>
|
|
|
|
|
|
<style type="text/css">
|
|
/* bloodish style */
|
|
|
|
body {
|
|
font-family: Helvetica, Verdana, Arial, Sans-serif;
|
|
color: #404040;
|
|
background: #ffffff;
|
|
}
|
|
h1 { font-size: 1.8em; color: #8A0808; }
|
|
h2 { font-size: 1.6em; color: #8A0808; }
|
|
h3 { font-size: 1.4em; color: #8A0808; }
|
|
h4 { color: #8A0808; }
|
|
a { color: #8A0808; text-decoration:none; }
|
|
tt { font-family: "Courier New", Courier; }
|
|
/* pre style removed because it will interfer with pygments */
|
|
p { text-indent: 0px; }
|
|
hr { border: 0; width: 80%; border-bottom: 1px solid #aaa}
|
|
p.caption { width: 80%; font-style: normal; text-align: left; }
|
|
hr.figure { border: 0; width: 80%; border-bottom: 1px solid #aaa}
|
|
|
|
div { text-align: justify; text-justify: inter-word; }
|
|
</style>
|
|
|
|
|
|
</head>
|
|
|
|
<!-- tocinfo
|
|
{'highest level': 2,
|
|
'sections': [('Plans for week 38', 2, None, 'plans-for-week-38'),
|
|
('Thursday September 23', 2, None, 'thursday-september-23'),
|
|
('Ridge and LASSO Regression, reminder',
|
|
2,
|
|
None,
|
|
'ridge-and-lasso-regression-reminder'),
|
|
('Various steps in cross-validation',
|
|
2,
|
|
None,
|
|
'various-steps-in-cross-validation'),
|
|
('How to set up the cross-validation for Ridge and/or Lasso',
|
|
2,
|
|
None,
|
|
'how-to-set-up-the-cross-validation-for-ridge-and-or-lasso'),
|
|
('Cross-validation in brief',
|
|
2,
|
|
None,
|
|
'cross-validation-in-brief'),
|
|
('Code Example for Cross-validation and $k$-fold '
|
|
'Cross-validation',
|
|
2,
|
|
None,
|
|
'code-example-for-cross-validation-and-k-fold-cross-validation'),
|
|
('To think about, first part',
|
|
2,
|
|
None,
|
|
'to-think-about-first-part'),
|
|
('More thinking', 2, None, 'more-thinking'),
|
|
('Still thinking', 2, None, 'still-thinking'),
|
|
('What does centering (subtracting the mean values) mean '
|
|
'mathematically?',
|
|
2,
|
|
None,
|
|
'what-does-centering-subtracting-the-mean-values-mean-mathematically'),
|
|
('Further Manipulations', 2, None, 'further-manipulations'),
|
|
('Wrapping it up', 2, None, 'wrapping-it-up'),
|
|
('Linear Regression code, Intercept handling first',
|
|
2,
|
|
None,
|
|
'linear-regression-code-intercept-handling-first'),
|
|
('Code Examples', 2, None, 'code-examples'),
|
|
('Taking out the mean', 2, None, 'taking-out-the-mean'),
|
|
('More complicated Example: The Ising model',
|
|
2,
|
|
None,
|
|
'more-complicated-example-the-ising-model'),
|
|
('Reformulating the problem to suit regression',
|
|
2,
|
|
None,
|
|
'reformulating-the-problem-to-suit-regression'),
|
|
('Linear regression', 2, None, 'linear-regression'),
|
|
('Singular Value decomposition',
|
|
2,
|
|
None,
|
|
'singular-value-decomposition'),
|
|
('The one-dimensional Ising model',
|
|
2,
|
|
None,
|
|
'the-one-dimensional-ising-model'),
|
|
('Ridge regression', 2, None, 'ridge-regression'),
|
|
('LASSO regression', 2, None, 'lasso-regression'),
|
|
('Performance as function of the regularization parameter',
|
|
2,
|
|
None,
|
|
'performance-as-function-of-the-regularization-parameter'),
|
|
('Finding the optimal value of $\\lambda$',
|
|
2,
|
|
None,
|
|
'finding-the-optimal-value-of-lambda'),
|
|
('Logistic Regression', 2, None, 'logistic-regression'),
|
|
('Classification problems', 2, None, 'classification-problems'),
|
|
('Optimization and Deep learning',
|
|
2,
|
|
None,
|
|
'optimization-and-deep-learning'),
|
|
('Basics', 2, None, 'basics'),
|
|
('Linear classifier', 2, None, 'linear-classifier'),
|
|
('Some selected properties', 2, None, 'some-selected-properties'),
|
|
('Simple example', 2, None, 'simple-example'),
|
|
('Plotting the mean value for each group',
|
|
2,
|
|
None,
|
|
'plotting-the-mean-value-for-each-group'),
|
|
('The logistic function', 2, None, 'the-logistic-function'),
|
|
('Examples of likelihood functions used in logistic regression '
|
|
'and nueral networks',
|
|
2,
|
|
None,
|
|
'examples-of-likelihood-functions-used-in-logistic-regression-and-nueral-networks'),
|
|
('Two parameters', 2, None, 'two-parameters'),
|
|
('Maximum likelihood', 2, None, 'maximum-likelihood'),
|
|
('The cost function rewritten',
|
|
2,
|
|
None,
|
|
'the-cost-function-rewritten'),
|
|
('Minimizing the cross entropy',
|
|
2,
|
|
None,
|
|
'minimizing-the-cross-entropy'),
|
|
('A more compact expression',
|
|
2,
|
|
None,
|
|
'a-more-compact-expression'),
|
|
('Extending to more predictors',
|
|
2,
|
|
None,
|
|
'extending-to-more-predictors'),
|
|
('Including more classes', 2, None, 'including-more-classes'),
|
|
('More classes', 2, None, 'more-classes'),
|
|
('Friday September 24', 2, None, 'friday-september-24'),
|
|
('Wisconsin Cancer Data', 2, None, 'wisconsin-cancer-data'),
|
|
('Using the correlation matrix',
|
|
2,
|
|
None,
|
|
'using-the-correlation-matrix'),
|
|
('Discussing the correlation data',
|
|
2,
|
|
None,
|
|
'discussing-the-correlation-data'),
|
|
('Other measures in classification studies: Cancer Data again',
|
|
2,
|
|
None,
|
|
'other-measures-in-classification-studies-cancer-data-again'),
|
|
('Friday September 25', 2, None, 'friday-september-25'),
|
|
('Optimization, the central part of any Machine Learning '
|
|
'algortithm',
|
|
2,
|
|
None,
|
|
'optimization-the-central-part-of-any-machine-learning-algortithm'),
|
|
('Revisiting our Logistic Regression case',
|
|
2,
|
|
None,
|
|
'revisiting-our-logistic-regression-case'),
|
|
('The equations to solve', 2, None, 'the-equations-to-solve'),
|
|
("Solving using Newton-Raphson's method",
|
|
2,
|
|
None,
|
|
'solving-using-newton-raphson-s-method'),
|
|
("Brief reminder on Newton-Raphson's method",
|
|
2,
|
|
None,
|
|
'brief-reminder-on-newton-raphson-s-method'),
|
|
('The equations', 2, None, 'the-equations'),
|
|
('Simple geometric interpretation',
|
|
2,
|
|
None,
|
|
'simple-geometric-interpretation'),
|
|
('Extending to more than one variable',
|
|
2,
|
|
None,
|
|
'extending-to-more-than-one-variable'),
|
|
('Steepest descent', 2, None, 'steepest-descent'),
|
|
('More on Steepest descent', 2, None, 'more-on-steepest-descent'),
|
|
('The ideal', 2, None, 'the-ideal'),
|
|
('The sensitiveness of the gradient descent',
|
|
2,
|
|
None,
|
|
'the-sensitiveness-of-the-gradient-descent')]}
|
|
end of tocinfo -->
|
|
|
|
<body>
|
|
|
|
|
|
|
|
<script type="text/x-mathjax-config">
|
|
MathJax.Hub.Config({
|
|
TeX: {
|
|
equationNumbers: { autoNumber: "AMS" },
|
|
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>
|
|
|
|
|
|
|
|
|
|
<!-- ------------------- main content ---------------------- -->
|
|
|
|
|
|
|
|
<center><h1>Data Analysis and Machine Learning: Logistic Regression</h1></center> <!-- document title -->
|
|
|
|
<p>
|
|
<!-- author(s): Morten Hjorth-Jensen -->
|
|
|
|
<center>
|
|
<b>Morten Hjorth-Jensen</b> [1, 2]
|
|
</center>
|
|
|
|
<p>
|
|
<!-- institution(s) -->
|
|
|
|
<center>[1] <b>Department of Physics, University of Oslo</b></center>
|
|
<center>[2] <b>Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University</b></center>
|
|
<br>
|
|
<p>
|
|
<center><h4>Sep 28, 2021</h4></center> <!-- date -->
|
|
<br>
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="plans-for-week-38">Plans for week 38 </h2>
|
|
|
|
<ul>
|
|
<li> Thursday: Summary of regression methods and discussion of project 1. Start Logistic Regression</li>
|
|
<li> <a href="https://www.uio.no/studier/emner/matnat/fys/FYS-STK4155/h21/forelesningsvideoer/LectureSeptember23.mp4?vrtx=view-as-webpage" target="_blank">Video of Lecture September 23</a></li>
|
|
<li> Friday: Logistic Regression and Optimization methods</li>
|
|
<li> <a href="https://www.uio.no/studier/emner/matnat/fys/FYS-STK3155/h21/forelesningsvideoer/LectureSeptember24.mp4?vrtx=view-as-webpage" target="_blank">Video of Lecture September 24</a></li>
|
|
</ul>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="thursday-september-23">Thursday September 23 </h2>
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="ridge-and-lasso-regression-reminder">Ridge and LASSO Regression, reminder </h2>
|
|
|
|
<p>
|
|
The expression for the standard Mean Squared Error (MSE) which we used to define our cost function and the equations for the ordinary least squares (OLS) method, that is
|
|
our optimization problem is
|
|
$$
|
|
{\displaystyle \min_{\boldsymbol{\beta}\in {\mathbb{R}}^{p}}}\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)^T\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)\right\}.
|
|
$$
|
|
|
|
or we can state it as
|
|
$$
|
|
{\displaystyle \min_{\boldsymbol{\beta}\in
|
|
{\mathbb{R}}^{p}}}\frac{1}{n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2=\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2,
|
|
$$
|
|
|
|
where we have used the definition of a norm-2 vector, that is
|
|
$$
|
|
\vert\vert \boldsymbol{x}\vert\vert_2 = \sqrt{\sum_i x_i^2}.
|
|
$$
|
|
|
|
<p>
|
|
By minimizing the above equation with respect to the parameters
|
|
\( \boldsymbol{\beta} \) we could then obtain an analytical expression for the
|
|
parameters \( \boldsymbol{\beta} \). We can add a regularization parameter \( \lambda \) by
|
|
defining a new cost function to be optimized, that is
|
|
|
|
$$
|
|
{\displaystyle \min_{\boldsymbol{\beta}\in
|
|
{\mathbb{R}}^{p}}}\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2+\lambda\vert\vert \boldsymbol{\beta}\vert\vert_2^2
|
|
$$
|
|
|
|
<p>
|
|
which leads to the Ridge regression minimization problem where we
|
|
require that \( \vert\vert \boldsymbol{\beta}\vert\vert_2^2\le t \), where \( t \) is
|
|
a finite number larger than zero. By defining
|
|
|
|
$$
|
|
C(\boldsymbol{X},\boldsymbol{\beta})=\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2+\lambda\vert\vert \boldsymbol{\beta}\vert\vert_1,
|
|
$$
|
|
|
|
<p>
|
|
we have a new optimization equation
|
|
$$
|
|
{\displaystyle \min_{\boldsymbol{\beta}\in
|
|
{\mathbb{R}}^{p}}}\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2+\lambda\vert\vert \boldsymbol{\beta}\vert\vert_1
|
|
$$
|
|
|
|
which leads to Lasso regression. Lasso stands for least absolute shrinkage and selection operator.
|
|
|
|
<p>
|
|
Here we have defined the norm-1 as
|
|
$$
|
|
\vert\vert \boldsymbol{x}\vert\vert_1 = \sum_i \vert x_i\vert.
|
|
$$
|
|
|
|
<p>
|
|
<!-- !split -->
|
|
|
|
<h2 id="various-steps-in-cross-validation">Various steps in cross-validation </h2>
|
|
|
|
<p>
|
|
When the repetitive splitting of the data set is done randomly,
|
|
samples may accidently end up in a fast majority of the splits in
|
|
either training or test set. Such samples may have an unbalanced
|
|
influence on either model building or prediction evaluation. To avoid
|
|
this \( k \)-fold cross-validation structures the data splitting. The
|
|
samples are divided into \( k \) more or less equally sized exhaustive and
|
|
mutually exclusive subsets. In turn (at each split) one of these
|
|
subsets plays the role of the test set while the union of the
|
|
remaining subsets constitutes the training set. Such a splitting
|
|
warrants a balanced representation of each sample in both training and
|
|
test set over the splits. Still the division into the \( k \) subsets
|
|
involves a degree of randomness. This may be fully excluded when
|
|
choosing \( k=n \). This particular case is referred to as leave-one-out
|
|
cross-validation (LOOCV).
|
|
|
|
<p>
|
|
<!-- !split -->
|
|
|
|
<h2 id="how-to-set-up-the-cross-validation-for-ridge-and-or-lasso">How to set up the cross-validation for Ridge and/or Lasso </h2>
|
|
|
|
<ul>
|
|
<li> Define a range of interest for the penalty parameter.</li>
|
|
<li> Divide the data set into training and test set comprising samples \( \{1, \ldots, n\} \setminus i \) and \( \{ i \} \), respectively.</li>
|
|
<li> Fit the linear regression model by means of ridge estimation for each \( \lambda \) in the grid using the training set, and the corresponding estimate of the error variance \( \boldsymbol{\sigma}_{-i}^2(\lambda) \), as</li>
|
|
</ul>
|
|
|
|
$$
|
|
\begin{align*}
|
|
\boldsymbol{\beta}_{-i}(\lambda) & = ( \boldsymbol{X}_{-i, \ast}^{T}
|
|
\boldsymbol{X}_{-i, \ast} + \lambda \boldsymbol{I}_{pp})^{-1}
|
|
\boldsymbol{X}_{-i, \ast}^{T} \boldsymbol{y}_{-i}
|
|
\end{align*}
|
|
$$
|
|
|
|
|
|
<ul>
|
|
<li> Evaluate the prediction performance of these models on the test set by \( C[y_i, \boldsymbol{X}_{i, \ast}; \boldsymbol{\beta}_{-i}(\lambda), \boldsymbol{\sigma}_{-i}^2(\lambda)] \). Or, by the prediction error \( |y_i - \boldsymbol{X}_{i, \ast} \boldsymbol{\beta}_{-i}(\lambda)| \), the relative error, the error squared or the R2 score function.</li>
|
|
<li> Repeat the first three steps such that each sample plays the role of the test set once.</li>
|
|
<li> Average the prediction performances of the test sets at each grid point of the penalty bias/parameter. It is an estimate of the prediction performance of the model corresponding to this value of the penalty parameter on novel data.</li>
|
|
</ul>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="cross-validation-in-brief">Cross-validation in brief </h2>
|
|
|
|
<p>
|
|
For the various values of \( k \)
|
|
|
|
<ol>
|
|
<li> shuffle the dataset randomly.</li>
|
|
<li> Split the dataset into \( k \) groups.</li>
|
|
<li> For each unique group:
|
|
|
|
<ol type="a"></li>
|
|
<li> Decide which group to use as set for test data</li>
|
|
<li> Take the remaining groups as a training data set</li>
|
|
<li> Fit a model on the training set and evaluate it on the test set</li>
|
|
<li> Retain the evaluation score and discard the model</li>
|
|
</ol>
|
|
|
|
<li> Summarize the model using the sample of model evaluation scores</li>
|
|
</ol>
|
|
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="code-example-for-cross-validation-and-k-fold-cross-validation">Code Example for Cross-validation and \( k \)-fold Cross-validation </h2>
|
|
|
|
<p>
|
|
The code here uses Ridge regression with cross-validation (CV) resampling and \( k \)-fold CV in order to fit a specific polynomial.
|
|
<p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></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">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> KFold
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.linear_model</span> <span style="color: #008000; font-weight: bold">import</span> Ridge
|
|
<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> cross_val_score
|
|
<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> PolynomialFeatures
|
|
|
|
<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>)
|
|
|
|
<span style="color: #408080; font-style: italic"># Generate the data.</span>
|
|
nsamples <span style="color: #666666">=</span> <span style="color: #666666">100</span>
|
|
x <span style="color: #666666">=</span> np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>randn(nsamples)
|
|
y <span style="color: #666666">=</span> <span style="color: #666666">3*</span>x<span style="color: #666666">**2</span> <span style="color: #666666">+</span> np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>randn(nsamples)
|
|
|
|
<span style="color: #408080; font-style: italic">## Cross-validation on Ridge regression using KFold only</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Decide degree on polynomial to fit</span>
|
|
poly <span style="color: #666666">=</span> PolynomialFeatures(degree <span style="color: #666666">=</span> <span style="color: #666666">6</span>)
|
|
|
|
<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">500</span>
|
|
lambdas <span style="color: #666666">=</span> np<span style="color: #666666">.</span>logspace(<span style="color: #666666">-3</span>, <span style="color: #666666">5</span>, nlambdas)
|
|
|
|
<span style="color: #408080; font-style: italic"># Initialize a KFold instance</span>
|
|
k <span style="color: #666666">=</span> <span style="color: #666666">5</span>
|
|
kfold <span style="color: #666666">=</span> KFold(n_splits <span style="color: #666666">=</span> k)
|
|
|
|
<span style="color: #408080; font-style: italic"># Perform the cross-validation to estimate MSE</span>
|
|
scores_KFold <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros((nlambdas, k))
|
|
|
|
i <span style="color: #666666">=</span> <span style="color: #666666">0</span>
|
|
<span style="color: #008000; font-weight: bold">for</span> lmb <span style="color: #AA22FF; font-weight: bold">in</span> lambdas:
|
|
ridge <span style="color: #666666">=</span> Ridge(alpha <span style="color: #666666">=</span> lmb)
|
|
j <span style="color: #666666">=</span> <span style="color: #666666">0</span>
|
|
<span style="color: #008000; font-weight: bold">for</span> train_inds, test_inds <span style="color: #AA22FF; font-weight: bold">in</span> kfold<span style="color: #666666">.</span>split(x):
|
|
xtrain <span style="color: #666666">=</span> x[train_inds]
|
|
ytrain <span style="color: #666666">=</span> y[train_inds]
|
|
|
|
xtest <span style="color: #666666">=</span> x[test_inds]
|
|
ytest <span style="color: #666666">=</span> y[test_inds]
|
|
|
|
Xtrain <span style="color: #666666">=</span> poly<span style="color: #666666">.</span>fit_transform(xtrain[:, np<span style="color: #666666">.</span>newaxis])
|
|
ridge<span style="color: #666666">.</span>fit(Xtrain, ytrain[:, np<span style="color: #666666">.</span>newaxis])
|
|
|
|
Xtest <span style="color: #666666">=</span> poly<span style="color: #666666">.</span>fit_transform(xtest[:, np<span style="color: #666666">.</span>newaxis])
|
|
ypred <span style="color: #666666">=</span> ridge<span style="color: #666666">.</span>predict(Xtest)
|
|
|
|
scores_KFold[i,j] <span style="color: #666666">=</span> np<span style="color: #666666">.</span>sum((ypred <span style="color: #666666">-</span> ytest[:, np<span style="color: #666666">.</span>newaxis])<span style="color: #666666">**2</span>)<span style="color: #666666">/</span>np<span style="color: #666666">.</span>size(ypred)
|
|
|
|
j <span style="color: #666666">+=</span> <span style="color: #666666">1</span>
|
|
i <span style="color: #666666">+=</span> <span style="color: #666666">1</span>
|
|
|
|
|
|
estimated_mse_KFold <span style="color: #666666">=</span> np<span style="color: #666666">.</span>mean(scores_KFold, axis <span style="color: #666666">=</span> <span style="color: #666666">1</span>)
|
|
|
|
<span style="color: #408080; font-style: italic">## Cross-validation using cross_val_score from sklearn along with KFold</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># kfold is an instance initialized above as:</span>
|
|
<span style="color: #408080; font-style: italic"># kfold = KFold(n_splits = k)</span>
|
|
|
|
estimated_mse_sklearn <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(nlambdas)
|
|
i <span style="color: #666666">=</span> <span style="color: #666666">0</span>
|
|
<span style="color: #008000; font-weight: bold">for</span> lmb <span style="color: #AA22FF; font-weight: bold">in</span> lambdas:
|
|
ridge <span style="color: #666666">=</span> Ridge(alpha <span style="color: #666666">=</span> lmb)
|
|
|
|
X <span style="color: #666666">=</span> poly<span style="color: #666666">.</span>fit_transform(x[:, np<span style="color: #666666">.</span>newaxis])
|
|
estimated_mse_folds <span style="color: #666666">=</span> cross_val_score(ridge, X, y[:, np<span style="color: #666666">.</span>newaxis], scoring<span style="color: #666666">=</span><span style="color: #BA2121">'neg_mean_squared_error'</span>, cv<span style="color: #666666">=</span>kfold)
|
|
|
|
<span style="color: #408080; font-style: italic"># cross_val_score return an array containing the estimated negative mse for every fold.</span>
|
|
<span style="color: #408080; font-style: italic"># we have to the the mean of every array in order to get an estimate of the mse of the model</span>
|
|
estimated_mse_sklearn[i] <span style="color: #666666">=</span> np<span style="color: #666666">.</span>mean(<span style="color: #666666">-</span>estimated_mse_folds)
|
|
|
|
i <span style="color: #666666">+=</span> <span style="color: #666666">1</span>
|
|
|
|
<span style="color: #408080; font-style: italic">## Plot and compare the slightly different ways to perform cross-validation</span>
|
|
|
|
plt<span style="color: #666666">.</span>figure()
|
|
|
|
plt<span style="color: #666666">.</span>plot(np<span style="color: #666666">.</span>log10(lambdas), estimated_mse_sklearn, label <span style="color: #666666">=</span> <span style="color: #BA2121">'cross_val_score'</span>)
|
|
plt<span style="color: #666666">.</span>plot(np<span style="color: #666666">.</span>log10(lambdas), estimated_mse_KFold, <span style="color: #BA2121">'r--'</span>, label <span style="color: #666666">=</span> <span style="color: #BA2121">'KFold'</span>)
|
|
|
|
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">'log10(lambda)'</span>)
|
|
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">'mse'</span>)
|
|
|
|
plt<span style="color: #666666">.</span>legend()
|
|
|
|
plt<span style="color: #666666">.</span>show()
|
|
</pre></div>
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="to-think-about-first-part">To think about, first part </h2>
|
|
|
|
<p>
|
|
When you are comparing your own code with for example <b>Scikit-Learn</b>'s
|
|
library, there are some technicalities to keep in mind. The examples
|
|
here demonstrate some of these aspects with potential pitfalls.
|
|
|
|
<p>
|
|
The discussion here focuses on the role of the intercept, how we can
|
|
set up the design matrix, what scaling we should use and other topics
|
|
which tend confuse us.
|
|
|
|
<p>
|
|
The intercept can be interpreted as the expected value of our
|
|
target/output variables when all other predictors are set to zero.
|
|
Thus, if we cannot assume that the expected outputs/targets are zero
|
|
when all predictors are zero (the columns in the design matrix), it
|
|
may be a bad idea to implement a model which penalizes the intercept.
|
|
Furthermore, in for example Ridge and Lasso regression, the default solutions
|
|
from the library <b>Scikit-Learn</b> (when not shrinking \( \beta_0 \)) for the unknown parameters
|
|
\( \boldsymbol{\beta} \), are derived under the assumption that both \( \boldsymbol{y} \) and
|
|
\( \boldsymbol{X} \) are zero centered, that is we subtract the mean values.
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="more-thinking">More thinking </h2>
|
|
|
|
<p>
|
|
If our predictors represent different scales, then it is important to
|
|
standardize the design matrix \( \boldsymbol{X} \) by subtracting the mean of each
|
|
column from the corresponding column and dividing the column with its
|
|
standard deviation. Most machine learning libraries do this as a default. This means that if you compare your code with the results from a given library,
|
|
the results may differ.
|
|
|
|
<p>
|
|
The
|
|
<a href="https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.StandardScaler.html" target="_blank">Standadscaler</a>
|
|
function in <b>Scikit-Learn</b> does this for us. For the data sets we
|
|
have been studying in our various examples, the data are in many cases
|
|
already scaled and there is no need to scale them. You as a user of different machine learning algorithms, should always perform a
|
|
survey of your data, with a critical assessment of them in case you need to scale the data.
|
|
|
|
<p>
|
|
If you need to scale the data, not doing so will give an <em>unfair</em>
|
|
penalization of the parameters since their magnitude depends on the
|
|
scale of their corresponding predictor.
|
|
|
|
<p>
|
|
Suppose as an example that you
|
|
you have an input variable given by the heights of different persons.
|
|
Human height might be measured in inches or meters or
|
|
kilometers. If measured in kilometers, a standard linear regression
|
|
model with this predictor would probably give a much bigger
|
|
coefficient term, than if measured in millimeters.
|
|
This can clearly lead to problems in evaluating the cost/loss functions.
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="still-thinking">Still thinking </h2>
|
|
|
|
<p>
|
|
Keep in mind that when you transform your data set before training a model, the same transformation needs to be done
|
|
on your eventual new data set before making a prediction. If we translate this into a Python code, it would could be implemented as follows
|
|
|
|
<p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span><span style="color: #408080; font-style: italic">#Model training, we compute the mean value of y and X</span>
|
|
y_train_mean <span style="color: #666666">=</span> np<span style="color: #666666">.</span>mean(y_train)
|
|
X_train_mean <span style="color: #666666">=</span> np<span style="color: #666666">.</span>mean(X_train,axis<span style="color: #666666">=0</span>)
|
|
X_train <span style="color: #666666">=</span> X_train <span style="color: #666666">-</span> X_train_mean
|
|
y_train <span style="color: #666666">=</span> y_train <span style="color: #666666">-</span> y_train_mean
|
|
|
|
<span style="color: #408080; font-style: italic"># The we fit our model with the training data</span>
|
|
trained_model <span style="color: #666666">=</span> some_model<span style="color: #666666">.</span>fit(X_train,y_train)
|
|
|
|
|
|
<span style="color: #408080; font-style: italic">#Model prediction, we need also to transform our data set used for the prediction.</span>
|
|
X_test <span style="color: #666666">=</span> X_test <span style="color: #666666">-</span> X_train_mean <span style="color: #408080; font-style: italic">#Use mean from training data</span>
|
|
y_pred <span style="color: #666666">=</span> trained_model(X_test)
|
|
y_pred <span style="color: #666666">=</span> y_pred <span style="color: #666666">+</span> y_train_mean
|
|
</pre></div>
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="what-does-centering-subtracting-the-mean-values-mean-mathematically">What does centering (subtracting the mean values) mean mathematically? </h2>
|
|
|
|
<p>
|
|
Let us try to understand what this may imply mathematically when we
|
|
subtract the mean values, also known as <em>zero centering</em>. For
|
|
simplicity, we will focus on ordinary regression, as done in the above example.
|
|
|
|
<p>
|
|
The cost/loss function for regression is
|
|
$$
|
|
C(\beta_0, \beta_1, ... , \beta_{p-1}) = \frac{1}{n}\sum_{i=0}^{n} \left(y_i - \beta_0 - \sum_{j=1}^{p-1} X_{ij}\beta_j\right)^2,.
|
|
$$
|
|
|
|
Recall also that we use the squared value since this leads to an increase of the penalty for higher differences between predicted and output/target values.
|
|
|
|
<p>
|
|
What we have done is to single out the \( \beta_0 \) term in the definition of the mean squared error (MSE).
|
|
The design matrix
|
|
\( X \) does in this case not contain any intercept column.
|
|
When we take the derivative with respect to \( \beta_0 \), we want the derivative to obey
|
|
$$
|
|
\frac{\partial C}{\partial \beta_j} = 0,
|
|
$$
|
|
|
|
<p>
|
|
for all \( j \). For \( \beta_0 \) we have
|
|
|
|
$$
|
|
\frac{\partial C}{\partial \beta_0} = -\frac{2}{n}\sum_{i=0}^{n-1} \left(y_i - \beta_0 - \sum_{j=1}^{p-1} X_{ij} \beta_j\right).
|
|
$$
|
|
|
|
Multiplying away the constant \( 2/n \), we obtain
|
|
$$
|
|
\sum_{i=0}^{n-1} \beta_0 = \sum_{i=0}^{n-1}y_i - \sum_{i=0}^{n-1} \sum_{j=1}^{p-1} X_{ij} \beta_j.
|
|
$$
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="further-manipulations">Further Manipulations </h2>
|
|
|
|
<p>
|
|
We assume
|
|
that every column of \( \boldsymbol{X} \) is centered, which we can do by subtracting the mean,
|
|
<p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span>X <span style="color: #666666">=</span> X <span style="color: #666666">-</span> np<span style="color: #666666">.</span>mean(X,axis<span style="color: #666666">=0</span>)
|
|
</pre></div>
|
|
<p>
|
|
This means that we need to rewrite \( X_{ij} \) as \( \tilde{X}_{ij}=X_{ij}-\mu_j \), where
|
|
$$
|
|
\mu_j = \frac{1}{n}\sum_{i=0}^{n-1}X_{ij}.
|
|
$$
|
|
|
|
<p>
|
|
Let us special first to the case where we have only two parameters \( \beta_0 \) and \( \beta_1 \).
|
|
Our result for \( \beta_0 \) simplifies then to
|
|
$$
|
|
n\beta_0 = \sum_{i=0}^{n-1}y_i - \sum_{i=0}^{n-1} X_{i1} \beta_1.
|
|
$$
|
|
|
|
Assuming that the matrix elements \( X_{i1} \) are centered, what we have is
|
|
$$
|
|
\beta_0 = \frac{1}{n}\sum_{i=0}^{n-1}y_i - \beta_1\frac{1}{n}\sum_{i=0}^{n-1} \left(X_{i1}-\mu_{1}\right),
|
|
$$
|
|
|
|
where
|
|
$$
|
|
\mu_1=\frac{1}{n}\sum_{i=0}^{n-1} (X_{i1},
|
|
$$
|
|
|
|
and if we define the mean value of the outputs as
|
|
$$
|
|
\mu_y=\frac{1}{n}\sum_{i=0}^{n-1}y_i,
|
|
$$
|
|
|
|
we have
|
|
$$
|
|
\beta_0 = \mu_y - \beta_1\frac{1}{n}\sum_{i=0}^{n-1} (X_{i1}-\mu_{1}),
|
|
$$
|
|
|
|
and it is easy to see that the last sum equals zero! This means that we have
|
|
$$
|
|
\beta_0 = \mu_y,
|
|
$$
|
|
|
|
if the columns of the design matrix are centered. It is straight forward to generalize this results to more values of \( \beta \).
|
|
We have thus
|
|
$$
|
|
\beta_0 = \frac{1}{n}\sum_{i=0}^{n-1} y_i = \overline{\boldsymbol{y}},
|
|
$$
|
|
|
|
the average value of \( \boldsymbol{y} \).
|
|
|
|
<p>
|
|
Replacing \( y_i \) with \( y_i - \beta_0 = y_i - \overline{\boldsymbol{y}} \) and centering also our design matrix results in a cost function (in vector-matrix disguise)
|
|
$$
|
|
C(\boldsymbol{\beta}) = (\boldsymbol{\tilde{y}} - \tilde{X}\boldsymbol{\beta})^T(\boldsymbol{\tilde{y}} - \tilde{X}\boldsymbol{\beta}).
|
|
$$
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="wrapping-it-up">Wrapping it up </h2>
|
|
|
|
<p>
|
|
If we minimize with respect to \( \boldsymbol{\beta} \) we have then
|
|
|
|
$$
|
|
\hat{\boldsymbol{\beta}} = (\tilde{X}^T\tilde{X})^{-1}\tilde{X}^T\boldsymbol{\tilde{y}},
|
|
$$
|
|
|
|
<p>
|
|
where \( \boldsymbol{\tilde{y}} = \boldsymbol{y} - \overline{\boldsymbol{y}} \)
|
|
and \( \tilde{X}_{ij} = X_{ij} - \frac{1}{n}\sum_{k=0}^{n-1}X_{kj} \).
|
|
|
|
<p>
|
|
For Ridge regression we need to add \( \lambda \boldsymbol{\beta}^T\boldsymbol{\beta} \) to the cost function and get then
|
|
$$
|
|
\hat{\boldsymbol{\beta}} = (\tilde{X}^T\tilde{X} + \lambda I)^{-1}\tilde{X}^T\boldsymbol{\tilde{y}}.
|
|
$$
|
|
|
|
<p>
|
|
What does this mean? And why do we insist on all this? Let us look at some examples.
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="linear-regression-code-intercept-handling-first">Linear Regression code, Intercept handling first </h2>
|
|
|
|
<p>
|
|
This code shows a simple first-order fit to a data set using the above transformed data, where we consider the role of the intercept first, by either excluding it or including it (<em>code example thanks to Øyvind Sigmundson Schøyen</em>). Here our scaling of the data is done by subtracting the mean values only.
|
|
Note also that we do not split the data into training and test.
|
|
|
|
<p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></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">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.linear_model</span> <span style="color: #008000; font-weight: bold">import</span> LinearRegression
|
|
|
|
|
|
np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>seed(<span style="color: #666666">2021</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: #008000; font-weight: bold">def</span> <span style="color: #0000FF">fit_beta</span>(X, y):
|
|
<span style="color: #008000; font-weight: bold">return</span> np<span style="color: #666666">.</span>linalg<span style="color: #666666">.</span>pinv(X<span style="color: #666666">.</span>T <span style="color: #666666">@</span> X) <span style="color: #666666">@</span> X<span style="color: #666666">.</span>T <span style="color: #666666">@</span> y
|
|
|
|
|
|
true_beta <span style="color: #666666">=</span> [<span style="color: #666666">2</span>, <span style="color: #666666">0.5</span>, <span style="color: #666666">3.7</span>]
|
|
|
|
x <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linspace(<span style="color: #666666">0</span>, <span style="color: #666666">1</span>, <span style="color: #666666">11</span>)
|
|
y <span style="color: #666666">=</span> np<span style="color: #666666">.</span>sum(
|
|
np<span style="color: #666666">.</span>asarray([x <span style="color: #666666">**</span> p <span style="color: #666666">*</span> b <span style="color: #008000; font-weight: bold">for</span> p, b <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">enumerate</span>(true_beta)]), axis<span style="color: #666666">=0</span>
|
|
) <span style="color: #666666">+</span> <span style="color: #666666">0.1</span> <span style="color: #666666">*</span> np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>normal(size<span style="color: #666666">=</span><span style="color: #008000">len</span>(x))
|
|
|
|
degree <span style="color: #666666">=</span> <span style="color: #666666">3</span>
|
|
X <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros((<span style="color: #008000">len</span>(x), degree))
|
|
|
|
<span style="color: #408080; font-style: italic"># Include the intercept in the design matrix</span>
|
|
<span style="color: #008000; font-weight: bold">for</span> p <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(degree):
|
|
X[:, p] <span style="color: #666666">=</span> x <span style="color: #666666">**</span> p
|
|
|
|
beta <span style="color: #666666">=</span> fit_beta(X, y)
|
|
|
|
<span style="color: #408080; font-style: italic"># Intercept is included in the design matrix</span>
|
|
skl <span style="color: #666666">=</span> LinearRegression(fit_intercept<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">False</span>)<span style="color: #666666">.</span>fit(X, y)
|
|
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">f"True beta: </span><span style="color: #BB6688; font-weight: bold">{</span>true_beta<span style="color: #BB6688; font-weight: bold">}</span><span style="color: #BA2121">"</span>)
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">f"Fitted beta: </span><span style="color: #BB6688; font-weight: bold">{</span>beta<span style="color: #BB6688; font-weight: bold">}</span><span style="color: #BA2121">"</span>)
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">f"Sklearn fitted beta: </span><span style="color: #BB6688; font-weight: bold">{</span>skl<span style="color: #666666">.</span>coef_<span style="color: #BB6688; font-weight: bold">}</span><span style="color: #BA2121">"</span>)
|
|
ypredictOwn <span style="color: #666666">=</span> X <span style="color: #666666">@</span> beta
|
|
ypredictSKL <span style="color: #666666">=</span> skl<span style="color: #666666">.</span>predict(X)
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">f"MSE with intercept column"</span>)
|
|
<span style="color: #008000">print</span>(MSE(y,ypredictOwn))
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">f"MSE with intercept column from SKL"</span>)
|
|
<span style="color: #008000">print</span>(MSE(y,ypredictSKL))
|
|
|
|
|
|
plt<span style="color: #666666">.</span>figure()
|
|
plt<span style="color: #666666">.</span>scatter(x, y, label<span style="color: #666666">=</span><span style="color: #BA2121">"Data"</span>)
|
|
plt<span style="color: #666666">.</span>plot(x, X <span style="color: #666666">@</span> beta, label<span style="color: #666666">=</span><span style="color: #BA2121">"Fit"</span>)
|
|
plt<span style="color: #666666">.</span>plot(x, skl<span style="color: #666666">.</span>predict(X), label<span style="color: #666666">=</span><span style="color: #BA2121">"Sklearn (fit_intercept=False)"</span>)
|
|
|
|
|
|
<span style="color: #408080; font-style: italic"># Do not include the intercept in the design matrix</span>
|
|
X <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros((<span style="color: #008000">len</span>(x), degree <span style="color: #666666">-</span> <span style="color: #666666">1</span>))
|
|
|
|
<span style="color: #008000; font-weight: bold">for</span> p <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(degree <span style="color: #666666">-</span> <span style="color: #666666">1</span>):
|
|
X[:, p] <span style="color: #666666">=</span> x <span style="color: #666666">**</span> (p <span style="color: #666666">+</span> <span style="color: #666666">1</span>)
|
|
|
|
<span style="color: #408080; font-style: italic"># Intercept is not included in the design matrix</span>
|
|
skl <span style="color: #666666">=</span> LinearRegression(fit_intercept<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>)<span style="color: #666666">.</span>fit(X, y)
|
|
|
|
<span style="color: #408080; font-style: italic"># Use centered values for X and y when computing coefficients</span>
|
|
y_offset <span style="color: #666666">=</span> np<span style="color: #666666">.</span>average(y, axis<span style="color: #666666">=0</span>)
|
|
X_offset <span style="color: #666666">=</span> np<span style="color: #666666">.</span>average(X, axis<span style="color: #666666">=0</span>)
|
|
|
|
beta <span style="color: #666666">=</span> fit_beta(X <span style="color: #666666">-</span> X_offset, y <span style="color: #666666">-</span> y_offset)
|
|
intercept <span style="color: #666666">=</span> np<span style="color: #666666">.</span>mean(y_offset <span style="color: #666666">-</span> X_offset <span style="color: #666666">@</span> beta)
|
|
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">f"Manual intercept: </span><span style="color: #BB6688; font-weight: bold">{</span>intercept<span style="color: #BB6688; font-weight: bold">}</span><span style="color: #BA2121">"</span>)
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">f"Fitted beta (wiothout intercept): </span><span style="color: #BB6688; font-weight: bold">{</span>beta<span style="color: #BB6688; font-weight: bold">}</span><span style="color: #BA2121">"</span>)
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">f"Sklearn intercept: </span><span style="color: #BB6688; font-weight: bold">{</span>skl<span style="color: #666666">.</span>intercept_<span style="color: #BB6688; font-weight: bold">}</span><span style="color: #BA2121">"</span>)
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">f"Sklearn fitted beta (without intercept): </span><span style="color: #BB6688; font-weight: bold">{</span>skl<span style="color: #666666">.</span>coef_<span style="color: #BB6688; font-weight: bold">}</span><span style="color: #BA2121">"</span>)
|
|
ypredictOwn <span style="color: #666666">=</span> X <span style="color: #666666">@</span> beta
|
|
ypredictSKL <span style="color: #666666">=</span> skl<span style="color: #666666">.</span>predict(X)
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">f"MSE with Manual intercept"</span>)
|
|
<span style="color: #008000">print</span>(MSE(y,ypredictOwn<span style="color: #666666">+</span>intercept))
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">f"MSE with Sklearn intercept"</span>)
|
|
<span style="color: #008000">print</span>(MSE(y,ypredictSKL))
|
|
|
|
plt<span style="color: #666666">.</span>plot(x, X <span style="color: #666666">@</span> beta <span style="color: #666666">+</span> intercept, <span style="color: #BA2121">"--"</span>, label<span style="color: #666666">=</span><span style="color: #BA2121">"Fit (manual intercept)"</span>)
|
|
plt<span style="color: #666666">.</span>plot(x, skl<span style="color: #666666">.</span>predict(X), <span style="color: #BA2121">"--"</span>, label<span style="color: #666666">=</span><span style="color: #BA2121">"Sklearn (fit_intercept=True)"</span>)
|
|
plt<span style="color: #666666">.</span>grid()
|
|
plt<span style="color: #666666">.</span>legend()
|
|
|
|
plt<span style="color: #666666">.</span>show()
|
|
</pre></div>
|
|
<p>
|
|
The intercept is the value of our output/target variable
|
|
when all our features are zero and our function crosses the \( y \)-axis (for a one-dimensional case).
|
|
|
|
<p>
|
|
Printing the MSE, we see first that both methods give the same MSE, as
|
|
they should. However, when we move to for example Ridge regression,
|
|
the way we treat the intercept may give a larger or smaller MSE,
|
|
meaning that the MSE can be penalized by the value of the
|
|
intercept. Not including the intercept in the fit, means that the
|
|
regularization term does not include \( \beta_0 \). For different values
|
|
of \( \lambda \), this may lead to differeing MSE values.
|
|
|
|
<p>
|
|
To remind the reader, the regularization term, with the intercept in Ridge regression is given by
|
|
$$
|
|
\lambda \vert\vert \boldsymbol{\beta} \vert\vert_2^2 = \lambda \sum_{j=0}^{p-1}\beta_j^2,
|
|
$$
|
|
|
|
but when we take out the intercept, this equation becomes
|
|
$$
|
|
\lambda \vert\vert \boldsymbol{\beta} \vert\vert_2^2 = \lambda \sum_{j=1}^{p-1}\beta_j^2.
|
|
$$
|
|
|
|
<p>
|
|
For Lasso regression we have
|
|
$$
|
|
\lambda \vert\vert \boldsymbol{\beta} \vert\vert_1 = \lambda \sum_{j=1}^{p-1}\vert\beta_j\vert.
|
|
$$
|
|
|
|
<p>
|
|
It means that, when scaling the design matrix and the outputs/targets, by subtracting the mean values, we have an optimization problem which is not penalized by the intercept. The MSE value can then be smaller since it focuses only on the remaining quantities. If we however bring back the intercept, we will get a MSE which then contains the intercept.
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="code-examples">Code Examples </h2>
|
|
|
|
<p>
|
|
Armed with this wisdom, we attempt first to simply set the intercept equal to <b>False</b> in our implementation of Ridge regression for our well-known vanilla data set.
|
|
|
|
<p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></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</span> <span style="color: #008000; font-weight: bold">import</span> linear_model
|
|
|
|
<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>)
|
|
|
|
n <span style="color: #666666">=</span> <span style="color: #666666">100</span>
|
|
x <span style="color: #666666">=</span> np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>rand(n)
|
|
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>)
|
|
|
|
Maxpolydegree <span style="color: #666666">=</span> <span style="color: #666666">20</span>
|
|
X <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros((n,Maxpolydegree))
|
|
<span style="color: #408080; font-style: italic">#We include explicitely the intercept column</span>
|
|
<span style="color: #008000; font-weight: bold">for</span> degree <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(Maxpolydegree):
|
|
X[:,degree] <span style="color: #666666">=</span> x<span style="color: #666666">**</span>degree
|
|
<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>)
|
|
|
|
p <span style="color: #666666">=</span> Maxpolydegree
|
|
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">6</span>
|
|
MSEOwnRidgePredict <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(nlambdas)
|
|
MSERidgePredict <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">2</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]
|
|
OwnRidgeBeta <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linalg<span style="color: #666666">.</span>pinv(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"># Note: we include the intercept column and no scaling</span>
|
|
RegRidge <span style="color: #666666">=</span> linear_model<span style="color: #666666">.</span>Ridge(lmb,fit_intercept<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">False</span>)
|
|
RegRidge<span style="color: #666666">.</span>fit(X_train,y_train)
|
|
<span style="color: #408080; font-style: italic"># and then make the prediction</span>
|
|
ytildeOwnRidge <span style="color: #666666">=</span> X_train <span style="color: #666666">@</span> OwnRidgeBeta
|
|
ypredictOwnRidge <span style="color: #666666">=</span> X_test <span style="color: #666666">@</span> OwnRidgeBeta
|
|
ytildeRidge <span style="color: #666666">=</span> RegRidge<span style="color: #666666">.</span>predict(X_train)
|
|
ypredictRidge <span style="color: #666666">=</span> RegRidge<span style="color: #666666">.</span>predict(X_test)
|
|
MSEOwnRidgePredict[i] <span style="color: #666666">=</span> MSE(y_test,ypredictOwnRidge)
|
|
MSERidgePredict[i] <span style="color: #666666">=</span> MSE(y_test,ypredictRidge)
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"Beta values for own Ridge implementation"</span>)
|
|
<span style="color: #008000">print</span>(OwnRidgeBeta)
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"Beta values for Scikit-Learn Ridge implementation"</span>)
|
|
<span style="color: #008000">print</span>(RegRidge<span style="color: #666666">.</span>coef_)
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"MSE values for own Ridge implementation"</span>)
|
|
<span style="color: #008000">print</span>(MSEOwnRidgePredict[i])
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"MSE values for Scikit-Learn Ridge implementation"</span>)
|
|
<span style="color: #008000">print</span>(MSERidgePredict[i])
|
|
|
|
<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), MSEOwnRidgePredict, <span style="color: #BA2121">'r'</span>, label <span style="color: #666666">=</span> <span style="color: #BA2121">'MSE own Ridge Test'</span>)
|
|
plt<span style="color: #666666">.</span>plot(np<span style="color: #666666">.</span>log10(lambdas), MSERidgePredict, <span style="color: #BA2121">'g'</span>, label <span style="color: #666666">=</span> <span style="color: #BA2121">'MSE Ridge Test'</span>)
|
|
|
|
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">'log10(lambda)'</span>)
|
|
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">'MSE'</span>)
|
|
plt<span style="color: #666666">.</span>legend()
|
|
plt<span style="color: #666666">.</span>show()
|
|
</pre></div>
|
|
<p>
|
|
The results here agree when we force <b>Scikit-Learn</b>'s Ridge function to include the first column in our design matrix.
|
|
We see that the results agree very well. Here we have thus explicitely included the intercept column in the design matrix.
|
|
What happens if we do not include the intercept in our fit?
|
|
Let us see how we can change this code by zero centering (thanks to Stian Bilek for inpouts here).
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="taking-out-the-mean">Taking out the mean </h2>
|
|
<p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></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</span> <span style="color: #008000; font-weight: bold">import</span> linear_model
|
|
<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">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">315</span>)
|
|
|
|
n <span style="color: #666666">=</span> <span style="color: #666666">100</span>
|
|
x <span style="color: #666666">=</span> np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>rand(n)
|
|
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>)
|
|
|
|
Maxpolydegree <span style="color: #666666">=</span> <span style="color: #666666">20</span>
|
|
X <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros((n,Maxpolydegree<span style="color: #666666">-1</span>))
|
|
|
|
<span style="color: #008000; font-weight: bold">for</span> degree <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">range</span>(<span style="color: #666666">1</span>,Maxpolydegree): <span style="color: #408080; font-style: italic">#No intercept column</span>
|
|
X[:,degree<span style="color: #666666">-1</span>] <span style="color: #666666">=</span> x<span style="color: #666666">**</span>(degree)
|
|
|
|
<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">#For our own implementation, we will need to deal with the intercept by centering the design matrix and the target variable</span>
|
|
X_train_mean <span style="color: #666666">=</span> np<span style="color: #666666">.</span>mean(X_train,axis<span style="color: #666666">=0</span>)
|
|
<span style="color: #408080; font-style: italic">#Center by removing mean from each feature</span>
|
|
X_train_scaled <span style="color: #666666">=</span> X_train <span style="color: #666666">-</span> X_train_mean
|
|
X_test_scaled <span style="color: #666666">=</span> X_test <span style="color: #666666">-</span> X_train_mean
|
|
<span style="color: #408080; font-style: italic">#The model intercept (called y_scaler) is given by the mean of the target variable (IF X is centered)</span>
|
|
<span style="color: #408080; font-style: italic">#Remove the intercept from the training data.</span>
|
|
y_scaler <span style="color: #666666">=</span> np<span style="color: #666666">.</span>mean(y_train)
|
|
y_train_scaled <span style="color: #666666">=</span> y_train <span style="color: #666666">-</span> y_scaler
|
|
|
|
p <span style="color: #666666">=</span> Maxpolydegree<span style="color: #666666">-1</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">6</span>
|
|
MSEOwnRidgePredict <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(nlambdas)
|
|
MSERidgePredict <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">2</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]
|
|
OwnRidgeBeta <span style="color: #666666">=</span> np<span style="color: #666666">.</span>linalg<span style="color: #666666">.</span>pinv(X_train_scaled<span style="color: #666666">.</span>T <span style="color: #666666">@</span> X_train_scaled<span style="color: #666666">+</span>lmb<span style="color: #666666">*</span>I) <span style="color: #666666">@</span> X_train_scaled<span style="color: #666666">.</span>T <span style="color: #666666">@</span> (y_train_scaled)
|
|
intercept_ <span style="color: #666666">=</span> y_scaler <span style="color: #666666">-</span> X_train_mean<span style="color: #AA22FF">@OwnRidgeBeta</span> <span style="color: #408080; font-style: italic">#The intercept can be shifted so the model can predict on uncentered data</span>
|
|
<span style="color: #408080; font-style: italic">#Add intercept to prediction</span>
|
|
ypredictOwnRidge <span style="color: #666666">=</span> X_test <span style="color: #666666">@</span> OwnRidgeBeta <span style="color: #666666">+</span> intercept_
|
|
<span style="color: #408080; font-style: italic">#Add intercept to prediction</span>
|
|
ypredictOwnRidge <span style="color: #666666">=</span> X_test_scaled <span style="color: #666666">@</span> OwnRidgeBeta <span style="color: #666666">+</span> y_scaler
|
|
RegRidge <span style="color: #666666">=</span> linear_model<span style="color: #666666">.</span>Ridge(lmb)
|
|
RegRidge<span style="color: #666666">.</span>fit(X_train,y_train)
|
|
ypredictRidge <span style="color: #666666">=</span> RegRidge<span style="color: #666666">.</span>predict(X_test)
|
|
MSEOwnRidgePredict[i] <span style="color: #666666">=</span> MSE(y_test,ypredictOwnRidge)
|
|
MSERidgePredict[i] <span style="color: #666666">=</span> MSE(y_test,ypredictRidge)
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"Beta values for own Ridge implementation"</span>)
|
|
<span style="color: #008000">print</span>(OwnRidgeBeta) <span style="color: #408080; font-style: italic">#Intercept is given by mean of target variable</span>
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"Beta values for Scikit-Learn Ridge implementation"</span>)
|
|
<span style="color: #008000">print</span>(RegRidge<span style="color: #666666">.</span>coef_)
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">'Intercept from own implementation:'</span>)
|
|
<span style="color: #008000">print</span>(intercept_)
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">'Intercept from Scikit-Learn Ridge implementation'</span>)
|
|
<span style="color: #008000">print</span>(RegRidge<span style="color: #666666">.</span>intercept_)
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"MSE values for own Ridge implementation"</span>)
|
|
<span style="color: #008000">print</span>(MSEOwnRidgePredict[i])
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"MSE values for Scikit-Learn Ridge implementation"</span>)
|
|
<span style="color: #008000">print</span>(MSERidgePredict[i])
|
|
|
|
|
|
<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), MSEOwnRidgePredict, <span style="color: #BA2121">'b--'</span>, label <span style="color: #666666">=</span> <span style="color: #BA2121">'MSE own Ridge Test'</span>)
|
|
plt<span style="color: #666666">.</span>plot(np<span style="color: #666666">.</span>log10(lambdas), MSERidgePredict, <span style="color: #BA2121">'g--'</span>, label <span style="color: #666666">=</span> <span style="color: #BA2121">'MSE SL Ridge Test'</span>)
|
|
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">'log10(lambda)'</span>)
|
|
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">'MSE'</span>)
|
|
plt<span style="color: #666666">.</span>legend()
|
|
plt<span style="color: #666666">.</span>show()
|
|
</pre></div>
|
|
<p>
|
|
We see here, when compared to the code which includes explicitely the
|
|
intercept column, that our MSE value is actually smaller. This is
|
|
because the regularization term does not include the intercept value
|
|
\( \beta_0 \) in the fitting. This applies to Lasso regularization as
|
|
well. It means that our optimization is now done only with the
|
|
centered matrix and/or vector that enter the fitting procedure. Note
|
|
also that the problem with the intercept occurs mainly in these type
|
|
of polynomial fitting problem.
|
|
|
|
<p>
|
|
The next example is indeed an example where all these discussions about the role of intercept are not present.
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="more-complicated-example-the-ising-model">More complicated Example: The Ising model </h2>
|
|
|
|
<p>
|
|
The one-dimensional Ising model with nearest neighbor interaction, no
|
|
external field and a constant coupling constant \( J \) is given by
|
|
|
|
$$
|
|
\begin{align}
|
|
H = -J \sum_{k}^L s_k s_{k + 1},
|
|
\label{_auto1}
|
|
\end{align}
|
|
$$
|
|
|
|
<p>
|
|
where \( s_i \in \{-1, 1\} \) and \( s_{N + 1} = s_1 \). The number of spins
|
|
in the system is determined by \( L \). For the one-dimensional system
|
|
there is no phase transition.
|
|
|
|
<p>
|
|
We will look at a system of \( L = 40 \) spins with a coupling constant of
|
|
\( J = 1 \). To get enough training data we will generate 10000 states
|
|
with their respective energies.
|
|
|
|
<p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></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">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">mpl_toolkits.axes_grid1</span> <span style="color: #008000; font-weight: bold">import</span> make_axes_locatable
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">seaborn</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">sns</span>
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">scipy.linalg</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">scl</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">import</span> <span style="color: #0000FF; font-weight: bold">tqdm</span>
|
|
sns<span style="color: #666666">.</span>set(color_codes<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>)
|
|
cmap_args<span style="color: #666666">=</span><span style="color: #008000">dict</span>(vmin<span style="color: #666666">=-1.</span>, vmax<span style="color: #666666">=1.</span>, cmap<span style="color: #666666">=</span><span style="color: #BA2121">'seismic'</span>)
|
|
|
|
L <span style="color: #666666">=</span> <span style="color: #666666">40</span>
|
|
n <span style="color: #666666">=</span> <span style="color: #008000">int</span>(<span style="color: #666666">1e4</span>)
|
|
|
|
spins <span style="color: #666666">=</span> np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>choice([<span style="color: #666666">-1</span>, <span style="color: #666666">1</span>], size<span style="color: #666666">=</span>(n, L))
|
|
J <span style="color: #666666">=</span> <span style="color: #666666">1.0</span>
|
|
|
|
energies <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(n)
|
|
|
|
<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>(n):
|
|
energies[i] <span style="color: #666666">=</span> <span style="color: #666666">-</span> J <span style="color: #666666">*</span> np<span style="color: #666666">.</span>dot(spins[i], np<span style="color: #666666">.</span>roll(spins[i], <span style="color: #666666">1</span>))
|
|
</pre></div>
|
|
<p>
|
|
Here we use ordinary least squares
|
|
regression to predict the energy for the nearest neighbor
|
|
one-dimensional Ising model on a ring, i.e., the endpoints wrap
|
|
around. We will use linear regression to fit a value for
|
|
the coupling constant to achieve this.
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="reformulating-the-problem-to-suit-regression">Reformulating the problem to suit regression </h2>
|
|
|
|
<p>
|
|
A more general form for the one-dimensional Ising model is
|
|
|
|
$$
|
|
\begin{align}
|
|
H = - \sum_j^L \sum_k^L s_j s_k J_{jk}.
|
|
\label{_auto2}
|
|
\end{align}
|
|
$$
|
|
|
|
<p>
|
|
Here we allow for interactions beyond the nearest neighbors and a state dependent
|
|
coupling constant. This latter expression can be formulated as
|
|
a matrix-product
|
|
$$
|
|
\begin{align}
|
|
\boldsymbol{H} = \boldsymbol{X} J,
|
|
\label{_auto3}
|
|
\end{align}
|
|
$$
|
|
|
|
<p>
|
|
where \( X_{jk} = s_j s_k \) and \( J \) is a matrix which consists of the
|
|
elements \( -J_{jk} \). This form of writing the energy fits perfectly
|
|
with the form utilized in linear regression, that is
|
|
|
|
$$
|
|
\begin{align}
|
|
\boldsymbol{y} = \boldsymbol{X}\boldsymbol{\beta} + \boldsymbol{\epsilon},
|
|
\label{_auto4}
|
|
\end{align}
|
|
$$
|
|
|
|
<p>
|
|
We split the data in training and test data as discussed in the previous example
|
|
|
|
<p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span>X <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros((n, L <span style="color: #666666">**</span> <span style="color: #666666">2</span>))
|
|
<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>(n):
|
|
X[i] <span style="color: #666666">=</span> np<span style="color: #666666">.</span>outer(spins[i], spins[i])<span style="color: #666666">.</span>ravel()
|
|
y <span style="color: #666666">=</span> energies
|
|
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>
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="linear-regression">Linear regression </h2>
|
|
|
|
<p>
|
|
In the ordinary least squares method we choose the cost function
|
|
|
|
$$
|
|
\begin{align}
|
|
C(\boldsymbol{X}, \boldsymbol{\beta})= \frac{1}{n}\left\{(\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y})^T(\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y})\right\}.
|
|
\label{_auto5}
|
|
\end{align}
|
|
$$
|
|
|
|
<p>
|
|
We then find the extremal point of \( C \) by taking the derivative with respect to \( \boldsymbol{\beta} \) as discussed above.
|
|
This yields the expression for \( \boldsymbol{\beta} \) to be
|
|
|
|
$$
|
|
\boldsymbol{\beta} = \frac{\boldsymbol{X}^T \boldsymbol{y}}{\boldsymbol{X}^T \boldsymbol{X}},
|
|
$$
|
|
|
|
<p>
|
|
which immediately imposes some requirements on \( \boldsymbol{X} \) as there must exist
|
|
an inverse of \( \boldsymbol{X}^T \boldsymbol{X} \). If the expression we are modeling contains an
|
|
intercept, i.e., a constant term, we must make sure that the
|
|
first column of \( \boldsymbol{X} \) consists of \( 1 \). We do this here
|
|
|
|
<p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span>X_train_own <span style="color: #666666">=</span> np<span style="color: #666666">.</span>concatenate(
|
|
(np<span style="color: #666666">.</span>ones(<span style="color: #008000">len</span>(X_train))[:, np<span style="color: #666666">.</span>newaxis], X_train),
|
|
axis<span style="color: #666666">=1</span>
|
|
)
|
|
X_test_own <span style="color: #666666">=</span> np<span style="color: #666666">.</span>concatenate(
|
|
(np<span style="color: #666666">.</span>ones(<span style="color: #008000">len</span>(X_test))[:, np<span style="color: #666666">.</span>newaxis], X_test),
|
|
axis<span style="color: #666666">=1</span>
|
|
)
|
|
</pre></div>
|
|
<p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span><span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">ols_inv</span>(x: np<span style="color: #666666">.</span>ndarray, y: np<span style="color: #666666">.</span>ndarray) <span style="color: #666666">-></span> np<span style="color: #666666">.</span>ndarray:
|
|
<span style="color: #008000; font-weight: bold">return</span> scl<span style="color: #666666">.</span>inv(x<span style="color: #666666">.</span>T <span style="color: #666666">@</span> x) <span style="color: #666666">@</span> (x<span style="color: #666666">.</span>T <span style="color: #666666">@</span> y)
|
|
beta <span style="color: #666666">=</span> ols_inv(X_train_own, y_train)
|
|
</pre></div>
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="singular-value-decomposition">Singular Value decomposition </h2>
|
|
|
|
<p>
|
|
Doing the inversion directly turns out to be a bad idea since the matrix
|
|
\( \boldsymbol{X}^T\boldsymbol{X} \) is singular. An alternative approach is to use the <b>singular
|
|
value decomposition</b>. Using the definition of the Moore-Penrose
|
|
pseudoinverse we can write the equation for \( \boldsymbol{\beta} \) as
|
|
|
|
$$
|
|
\boldsymbol{\beta} = \boldsymbol{X}^{+}\boldsymbol{y},
|
|
$$
|
|
|
|
<p>
|
|
where the pseudoinverse of \( \boldsymbol{X} \) is given by
|
|
|
|
$$
|
|
\boldsymbol{X}^{+} = \frac{\boldsymbol{X}^T}{\boldsymbol{X}^T\boldsymbol{X}}.
|
|
$$
|
|
|
|
<p>
|
|
Using singular value decomposition we can decompose the matrix \( \boldsymbol{X} = \boldsymbol{U}\boldsymbol{\Sigma} \boldsymbol{V}^T \),
|
|
where \( \boldsymbol{U} \) and \( \boldsymbol{V} \) are orthogonal(unitary) matrices and \( \boldsymbol{\Sigma} \) contains the singular values (more details below).
|
|
where \( X^{+} = V\Sigma^{+} U^T \). This reduces the equation for
|
|
\( \omega \) to
|
|
$$
|
|
\begin{align}
|
|
\boldsymbol{\beta} = \boldsymbol{V}\boldsymbol{\Sigma}^{+} \boldsymbol{U}^T \boldsymbol{y}.
|
|
\label{_auto6}
|
|
\end{align}
|
|
$$
|
|
|
|
<p>
|
|
Note that solving this equation by actually doing the pseudoinverse
|
|
(which is what we will do) is not a good idea as this operation scales
|
|
as \( \mathcal{O}(n^3) \), where \( n \) is the number of elements in a
|
|
general matrix. Instead, doing \( QR \)-factorization and solving the
|
|
linear system as an equation would reduce this down to
|
|
\( \mathcal{O}(n^2) \) operations.
|
|
|
|
<p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span><span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">ols_svd</span>(x: np<span style="color: #666666">.</span>ndarray, y: np<span style="color: #666666">.</span>ndarray) <span style="color: #666666">-></span> np<span style="color: #666666">.</span>ndarray:
|
|
u, s, v <span style="color: #666666">=</span> scl<span style="color: #666666">.</span>svd(x)
|
|
<span style="color: #008000; font-weight: bold">return</span> v<span style="color: #666666">.</span>T <span style="color: #666666">@</span> scl<span style="color: #666666">.</span>pinv(scl<span style="color: #666666">.</span>diagsvd(s, u<span style="color: #666666">.</span>shape[<span style="color: #666666">0</span>], v<span style="color: #666666">.</span>shape[<span style="color: #666666">0</span>])) <span style="color: #666666">@</span> u<span style="color: #666666">.</span>T <span style="color: #666666">@</span> y
|
|
</pre></div>
|
|
<p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span>beta <span style="color: #666666">=</span> ols_svd(X_train_own,y_train)
|
|
</pre></div>
|
|
<p>
|
|
When extracting the \( J \)-matrix we need to make sure that we remove the intercept, as is done here
|
|
|
|
<p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span>J <span style="color: #666666">=</span> beta[<span style="color: #666666">1</span>:]<span style="color: #666666">.</span>reshape(L, L)
|
|
</pre></div>
|
|
<p>
|
|
A way of looking at the coefficients in \( J \) is to plot the matrices as images.
|
|
|
|
<p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span>fig <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">20</span>, <span style="color: #666666">14</span>))
|
|
im <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>imshow(J, <span style="color: #666666">**</span>cmap_args)
|
|
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">"OLS"</span>, fontsize<span style="color: #666666">=18</span>)
|
|
plt<span style="color: #666666">.</span>xticks(fontsize<span style="color: #666666">=18</span>)
|
|
plt<span style="color: #666666">.</span>yticks(fontsize<span style="color: #666666">=18</span>)
|
|
cb <span style="color: #666666">=</span> fig<span style="color: #666666">.</span>colorbar(im)
|
|
cb<span style="color: #666666">.</span>ax<span style="color: #666666">.</span>set_yticklabels(cb<span style="color: #666666">.</span>ax<span style="color: #666666">.</span>get_yticklabels(), fontsize<span style="color: #666666">=18</span>)
|
|
plt<span style="color: #666666">.</span>show()
|
|
</pre></div>
|
|
<p>
|
|
It is interesting to note that OLS
|
|
considers both \( J_{j, j + 1} = -0.5 \) and \( J_{j, j - 1} = -0.5 \) as
|
|
valid matrix elements for \( J \).
|
|
In our discussion below on hyperparameters and Ridge and Lasso regression we will see that
|
|
this problem can be removed, partly and only with Lasso regression.
|
|
|
|
<p>
|
|
In this case our matrix inversion was actually possible. The obvious question now is what is the mathematics behind the SVD?
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="the-one-dimensional-ising-model">The one-dimensional Ising model </h2>
|
|
|
|
<p>
|
|
Let us bring back the Ising model again, but now with an additional
|
|
focus on Ridge and Lasso regression as well. We repeat some of the
|
|
basic parts of the Ising model and the setup of the training and test
|
|
data. The one-dimensional Ising model with nearest neighbor
|
|
interaction, no external field and a constant coupling constant \( J \) is
|
|
given by
|
|
|
|
$$
|
|
\begin{align}
|
|
H = -J \sum_{k}^L s_k s_{k + 1},
|
|
\label{_auto7}
|
|
\end{align}
|
|
$$
|
|
|
|
where \( s_i \in \{-1, 1\} \) and \( s_{N + 1} = s_1 \). The number of spins in the system is determined by \( L \). For the one-dimensional system there is no phase transition.
|
|
|
|
<p>
|
|
We will look at a system of \( L = 40 \) spins with a coupling constant of \( J = 1 \). To get enough training data we will generate 10000 states with their respective energies.
|
|
|
|
<p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></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">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">mpl_toolkits.axes_grid1</span> <span style="color: #008000; font-weight: bold">import</span> make_axes_locatable
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">seaborn</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">sns</span>
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">scipy.linalg</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">scl</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">import</span> <span style="color: #0000FF; font-weight: bold">sklearn.linear_model</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">skl</span>
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">tqdm</span>
|
|
sns<span style="color: #666666">.</span>set(color_codes<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>)
|
|
cmap_args<span style="color: #666666">=</span><span style="color: #008000">dict</span>(vmin<span style="color: #666666">=-1.</span>, vmax<span style="color: #666666">=1.</span>, cmap<span style="color: #666666">=</span><span style="color: #BA2121">'seismic'</span>)
|
|
|
|
L <span style="color: #666666">=</span> <span style="color: #666666">40</span>
|
|
n <span style="color: #666666">=</span> <span style="color: #008000">int</span>(<span style="color: #666666">1e4</span>)
|
|
|
|
spins <span style="color: #666666">=</span> np<span style="color: #666666">.</span>random<span style="color: #666666">.</span>choice([<span style="color: #666666">-1</span>, <span style="color: #666666">1</span>], size<span style="color: #666666">=</span>(n, L))
|
|
J <span style="color: #666666">=</span> <span style="color: #666666">1.0</span>
|
|
|
|
energies <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros(n)
|
|
|
|
<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>(n):
|
|
energies[i] <span style="color: #666666">=</span> <span style="color: #666666">-</span> J <span style="color: #666666">*</span> np<span style="color: #666666">.</span>dot(spins[i], np<span style="color: #666666">.</span>roll(spins[i], <span style="color: #666666">1</span>))
|
|
</pre></div>
|
|
<p>
|
|
A more general form for the one-dimensional Ising model is
|
|
|
|
$$
|
|
\begin{align}
|
|
H = - \sum_j^L \sum_k^L s_j s_k J_{jk}.
|
|
\label{_auto8}
|
|
\end{align}
|
|
$$
|
|
|
|
<p>
|
|
Here we allow for interactions beyond the nearest neighbors and a more
|
|
adaptive coupling matrix. This latter expression can be formulated as
|
|
a matrix-product on the form
|
|
$$
|
|
\begin{align}
|
|
H = X J,
|
|
\label{_auto9}
|
|
\end{align}
|
|
$$
|
|
|
|
<p>
|
|
where \( X_{jk} = s_j s_k \) and \( J \) is the matrix consisting of the
|
|
elements \( -J_{jk} \). This form of writing the energy fits perfectly
|
|
with the form utilized in linear regression, viz.
|
|
$$
|
|
\begin{align}
|
|
\boldsymbol{y} = \boldsymbol{X}\boldsymbol{\beta} + \boldsymbol{\epsilon}.
|
|
\label{_auto10}
|
|
\end{align}
|
|
$$
|
|
|
|
We organize the data as we did above
|
|
<p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span>X <span style="color: #666666">=</span> np<span style="color: #666666">.</span>zeros((n, L <span style="color: #666666">**</span> <span style="color: #666666">2</span>))
|
|
<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>(n):
|
|
X[i] <span style="color: #666666">=</span> np<span style="color: #666666">.</span>outer(spins[i], spins[i])<span style="color: #666666">.</span>ravel()
|
|
y <span style="color: #666666">=</span> energies
|
|
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.96</span>)
|
|
|
|
X_train_own <span style="color: #666666">=</span> np<span style="color: #666666">.</span>concatenate(
|
|
(np<span style="color: #666666">.</span>ones(<span style="color: #008000">len</span>(X_train))[:, np<span style="color: #666666">.</span>newaxis], X_train),
|
|
axis<span style="color: #666666">=1</span>
|
|
)
|
|
|
|
X_test_own <span style="color: #666666">=</span> np<span style="color: #666666">.</span>concatenate(
|
|
(np<span style="color: #666666">.</span>ones(<span style="color: #008000">len</span>(X_test))[:, np<span style="color: #666666">.</span>newaxis], X_test),
|
|
axis<span style="color: #666666">=1</span>
|
|
)
|
|
</pre></div>
|
|
<p>
|
|
We will do all fitting with <b>Scikit-Learn</b>,
|
|
|
|
<p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span>clf <span style="color: #666666">=</span> skl<span style="color: #666666">.</span>LinearRegression()<span style="color: #666666">.</span>fit(X_train, y_train)
|
|
</pre></div>
|
|
<p>
|
|
When extracting the \( J \)-matrix we make sure to remove the intercept
|
|
<p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span>J_sk <span style="color: #666666">=</span> clf<span style="color: #666666">.</span>coef_<span style="color: #666666">.</span>reshape(L, L)
|
|
</pre></div>
|
|
<p>
|
|
And then we plot the results
|
|
<p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span>fig <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">20</span>, <span style="color: #666666">14</span>))
|
|
im <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>imshow(J_sk, <span style="color: #666666">**</span>cmap_args)
|
|
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">"LinearRegression from Scikit-learn"</span>, fontsize<span style="color: #666666">=18</span>)
|
|
plt<span style="color: #666666">.</span>xticks(fontsize<span style="color: #666666">=18</span>)
|
|
plt<span style="color: #666666">.</span>yticks(fontsize<span style="color: #666666">=18</span>)
|
|
cb <span style="color: #666666">=</span> fig<span style="color: #666666">.</span>colorbar(im)
|
|
cb<span style="color: #666666">.</span>ax<span style="color: #666666">.</span>set_yticklabels(cb<span style="color: #666666">.</span>ax<span style="color: #666666">.</span>get_yticklabels(), fontsize<span style="color: #666666">=18</span>)
|
|
plt<span style="color: #666666">.</span>show()
|
|
</pre></div>
|
|
<p>
|
|
The results perfectly with our previous discussion where we used our own code.
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="ridge-regression">Ridge regression </h2>
|
|
|
|
<p>
|
|
Having explored the ordinary least squares we move on to ridge
|
|
regression. In ridge regression we include a <b>regularizer</b>. This
|
|
involves a new cost function which leads to a new estimate for the
|
|
weights \( \boldsymbol{\beta} \). This results in a penalized regression problem. The
|
|
cost function is given by
|
|
|
|
$$
|
|
\begin{align}
|
|
C(\boldsymbol{X}, \boldsymbol{\beta}; \lambda) = (\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y})^T(\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y}) + \lambda \boldsymbol{\beta}^T\boldsymbol{\beta}.
|
|
\label{_auto11}
|
|
\end{align}
|
|
$$
|
|
|
|
<p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span>_lambda <span style="color: #666666">=</span> <span style="color: #666666">0.1</span>
|
|
clf_ridge <span style="color: #666666">=</span> skl<span style="color: #666666">.</span>Ridge(alpha<span style="color: #666666">=</span>_lambda)<span style="color: #666666">.</span>fit(X_train, y_train)
|
|
J_ridge_sk <span style="color: #666666">=</span> clf_ridge<span style="color: #666666">.</span>coef_<span style="color: #666666">.</span>reshape(L, L)
|
|
fig <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">20</span>, <span style="color: #666666">14</span>))
|
|
im <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>imshow(J_ridge_sk, <span style="color: #666666">**</span>cmap_args)
|
|
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">"Ridge from Scikit-learn"</span>, fontsize<span style="color: #666666">=18</span>)
|
|
plt<span style="color: #666666">.</span>xticks(fontsize<span style="color: #666666">=18</span>)
|
|
plt<span style="color: #666666">.</span>yticks(fontsize<span style="color: #666666">=18</span>)
|
|
cb <span style="color: #666666">=</span> fig<span style="color: #666666">.</span>colorbar(im)
|
|
cb<span style="color: #666666">.</span>ax<span style="color: #666666">.</span>set_yticklabels(cb<span style="color: #666666">.</span>ax<span style="color: #666666">.</span>get_yticklabels(), fontsize<span style="color: #666666">=18</span>)
|
|
|
|
plt<span style="color: #666666">.</span>show()
|
|
</pre></div>
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="lasso-regression">LASSO regression </h2>
|
|
|
|
<p>
|
|
In the <b>Least Absolute Shrinkage and Selection Operator</b> (LASSO)-method we get a third cost function.
|
|
|
|
$$
|
|
\begin{align}
|
|
C(\boldsymbol{X}, \boldsymbol{\beta}; \lambda) = (\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y})^T(\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y}) + \lambda \sqrt{\boldsymbol{\beta}^T\boldsymbol{\beta}}.
|
|
\label{_auto12}
|
|
\end{align}
|
|
$$
|
|
|
|
<p>
|
|
Finding the extremal point of this cost function is not so straight-forward as in least squares and ridge. We will therefore rely solely on the function ``Lasso`` from <b>Scikit-Learn</b>.
|
|
|
|
<p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span>clf_lasso <span style="color: #666666">=</span> skl<span style="color: #666666">.</span>Lasso(alpha<span style="color: #666666">=</span>_lambda)<span style="color: #666666">.</span>fit(X_train, y_train)
|
|
J_lasso_sk <span style="color: #666666">=</span> clf_lasso<span style="color: #666666">.</span>coef_<span style="color: #666666">.</span>reshape(L, L)
|
|
fig <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">20</span>, <span style="color: #666666">14</span>))
|
|
im <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>imshow(J_lasso_sk, <span style="color: #666666">**</span>cmap_args)
|
|
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">"Lasso from Scikit-learn"</span>, fontsize<span style="color: #666666">=18</span>)
|
|
plt<span style="color: #666666">.</span>xticks(fontsize<span style="color: #666666">=18</span>)
|
|
plt<span style="color: #666666">.</span>yticks(fontsize<span style="color: #666666">=18</span>)
|
|
cb <span style="color: #666666">=</span> fig<span style="color: #666666">.</span>colorbar(im)
|
|
cb<span style="color: #666666">.</span>ax<span style="color: #666666">.</span>set_yticklabels(cb<span style="color: #666666">.</span>ax<span style="color: #666666">.</span>get_yticklabels(), fontsize<span style="color: #666666">=18</span>)
|
|
|
|
plt<span style="color: #666666">.</span>show()
|
|
</pre></div>
|
|
<p>
|
|
It is quite striking how LASSO breaks the symmetry of the coupling
|
|
constant as opposed to ridge and OLS. We get a sparse solution with
|
|
\( J_{j, j + 1} = -1 \).
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="performance-as-function-of-the-regularization-parameter">Performance as function of the regularization parameter </h2>
|
|
|
|
<p>
|
|
We see how the different models perform for a different set of values for \( \lambda \).
|
|
|
|
<p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span>lambdas <span style="color: #666666">=</span> np<span style="color: #666666">.</span>logspace(<span style="color: #666666">-4</span>, <span style="color: #666666">5</span>, <span style="color: #666666">10</span>)
|
|
|
|
train_errors <span style="color: #666666">=</span> {
|
|
<span style="color: #BA2121">"ols_sk"</span>: np<span style="color: #666666">.</span>zeros(lambdas<span style="color: #666666">.</span>size),
|
|
<span style="color: #BA2121">"ridge_sk"</span>: np<span style="color: #666666">.</span>zeros(lambdas<span style="color: #666666">.</span>size),
|
|
<span style="color: #BA2121">"lasso_sk"</span>: np<span style="color: #666666">.</span>zeros(lambdas<span style="color: #666666">.</span>size)
|
|
}
|
|
|
|
test_errors <span style="color: #666666">=</span> {
|
|
<span style="color: #BA2121">"ols_sk"</span>: np<span style="color: #666666">.</span>zeros(lambdas<span style="color: #666666">.</span>size),
|
|
<span style="color: #BA2121">"ridge_sk"</span>: np<span style="color: #666666">.</span>zeros(lambdas<span style="color: #666666">.</span>size),
|
|
<span style="color: #BA2121">"lasso_sk"</span>: np<span style="color: #666666">.</span>zeros(lambdas<span style="color: #666666">.</span>size)
|
|
}
|
|
|
|
plot_counter <span style="color: #666666">=</span> <span style="color: #666666">1</span>
|
|
|
|
fig <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">32</span>, <span style="color: #666666">54</span>))
|
|
|
|
<span style="color: #008000; font-weight: bold">for</span> i, _lambda <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">enumerate</span>(tqdm<span style="color: #666666">.</span>tqdm(lambdas)):
|
|
<span style="color: #008000; font-weight: bold">for</span> key, method <span style="color: #AA22FF; font-weight: bold">in</span> <span style="color: #008000">zip</span>(
|
|
[<span style="color: #BA2121">"ols_sk"</span>, <span style="color: #BA2121">"ridge_sk"</span>, <span style="color: #BA2121">"lasso_sk"</span>],
|
|
[skl<span style="color: #666666">.</span>LinearRegression(), skl<span style="color: #666666">.</span>Ridge(alpha<span style="color: #666666">=</span>_lambda), skl<span style="color: #666666">.</span>Lasso(alpha<span style="color: #666666">=</span>_lambda)]
|
|
):
|
|
method <span style="color: #666666">=</span> method<span style="color: #666666">.</span>fit(X_train, y_train)
|
|
|
|
train_errors[key][i] <span style="color: #666666">=</span> method<span style="color: #666666">.</span>score(X_train, y_train)
|
|
test_errors[key][i] <span style="color: #666666">=</span> method<span style="color: #666666">.</span>score(X_test, y_test)
|
|
|
|
omega <span style="color: #666666">=</span> method<span style="color: #666666">.</span>coef_<span style="color: #666666">.</span>reshape(L, L)
|
|
|
|
plt<span style="color: #666666">.</span>subplot(<span style="color: #666666">10</span>, <span style="color: #666666">5</span>, plot_counter)
|
|
plt<span style="color: #666666">.</span>imshow(omega, <span style="color: #666666">**</span>cmap_args)
|
|
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">r"</span><span style="color: #BB6688; font-weight: bold">%s</span><span style="color: #BA2121">, $\lambda = </span><span style="color: #BB6688; font-weight: bold">%.4f</span><span style="color: #BA2121">$"</span> <span style="color: #666666">%</span> (key, _lambda))
|
|
plot_counter <span style="color: #666666">+=</span> <span style="color: #666666">1</span>
|
|
|
|
plt<span style="color: #666666">.</span>show()
|
|
</pre></div>
|
|
<p>
|
|
We see that LASSO reaches a good solution for low
|
|
values of \( \lambda \), but will "wither" when we increase \( \lambda \) too
|
|
much. Ridge is more stable over a larger range of values for
|
|
\( \lambda \), but eventually also fades away.
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="finding-the-optimal-value-of-lambda">Finding the optimal value of \( \lambda \) </h2>
|
|
|
|
<p>
|
|
To determine which value of \( \lambda \) is best we plot the accuracy of
|
|
the models when predicting the training and the testing set. We expect
|
|
the accuracy of the training set to be quite good, but if the accuracy
|
|
of the testing set is much lower this tells us that we might be
|
|
subject to an overfit model. The ideal scenario is an accuracy on the
|
|
testing set that is close to the accuracy of the training set.
|
|
|
|
<p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span>fig <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">20</span>, <span style="color: #666666">14</span>))
|
|
|
|
colors <span style="color: #666666">=</span> {
|
|
<span style="color: #BA2121">"ols_sk"</span>: <span style="color: #BA2121">"r"</span>,
|
|
<span style="color: #BA2121">"ridge_sk"</span>: <span style="color: #BA2121">"y"</span>,
|
|
<span style="color: #BA2121">"lasso_sk"</span>: <span style="color: #BA2121">"c"</span>
|
|
}
|
|
|
|
<span style="color: #008000; font-weight: bold">for</span> key <span style="color: #AA22FF; font-weight: bold">in</span> train_errors:
|
|
plt<span style="color: #666666">.</span>semilogx(
|
|
lambdas,
|
|
train_errors[key],
|
|
colors[key],
|
|
label<span style="color: #666666">=</span><span style="color: #BA2121">"Train </span><span style="color: #BB6688; font-weight: bold">{0}</span><span style="color: #BA2121">"</span><span style="color: #666666">.</span>format(key),
|
|
linewidth<span style="color: #666666">=4.0</span>
|
|
)
|
|
|
|
<span style="color: #008000; font-weight: bold">for</span> key <span style="color: #AA22FF; font-weight: bold">in</span> test_errors:
|
|
plt<span style="color: #666666">.</span>semilogx(
|
|
lambdas,
|
|
test_errors[key],
|
|
colors[key] <span style="color: #666666">+</span> <span style="color: #BA2121">"--"</span>,
|
|
label<span style="color: #666666">=</span><span style="color: #BA2121">"Test </span><span style="color: #BB6688; font-weight: bold">{0}</span><span style="color: #BA2121">"</span><span style="color: #666666">.</span>format(key),
|
|
linewidth<span style="color: #666666">=4.0</span>
|
|
)
|
|
plt<span style="color: #666666">.</span>legend(loc<span style="color: #666666">=</span><span style="color: #BA2121">"best"</span>, fontsize<span style="color: #666666">=18</span>)
|
|
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">r"$\lambda$"</span>, fontsize<span style="color: #666666">=18</span>)
|
|
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">r"$R^2$"</span>, fontsize<span style="color: #666666">=18</span>)
|
|
plt<span style="color: #666666">.</span>tick_params(labelsize<span style="color: #666666">=18</span>)
|
|
plt<span style="color: #666666">.</span>show()
|
|
</pre></div>
|
|
<p>
|
|
From the above figure we can see that LASSO with \( \lambda = 10^{-2} \)
|
|
achieves a very good accuracy on the test set. This by far surpasses the
|
|
other models for all values of \( \lambda \).
|
|
|
|
<p>
|
|
<!-- !split -->
|
|
|
|
<h2 id="logistic-regression">Logistic Regression </h2>
|
|
|
|
<p>
|
|
In linear regression our main interest was centered on learning the
|
|
coefficients of a functional fit (say a polynomial) in order to be
|
|
able to predict the response of a continuous variable on some unseen
|
|
data. The fit to the continuous variable \( y_i \) is based on some
|
|
independent variables \( \boldsymbol{x}_i \). Linear regression resulted in
|
|
analytical expressions for standard ordinary Least Squares or Ridge
|
|
regression (in terms of matrices to invert) for several quantities,
|
|
ranging from the variance and thereby the confidence intervals of the
|
|
parameters \( \boldsymbol{\beta} \) to the mean squared error. If we can invert
|
|
the product of the design matrices, linear regression gives then a
|
|
simple recipe for fitting our data.
|
|
|
|
<p>
|
|
<!-- !split -->
|
|
|
|
<h2 id="classification-problems">Classification problems </h2>
|
|
|
|
<p>
|
|
Classification problems, however, are concerned with outcomes taking
|
|
the form of discrete variables (i.e. categories). We may for example,
|
|
on the basis of DNA sequencing for a number of patients, like to find
|
|
out which mutations are important for a certain disease; or based on
|
|
scans of various patients' brains, figure out if there is a tumor or
|
|
not; or given a specific physical system, we'd like to identify its
|
|
state, say whether it is an ordered or disordered system (typical
|
|
situation in solid state physics); or classify the status of a
|
|
patient, whether she/he has a stroke or not and many other similar
|
|
situations.
|
|
|
|
<p>
|
|
The most common situation we encounter when we apply logistic
|
|
regression is that of two possible outcomes, normally denoted as a
|
|
binary outcome, true or false, positive or negative, success or
|
|
failure etc.
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="optimization-and-deep-learning">Optimization and Deep learning </h2>
|
|
|
|
<p>
|
|
Logistic regression will also serve as our stepping stone towards
|
|
neural network algorithms and supervised deep learning. For logistic
|
|
learning, the minimization of the cost function leads to a non-linear
|
|
equation in the parameters \( \boldsymbol{\beta} \). The optimization of the
|
|
problem calls therefore for minimization algorithms. This forms the
|
|
bottle neck of all machine learning algorithms, namely how to find
|
|
reliable minima of a multi-variable function. This leads us to the
|
|
family of gradient descent methods. The latter are the working horses
|
|
of basically all modern machine learning algorithms.
|
|
|
|
<p>
|
|
We note also that many of the topics discussed here on logistic
|
|
regression are also commonly used in modern supervised Deep Learning
|
|
models, as we will see later.
|
|
|
|
<p>
|
|
<!-- !split -->
|
|
|
|
<h2 id="basics">Basics </h2>
|
|
|
|
<p>
|
|
We consider the case where the dependent variables, also called the
|
|
responses or the outcomes, \( y_i \) are discrete and only take values
|
|
from \( k=0,\dots,K-1 \) (i.e. \( K \) classes).
|
|
|
|
<p>
|
|
The goal is to predict the
|
|
output classes from the design matrix \( \boldsymbol{X}\in\mathbb{R}^{n\times p} \)
|
|
made of \( n \) samples, each of which carries \( p \) features or predictors. The
|
|
primary goal is to identify the classes to which new unseen samples
|
|
belong.
|
|
|
|
<p>
|
|
Let us specialize to the case of two classes only, with outputs
|
|
\( y_i=0 \) and \( y_i=1 \). Our outcomes could represent the status of a
|
|
credit card user that could default or not on her/his credit card
|
|
debt. That is
|
|
|
|
$$
|
|
y_i = \begin{bmatrix} 0 & \mathrm{no}\\ 1 & \mathrm{yes} \end{bmatrix}.
|
|
$$
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="linear-classifier">Linear classifier </h2>
|
|
|
|
<p>
|
|
Before moving to the logistic model, let us try to use our linear
|
|
regression model to classify these two outcomes. We could for example
|
|
fit a linear model to the default case if \( y_i > 0.5 \) and the no
|
|
default case \( y_i \leq 0.5 \).
|
|
|
|
<p>
|
|
We would then have our
|
|
weighted linear combination, namely
|
|
$$
|
|
\begin{equation}
|
|
\boldsymbol{y} = \boldsymbol{X}^T\boldsymbol{\beta} + \boldsymbol{\epsilon},
|
|
\label{_auto13}
|
|
\end{equation}
|
|
$$
|
|
|
|
where \( \boldsymbol{y} \) is a vector representing the possible outcomes, \( \boldsymbol{X} \) is our
|
|
\( n\times p \) design matrix and \( \boldsymbol{\beta} \) represents our estimators/predictors.
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="some-selected-properties">Some selected properties </h2>
|
|
|
|
<p>
|
|
The main problem with our function is that it takes values on the
|
|
entire real axis. In the case of logistic regression, however, the
|
|
labels \( y_i \) are discrete variables. A typical example is the credit
|
|
card data discussed below here, where we can set the state of
|
|
defaulting the debt to \( y_i=1 \) and not to \( y_i=0 \) for one the persons
|
|
in the data set (see the full example below).
|
|
|
|
<p>
|
|
One simple way to get a discrete output is to have sign
|
|
functions that map the output of a linear regressor to values \( \{0,1\} \),
|
|
\( f(s_i)=sign(s_i)=1 \) if \( s_i\ge 0 \) and 0 if otherwise.
|
|
We will encounter this model in our first demonstration of neural networks. Historically it is called the ``perceptron" model in the machine learning
|
|
literature. This model is extremely simple. However, in many cases it is more
|
|
favorable to use a ``soft" classifier that outputs
|
|
the probability of a given category. This leads us to the logistic function.
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="simple-example">Simple example </h2>
|
|
|
|
<p>
|
|
The following example on data for coronary heart disease (CHD) as function of age may serve as an illustration. In the code here we read and plot whether a person has had CHD (output = 1) or not (output = 0). This ouput is plotted the person's against age. Clearly, the figure shows that attempting to make a standard linear regression fit may not be very meaningful.
|
|
|
|
<p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span><span style="color: #408080; font-style: italic"># Common imports</span>
|
|
<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.linear_model</span> <span style="color: #008000; font-weight: bold">import</span> LinearRegression, Ridge, Lasso
|
|
<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.utils</span> <span style="color: #008000; font-weight: bold">import</span> resample
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.metrics</span> <span style="color: #008000; font-weight: bold">import</span> mean_squared_error
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">IPython.display</span> <span style="color: #008000; font-weight: bold">import</span> display
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">pylab</span> <span style="color: #008000; font-weight: bold">import</span> plt, mpl
|
|
plt<span style="color: #666666">.</span>style<span style="color: #666666">.</span>use(<span style="color: #BA2121">'seaborn'</span>)
|
|
mpl<span style="color: #666666">.</span>rcParams[<span style="color: #BA2121">'font.family'</span>] <span style="color: #666666">=</span> <span style="color: #BA2121">'serif'</span>
|
|
|
|
<span style="color: #408080; font-style: italic"># Where to save the figures and data files</span>
|
|
PROJECT_ROOT_DIR <span style="color: #666666">=</span> <span style="color: #BA2121">"Results"</span>
|
|
FIGURE_ID <span style="color: #666666">=</span> <span style="color: #BA2121">"Results/FigureFiles"</span>
|
|
DATA_ID <span style="color: #666666">=</span> <span style="color: #BA2121">"DataFiles/"</span>
|
|
|
|
<span style="color: #008000; font-weight: bold">if</span> <span style="color: #AA22FF; font-weight: bold">not</span> os<span style="color: #666666">.</span>path<span style="color: #666666">.</span>exists(PROJECT_ROOT_DIR):
|
|
os<span style="color: #666666">.</span>mkdir(PROJECT_ROOT_DIR)
|
|
|
|
<span style="color: #008000; font-weight: bold">if</span> <span style="color: #AA22FF; font-weight: bold">not</span> os<span style="color: #666666">.</span>path<span style="color: #666666">.</span>exists(FIGURE_ID):
|
|
os<span style="color: #666666">.</span>makedirs(FIGURE_ID)
|
|
|
|
<span style="color: #008000; font-weight: bold">if</span> <span style="color: #AA22FF; font-weight: bold">not</span> os<span style="color: #666666">.</span>path<span style="color: #666666">.</span>exists(DATA_ID):
|
|
os<span style="color: #666666">.</span>makedirs(DATA_ID)
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">image_path</span>(fig_id):
|
|
<span style="color: #008000; font-weight: bold">return</span> os<span style="color: #666666">.</span>path<span style="color: #666666">.</span>join(FIGURE_ID, fig_id)
|
|
|
|
<span style="color: #008000; font-weight: bold">def</span> <span style="color: #0000FF">data_path</span>(dat_id):
|
|
<span style="color: #008000; font-weight: bold">return</span> os<span style="color: #666666">.</span>path<span style="color: #666666">.</span>join(DATA_ID, dat_id)
|
|
|
|
<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">".png"</span>, <span style="color: #008000">format</span><span style="color: #666666">=</span><span style="color: #BA2121">'png'</span>)
|
|
|
|
infile <span style="color: #666666">=</span> <span style="color: #008000">open</span>(data_path(<span style="color: #BA2121">"chddata.csv"</span>),<span style="color: #BA2121">'r'</span>)
|
|
|
|
<span style="color: #408080; font-style: italic"># Read the chd data as csv file and organize the data into arrays with age group, age, and chd</span>
|
|
chd <span style="color: #666666">=</span> pd<span style="color: #666666">.</span>read_csv(infile, names<span style="color: #666666">=</span>(<span style="color: #BA2121">'ID'</span>, <span style="color: #BA2121">'Age'</span>, <span style="color: #BA2121">'Agegroup'</span>, <span style="color: #BA2121">'CHD'</span>))
|
|
chd<span style="color: #666666">.</span>columns <span style="color: #666666">=</span> [<span style="color: #BA2121">'ID'</span>, <span style="color: #BA2121">'Age'</span>, <span style="color: #BA2121">'Agegroup'</span>, <span style="color: #BA2121">'CHD'</span>]
|
|
output <span style="color: #666666">=</span> chd[<span style="color: #BA2121">'CHD'</span>]
|
|
age <span style="color: #666666">=</span> chd[<span style="color: #BA2121">'Age'</span>]
|
|
agegroup <span style="color: #666666">=</span> chd[<span style="color: #BA2121">'Agegroup'</span>]
|
|
numberID <span style="color: #666666">=</span> chd[<span style="color: #BA2121">'ID'</span>]
|
|
display(chd)
|
|
|
|
plt<span style="color: #666666">.</span>scatter(age, output, marker<span style="color: #666666">=</span><span style="color: #BA2121">'o'</span>)
|
|
plt<span style="color: #666666">.</span>axis([<span style="color: #666666">18</span>,<span style="color: #666666">70.0</span>,<span style="color: #666666">-0.1</span>, <span style="color: #666666">1.2</span>])
|
|
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">r'Age'</span>)
|
|
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">r'CHD'</span>)
|
|
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">r'Age distribution and Coronary heart disease'</span>)
|
|
plt<span style="color: #666666">.</span>show()
|
|
</pre></div>
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="plotting-the-mean-value-for-each-group">Plotting the mean value for each group </h2>
|
|
|
|
<p>
|
|
What we could attempt however is to plot the mean value for each group.
|
|
|
|
<p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span>agegroupmean <span style="color: #666666">=</span> np<span style="color: #666666">.</span>array([<span style="color: #666666">0.1</span>, <span style="color: #666666">0.133</span>, <span style="color: #666666">0.250</span>, <span style="color: #666666">0.333</span>, <span style="color: #666666">0.462</span>, <span style="color: #666666">0.625</span>, <span style="color: #666666">0.765</span>, <span style="color: #666666">0.800</span>])
|
|
group <span style="color: #666666">=</span> np<span style="color: #666666">.</span>array([<span style="color: #666666">1</span>, <span style="color: #666666">2</span>, <span style="color: #666666">3</span>, <span style="color: #666666">4</span>, <span style="color: #666666">5</span>, <span style="color: #666666">6</span>, <span style="color: #666666">7</span>, <span style="color: #666666">8</span>])
|
|
plt<span style="color: #666666">.</span>plot(group, agegroupmean, <span style="color: #BA2121">"r-"</span>)
|
|
plt<span style="color: #666666">.</span>axis([<span style="color: #666666">0</span>,<span style="color: #666666">9</span>,<span style="color: #666666">0</span>, <span style="color: #666666">1.0</span>])
|
|
plt<span style="color: #666666">.</span>xlabel(<span style="color: #BA2121">r'Age group'</span>)
|
|
plt<span style="color: #666666">.</span>ylabel(<span style="color: #BA2121">r'CHD mean values'</span>)
|
|
plt<span style="color: #666666">.</span>title(<span style="color: #BA2121">r'Mean values for each age group'</span>)
|
|
plt<span style="color: #666666">.</span>show()
|
|
</pre></div>
|
|
<p>
|
|
We are now trying to find a function \( f(y\vert x) \), that is a function which gives us an expected value for the output \( y \) with a given input \( x \).
|
|
In standard linear regression with a linear dependence on \( x \), we would write this in terms of our model
|
|
$$
|
|
f(y_i\vert x_i)=\beta_0+\beta_1 x_i.
|
|
$$
|
|
|
|
<p>
|
|
This expression implies however that \( f(y_i\vert x_i) \) could take any
|
|
value from minus infinity to plus infinity. If we however let
|
|
\( f(y\vert y) \) be represented by the mean value, the above example
|
|
shows us that we can constrain the function to take values between
|
|
zero and one, that is we have \( 0 \le f(y_i\vert x_i) \le 1 \). Looking
|
|
at our last curve we see also that it has an S-shaped form. This leads
|
|
us to a very popular model for the function \( f \), namely the so-called
|
|
Sigmoid function or logistic model. We will consider this function as
|
|
representing the probability for finding a value of \( y_i \) with a given
|
|
\( x_i \).
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="the-logistic-function">The logistic function </h2>
|
|
|
|
<p>
|
|
Another widely studied model, is the so-called
|
|
perceptron model, which is an example of a "hard classification" model. We
|
|
will encounter this model when we discuss neural networks as
|
|
well. Each datapoint is deterministically assigned to a category (i.e
|
|
\( y_i=0 \) or \( y_i=1 \)). In many cases, and the coronary heart disease data forms one of many such examples, it is favorable to have a "soft"
|
|
classifier that outputs the probability of a given category rather
|
|
than a single value. For example, given \( x_i \), the classifier
|
|
outputs the probability of being in a category \( k \). Logistic regression
|
|
is the most common example of a so-called soft classifier. In logistic
|
|
regression, the probability that a data point \( x_i \)
|
|
belongs to a category \( y_i=\{0,1\} \) is given by the so-called logit function (or Sigmoid) which is meant to represent the likelihood for a given event,
|
|
$$
|
|
p(t) = \frac{1}{1+\mathrm \exp{-t}}=\frac{\exp{t}}{1+\mathrm \exp{t}}.
|
|
$$
|
|
|
|
Note that \( 1-p(t)= p(-t) \).
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="examples-of-likelihood-functions-used-in-logistic-regression-and-nueral-networks">Examples of likelihood functions used in logistic regression and nueral networks </h2>
|
|
|
|
<p>
|
|
The following code plots the logistic function, the step function and other functions we will encounter from here and on.
|
|
|
|
<p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span><span style="color: #BA2121; font-style: italic">"""The sigmoid function (or the logistic curve) is a</span>
|
|
<span style="color: #BA2121; font-style: italic">function that takes any real number, z, and outputs a number (0,1).</span>
|
|
<span style="color: #BA2121; font-style: italic">It is useful in neural networks for assigning weights on a relative scale.</span>
|
|
<span style="color: #BA2121; font-style: italic">The value z is the weighted sum of parameters involved in the learning algorithm."""</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">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">import</span> <span style="color: #0000FF; font-weight: bold">math</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">mt</span>
|
|
|
|
z <span style="color: #666666">=</span> numpy<span style="color: #666666">.</span>arange(<span style="color: #666666">-5</span>, <span style="color: #666666">5</span>, <span style="color: #666666">.1</span>)
|
|
sigma_fn <span style="color: #666666">=</span> numpy<span style="color: #666666">.</span>vectorize(<span style="color: #008000; font-weight: bold">lambda</span> z: <span style="color: #666666">1/</span>(<span style="color: #666666">1+</span>numpy<span style="color: #666666">.</span>exp(<span style="color: #666666">-</span>z)))
|
|
sigma <span style="color: #666666">=</span> sigma_fn(z)
|
|
|
|
fig <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>figure()
|
|
ax <span style="color: #666666">=</span> fig<span style="color: #666666">.</span>add_subplot(<span style="color: #666666">111</span>)
|
|
ax<span style="color: #666666">.</span>plot(z, sigma)
|
|
ax<span style="color: #666666">.</span>set_ylim([<span style="color: #666666">-0.1</span>, <span style="color: #666666">1.1</span>])
|
|
ax<span style="color: #666666">.</span>set_xlim([<span style="color: #666666">-5</span>,<span style="color: #666666">5</span>])
|
|
ax<span style="color: #666666">.</span>grid(<span style="color: #008000; font-weight: bold">True</span>)
|
|
ax<span style="color: #666666">.</span>set_xlabel(<span style="color: #BA2121">'z'</span>)
|
|
ax<span style="color: #666666">.</span>set_title(<span style="color: #BA2121">'sigmoid function'</span>)
|
|
|
|
plt<span style="color: #666666">.</span>show()
|
|
|
|
<span style="color: #BA2121; font-style: italic">"""Step Function"""</span>
|
|
z <span style="color: #666666">=</span> numpy<span style="color: #666666">.</span>arange(<span style="color: #666666">-5</span>, <span style="color: #666666">5</span>, <span style="color: #666666">.02</span>)
|
|
step_fn <span style="color: #666666">=</span> numpy<span style="color: #666666">.</span>vectorize(<span style="color: #008000; font-weight: bold">lambda</span> z: <span style="color: #666666">1.0</span> <span style="color: #008000; font-weight: bold">if</span> z <span style="color: #666666">>=</span> <span style="color: #666666">0.0</span> <span style="color: #008000; font-weight: bold">else</span> <span style="color: #666666">0.0</span>)
|
|
step <span style="color: #666666">=</span> step_fn(z)
|
|
|
|
fig <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>figure()
|
|
ax <span style="color: #666666">=</span> fig<span style="color: #666666">.</span>add_subplot(<span style="color: #666666">111</span>)
|
|
ax<span style="color: #666666">.</span>plot(z, step)
|
|
ax<span style="color: #666666">.</span>set_ylim([<span style="color: #666666">-0.5</span>, <span style="color: #666666">1.5</span>])
|
|
ax<span style="color: #666666">.</span>set_xlim([<span style="color: #666666">-5</span>,<span style="color: #666666">5</span>])
|
|
ax<span style="color: #666666">.</span>grid(<span style="color: #008000; font-weight: bold">True</span>)
|
|
ax<span style="color: #666666">.</span>set_xlabel(<span style="color: #BA2121">'z'</span>)
|
|
ax<span style="color: #666666">.</span>set_title(<span style="color: #BA2121">'step function'</span>)
|
|
|
|
plt<span style="color: #666666">.</span>show()
|
|
|
|
<span style="color: #BA2121; font-style: italic">"""tanh Function"""</span>
|
|
z <span style="color: #666666">=</span> numpy<span style="color: #666666">.</span>arange(<span style="color: #666666">-2*</span>mt<span style="color: #666666">.</span>pi, <span style="color: #666666">2*</span>mt<span style="color: #666666">.</span>pi, <span style="color: #666666">0.1</span>)
|
|
t <span style="color: #666666">=</span> numpy<span style="color: #666666">.</span>tanh(z)
|
|
|
|
fig <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>figure()
|
|
ax <span style="color: #666666">=</span> fig<span style="color: #666666">.</span>add_subplot(<span style="color: #666666">111</span>)
|
|
ax<span style="color: #666666">.</span>plot(z, t)
|
|
ax<span style="color: #666666">.</span>set_ylim([<span style="color: #666666">-1.0</span>, <span style="color: #666666">1.0</span>])
|
|
ax<span style="color: #666666">.</span>set_xlim([<span style="color: #666666">-2*</span>mt<span style="color: #666666">.</span>pi,<span style="color: #666666">2*</span>mt<span style="color: #666666">.</span>pi])
|
|
ax<span style="color: #666666">.</span>grid(<span style="color: #008000; font-weight: bold">True</span>)
|
|
ax<span style="color: #666666">.</span>set_xlabel(<span style="color: #BA2121">'z'</span>)
|
|
ax<span style="color: #666666">.</span>set_title(<span style="color: #BA2121">'tanh function'</span>)
|
|
|
|
plt<span style="color: #666666">.</span>show()
|
|
</pre></div>
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="two-parameters">Two parameters </h2>
|
|
|
|
<p>
|
|
We assume now that we have two classes with \( y_i \) either \( 0 \) or \( 1 \). Furthermore we assume also that we have only two parameters \( \beta \) in our fitting of the Sigmoid function, that is we define probabilities
|
|
$$
|
|
\begin{align*}
|
|
p(y_i=1|x_i,\boldsymbol{\beta}) &= \frac{\exp{(\beta_0+\beta_1x_i)}}{1+\exp{(\beta_0+\beta_1x_i)}},\nonumber\\
|
|
p(y_i=0|x_i,\boldsymbol{\beta}) &= 1 - p(y_i=1|x_i,\boldsymbol{\beta}),
|
|
\end{align*}
|
|
$$
|
|
|
|
where \( \boldsymbol{\beta} \) are the weights we wish to extract from data, in our case \( \beta_0 \) and \( \beta_1 \).
|
|
|
|
<p>
|
|
Note that we used
|
|
$$
|
|
p(y_i=0\vert x_i, \boldsymbol{\beta}) = 1-p(y_i=1\vert x_i, \boldsymbol{\beta}).
|
|
$$
|
|
|
|
<p>
|
|
<!-- !split -->
|
|
|
|
<h2 id="maximum-likelihood">Maximum likelihood </h2>
|
|
|
|
<p>
|
|
In order to define the total likelihood for all possible outcomes from a
|
|
dataset \( \mathcal{D}=\{(y_i,x_i)\} \), with the binary labels
|
|
\( y_i\in\{0,1\} \) and where the data points are drawn independently, we use the so-called <a href="https://en.wikipedia.org/wiki/Maximum_likelihood_estimation" target="_blank">Maximum Likelihood Estimation</a> (MLE) principle.
|
|
We aim thus at maximizing
|
|
the probability of seeing the observed data. We can then approximate the
|
|
likelihood in terms of the product of the individual probabilities of a specific outcome \( y_i \), that is
|
|
$$
|
|
\begin{align*}
|
|
P(\mathcal{D}|\boldsymbol{\beta})& = \prod_{i=1}^n \left[p(y_i=1|x_i,\boldsymbol{\beta})\right]^{y_i}\left[1-p(y_i=1|x_i,\boldsymbol{\beta}))\right]^{1-y_i}\nonumber \\
|
|
\end{align*}
|
|
$$
|
|
|
|
from which we obtain the log-likelihood and our <b>cost/loss</b> function
|
|
$$
|
|
\mathcal{C}(\boldsymbol{\beta}) = \sum_{i=1}^n \left( y_i\log{p(y_i=1|x_i,\boldsymbol{\beta})} + (1-y_i)\log\left[1-p(y_i=1|x_i,\boldsymbol{\beta}))\right]\right).
|
|
$$
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="the-cost-function-rewritten">The cost function rewritten </h2>
|
|
|
|
<p>
|
|
Reordering the logarithms, we can rewrite the <b>cost/loss</b> function as
|
|
$$
|
|
\mathcal{C}(\boldsymbol{\beta}) = \sum_{i=1}^n \left(y_i(\beta_0+\beta_1x_i) -\log{(1+\exp{(\beta_0+\beta_1x_i)})}\right).
|
|
$$
|
|
|
|
<p>
|
|
The maximum likelihood estimator is defined as the set of parameters that maximize the log-likelihood where we maximize with respect to \( \beta \).
|
|
Since the cost (error) function is just the negative log-likelihood, for logistic regression we have that
|
|
$$
|
|
\mathcal{C}(\boldsymbol{\beta})=-\sum_{i=1}^n \left(y_i(\beta_0+\beta_1x_i) -\log{(1+\exp{(\beta_0+\beta_1x_i)})}\right).
|
|
$$
|
|
|
|
This equation is known in statistics as the <b>cross entropy</b>. Finally, we note that just as in linear regression,
|
|
in practice we often supplement the cross-entropy with additional regularization terms, usually \( L_1 \) and \( L_2 \) regularization as we did for Ridge and Lasso regression.
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="minimizing-the-cross-entropy">Minimizing the cross entropy </h2>
|
|
|
|
<p>
|
|
The cross entropy is a convex function of the weights \( \boldsymbol{\beta} \) and,
|
|
therefore, any local minimizer is a global minimizer.
|
|
|
|
<p>
|
|
Minimizing this
|
|
cost function with respect to the two parameters \( \beta_0 \) and \( \beta_1 \) we obtain
|
|
|
|
$$
|
|
\frac{\partial \mathcal{C}(\boldsymbol{\beta})}{\partial \beta_0} = -\sum_{i=1}^n \left(y_i -\frac{\exp{(\beta_0+\beta_1x_i)}}{1+\exp{(\beta_0+\beta_1x_i)}}\right),
|
|
$$
|
|
|
|
and
|
|
$$
|
|
\frac{\partial \mathcal{C}(\boldsymbol{\beta})}{\partial \beta_1} = -\sum_{i=1}^n \left(y_ix_i -x_i\frac{\exp{(\beta_0+\beta_1x_i)}}{1+\exp{(\beta_0+\beta_1x_i)}}\right).
|
|
$$
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="a-more-compact-expression">A more compact expression </h2>
|
|
|
|
<p>
|
|
Let us now define a vector \( \boldsymbol{y} \) with \( n \) elements \( y_i \), an
|
|
\( n\times p \) matrix \( \boldsymbol{X} \) which contains the \( x_i \) values and a
|
|
vector \( \boldsymbol{p} \) of fitted probabilities \( p(y_i\vert x_i,\boldsymbol{\beta}) \). We can rewrite in a more compact form the first
|
|
derivative of cost function as
|
|
|
|
$$
|
|
\frac{\partial \mathcal{C}(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}} = -\boldsymbol{X}^T\left(\boldsymbol{y}-\boldsymbol{p}\right).
|
|
$$
|
|
|
|
<p>
|
|
If we in addition define a diagonal matrix \( \boldsymbol{W} \) with elements
|
|
\( p(y_i\vert x_i,\boldsymbol{\beta})(1-p(y_i\vert x_i,\boldsymbol{\beta}) \), we can obtain a compact expression of the second derivative as
|
|
|
|
$$
|
|
\frac{\partial^2 \mathcal{C}(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}\partial \boldsymbol{\beta}^T} = \boldsymbol{X}^T\boldsymbol{W}\boldsymbol{X}.
|
|
$$
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="extending-to-more-predictors">Extending to more predictors </h2>
|
|
|
|
<p>
|
|
Within a binary classification problem, we can easily expand our model to include multiple predictors. Our ratio between likelihoods is then with \( p \) predictors
|
|
$$
|
|
\log{ \frac{p(\boldsymbol{\beta}\boldsymbol{x})}{1-p(\boldsymbol{\beta}\boldsymbol{x})}} = \beta_0+\beta_1x_1+\beta_2x_2+\dots+\beta_px_p.
|
|
$$
|
|
|
|
Here we defined \( \boldsymbol{x}=[1,x_1,x_2,\dots,x_p] \) and \( \boldsymbol{\beta}=[\beta_0, \beta_1, \dots, \beta_p] \) leading to
|
|
$$
|
|
p(\boldsymbol{\beta}\boldsymbol{x})=\frac{ \exp{(\beta_0+\beta_1x_1+\beta_2x_2+\dots+\beta_px_p)}}{1+\exp{(\beta_0+\beta_1x_1+\beta_2x_2+\dots+\beta_px_p)}}.
|
|
$$
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="including-more-classes">Including more classes </h2>
|
|
|
|
<p>
|
|
Till now we have mainly focused on two classes, the so-called binary
|
|
system. Suppose we wish to extend to \( K \) classes. Let us for the sake
|
|
of simplicity assume we have only two predictors. We have then following model
|
|
|
|
$$
|
|
\log{\frac{p(C=1\vert x)}{p(K\vert x)}} = \beta_{10}+\beta_{11}x_1,
|
|
$$
|
|
|
|
and
|
|
$$
|
|
\log{\frac{p(C=2\vert x)}{p(K\vert x)}} = \beta_{20}+\beta_{21}x_1,
|
|
$$
|
|
|
|
and so on till the class \( C=K-1 \) class
|
|
$$
|
|
\log{\frac{p(C=K-1\vert x)}{p(K\vert x)}} = \beta_{(K-1)0}+\beta_{(K-1)1}x_1,
|
|
$$
|
|
|
|
<p>
|
|
and the model is specified in term of \( K-1 \) so-called log-odds or
|
|
<b>logit</b> transformations.
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="more-classes">More classes </h2>
|
|
|
|
<p>
|
|
In our discussion of neural networks we will encounter the above again
|
|
in terms of a slightly modified function, the so-called <b>Softmax</b> function.
|
|
|
|
<p>
|
|
The softmax function is used in various multiclass classification
|
|
methods, such as multinomial logistic regression (also known as
|
|
softmax regression), multiclass linear discriminant analysis, naive
|
|
Bayes classifiers, and artificial neural networks. Specifically, in
|
|
multinomial logistic regression and linear discriminant analysis, the
|
|
input to the function is the result of \( K \) distinct linear functions,
|
|
and the predicted probability for the \( k \)-th class given a sample
|
|
vector \( \boldsymbol{x} \) and a weighting vector \( \boldsymbol{\beta} \) is (with two
|
|
predictors):
|
|
|
|
$$
|
|
p(C=k\vert \mathbf {x} )=\frac{\exp{(\beta_{k0}+\beta_{k1}x_1)}}{1+\sum_{l=1}^{K-1}\exp{(\beta_{l0}+\beta_{l1}x_1)}}.
|
|
$$
|
|
|
|
It is easy to extend to more predictors. The final class is
|
|
$$
|
|
p(C=K\vert \mathbf {x} )=\frac{1}{1+\sum_{l=1}^{K-1}\exp{(\beta_{l0}+\beta_{l1}x_1)}},
|
|
$$
|
|
|
|
<p>
|
|
and they sum to one. Our earlier discussions were all specialized to
|
|
the case with two classes only. It is easy to see from the above that
|
|
what we derived earlier is compatible with these equations.
|
|
|
|
<p>
|
|
To find the optimal parameters we would typically use a gradient
|
|
descent method. Newton's method and gradient descent methods are
|
|
discussed in the material on <a href="https://compphysics.github.io/MachineLearning/doc/pub/Splines/html/Splines-bs.html" target="_blank">optimization
|
|
methods</a>.
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="friday-september-24">Friday September 24 </h2>
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="wisconsin-cancer-data">Wisconsin Cancer Data </h2>
|
|
|
|
<p>
|
|
We show here how we can use a simple regression case on the breast
|
|
cancer data using Logistic regression as our algorithm for
|
|
classification.
|
|
|
|
<p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></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">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">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.datasets</span> <span style="color: #008000; font-weight: bold">import</span> load_breast_cancer
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.linear_model</span> <span style="color: #008000; font-weight: bold">import</span> LogisticRegression
|
|
|
|
<span style="color: #408080; font-style: italic"># Load the data</span>
|
|
cancer <span style="color: #666666">=</span> load_breast_cancer()
|
|
|
|
X_train, X_test, y_train, y_test <span style="color: #666666">=</span> train_test_split(cancer<span style="color: #666666">.</span>data,cancer<span style="color: #666666">.</span>target,random_state<span style="color: #666666">=0</span>)
|
|
<span style="color: #008000">print</span>(X_train<span style="color: #666666">.</span>shape)
|
|
<span style="color: #008000">print</span>(X_test<span style="color: #666666">.</span>shape)
|
|
<span style="color: #408080; font-style: italic"># Logistic Regression</span>
|
|
logreg <span style="color: #666666">=</span> LogisticRegression(solver<span style="color: #666666">=</span><span style="color: #BA2121">'lbfgs'</span>)
|
|
logreg<span style="color: #666666">.</span>fit(X_train, y_train)
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"Test set accuracy with Logistic Regression: </span><span style="color: #BB6688; font-weight: bold">{:.2f}</span><span style="color: #BA2121">"</span><span style="color: #666666">.</span>format(logreg<span style="color: #666666">.</span>score(X_test,y_test)))
|
|
<span style="color: #408080; font-style: italic">#now scale the data</span>
|
|
<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
|
|
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)
|
|
<span style="color: #408080; font-style: italic"># Logistic Regression</span>
|
|
logreg<span style="color: #666666">.</span>fit(X_train_scaled, y_train)
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"Test set accuracy Logistic Regression with scaled data: </span><span style="color: #BB6688; font-weight: bold">{:.2f}</span><span style="color: #BA2121">"</span><span style="color: #666666">.</span>format(logreg<span style="color: #666666">.</span>score(X_test_scaled,y_test)))
|
|
</pre></div>
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="using-the-correlation-matrix">Using the correlation matrix </h2>
|
|
|
|
<p>
|
|
In addition to the above scores, we could also study the covariance (and the correlation matrix).
|
|
We use <b>Pandas</b> to compute the correlation matrix.
|
|
<p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></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">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">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.datasets</span> <span style="color: #008000; font-weight: bold">import</span> load_breast_cancer
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.linear_model</span> <span style="color: #008000; font-weight: bold">import</span> LogisticRegression
|
|
cancer <span style="color: #666666">=</span> load_breast_cancer()
|
|
<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: #408080; font-style: italic"># Making a data frame</span>
|
|
cancerpd <span style="color: #666666">=</span> pd<span style="color: #666666">.</span>DataFrame(cancer<span style="color: #666666">.</span>data, columns<span style="color: #666666">=</span>cancer<span style="color: #666666">.</span>feature_names)
|
|
|
|
fig, axes <span style="color: #666666">=</span> plt<span style="color: #666666">.</span>subplots(<span style="color: #666666">15</span>,<span style="color: #666666">2</span>,figsize<span style="color: #666666">=</span>(<span style="color: #666666">10</span>,<span style="color: #666666">20</span>))
|
|
malignant <span style="color: #666666">=</span> cancer<span style="color: #666666">.</span>data[cancer<span style="color: #666666">.</span>target <span style="color: #666666">==</span> <span style="color: #666666">0</span>]
|
|
benign <span style="color: #666666">=</span> cancer<span style="color: #666666">.</span>data[cancer<span style="color: #666666">.</span>target <span style="color: #666666">==</span> <span style="color: #666666">1</span>]
|
|
ax <span style="color: #666666">=</span> axes<span style="color: #666666">.</span>ravel()
|
|
|
|
<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>(<span style="color: #666666">30</span>):
|
|
_, bins <span style="color: #666666">=</span> np<span style="color: #666666">.</span>histogram(cancer<span style="color: #666666">.</span>data[:,i], bins <span style="color: #666666">=50</span>)
|
|
ax[i]<span style="color: #666666">.</span>hist(malignant[:,i], bins <span style="color: #666666">=</span> bins, alpha <span style="color: #666666">=</span> <span style="color: #666666">0.5</span>)
|
|
ax[i]<span style="color: #666666">.</span>hist(benign[:,i], bins <span style="color: #666666">=</span> bins, alpha <span style="color: #666666">=</span> <span style="color: #666666">0.5</span>)
|
|
ax[i]<span style="color: #666666">.</span>set_title(cancer<span style="color: #666666">.</span>feature_names[i])
|
|
ax[i]<span style="color: #666666">.</span>set_yticks(())
|
|
ax[<span style="color: #666666">0</span>]<span style="color: #666666">.</span>set_xlabel(<span style="color: #BA2121">"Feature magnitude"</span>)
|
|
ax[<span style="color: #666666">0</span>]<span style="color: #666666">.</span>set_ylabel(<span style="color: #BA2121">"Frequency"</span>)
|
|
ax[<span style="color: #666666">0</span>]<span style="color: #666666">.</span>legend([<span style="color: #BA2121">"Malignant"</span>, <span style="color: #BA2121">"Benign"</span>], loc <span style="color: #666666">=</span><span style="color: #BA2121">"best"</span>)
|
|
fig<span style="color: #666666">.</span>tight_layout()
|
|
plt<span style="color: #666666">.</span>show()
|
|
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">seaborn</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">sns</span>
|
|
correlation_matrix <span style="color: #666666">=</span> cancerpd<span style="color: #666666">.</span>corr()<span style="color: #666666">.</span>round(<span style="color: #666666">1</span>)
|
|
<span style="color: #408080; font-style: italic"># use the heatmap function from seaborn to plot the correlation matrix</span>
|
|
<span style="color: #408080; font-style: italic"># annot = True to print the values inside the square</span>
|
|
plt<span style="color: #666666">.</span>figure(figsize<span style="color: #666666">=</span>(<span style="color: #666666">15</span>,<span style="color: #666666">8</span>))
|
|
sns<span style="color: #666666">.</span>heatmap(data<span style="color: #666666">=</span>correlation_matrix, annot<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>)
|
|
plt<span style="color: #666666">.</span>show()
|
|
</pre></div>
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="discussing-the-correlation-data">Discussing the correlation data </h2>
|
|
|
|
<p>
|
|
In the above example we note two things. In the first plot we display
|
|
the overlap of benign and malignant tumors as functions of the various
|
|
features in the Wisconsing breast cancer data set. We see that for
|
|
some of the features we can distinguish clearly the benign and
|
|
malignant cases while for other features we cannot. This can point to
|
|
us which features may be of greater interest when we wish to classify
|
|
a benign or not benign tumour.
|
|
|
|
<p>
|
|
In the second figure we have computed the so-called correlation
|
|
matrix, which in our case with thirty features becomes a \( 30\times 30 \)
|
|
matrix.
|
|
|
|
<p>
|
|
We constructed this matrix using <b>pandas</b> via the statements
|
|
<p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span>cancerpd <span style="color: #666666">=</span> pd<span style="color: #666666">.</span>DataFrame(cancer<span style="color: #666666">.</span>data, columns<span style="color: #666666">=</span>cancer<span style="color: #666666">.</span>feature_names)
|
|
</pre></div>
|
|
<p>
|
|
and then
|
|
<p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></span>correlation_matrix <span style="color: #666666">=</span> cancerpd<span style="color: #666666">.</span>corr()<span style="color: #666666">.</span>round(<span style="color: #666666">1</span>)
|
|
</pre></div>
|
|
<p>
|
|
Diagonalizing this matrix we can in turn say something about which
|
|
features are of relevance and which are not. This leads us to
|
|
the classical Principal Component Analysis (PCA) theorem with
|
|
applications. This will be discussed later this semester (<a href="https://compphysics.github.io/MachineLearning/doc/pub/week43/html/week43-bs.html" target="_blank">week 43</a>).
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="other-measures-in-classification-studies-cancer-data-again">Other measures in classification studies: Cancer Data again </h2>
|
|
<p>
|
|
|
|
<!-- code=python (!bc pycod) typeset with pygments style "default" -->
|
|
<div class="highlight" style="background: #f8f8f8"><pre style="line-height: 125%;"><span></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">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">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.datasets</span> <span style="color: #008000; font-weight: bold">import</span> load_breast_cancer
|
|
<span style="color: #008000; font-weight: bold">from</span> <span style="color: #0000FF; font-weight: bold">sklearn.linear_model</span> <span style="color: #008000; font-weight: bold">import</span> LogisticRegression
|
|
|
|
<span style="color: #408080; font-style: italic"># Load the data</span>
|
|
cancer <span style="color: #666666">=</span> load_breast_cancer()
|
|
|
|
X_train, X_test, y_train, y_test <span style="color: #666666">=</span> train_test_split(cancer<span style="color: #666666">.</span>data,cancer<span style="color: #666666">.</span>target,random_state<span style="color: #666666">=0</span>)
|
|
<span style="color: #008000">print</span>(X_train<span style="color: #666666">.</span>shape)
|
|
<span style="color: #008000">print</span>(X_test<span style="color: #666666">.</span>shape)
|
|
<span style="color: #408080; font-style: italic"># Logistic Regression</span>
|
|
logreg <span style="color: #666666">=</span> LogisticRegression(solver<span style="color: #666666">=</span><span style="color: #BA2121">'lbfgs'</span>)
|
|
logreg<span style="color: #666666">.</span>fit(X_train, y_train)
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"Test set accuracy with Logistic Regression: </span><span style="color: #BB6688; font-weight: bold">{:.2f}</span><span style="color: #BA2121">"</span><span style="color: #666666">.</span>format(logreg<span style="color: #666666">.</span>score(X_test,y_test)))
|
|
<span style="color: #408080; font-style: italic">#now scale the data</span>
|
|
<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
|
|
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)
|
|
<span style="color: #408080; font-style: italic"># Logistic Regression</span>
|
|
logreg<span style="color: #666666">.</span>fit(X_train_scaled, y_train)
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"Test set accuracy Logistic Regression with scaled data: </span><span style="color: #BB6688; font-weight: bold">{:.2f}</span><span style="color: #BA2121">"</span><span style="color: #666666">.</span>format(logreg<span style="color: #666666">.</span>score(X_test_scaled,y_test)))
|
|
|
|
|
|
<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> LabelEncoder
|
|
<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> cross_validate
|
|
<span style="color: #408080; font-style: italic">#Cross validation</span>
|
|
accuracy <span style="color: #666666">=</span> cross_validate(logreg,X_test_scaled,y_test,cv<span style="color: #666666">=10</span>)[<span style="color: #BA2121">'test_score'</span>]
|
|
<span style="color: #008000">print</span>(accuracy)
|
|
<span style="color: #008000">print</span>(<span style="color: #BA2121">"Test set accuracy with Logistic Regression and scaled data: </span><span style="color: #BB6688; font-weight: bold">{:.2f}</span><span style="color: #BA2121">"</span><span style="color: #666666">.</span>format(logreg<span style="color: #666666">.</span>score(X_test_scaled,y_test)))
|
|
|
|
|
|
<span style="color: #008000; font-weight: bold">import</span> <span style="color: #0000FF; font-weight: bold">scikitplot</span> <span style="color: #008000; font-weight: bold">as</span> <span style="color: #0000FF; font-weight: bold">skplt</span>
|
|
y_pred <span style="color: #666666">=</span> logreg<span style="color: #666666">.</span>predict(X_test_scaled)
|
|
skplt<span style="color: #666666">.</span>metrics<span style="color: #666666">.</span>plot_confusion_matrix(y_test, y_pred, normalize<span style="color: #666666">=</span><span style="color: #008000; font-weight: bold">True</span>)
|
|
plt<span style="color: #666666">.</span>show()
|
|
y_probas <span style="color: #666666">=</span> logreg<span style="color: #666666">.</span>predict_proba(X_test_scaled)
|
|
skplt<span style="color: #666666">.</span>metrics<span style="color: #666666">.</span>plot_roc(y_test, y_probas)
|
|
plt<span style="color: #666666">.</span>show()
|
|
skplt<span style="color: #666666">.</span>metrics<span style="color: #666666">.</span>plot_cumulative_gain(y_test, y_probas)
|
|
plt<span style="color: #666666">.</span>show()
|
|
</pre></div>
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="friday-september-25">Friday September 25 </h2>
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="optimization-the-central-part-of-any-machine-learning-algortithm">Optimization, the central part of any Machine Learning algortithm </h2>
|
|
|
|
<p>
|
|
<a href="https://www.uio.no/studier/emner/matnat/fys/FYS-STK3155/h20/forelesningsvideoer/OverarchingAimsWeek39.mp4?vrtx=view-as-webpage" target="_blank">Overview Video, why do we care about gradient methods?</a>
|
|
|
|
<p>
|
|
Almost every problem in machine learning and data science starts with
|
|
a dataset \( X \), a model \( g(\beta) \), which is a function of the
|
|
parameters \( \beta \) and a cost function \( C(X, g(\beta)) \) that allows
|
|
us to judge how well the model \( g(\beta) \) explains the observations
|
|
\( X \). The model is fit by finding the values of \( \beta \) that minimize
|
|
the cost function. Ideally we would be able to solve for \( \beta \)
|
|
analytically, however this is not possible in general and we must use
|
|
some approximative/numerical method to compute the minimum.
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="revisiting-our-logistic-regression-case">Revisiting our Logistic Regression case </h2>
|
|
|
|
<p>
|
|
In our discussion on Logistic Regression we studied the
|
|
case of
|
|
two classes, with \( y_i \) either
|
|
\( 0 \) or \( 1 \). Furthermore we assumed also that we have only two
|
|
parameters \( \beta \) in our fitting, that is we
|
|
defined probabilities
|
|
|
|
$$
|
|
\begin{align*}
|
|
p(y_i=1|x_i,\boldsymbol{\beta}) &= \frac{\exp{(\beta_0+\beta_1x_i)}}{1+\exp{(\beta_0+\beta_1x_i)}},\nonumber\\
|
|
p(y_i=0|x_i,\boldsymbol{\beta}) &= 1 - p(y_i=1|x_i,\boldsymbol{\beta}),
|
|
\end{align*}
|
|
$$
|
|
|
|
where \( \boldsymbol{\beta} \) are the weights we wish to extract from data, in our case \( \beta_0 \) and \( \beta_1 \).
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="the-equations-to-solve">The equations to solve </h2>
|
|
|
|
<p>
|
|
Our compact equations used a definition of a vector \( \boldsymbol{y} \) with \( n \)
|
|
elements \( y_i \), an \( n\times p \) matrix \( \boldsymbol{X} \) which contains the
|
|
\( x_i \) values and a vector \( \boldsymbol{p} \) of fitted probabilities
|
|
\( p(y_i\vert x_i,\boldsymbol{\beta}) \). We rewrote in a more compact form
|
|
the first derivative of the cost function as
|
|
|
|
$$
|
|
\frac{\partial \mathcal{C}(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}} = -\boldsymbol{X}^T\left(\boldsymbol{y}-\boldsymbol{p}\right).
|
|
$$
|
|
|
|
<p>
|
|
If we in addition define a diagonal matrix \( \boldsymbol{W} \) with elements
|
|
\( p(y_i\vert x_i,\boldsymbol{\beta})(1-p(y_i\vert x_i,\boldsymbol{\beta}) \), we can obtain a compact expression of the second derivative as
|
|
|
|
$$
|
|
\frac{\partial^2 \mathcal{C}(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}\partial \boldsymbol{\beta}^T} = \boldsymbol{X}^T\boldsymbol{W}\boldsymbol{X}.
|
|
$$
|
|
|
|
This defines what is called the Hessian matrix.
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="solving-using-newton-raphson-s-method">Solving using Newton-Raphson's method </h2>
|
|
|
|
<p>
|
|
If we can set up these equations, Newton-Raphson's iterative method is normally the method of choice. It requires however that we can compute in an efficient way the matrices that define the first and second derivatives.
|
|
|
|
<p>
|
|
Our iterative scheme is then given by
|
|
|
|
$$
|
|
\boldsymbol{\beta}^{\mathrm{new}} = \boldsymbol{\beta}^{\mathrm{old}}-\left(\frac{\partial^2 \mathcal{C}(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}\partial \boldsymbol{\beta}^T}\right)^{-1}_{\boldsymbol{\beta}^{\mathrm{old}}}\times \left(\frac{\partial \mathcal{C}(\boldsymbol{\beta})}{\partial \boldsymbol{\beta}}\right)_{\boldsymbol{\beta}^{\mathrm{old}}},
|
|
$$
|
|
|
|
or in matrix form as
|
|
|
|
$$
|
|
\boldsymbol{\beta}^{\mathrm{new}} = \boldsymbol{\beta}^{\mathrm{old}}-\left(\boldsymbol{X}^T\boldsymbol{W}\boldsymbol{X} \right)^{-1}\times \left(-\boldsymbol{X}^T(\boldsymbol{y}-\boldsymbol{p}) \right)_{\boldsymbol{\beta}^{\mathrm{old}}}.
|
|
$$
|
|
|
|
The right-hand side is computed with the old values of \( \beta \).
|
|
|
|
<p>
|
|
If we can compute these matrices, in particular the Hessian, the above is often the easiest method to implement.
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="brief-reminder-on-newton-raphson-s-method">Brief reminder on Newton-Raphson's method </h2>
|
|
|
|
<p>
|
|
Let us quickly remind ourselves how we derive the above method.
|
|
|
|
<p>
|
|
Perhaps the most celebrated of all one-dimensional root-finding
|
|
routines is Newton's method, also called the Newton-Raphson
|
|
method. This method requires the evaluation of both the
|
|
function \( f \) and its derivative \( f' \) at arbitrary points.
|
|
If you can only calculate the derivative
|
|
numerically and/or your function is not of the smooth type, we
|
|
normally discourage the use of this method.
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="the-equations">The equations </h2>
|
|
|
|
<p>
|
|
The Newton-Raphson formula consists geometrically of extending the
|
|
tangent line at a current point until it crosses zero, then setting
|
|
the next guess to the abscissa of that zero-crossing. The mathematics
|
|
behind this method is rather simple. Employing a Taylor expansion for
|
|
\( x \) sufficiently close to the solution \( s \), we have
|
|
|
|
$$
|
|
f(s)=0=f(x)+(s-x)f'(x)+\frac{(s-x)^2}{2}f''(x) +\dots.
|
|
\label{eq:taylornr}
|
|
$$
|
|
|
|
<p>
|
|
For small enough values of the function and for well-behaved
|
|
functions, the terms beyond linear are unimportant, hence we obtain
|
|
|
|
$$
|
|
f(x)+(s-x)f'(x)\approx 0,
|
|
$$
|
|
|
|
yielding
|
|
$$
|
|
s\approx x-\frac{f(x)}{f'(x)}.
|
|
$$
|
|
|
|
<p>
|
|
Having in mind an iterative procedure, it is natural to start iterating with
|
|
$$
|
|
x_{n+1}=x_n-\frac{f(x_n)}{f'(x_n)}.
|
|
$$
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="simple-geometric-interpretation">Simple geometric interpretation </h2>
|
|
|
|
<p>
|
|
The above is Newton-Raphson's method. It has a simple geometric
|
|
interpretation, namely \( x_{n+1} \) is the point where the tangent from
|
|
\( (x_n,f(x_n)) \) crosses the \( x \)-axis. Close to the solution,
|
|
Newton-Raphson converges fast to the desired result. However, if we
|
|
are far from a root, where the higher-order terms in the series are
|
|
important, the Newton-Raphson formula can give grossly inaccurate
|
|
results. For instance, the initial guess for the root might be so far
|
|
from the true root as to let the search interval include a local
|
|
maximum or minimum of the function. If an iteration places a trial
|
|
guess near such a local extremum, so that the first derivative nearly
|
|
vanishes, then Newton-Raphson may fail totally
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="extending-to-more-than-one-variable">Extending to more than one variable </h2>
|
|
|
|
<p>
|
|
Newton's method can be generalized to systems of several non-linear equations
|
|
and variables. Consider the case with two equations
|
|
$$
|
|
\begin{array}{cc} f_1(x_1,x_2) &=0\\
|
|
f_2(x_1,x_2) &=0,\end{array}
|
|
$$
|
|
|
|
which we Taylor expand to obtain
|
|
|
|
$$
|
|
\begin{array}{cc} 0=f_1(x_1+h_1,x_2+h_2)=&f_1(x_1,x_2)+h_1
|
|
\partial f_1/\partial x_1+h_2
|
|
\partial f_1/\partial x_2+\dots\\
|
|
0=f_2(x_1+h_1,x_2+h_2)=&f_2(x_1,x_2)+h_1
|
|
\partial f_2/\partial x_1+h_2
|
|
\partial f_2/\partial x_2+\dots
|
|
\end{array}.
|
|
$$
|
|
|
|
Defining the Jacobian matrix \( {\bf \boldsymbol{J}} \) we have
|
|
$$
|
|
{\bf \boldsymbol{J}}=\left( \begin{array}{cc}
|
|
\partial f_1/\partial x_1 & \partial f_1/\partial x_2 \\
|
|
\partial f_2/\partial x_1 &\partial f_2/\partial x_2
|
|
\end{array} \right),
|
|
$$
|
|
|
|
we can rephrase Newton's method as
|
|
$$
|
|
\left(\begin{array}{c} x_1^{n+1} \\ x_2^{n+1} \end{array} \right)=
|
|
\left(\begin{array}{c} x_1^{n} \\ x_2^{n} \end{array} \right)+
|
|
\left(\begin{array}{c} h_1^{n} \\ h_2^{n} \end{array} \right),
|
|
$$
|
|
|
|
where we have defined
|
|
$$
|
|
\left(\begin{array}{c} h_1^{n} \\ h_2^{n} \end{array} \right)=
|
|
-{\bf \boldsymbol{J}}^{-1}
|
|
\left(\begin{array}{c} f_1(x_1^{n},x_2^{n}) \\ f_2(x_1^{n},x_2^{n}) \end{array} \right).
|
|
$$
|
|
|
|
We need thus to compute the inverse of the Jacobian matrix and it
|
|
is to understand that difficulties may
|
|
arise in case \( {\bf \boldsymbol{J}} \) is nearly singular.
|
|
|
|
<p>
|
|
It is rather straightforward to extend the above scheme to systems of
|
|
more than two non-linear equations. In our case, the Jacobian matrix is given by the Hessian that represents the second derivative of cost function.
|
|
|
|
<p>
|
|
<!-- !split --><br><br><br><br><br><br><br><br><br><br>
|
|
|
|
<h2 id="steepest-descent">Steepest descent </h2>
|
|
|
|
<p>
|
|
The basic idea of gradient descent is
|
|
that a function \( F(\mathbf{x}) \),
|
|
\( \mathbf{x} \equiv (x_1,\cdots,x_n) \), decreases fastest if one goes from \( \bf {x} \) in the
|
|
direction of the negative gradient \( -\nabla F(\mathbf{x}) \).
|
|
|
|
<p>
|
|
It can be shown that if
|
|
$$
|
|
\mathbf{x}_{k+1} = \mathbf{x}_k - \gamma_k \nabla F(\mathbf{x}_k),
|
|
$$
|
|
|
|
with \( \gamma_k > 0 \).
|
|
|
|
<p>
|
|
For \( \gamma_k \) small enough, then \( F(\mathbf{x}_{k+1}) \leq
|
|
F(\mathbf{x}_k) \). This means that for a sufficiently small \( \gamma_k \)
|
|
we are always moving towards smaller function values, i.e a minimum.
|
|
|
|
<p>
|
|
<!-- !split -->
|
|
|
|
<h2 id="more-on-steepest-descent">More on Steepest descent </h2>
|
|
|
|
<p>
|
|
The previous observation is the basis of the method of steepest
|
|
descent, which is also referred to as just gradient descent (GD). One
|
|
starts with an initial guess \( \mathbf{x}_0 \) for a minimum of \( F \) and
|
|
computes new approximations according to
|
|
|
|
$$
|
|
\mathbf{x}_{k+1} = \mathbf{x}_k - \gamma_k \nabla F(\mathbf{x}_k), \ \ k \geq 0.
|
|
$$
|
|
|
|
<p>
|
|
The parameter \( \gamma_k \) is often referred to as the step length or
|
|
the learning rate within the context of Machine Learning.
|
|
|
|
<p>
|
|
<!-- !split -->
|
|
|
|
<h2 id="the-ideal">The ideal </h2>
|
|
|
|
<p>
|
|
Ideally the sequence \( \{\mathbf{x}_k \}_{k=0} \) converges to a global
|
|
minimum of the function \( F \). In general we do not know if we are in a
|
|
global or local minimum. In the special case when \( F \) is a convex
|
|
function, all local minima are also global minima, so in this case
|
|
gradient descent can converge to the global solution. The advantage of
|
|
this scheme is that it is conceptually simple and straightforward to
|
|
implement. However the method in this form has some severe
|
|
limitations:
|
|
|
|
<p>
|
|
In machine learing we are often faced with non-convex high dimensional
|
|
cost functions with many local minima. Since GD is deterministic we
|
|
will get stuck in a local minimum, if the method converges, unless we
|
|
have a very good intial guess. This also implies that the scheme is
|
|
sensitive to the chosen initial condition.
|
|
|
|
<p>
|
|
Note that the gradient is a function of \( \mathbf{x} =
|
|
(x_1,\cdots,x_n) \) which makes it expensive to compute numerically.
|
|
|
|
<p>
|
|
<!-- !split -->
|
|
|
|
<h2 id="the-sensitiveness-of-the-gradient-descent">The sensitiveness of the gradient descent </h2>
|
|
|
|
<p>
|
|
The gradient descent method
|
|
is sensitive to the choice of learning rate \( \gamma_k \). This is due
|
|
to the fact that we are only guaranteed that \( F(\mathbf{x}_{k+1}) \leq
|
|
F(\mathbf{x}_k) \) for sufficiently small \( \gamma_k \). The problem is to
|
|
determine an optimal learning rate. If the learning rate is chosen too
|
|
small the method will take a long time to converge and if it is too
|
|
large we can experience erratic behavior.
|
|
|
|
<p>
|
|
Many of these shortcomings can be alleviated by introducing
|
|
randomness. One such method is that of Stochastic Gradient Descent
|
|
(SGD), see below.
|
|
|
|
<p>
|
|
|
|
<!-- ------------------- end of main content --------------- -->
|
|
|
|
|
|
<center style="font-size:80%">
|
|
<!-- copyright --> © 1999-2021, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license
|
|
</center>
|
|
|
|
|
|
</body>
|
|
</html>
|
|
|
|
|