From 408711dfc9740dd1a93d962e7570ba70e07438ed Mon Sep 17 00:00:00 2001 From: Morten Hjorth-Jensen Date: Tue, 14 Sep 2021 22:49:47 +0200 Subject: [PATCH] update week 37 --- doc/LectureNotes/schedule.md | 9 +- doc/pub/week37/html/._week37-bs000.html | 54 +-- doc/pub/week37/html/._week37-bs001.html | 60 +-- doc/pub/week37/html/._week37-bs002.html | 52 +-- doc/pub/week37/html/._week37-bs003.html | 52 +-- doc/pub/week37/html/._week37-bs004.html | 52 +-- doc/pub/week37/html/._week37-bs005.html | 52 +-- doc/pub/week37/html/._week37-bs006.html | 52 +-- doc/pub/week37/html/._week37-bs007.html | 52 +-- doc/pub/week37/html/._week37-bs008.html | 52 +-- doc/pub/week37/html/._week37-bs009.html | 52 +-- doc/pub/week37/html/._week37-bs010.html | 52 +-- doc/pub/week37/html/._week37-bs011.html | 52 +-- doc/pub/week37/html/._week37-bs012.html | 52 +-- doc/pub/week37/html/._week37-bs013.html | 52 +-- doc/pub/week37/html/._week37-bs014.html | 52 +-- doc/pub/week37/html/._week37-bs015.html | 52 +-- doc/pub/week37/html/._week37-bs016.html | 52 +-- doc/pub/week37/html/._week37-bs017.html | 52 +-- doc/pub/week37/html/._week37-bs018.html | 52 +-- doc/pub/week37/html/._week37-bs019.html | 52 +-- doc/pub/week37/html/._week37-bs020.html | 52 +-- doc/pub/week37/html/._week37-bs021.html | 52 +-- doc/pub/week37/html/._week37-bs022.html | 52 +-- doc/pub/week37/html/._week37-bs023.html | 52 +-- doc/pub/week37/html/._week37-bs024.html | 52 +-- doc/pub/week37/html/._week37-bs025.html | 52 +-- doc/pub/week37/html/._week37-bs026.html | 52 +-- doc/pub/week37/html/._week37-bs027.html | 52 +-- doc/pub/week37/html/._week37-bs028.html | 129 ++++-- doc/pub/week37/html/._week37-bs029.html | 130 +++--- doc/pub/week37/html/._week37-bs030.html | 114 ++++-- doc/pub/week37/html/._week37-bs031.html | 173 +++----- doc/pub/week37/html/._week37-bs032.html | 165 ++++---- doc/pub/week37/html/._week37-bs033.html | 127 ++---- doc/pub/week37/html/._week37-bs034.html | 122 +++--- doc/pub/week37/html/._week37-bs035.html | 97 ++--- doc/pub/week37/html/._week37-bs036.html | 193 +++++---- doc/pub/week37/html/._week37-bs037.html | 52 +-- doc/pub/week37/html/._week37-bs038.html | 52 +-- doc/pub/week37/html/._week37-bs039.html | 52 +-- doc/pub/week37/html/week37-bs.html | 54 +-- doc/pub/week37/html/week37-reveal.html | 367 +++++++++-------- doc/pub/week37/html/week37-solarized.html | 394 +++++++++--------- doc/pub/week37/html/week37.html | 394 +++++++++--------- doc/pub/week37/ipynb/ipynb-week37-src.tar.gz | Bin 192 -> 192 bytes doc/pub/week37/ipynb/week37.ipynb | 403 ++++++++++--------- doc/src/week37/week37.do.txt | 327 +++++++-------- 48 files changed, 2437 insertions(+), 2383 deletions(-) diff --git a/doc/LectureNotes/schedule.md b/doc/LectureNotes/schedule.md index 9a54ff154..03fa6f0c1 100644 --- a/doc/LectureNotes/schedule.md +++ b/doc/LectureNotes/schedule.md @@ -52,8 +52,13 @@ For the reading assignments we use the following abbreviations: - Lab Wednesday: - Lecture Thursday: Resampling methods, cross-validation and Bootstrap - Lecture Friday: More on Resampling methods and summary of linear regression -- Reading recommendations: See lecture notes for week 37 at https://compphysics.github.io/MachineLearning/doc/web/course.html. - - Chapter +- Reading recommendations: +- Recommended Reading: + - Lectures on Resampling methods for week 37 at https://compphysics.github.io/MachineLearning/doc/web/course.html. + - Bishop 1.3 (cross-validation) and 3.2 (bias-variance tradeoff) + - Hastie et al Chapter 7, here we recommend 7.1-7.5 and 7.10 (cross-validation) and 7.11 (bootstrap). This chapter is better than Bishop's on these topics. Goodfellow et al discuss some of these topics in sections 5.2-5.5. + + ### Week 38 September 20-24 - Lab Wednesday: - Lecture Thursday: Classification problems and Logistic Regression, from binary cases to several categories diff --git a/doc/pub/week37/html/._week37-bs000.html b/doc/pub/week37/html/._week37-bs000.html index 907a5adda..6dc865aec 100644 --- a/doc/pub/week37/html/._week37-bs000.html +++ b/doc/pub/week37/html/._week37-bs000.html @@ -114,23 +114,6 @@ Automatically generated HTML file from DocOnce source 2, None, 'code-example-for-the-bootstrap-method'), - ('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'), ('The bias-variance tradeoff', 2, None, @@ -148,6 +131,23 @@ Automatically generated HTML file from DocOnce source 2, None, 'another-example-from-scikit-learn-s-repository'), + ('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'), ('More examples on bootstrap and cross-validation and errors', 2, None, @@ -224,15 +224,15 @@ MathJax.Hub.Config({
  • Resampling methods: Bootstrap approach
  • Resampling methods: Bootstrap steps
  • Code example for the Bootstrap method
  • -
  • Various steps in cross-validation
  • -
  • How to set up the cross-validation for Ridge and/or Lasso
  • -
  • Cross-validation in brief
  • -
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • -
  • The bias-variance tradeoff
  • -
  • Example code for Bias-Variance tradeoff
  • -
  • Understanding what happens
  • -
  • Summing up
  • -
  • Another Example from Scikit-Learn's Repository
  • +
  • The bias-variance tradeoff
  • +
  • Example code for Bias-Variance tradeoff
  • +
  • Understanding what happens
  • +
  • Summing up
  • +
  • Another Example from Scikit-Learn's Repository
  • +
  • Various steps in cross-validation
  • +
  • How to set up the cross-validation for Ridge and/or Lasso
  • +
  • Cross-validation in brief
  • +
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • More examples on bootstrap and cross-validation and errors
  • The same example but now with cross-validation
  • Cross-validation with Ridge
  • @@ -270,7 +270,7 @@ MathJax.Hub.Config({
    [2] Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University

    -

    Sep 12, 2021

    +

    Sep 14, 2021


    diff --git a/doc/pub/week37/html/._week37-bs001.html b/doc/pub/week37/html/._week37-bs001.html index 123a10296..65ca2ed47 100644 --- a/doc/pub/week37/html/._week37-bs001.html +++ b/doc/pub/week37/html/._week37-bs001.html @@ -114,23 +114,6 @@ Automatically generated HTML file from DocOnce source 2, None, 'code-example-for-the-bootstrap-method'), - ('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'), ('The bias-variance tradeoff', 2, None, @@ -148,6 +131,23 @@ Automatically generated HTML file from DocOnce source 2, None, 'another-example-from-scikit-learn-s-repository'), + ('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'), ('More examples on bootstrap and cross-validation and errors', 2, None, @@ -224,15 +224,15 @@ MathJax.Hub.Config({

  • Resampling methods: Bootstrap approach
  • Resampling methods: Bootstrap steps
  • Code example for the Bootstrap method
  • -
  • Various steps in cross-validation
  • -
  • How to set up the cross-validation for Ridge and/or Lasso
  • -
  • Cross-validation in brief
  • -
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • -
  • The bias-variance tradeoff
  • -
  • Example code for Bias-Variance tradeoff
  • -
  • Understanding what happens
  • -
  • Summing up
  • -
  • Another Example from Scikit-Learn's Repository
  • +
  • The bias-variance tradeoff
  • +
  • Example code for Bias-Variance tradeoff
  • +
  • Understanding what happens
  • +
  • Summing up
  • +
  • Another Example from Scikit-Learn's Repository
  • +
  • Various steps in cross-validation
  • +
  • How to set up the cross-validation for Ridge and/or Lasso
  • +
  • Cross-validation in brief
  • +
  • Code Example for Cross-validation and \( k \)-fold Cross-validation
  • More examples on bootstrap and cross-validation and errors
  • The same example but now with cross-validation
  • Cross-validation with Ridge
  • @@ -258,6 +258,14 @@ MathJax.Hub.Config({
  • Friday September 17: Resampling methods, Cross-validation, Bootstrapping and jackknife
  • +Recommended Reading: + +
      +
    1. Lectures on Resampling methods (these lectures)
    2. +
    3. Bishop 1.3 (cross-validation) and 3.2 (bias-variance tradeoff)
    4. +
    5. Hastie et al Chapter 7, here we recommend 7.1-7.5 and 7.10 (cross-validation) and 7.11 (bootstrap). This chapter is better than Bishop's on these topics. Goodfellow et al discuss this in a superficial way in sections 5.2-5.5.
    6. +
    +

    +Recommended Reading: + +
      +
    1. Lectures on Resampling methods (these lectures)
    2. +
    3. Bishop 1.3 (cross-validation) and 3.2 (bias-variance tradeoff)
    4. +
    5. Hastie et al Chapter 7, here we recommend 7.1-7.5 and 7.10 (cross-validation) and 7.11 (bootstrap). This chapter is better than Bishop's on these topics. Goodfellow et al discuss this in a superficial way in sections 5.2-5.5.
    6. +
    +









    Thursday September 16, Summary of Ridge and Lasso Regression and start Resampling methods

    @@ -982,181 +990,6 @@ plt.ylabel(' plt.axis([99.5, 100.6, 0, 3.0]) plt.grid(True) -plt.show() - -

    - - -

    Various steps in cross-validation

    - -

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

    - - -

    How to set up the cross-validation for Ridge and/or Lasso

    - - - -$$ -\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*} -$$ - - - - -$$ -\begin{align*} -\frac{1}{n} \sum_{i = 1}^n \log\{L[y_i, \mathbf{X}_{i, \ast}; \boldsymbol{\beta}_{-i}(\lambda), \boldsymbol{\sigma}_{-i}^2(\lambda)]\}. -\end{align*} -$$ - -

    -









    - -

    Cross-validation in brief

    - -

    -For the various values of \( k \) - -

      -
    1. shuffle the dataset randomly.
    2. -
    3. Split the dataset into \( k \) groups.
    4. -
    5. For each unique group: - -
        -
      1. Decide which group to use as set for test data
      2. -
      3. Take the remaining groups as a training data set
      4. -
      5. Fit a model on the training set and evaluate it on the test set
      6. -
      7. Retain the evaluation score and discard the model
      8. -
      - -
    6. Summarize the model using the sample of model evaluation scores
    7. -
    - -









    - -

    Code Example for Cross-validation and \( k \)-fold Cross-validation

    - -

    -The code here uses Ridge regression with cross-validation (CV) resampling and \( k \)-fold CV in order to fit a specific polynomial. -

    - - -

    import numpy as np
    -import matplotlib.pyplot as plt
    -from sklearn.model_selection import KFold
    -from sklearn.linear_model import Ridge
    -from sklearn.model_selection import cross_val_score
    -from sklearn.preprocessing import PolynomialFeatures
    -
    -# A seed just to ensure that the random numbers are the same for every run.
    -# Useful for eventual debugging.
    -np.random.seed(3155)
    -
    -# Generate the data.
    -nsamples = 100
    -x = np.random.randn(nsamples)
    -y = 3*x**2 + np.random.randn(nsamples)
    -
    -## Cross-validation on Ridge regression using KFold only
    -
    -# Decide degree on polynomial to fit
    -poly = PolynomialFeatures(degree = 6)
    -
    -# Decide which values of lambda to use
    -nlambdas = 500
    -lambdas = np.logspace(-3, 5, nlambdas)
    -
    -# Initialize a KFold instance
    -k = 5
    -kfold = KFold(n_splits = k)
    -
    -# Perform the cross-validation to estimate MSE
    -scores_KFold = np.zeros((nlambdas, k))
    -
    -i = 0
    -for lmb in lambdas:
    -    ridge = Ridge(alpha = lmb)
    -    j = 0
    -    for train_inds, test_inds in kfold.split(x):
    -        xtrain = x[train_inds]
    -        ytrain = y[train_inds]
    -
    -        xtest = x[test_inds]
    -        ytest = y[test_inds]
    -
    -        Xtrain = poly.fit_transform(xtrain[:, np.newaxis])
    -        ridge.fit(Xtrain, ytrain[:, np.newaxis])
    -
    -        Xtest = poly.fit_transform(xtest[:, np.newaxis])
    -        ypred = ridge.predict(Xtest)
    -
    -        scores_KFold[i,j] = np.sum((ypred - ytest[:, np.newaxis])**2)/np.size(ypred)
    -
    -        j += 1
    -    i += 1
    -
    -
    -estimated_mse_KFold = np.mean(scores_KFold, axis = 1)
    -
    -## Cross-validation using cross_val_score from sklearn along with KFold
    -
    -# kfold is an instance initialized above as:
    -# kfold = KFold(n_splits = k)
    -
    -estimated_mse_sklearn = np.zeros(nlambdas)
    -i = 0
    -for lmb in lambdas:
    -    ridge = Ridge(alpha = lmb)
    -
    -    X = poly.fit_transform(x[:, np.newaxis])
    -    estimated_mse_folds = cross_val_score(ridge, X, y[:, np.newaxis], scoring='neg_mean_squared_error', cv=kfold)
    -
    -    # cross_val_score return an array containing the estimated negative mse for every fold.
    -    # we have to the the mean of every array in order to get an estimate of the mse of the model
    -    estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds)
    -
    -    i += 1
    -
    -## Plot and compare the slightly different ways to perform cross-validation
    -
    -plt.figure()
    -
    -plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score')
    -plt.plot(np.log10(lambdas), estimated_mse_KFold, 'r--', label = 'KFold')
    -
    -plt.xlabel('log10(lambda)')
    -plt.ylabel('mse')
    -
    -plt.legend()
    -
     plt.show()
     

    @@ -1455,6 +1288,181 @@ plt.figure(figsize.legend(loc="best") plt.title("Degree {}\nMSE = {:.2e}(+/- {:.2e})".format( degrees[i], -scores.mean(), scores.std())) +plt.show() + +

    + + +

    Various steps in cross-validation

    + +

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

    + + +

    How to set up the cross-validation for Ridge and/or Lasso

    + + + +$$ +\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*} +$$ + + + + +$$ +\begin{align*} +\frac{1}{n} \sum_{i = 1}^n \log\{L[y_i, \mathbf{X}_{i, \ast}; \boldsymbol{\beta}_{-i}(\lambda), \boldsymbol{\sigma}_{-i}^2(\lambda)]\}. +\end{align*} +$$ + +

    +









    + +

    Cross-validation in brief

    + +

    +For the various values of \( k \) + +

      +
    1. shuffle the dataset randomly.
    2. +
    3. Split the dataset into \( k \) groups.
    4. +
    5. For each unique group: + +
        +
      1. Decide which group to use as set for test data
      2. +
      3. Take the remaining groups as a training data set
      4. +
      5. Fit a model on the training set and evaluate it on the test set
      6. +
      7. Retain the evaluation score and discard the model
      8. +
      + +
    6. Summarize the model using the sample of model evaluation scores
    7. +
    + +









    + +

    Code Example for Cross-validation and \( k \)-fold Cross-validation

    + +

    +The code here uses Ridge regression with cross-validation (CV) resampling and \( k \)-fold CV in order to fit a specific polynomial. +

    + + +

    import numpy as np
    +import matplotlib.pyplot as plt
    +from sklearn.model_selection import KFold
    +from sklearn.linear_model import Ridge
    +from sklearn.model_selection import cross_val_score
    +from sklearn.preprocessing import PolynomialFeatures
    +
    +# A seed just to ensure that the random numbers are the same for every run.
    +# Useful for eventual debugging.
    +np.random.seed(3155)
    +
    +# Generate the data.
    +nsamples = 100
    +x = np.random.randn(nsamples)
    +y = 3*x**2 + np.random.randn(nsamples)
    +
    +## Cross-validation on Ridge regression using KFold only
    +
    +# Decide degree on polynomial to fit
    +poly = PolynomialFeatures(degree = 6)
    +
    +# Decide which values of lambda to use
    +nlambdas = 500
    +lambdas = np.logspace(-3, 5, nlambdas)
    +
    +# Initialize a KFold instance
    +k = 5
    +kfold = KFold(n_splits = k)
    +
    +# Perform the cross-validation to estimate MSE
    +scores_KFold = np.zeros((nlambdas, k))
    +
    +i = 0
    +for lmb in lambdas:
    +    ridge = Ridge(alpha = lmb)
    +    j = 0
    +    for train_inds, test_inds in kfold.split(x):
    +        xtrain = x[train_inds]
    +        ytrain = y[train_inds]
    +
    +        xtest = x[test_inds]
    +        ytest = y[test_inds]
    +
    +        Xtrain = poly.fit_transform(xtrain[:, np.newaxis])
    +        ridge.fit(Xtrain, ytrain[:, np.newaxis])
    +
    +        Xtest = poly.fit_transform(xtest[:, np.newaxis])
    +        ypred = ridge.predict(Xtest)
    +
    +        scores_KFold[i,j] = np.sum((ypred - ytest[:, np.newaxis])**2)/np.size(ypred)
    +
    +        j += 1
    +    i += 1
    +
    +
    +estimated_mse_KFold = np.mean(scores_KFold, axis = 1)
    +
    +## Cross-validation using cross_val_score from sklearn along with KFold
    +
    +# kfold is an instance initialized above as:
    +# kfold = KFold(n_splits = k)
    +
    +estimated_mse_sklearn = np.zeros(nlambdas)
    +i = 0
    +for lmb in lambdas:
    +    ridge = Ridge(alpha = lmb)
    +
    +    X = poly.fit_transform(x[:, np.newaxis])
    +    estimated_mse_folds = cross_val_score(ridge, X, y[:, np.newaxis], scoring='neg_mean_squared_error', cv=kfold)
    +
    +    # cross_val_score return an array containing the estimated negative mse for every fold.
    +    # we have to the the mean of every array in order to get an estimate of the mse of the model
    +    estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds)
    +
    +    i += 1
    +
    +## Plot and compare the slightly different ways to perform cross-validation
    +
    +plt.figure()
    +
    +plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score')
    +plt.plot(np.log10(lambdas), estimated_mse_KFold, 'r--', label = 'KFold')
    +
    +plt.xlabel('log10(lambda)')
    +plt.ylabel('mse')
    +
    +plt.legend()
    +
     plt.show()
     

    diff --git a/doc/pub/week37/ipynb/ipynb-week37-src.tar.gz b/doc/pub/week37/ipynb/ipynb-week37-src.tar.gz index 4d7b11611e7add7c32abfa271d3d7c234f22bbf0..0c191f25818d136a2ff2f3b7bd927422cfccf4aa 100644 GIT binary patch literal 192 zcmV;x06+g9iwFSP3PE821MSbv3c@f92k@Qu6nTP?uIqLd^x#1d@dY~8xjNU*wnO*! z?gR9sco`z}cli?%LUP!w*1JvQ?k-piBBn_KV`eFv663j^5W;{YB*qvSr7<9(jL-mZ zxszTx>$n+CX{xhOR;YJ#!&q5<*fYNZ&-@d|N?O?Ndsk@%N;{EjUBgX?nr4w~dzC|> ug&kX9#I=(~09QTmqL5B%#V=uN^vUqXM&YlY@jTD-zV-m>1}Yo?2mk;fbz18H literal 192 zcmV;x06+g9iwFRrSw3L^1MSbv3c@f92k@Qu6nTQtx^_DY?%+WX@dY}TxjNU*wnO*! z?gR9sco`z}cli?%LUPE~n_U*Uy9*XW2uT=&G1G)kNmg?`p_Bt_Wl|}V#ZWt@e4}0cU;F*8oSV;@peeWu*Kxv1$)-~J^>o|>M+p8Q3 ujdpB-!D}ZCf>1q(qL5B%B`#rW^vQ_EM&YlY@jTD-zV-my{dXe(2mk;mRatWY diff --git a/doc/pub/week37/ipynb/week37.ipynb b/doc/pub/week37/ipynb/week37.ipynb index b8e187a88..971467289 100644 --- a/doc/pub/week37/ipynb/week37.ipynb +++ b/doc/pub/week37/ipynb/week37.ipynb @@ -10,7 +10,7 @@ " \n", "**Morten Hjorth-Jensen**, Department of Physics, University of Oslo and Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University\n", "\n", - "Date: **Sep 12, 2021**\n", + "Date: **Sep 14, 2021**\n", "\n", "Copyright 1999-2021, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license\n", "\n", @@ -22,6 +22,13 @@ "\n", "* Friday September 17: Resampling methods, Cross-validation, Bootstrapping and jackknife\n", "\n", + "Recommended Reading:\n", + "1. Lectures on Resampling methods (these lectures)\n", + "\n", + "2. Bishop 1.3 (cross-validation) and 3.2 (bias-variance tradeoff)\n", + "\n", + "3. Hastie et al Chapter 7, here we recommend 7.1-7.5 and 7.10 (cross-validation) and 7.11 (bootstrap). This chapter is better than Bishop's on these topics. Goodfellow et al discuss this in a superficial way in sections 5.2-5.5.\n", + "\n", "## Thursday September 16, Summary of Ridge and Lasso Regression and start Resampling methods\n", "\n", "\n", @@ -932,203 +939,6 @@ "plt.show()" ] }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "## Various steps in cross-validation\n", - "\n", - "When the repetitive splitting of the data set is done randomly,\n", - "samples may accidently end up in a fast majority of the splits in\n", - "either training or test set. Such samples may have an unbalanced\n", - "influence on either model building or prediction evaluation. To avoid\n", - "this $k$-fold cross-validation structures the data splitting. The\n", - "samples are divided into $k$ more or less equally sized exhaustive and\n", - "mutually exclusive subsets. In turn (at each split) one of these\n", - "subsets plays the role of the test set while the union of the\n", - "remaining subsets constitutes the training set. Such a splitting\n", - "warrants a balanced representation of each sample in both training and\n", - "test set over the splits. Still the division into the $k$ subsets\n", - "involves a degree of randomness. This may be fully excluded when\n", - "choosing $k=n$. This particular case is referred to as leave-one-out\n", - "cross-validation (LOOCV). \n", - "\n", - "\n", - "## How to set up the cross-validation for Ridge and/or Lasso\n", - "\n", - "* Define a range of interest for the penalty parameter.\n", - "\n", - "* Divide the data set into training and test set comprising samples $\\{1, \\ldots, n\\} \\setminus i$ and $\\{ i \\}$, respectively.\n", - "\n", - "* 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" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\begin{align*}\n", - "\\boldsymbol{\\beta}_{-i}(\\lambda) & = ( \\boldsymbol{X}_{-i, \\ast}^{T}\n", - "\\boldsymbol{X}_{-i, \\ast} + \\lambda \\boldsymbol{I}_{pp})^{-1}\n", - "\\boldsymbol{X}_{-i, \\ast}^{T} \\boldsymbol{y}_{-i}\n", - "\\end{align*}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "* Evaluate the prediction performance of these models on the test set by $\\log\\{L[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.\n", - "\n", - "* Repeat the first three steps such that each sample plays the role of the test set once.\n", - "\n", - "* 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. It is defined as" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "$$\n", - "\\begin{align*}\n", - "\\frac{1}{n} \\sum_{i = 1}^n \\log\\{L[y_i, \\mathbf{X}_{i, \\ast}; \\boldsymbol{\\beta}_{-i}(\\lambda), \\boldsymbol{\\sigma}_{-i}^2(\\lambda)]\\}.\n", - "\\end{align*}\n", - "$$" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Cross-validation in brief\n", - "\n", - "For the various values of $k$\n", - "\n", - "1. shuffle the dataset randomly.\n", - "\n", - "2. Split the dataset into $k$ groups.\n", - "\n", - "3. For each unique group:\n", - "\n", - "a. Decide which group to use as set for test data\n", - "\n", - "b. Take the remaining groups as a training data set\n", - "\n", - "c. Fit a model on the training set and evaluate it on the test set\n", - "\n", - "d. Retain the evaluation score and discard the model\n", - "\n", - "\n", - "5. Summarize the model using the sample of model evaluation scores\n", - "\n", - "## Code Example for Cross-validation and $k$-fold Cross-validation\n", - "\n", - "The code here uses Ridge regression with cross-validation (CV) resampling and $k$-fold CV in order to fit a specific polynomial." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "editable": true - }, - "outputs": [], - "source": [ - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from sklearn.model_selection import KFold\n", - "from sklearn.linear_model import Ridge\n", - "from sklearn.model_selection import cross_val_score\n", - "from sklearn.preprocessing import PolynomialFeatures\n", - "\n", - "# A seed just to ensure that the random numbers are the same for every run.\n", - "# Useful for eventual debugging.\n", - "np.random.seed(3155)\n", - "\n", - "# Generate the data.\n", - "nsamples = 100\n", - "x = np.random.randn(nsamples)\n", - "y = 3*x**2 + np.random.randn(nsamples)\n", - "\n", - "## Cross-validation on Ridge regression using KFold only\n", - "\n", - "# Decide degree on polynomial to fit\n", - "poly = PolynomialFeatures(degree = 6)\n", - "\n", - "# Decide which values of lambda to use\n", - "nlambdas = 500\n", - "lambdas = np.logspace(-3, 5, nlambdas)\n", - "\n", - "# Initialize a KFold instance\n", - "k = 5\n", - "kfold = KFold(n_splits = k)\n", - "\n", - "# Perform the cross-validation to estimate MSE\n", - "scores_KFold = np.zeros((nlambdas, k))\n", - "\n", - "i = 0\n", - "for lmb in lambdas:\n", - " ridge = Ridge(alpha = lmb)\n", - " j = 0\n", - " for train_inds, test_inds in kfold.split(x):\n", - " xtrain = x[train_inds]\n", - " ytrain = y[train_inds]\n", - "\n", - " xtest = x[test_inds]\n", - " ytest = y[test_inds]\n", - "\n", - " Xtrain = poly.fit_transform(xtrain[:, np.newaxis])\n", - " ridge.fit(Xtrain, ytrain[:, np.newaxis])\n", - "\n", - " Xtest = poly.fit_transform(xtest[:, np.newaxis])\n", - " ypred = ridge.predict(Xtest)\n", - "\n", - " scores_KFold[i,j] = np.sum((ypred - ytest[:, np.newaxis])**2)/np.size(ypred)\n", - "\n", - " j += 1\n", - " i += 1\n", - "\n", - "\n", - "estimated_mse_KFold = np.mean(scores_KFold, axis = 1)\n", - "\n", - "## Cross-validation using cross_val_score from sklearn along with KFold\n", - "\n", - "# kfold is an instance initialized above as:\n", - "# kfold = KFold(n_splits = k)\n", - "\n", - "estimated_mse_sklearn = np.zeros(nlambdas)\n", - "i = 0\n", - "for lmb in lambdas:\n", - " ridge = Ridge(alpha = lmb)\n", - "\n", - " X = poly.fit_transform(x[:, np.newaxis])\n", - " estimated_mse_folds = cross_val_score(ridge, X, y[:, np.newaxis], scoring='neg_mean_squared_error', cv=kfold)\n", - "\n", - " # cross_val_score return an array containing the estimated negative mse for every fold.\n", - " # we have to the the mean of every array in order to get an estimate of the mse of the model\n", - " estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds)\n", - "\n", - " i += 1\n", - "\n", - "## Plot and compare the slightly different ways to perform cross-validation\n", - "\n", - "plt.figure()\n", - "\n", - "plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score')\n", - "plt.plot(np.log10(lambdas), estimated_mse_KFold, 'r--', label = 'KFold')\n", - "\n", - "plt.xlabel('log10(lambda)')\n", - "plt.ylabel('mse')\n", - "\n", - "plt.legend()\n", - "\n", - "plt.show()" - ] - }, { "cell_type": "markdown", "metadata": {}, @@ -1517,6 +1327,203 @@ "plt.show()" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "## Various steps in cross-validation\n", + "\n", + "When the repetitive splitting of the data set is done randomly,\n", + "samples may accidently end up in a fast majority of the splits in\n", + "either training or test set. Such samples may have an unbalanced\n", + "influence on either model building or prediction evaluation. To avoid\n", + "this $k$-fold cross-validation structures the data splitting. The\n", + "samples are divided into $k$ more or less equally sized exhaustive and\n", + "mutually exclusive subsets. In turn (at each split) one of these\n", + "subsets plays the role of the test set while the union of the\n", + "remaining subsets constitutes the training set. Such a splitting\n", + "warrants a balanced representation of each sample in both training and\n", + "test set over the splits. Still the division into the $k$ subsets\n", + "involves a degree of randomness. This may be fully excluded when\n", + "choosing $k=n$. This particular case is referred to as leave-one-out\n", + "cross-validation (LOOCV). \n", + "\n", + "\n", + "## How to set up the cross-validation for Ridge and/or Lasso\n", + "\n", + "* Define a range of interest for the penalty parameter.\n", + "\n", + "* Divide the data set into training and test set comprising samples $\\{1, \\ldots, n\\} \\setminus i$ and $\\{ i \\}$, respectively.\n", + "\n", + "* 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" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\begin{align*}\n", + "\\boldsymbol{\\beta}_{-i}(\\lambda) & = ( \\boldsymbol{X}_{-i, \\ast}^{T}\n", + "\\boldsymbol{X}_{-i, \\ast} + \\lambda \\boldsymbol{I}_{pp})^{-1}\n", + "\\boldsymbol{X}_{-i, \\ast}^{T} \\boldsymbol{y}_{-i}\n", + "\\end{align*}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "* Evaluate the prediction performance of these models on the test set by $\\log\\{L[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.\n", + "\n", + "* Repeat the first three steps such that each sample plays the role of the test set once.\n", + "\n", + "* 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. It is defined as" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "$$\n", + "\\begin{align*}\n", + "\\frac{1}{n} \\sum_{i = 1}^n \\log\\{L[y_i, \\mathbf{X}_{i, \\ast}; \\boldsymbol{\\beta}_{-i}(\\lambda), \\boldsymbol{\\sigma}_{-i}^2(\\lambda)]\\}.\n", + "\\end{align*}\n", + "$$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Cross-validation in brief\n", + "\n", + "For the various values of $k$\n", + "\n", + "1. shuffle the dataset randomly.\n", + "\n", + "2. Split the dataset into $k$ groups.\n", + "\n", + "3. For each unique group:\n", + "\n", + "a. Decide which group to use as set for test data\n", + "\n", + "b. Take the remaining groups as a training data set\n", + "\n", + "c. Fit a model on the training set and evaluate it on the test set\n", + "\n", + "d. Retain the evaluation score and discard the model\n", + "\n", + "\n", + "5. Summarize the model using the sample of model evaluation scores\n", + "\n", + "## Code Example for Cross-validation and $k$-fold Cross-validation\n", + "\n", + "The code here uses Ridge regression with cross-validation (CV) resampling and $k$-fold CV in order to fit a specific polynomial." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false, + "editable": true + }, + "outputs": [], + "source": [ + "import numpy as np\n", + "import matplotlib.pyplot as plt\n", + "from sklearn.model_selection import KFold\n", + "from sklearn.linear_model import Ridge\n", + "from sklearn.model_selection import cross_val_score\n", + "from sklearn.preprocessing import PolynomialFeatures\n", + "\n", + "# A seed just to ensure that the random numbers are the same for every run.\n", + "# Useful for eventual debugging.\n", + "np.random.seed(3155)\n", + "\n", + "# Generate the data.\n", + "nsamples = 100\n", + "x = np.random.randn(nsamples)\n", + "y = 3*x**2 + np.random.randn(nsamples)\n", + "\n", + "## Cross-validation on Ridge regression using KFold only\n", + "\n", + "# Decide degree on polynomial to fit\n", + "poly = PolynomialFeatures(degree = 6)\n", + "\n", + "# Decide which values of lambda to use\n", + "nlambdas = 500\n", + "lambdas = np.logspace(-3, 5, nlambdas)\n", + "\n", + "# Initialize a KFold instance\n", + "k = 5\n", + "kfold = KFold(n_splits = k)\n", + "\n", + "# Perform the cross-validation to estimate MSE\n", + "scores_KFold = np.zeros((nlambdas, k))\n", + "\n", + "i = 0\n", + "for lmb in lambdas:\n", + " ridge = Ridge(alpha = lmb)\n", + " j = 0\n", + " for train_inds, test_inds in kfold.split(x):\n", + " xtrain = x[train_inds]\n", + " ytrain = y[train_inds]\n", + "\n", + " xtest = x[test_inds]\n", + " ytest = y[test_inds]\n", + "\n", + " Xtrain = poly.fit_transform(xtrain[:, np.newaxis])\n", + " ridge.fit(Xtrain, ytrain[:, np.newaxis])\n", + "\n", + " Xtest = poly.fit_transform(xtest[:, np.newaxis])\n", + " ypred = ridge.predict(Xtest)\n", + "\n", + " scores_KFold[i,j] = np.sum((ypred - ytest[:, np.newaxis])**2)/np.size(ypred)\n", + "\n", + " j += 1\n", + " i += 1\n", + "\n", + "\n", + "estimated_mse_KFold = np.mean(scores_KFold, axis = 1)\n", + "\n", + "## Cross-validation using cross_val_score from sklearn along with KFold\n", + "\n", + "# kfold is an instance initialized above as:\n", + "# kfold = KFold(n_splits = k)\n", + "\n", + "estimated_mse_sklearn = np.zeros(nlambdas)\n", + "i = 0\n", + "for lmb in lambdas:\n", + " ridge = Ridge(alpha = lmb)\n", + "\n", + " X = poly.fit_transform(x[:, np.newaxis])\n", + " estimated_mse_folds = cross_val_score(ridge, X, y[:, np.newaxis], scoring='neg_mean_squared_error', cv=kfold)\n", + "\n", + " # cross_val_score return an array containing the estimated negative mse for every fold.\n", + " # we have to the the mean of every array in order to get an estimate of the mse of the model\n", + " estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds)\n", + "\n", + " i += 1\n", + "\n", + "## Plot and compare the slightly different ways to perform cross-validation\n", + "\n", + "plt.figure()\n", + "\n", + "plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score')\n", + "plt.plot(np.log10(lambdas), estimated_mse_KFold, 'r--', label = 'KFold')\n", + "\n", + "plt.xlabel('log10(lambda)')\n", + "plt.ylabel('mse')\n", + "\n", + "plt.legend()\n", + "\n", + "plt.show()" + ] + }, { "cell_type": "markdown", "metadata": {}, diff --git a/doc/src/week37/week37.do.txt b/doc/src/week37/week37.do.txt index 2d818b100..e139db917 100644 --- a/doc/src/week37/week37.do.txt +++ b/doc/src/week37/week37.do.txt @@ -8,6 +8,12 @@ DATE: today * Thursday September 16: Summary of Ridge and Lasso with examples and start resampling techniques * Friday September 17: Resampling methods, Cross-validation, Bootstrapping and jackknife +Recommended Reading: +o Lectures on Resampling methods (these lectures) +o Bishop 1.3 (cross-validation) and 3.2 (bias-variance tradeoff) +o Hastie et al Chapter 7, here we recommend 7.1-7.5 and 7.10 (cross-validation) and 7.11 (bootstrap). This chapter is better than Bishop's on these topics. Goodfellow et al discuss this in a superficial way in sections 5.2-5.5. + + !split ===== Thursday September 16, Summary of Ridge and Lasso Regression and start Resampling methods ===== @@ -691,165 +697,6 @@ plt.show() !ec -!split -===== Various steps in cross-validation ===== - -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). - -!split -===== How to set up the cross-validation for Ridge and/or Lasso ===== - -* Define a range of interest for the penalty parameter. - -* Divide the data set into training and test set comprising samples $\{1, \ldots, n\} \setminus i$ and $\{ i \}$, respectively. - -* 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 $\bm{\sigma}_{-i}^2(\lambda)$, as -!bt -\begin{align*} -\bm{\beta}_{-i}(\lambda) & = ( \bm{X}_{-i, \ast}^{T} -\bm{X}_{-i, \ast} + \lambda \bm{I}_{pp})^{-1} -\bm{X}_{-i, \ast}^{T} \bm{y}_{-i} -\end{align*} -!et - -* Evaluate the prediction performance of these models on the test set by $\log\{L[y_i, \bm{X}_{i, \ast}; \bm{\beta}_{-i}(\lambda), \bm{\sigma}_{-i}^2(\lambda)]\}$. Or, by the prediction error $|y_i - \bm{X}_{i, \ast} \bm{\beta}_{-i}(\lambda)|$, the relative error, the error squared or the R2 score function. - -* Repeat the first three steps such that each sample plays the role of the test set once. - -* 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. It is defined as -!bt -\begin{align*} -\frac{1}{n} \sum_{i = 1}^n \log\{L[y_i, \mathbf{X}_{i, \ast}; \bm{\beta}_{-i}(\lambda), \bm{\sigma}_{-i}^2(\lambda)]\}. -\end{align*} -!et - -!split -===== Cross-validation in brief ===== - -For the various values of $k$ - -o shuffle the dataset randomly. -o Split the dataset into $k$ groups. -o For each unique group: - o Decide which group to use as set for test data - o Take the remaining groups as a training data set - o Fit a model on the training set and evaluate it on the test set - o Retain the evaluation score and discard the model -o Summarize the model using the sample of model evaluation scores - - - -!split -===== Code Example for Cross-validation and $k$-fold Cross-validation ===== - -The code here uses Ridge regression with cross-validation (CV) resampling and $k$-fold CV in order to fit a specific polynomial. -!bc pycod -import numpy as np -import matplotlib.pyplot as plt -from sklearn.model_selection import KFold -from sklearn.linear_model import Ridge -from sklearn.model_selection import cross_val_score -from sklearn.preprocessing import PolynomialFeatures - -# A seed just to ensure that the random numbers are the same for every run. -# Useful for eventual debugging. -np.random.seed(3155) - -# Generate the data. -nsamples = 100 -x = np.random.randn(nsamples) -y = 3*x**2 + np.random.randn(nsamples) - -## Cross-validation on Ridge regression using KFold only - -# Decide degree on polynomial to fit -poly = PolynomialFeatures(degree = 6) - -# Decide which values of lambda to use -nlambdas = 500 -lambdas = np.logspace(-3, 5, nlambdas) - -# Initialize a KFold instance -k = 5 -kfold = KFold(n_splits = k) - -# Perform the cross-validation to estimate MSE -scores_KFold = np.zeros((nlambdas, k)) - -i = 0 -for lmb in lambdas: - ridge = Ridge(alpha = lmb) - j = 0 - for train_inds, test_inds in kfold.split(x): - xtrain = x[train_inds] - ytrain = y[train_inds] - - xtest = x[test_inds] - ytest = y[test_inds] - - Xtrain = poly.fit_transform(xtrain[:, np.newaxis]) - ridge.fit(Xtrain, ytrain[:, np.newaxis]) - - Xtest = poly.fit_transform(xtest[:, np.newaxis]) - ypred = ridge.predict(Xtest) - - scores_KFold[i,j] = np.sum((ypred - ytest[:, np.newaxis])**2)/np.size(ypred) - - j += 1 - i += 1 - - -estimated_mse_KFold = np.mean(scores_KFold, axis = 1) - -## Cross-validation using cross_val_score from sklearn along with KFold - -# kfold is an instance initialized above as: -# kfold = KFold(n_splits = k) - -estimated_mse_sklearn = np.zeros(nlambdas) -i = 0 -for lmb in lambdas: - ridge = Ridge(alpha = lmb) - - X = poly.fit_transform(x[:, np.newaxis]) - estimated_mse_folds = cross_val_score(ridge, X, y[:, np.newaxis], scoring='neg_mean_squared_error', cv=kfold) - - # cross_val_score return an array containing the estimated negative mse for every fold. - # we have to the the mean of every array in order to get an estimate of the mse of the model - estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds) - - i += 1 - -## Plot and compare the slightly different ways to perform cross-validation - -plt.figure() - -plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score') -plt.plot(np.log10(lambdas), estimated_mse_KFold, 'r--', label = 'KFold') - -plt.xlabel('log10(lambda)') -plt.ylabel('mse') - -plt.legend() - -plt.show() - -!ec - - !split ===== The bias-variance tradeoff ===== @@ -1151,6 +998,168 @@ plt.show() !ec + + +!split +===== Various steps in cross-validation ===== + +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). + +!split +===== How to set up the cross-validation for Ridge and/or Lasso ===== + +* Define a range of interest for the penalty parameter. + +* Divide the data set into training and test set comprising samples $\{1, \ldots, n\} \setminus i$ and $\{ i \}$, respectively. + +* 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 $\bm{\sigma}_{-i}^2(\lambda)$, as +!bt +\begin{align*} +\bm{\beta}_{-i}(\lambda) & = ( \bm{X}_{-i, \ast}^{T} +\bm{X}_{-i, \ast} + \lambda \bm{I}_{pp})^{-1} +\bm{X}_{-i, \ast}^{T} \bm{y}_{-i} +\end{align*} +!et + +* Evaluate the prediction performance of these models on the test set by $\log\{L[y_i, \bm{X}_{i, \ast}; \bm{\beta}_{-i}(\lambda), \bm{\sigma}_{-i}^2(\lambda)]\}$. Or, by the prediction error $|y_i - \bm{X}_{i, \ast} \bm{\beta}_{-i}(\lambda)|$, the relative error, the error squared or the R2 score function. + +* Repeat the first three steps such that each sample plays the role of the test set once. + +* 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. It is defined as +!bt +\begin{align*} +\frac{1}{n} \sum_{i = 1}^n \log\{L[y_i, \mathbf{X}_{i, \ast}; \bm{\beta}_{-i}(\lambda), \bm{\sigma}_{-i}^2(\lambda)]\}. +\end{align*} +!et + +!split +===== Cross-validation in brief ===== + +For the various values of $k$ + +o shuffle the dataset randomly. +o Split the dataset into $k$ groups. +o For each unique group: + o Decide which group to use as set for test data + o Take the remaining groups as a training data set + o Fit a model on the training set and evaluate it on the test set + o Retain the evaluation score and discard the model +o Summarize the model using the sample of model evaluation scores + + + +!split +===== Code Example for Cross-validation and $k$-fold Cross-validation ===== + +The code here uses Ridge regression with cross-validation (CV) resampling and $k$-fold CV in order to fit a specific polynomial. +!bc pycod +import numpy as np +import matplotlib.pyplot as plt +from sklearn.model_selection import KFold +from sklearn.linear_model import Ridge +from sklearn.model_selection import cross_val_score +from sklearn.preprocessing import PolynomialFeatures + +# A seed just to ensure that the random numbers are the same for every run. +# Useful for eventual debugging. +np.random.seed(3155) + +# Generate the data. +nsamples = 100 +x = np.random.randn(nsamples) +y = 3*x**2 + np.random.randn(nsamples) + +## Cross-validation on Ridge regression using KFold only + +# Decide degree on polynomial to fit +poly = PolynomialFeatures(degree = 6) + +# Decide which values of lambda to use +nlambdas = 500 +lambdas = np.logspace(-3, 5, nlambdas) + +# Initialize a KFold instance +k = 5 +kfold = KFold(n_splits = k) + +# Perform the cross-validation to estimate MSE +scores_KFold = np.zeros((nlambdas, k)) + +i = 0 +for lmb in lambdas: + ridge = Ridge(alpha = lmb) + j = 0 + for train_inds, test_inds in kfold.split(x): + xtrain = x[train_inds] + ytrain = y[train_inds] + + xtest = x[test_inds] + ytest = y[test_inds] + + Xtrain = poly.fit_transform(xtrain[:, np.newaxis]) + ridge.fit(Xtrain, ytrain[:, np.newaxis]) + + Xtest = poly.fit_transform(xtest[:, np.newaxis]) + ypred = ridge.predict(Xtest) + + scores_KFold[i,j] = np.sum((ypred - ytest[:, np.newaxis])**2)/np.size(ypred) + + j += 1 + i += 1 + + +estimated_mse_KFold = np.mean(scores_KFold, axis = 1) + +## Cross-validation using cross_val_score from sklearn along with KFold + +# kfold is an instance initialized above as: +# kfold = KFold(n_splits = k) + +estimated_mse_sklearn = np.zeros(nlambdas) +i = 0 +for lmb in lambdas: + ridge = Ridge(alpha = lmb) + + X = poly.fit_transform(x[:, np.newaxis]) + estimated_mse_folds = cross_val_score(ridge, X, y[:, np.newaxis], scoring='neg_mean_squared_error', cv=kfold) + + # cross_val_score return an array containing the estimated negative mse for every fold. + # we have to the the mean of every array in order to get an estimate of the mse of the model + estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds) + + i += 1 + +## Plot and compare the slightly different ways to perform cross-validation + +plt.figure() + +plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score') +plt.plot(np.log10(lambdas), estimated_mse_KFold, 'r--', label = 'KFold') + +plt.xlabel('log10(lambda)') +plt.ylabel('mse') + +plt.legend() + +plt.show() + +!ec + + + !split ===== More examples on bootstrap and cross-validation and errors =====