What is Nested Cross Validation 🌱

Suppose we are given a dataset, a bunch of possible learners and hyperparameters, and we want to know what the best learner and hyperparameters are as well as an estimate for how well the best model (with best hyperparameters) will perform. The most common approach is to divide data into 3 sets: a training set, a validation set, and a testing set. We train all our models with their possible hyperparameters on the training set, select the model and hyperparameters that has the lowest error when predicting the outcomes on the validation set, and then estimate the performance of this model on the testing set. This approach works well. However, what if we don’t have a good way to split the data into these 3 sets without making a certain set biased or we have only a small amount of data that we don’t want to segment further into 3 separate classes. Another possible approach is to use nested cross validation.

Steps for Nested Cross Validation

  1. Divide the dataset into K cross-validation folds at random.
  2. Do the following for each fold k=1,2,…,K (this is the outer loop used for the evaluation of the model with selected hyperparameter)
    1. Set the testing set to be fold k
    2. Set all the data except those in fold k to be a set we will call trainval (composes both the training and validation sets)
    3. Randomly split trainval into L folds
    4. For each fold l=1,2,…,L (this is the inner loop used for hyperparameter tuning)
      1. Let the validation set be fold l
      2. Let training set be all the data except those in testing or validation
      3. Train with each hyperparameter on the training set, and evaluate it on the validation set. Keep track of the performance metrics.
    5. For each hyperparameter setting, calculate the average metrics score over the L folds, and choose the best hyperparameter setting.
    6. Train a model with the best hyperparameter on trainval. Evaluate its performance on the testing data and save the score for fold k.
  3. Calculate the mean score over all K folds, and report it as the generalization error.

Notes mentioning this note

There are no notes linking to this note.


Here are all the notes in this garden, along with their links, visualized as a graph.

5G and WiFiAWS Step FunctionsAnalyzing Reddit Post on the Dollar StandardAsync, Await, and PromisesBayesian AverageBias Variance DecompositionBlockchain PresentationBreakpoint Debugging in VSCodeBrief Look into Measure TheoryC4 Model for Software ArchitectureCache vs Session StoreCant compare mean and median from different setsClient vs Server Side RenderingCode Production in an AI CompanyComparing Client Side Storage MethodsComputational Perception HighlightsConfidence Intervals for Known Distributions and...Cool Stocks ListCrazy Meeting with Obama, McCain, and Bush Post...Curse of DimentionalityDatabase vs Data Warehouse vs Data LakeDifferent Git AddsDocker (containerization) vs Vagrant (virtual...Explaining Decision Boundary of a Support Vector...Exporting Databricks Files to GithubFloyds Tortoise and Hare AlgorithmFresh Mac Setup Installation EssentialsGraphical Model IndependenciesHighlights from Bad SamaritansHighlights from Good Economics for Hard TimesHighlights from The Righteous MindHow Does Chromosomal Heredity WorkHow Does Light Influence the Rate of Capture in a...How Does Sweating WorkHow Does Version Naming WorkHow Not To Be Wrong Excerpt Self Selecting BiasHow Not to be Wrong Excerpt Public Opinion Doesn't...How Quantum Computers Could Quickly Break...How Someone Made a Spectral Lamp that Can Emit all...How are images compressed and stored in a computerHow do SPACs WorkHow does Hypothesis Testing WorkHow does air slow objects downHow is Neural Network a Universal ApproximatorHow is Unit Testing DoneHow to Access a Previous Commit with GitHow to Add to Your System Path Variable for MacHow to Build a Full Stack ApplicationHow to Clear Unused Docker ContainersHow to Convert from Celsius to FahrenheitHow to Delete a Branch GithubHow to Export Pandas DataFrame to CSV ProperlyHow to Force Pull and Overwrite GitHow to Get the Bootstrapped Standard Error for a...How to handle violations in positivityHow to Properly Explain Technical ToolsHow to Push Code for ProductionHow to Read a Path in S3How to Set Up Python Aliasing In the Command LineHow to Set a Specific Branch to Track a Specific...How to Store and Access SQL Queries in DatabricksHow to Take a Weighted AverageHow to Temporarily Stash Changes with Git StashHow to Untrack Committed Files from GitHow to Use PyenvHow to Use Sample Splitting for Doubly Robust...How to Write Output to Text FileHow to edit Obsidian themes with CSSHow to make copies of DNA with PCRHow to use Bounds and Sensitivity Analysis in...How to use Scipy Optimize to solve for values when...Info on Stock OptionsInspirational Computer PioneersIntuition Behind the Doubly Robust EstimatorInverting Hypothesis TestsInvesting LessonsJupyter Widgets ExistML CheatsheetsMaking Sense of a Betting Market with...Managing Ruby Versions with rbenvMarket Makers and Quant TradingMarket Making PresentationMatching IntuitionMethodology for Managing Web AppsMicroservices vs Monolithic ArchitectureModeling Advice and Lessons Learned Working at a...Multinomial to Binomial Stick Breaking...Music Theory NotesNotes from Michael Nielsen Effective Research PostNotes from the Martian by Andy WeirNotes on Bayesian OptimizationNotes on Exon Skipping with ASOsNotes on Options SpreadsNotes on Quantum CountryOne Persons Perspective About Why We Shouldnt Read...Presentation on the Kronovet Family Clothing...Python Dataclasses UpdatePython Package Reference InstructionsRandom CMU Course WebpagesRandom Facts from What If by Randall MunroeReading about Internet ServicesRock Thrust ExplainedSSHing into AWS and Running ThingsSome Bash Commands to Find Redundant Files and...Some Cool Python FeaturesSome Notes on Exploding Gradient ProblemStats BlogsStock Options in a CompanyTesting Code on GithubThoughts after Reading Hillbilly ElegyThoughts on Andy Matuschak Article on Teaching...Thoughts on Approaching Infinite KnowledgeThoughts on Maria Konnikova Knowledge Project...Thoughts on the End of Natural SelectionTor Network and .Onion DomainsUsing nonparametric models in doubly robust...Various Treatment Effects and their...Virtual Environment in AWSWhat Database do I useWhat are Git Pull and Push RequestsWhat are Information CriteriaWhat are Javascript WorkersWhat are MakefilesWhat are Moment Generating FunctionsWhat are Multiple CPU CoresWhat are Progressive Web AppsWhat are Wasserstein and Earth Movers DistancesWhat are the Four Fundamental Forces in Our...What is Apache SparkWhat is Bootstrapping in StatisticsWhat is Cryptocurrency StakingWhat is ElasticsearchWhat is Express.jsWhat is GLUEWhat is GraphQLWhat is HTTPSWhat is IV CrushWhat is Integration ReallyJAMStackWhat is KubernetesWhat is Mahalanobis DistanceWhat is MakerDAO CryptoWhat is Markov Chain Monte Carlo SamplingWhat is Nested Cross ValidationWhat is Next.jsWhat is PAC LearningWhat is R SquaredWhat is RedisWhat is ShrinkageWhat is Spearman CorrelationWhat is SvelteWhat is TerraformWhat is The Graph (Blockchain)What is Variational InferenceWhat is Vue.jsWhat is WebAssemblyWhat is a Credible IntervalWhat is a Fourier transformWhat is a Gaussian Mixture ModelWhat is a Gaussian ProcessWhat is a Object Relational MapperWhat is a Qini CurveWhat is a Sufficient StatisticWhat is independent component analysisWhat is the C-Statistic for BenefitWhat is the Dirichlet ProcessWhat is the EM AlgorithmWhat is the Hidden Markov ModelWhat is the Indian Buffet ProcessWhat is the Naive Bayes algorithmWhat is the Negative Binomial DistributionWhat is the Runtime of a LanguageWhat is the Studentized BootstrapWhat is the Wake Sleep AlgorithmWhat is the hypergeometric distributionWhy are Conjugate Priors UsefulWhy are there 12 Notes in Western MusicWhy is Cross Fitting Useful for Estimating...Why is a room hotter when you leave the fridge...Working with ClientsWorking with Terminaldata science overviewhighlights from Debt The First 5000 Yearshighlights from Enlightenment Nowhighlights from Hacking Darwinhighlights from How Not to be Wronghighlights from Leonardo da Vincihighlights from Open an Autobiographyhighlights from Range Why Generalists Triumph in a...highlights from Salt, Fat, Acid, HeatSapiens a Brief History of Humankindhighlights from Stumbling on Happinesshighlights from The Genehighlights from Thinking Fast and Slowhighlights from Trick Mirror