Machine Learning for Beginners in Python: How to do Nested Cross Validation

Nested Cross Validation

Often we want to tune the parameters of a model (for example, C in a support vector machine). That is, we want to find the value of a parameter that minimizes our loss function. The best way to do this is cross validation:

  1. Set the parameter you want to tune to some value.
  2. Split your data into K ‘folds’ (sections).
  3. Train your model using K-1 folds using the parameter value.
  4. Test your model on the remaining fold.
  5. Repeat steps 3 and 4 so that every fold is the test data once.
  6. Repeat steps 1 to 5 for every possible value of the parameter.
  7. Report the parameter that produced the best result.


/* Load required packages */
from sklearn import datasets
from sklearn.model_selection import GridSearchCV, cross_val_score
from sklearn.preprocessing import StandardScaler
import numpy as np
from sklearn.svm import SVC

Get Data

The data for this tutorial is beast cancer data with 30 features and a binary target variable.

/* Load the data */
dataset = datasets.load_breast_cancer()

/* Create X from the features */
X =

/* Create y from the target */
y =

Standardize Data

/* Create a scaler object */
sc = StandardScaler()

/* Fit the scaler to the feature data and transform */
X_std = sc.fit_transform(X)

Create Inner Cross Validation (For Parameter Tuning)

This is our inner cross validation. We will use this to hunt for the best parameters for C, the penalty for misclassifying a data point. GridSearchCV will conduct steps 1-6 listed at the top of this tutorial.

/* Create a list of 10 candidate values for the C parameter */
C_candidates = dict(C=np.logspace(-4, 4, 10))

/* Create a gridsearch object with the support vector classifier and the C value candidates */
clf = GridSearchCV(estimator=SVC(), param_grid=C_candidates)

The code below isn’t necessary for parameter tuning using nested cross validation, however to demonstrate that our inner cross validation grid search can find the best value for the parameter C, we will run it once here:

/* Fit the cross validated grid search on the data  */, y)

/* Show the best value for C */

Create Outer Cross Validation (For Model Evaluation)

With our inner cross validation constructed, we can use cross_val_score to evaluate the model with a second (outer) cross validation.

The code below splits the data into three folds, running the inner cross validation on two of the folds (merged together) and then evaluating the model on the third fold. This is repeated three times so that every fold is used for testing once.

cross_val_score(clf, X_std, y)
array([ 0.94736842,  0.97894737,  0.98412698])

Each the values above is an unbiased evaluation of the model’s accuracy, once for each of the three test folds. Averaged together, they would represent the average accuracy of the model found in the inner cross validated grid search.



Python Example for Beginners

Two Machine Learning Fields

There are two sides to machine learning:

  • Practical Machine Learning:This is about querying databases, cleaning data, writing scripts to transform data and gluing algorithm and libraries together and writing custom code to squeeze reliable answers from data to satisfy difficult and ill defined questions. It’s the mess of reality.
  • Theoretical Machine Learning: This is about math and abstraction and idealized scenarios and limits and beauty and informing what is possible. It is a whole lot neater and cleaner and removed from the mess of reality.

Data Science Resources: Data Science Recipes and Applied Machine Learning Recipes

Introduction to Applied Machine Learning & Data Science for Beginners, Business Analysts, Students, Researchers and Freelancers with Python & R Codes @ Western Australian Center for Applied Machine Learning & Data Science (WACAMLDS) !!!

Latest end-to-end Learn by Coding Recipes in Project-Based Learning:

Applied Statistics with R for Beginners and Business Professionals

Data Science and Machine Learning Projects in Python: Tabular Data Analytics

Data Science and Machine Learning Projects in R: Tabular Data Analytics

Python Machine Learning & Data Science Recipes: Learn by Coding

R Machine Learning & Data Science Recipes: Learn by Coding

Comparing Different Machine Learning Algorithms in Python for Classification (FREE)

Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.  

Google –> SETScholars

A list of Python, R and SQL Codes for Applied Machine Learning and Data  Science at by Coding Categories:

  1. Classification:
  2. Data Analytics:
  3. Data Science:
  4. Data Visualisation:
  5. Machine Learning Recipe:
  6. Pandas:
  7. Python:
  9. Supervised Learning:
  10. Tabular Data Analytics:
  11. End-to-End Data Science Recipes:
  12. Applied Statistics:
  13. Bagging Ensemble:
  14. Boosting Ensemble:
  15. CatBoost:
  16. Clustering:
  17. Data Analytics:
  18. Data Science:
  19. Data Visualisation:
  20. Decision Tree:
  21. LightGBM:
  22. Machine Learning Recipe:
  23. Multi-Class Classification:
  24. Neural Networks:
  25. Python Machine Learning:
  26. Python Machine Learning Crash Course:
  27. R Classification:
  28. R for Beginners:
  29. R for Business Analytics:
  30. R for Data Science:
  31. R for Data Visualisation:
  32. R for Excel Users:
  33. R Machine Learning:
  34. R Machine Learning Crash Course:
  35. R Regression:
  36. Regression:
  37. XGBOOST:
  38. Excel examples for beginners:
  39. C Programming tutorials & examples:
  40. Javascript tutorials & examples:
  41. Python tutorials & examples:
  42. R tutorials & examples:
  43. SQL tutorials & examples:


( FREE downloadable Mathematics Worksheet for Kids )