Imagine you have a small dataset and want to estimate how well your machine learning model will perform on new data. Why is K-fold cross-validation a better choice than a single train-test split?
Think about how using all data for testing at some point helps get a fair estimate.
K-fold cross-validation splits data into K parts and uses each part once as test data while training on the rest. This way, every data point is tested exactly once, giving a less biased and more reliable estimate of model performance than a single train-test split.
What will be the output of the following Python code that uses KFold from scikit-learn?
from sklearn.model_selection import KFold import numpy as np X = np.array([10, 20, 30, 40, 50]) kf = KFold(n_splits=2, shuffle=False) splits = [] for train_index, test_index in kf.split(X): splits.append((train_index.tolist(), test_index.tolist())) print(splits)
Remember KFold splits data into equal parts without shuffling by default.
KFold with n_splits=2 splits the array into two parts: first 2 elements and last 3 elements. The first fold uses indices [0,1] as test and [2,3,4] as train, and the second fold reverses this.
You have a dataset with 1000 samples. You want to use K-fold cross-validation to estimate model performance. Which choice of K balances bias and variance best?
Think about how increasing K affects bias and variance of the estimate.
Choosing K=5 or 10 is common because it balances bias and variance well. Too few folds (like 2) can give high bias, and too many folds (like leave-one-out) can have high variance and be computationally expensive.
You performed 4-fold cross-validation and got these accuracy scores for each fold: [0.82, 0.85, 0.80, 0.83]. What is the correct average accuracy to report?
Calculate the mean of the scores.
The average accuracy is the sum of all accuracies divided by the number of folds: (0.82 + 0.85 + 0.80 + 0.83) / 4 = 0.825.
Consider this Python code snippet using KFold. It raises an error. What is the cause?
from sklearn.model_selection import KFold import numpy as np X = np.array([1, 2, 3]) kf = KFold(n_splits=5) for train_index, test_index in kf.split(X): print('Train:', train_index, 'Test:', test_index)
Check the relationship between n_splits and dataset size.
KFold requires that n_splits be less than or equal to the number of samples. Here, n_splits=5 but only 3 samples exist, causing a ValueError.
