Cross-validation helps check how well a model will work on new data. It splits data into parts to test the model many times.
Cross-validation (K-fold) in ML Python
from sklearn.model_selection import KFold kf = KFold(n_splits=5, shuffle=True, random_state=42) for train_index, test_index in kf.split(X): X_train, X_test = X[train_index], X[test_index] y_train, y_test = y[train_index], y[test_index] # Train and test your model here
n_splits is how many parts to split the data into.
shuffle=True mixes data before splitting to get better random parts.
kf = KFold(n_splits=3) for train_idx, test_idx in kf.split(X): print("Train size:", len(train_idx), "Test size:", len(test_idx))
kf = KFold(n_splits=4, shuffle=True, random_state=1) for train_idx, test_idx in kf.split(X): print(train_idx, test_idx)
This program uses 5-fold cross-validation on the Iris dataset with logistic regression. It prints accuracy for each fold and the average accuracy.
from sklearn.datasets import load_iris from sklearn.model_selection import KFold from sklearn.linear_model import LogisticRegression from sklearn.metrics import accuracy_score import numpy as np # Load data iris = load_iris() X = iris.data y = iris.target # Prepare KFold kf = KFold(n_splits=5, shuffle=True, random_state=42) accuracies = [] for train_index, test_index in kf.split(X): X_train, X_test = X[train_index], X[test_index] y_train, y_test = y[train_index], y[test_index] # Create and train model model = LogisticRegression(max_iter=200) model.fit(X_train, y_train) # Predict and evaluate y_pred = model.predict(X_test) acc = accuracy_score(y_test, y_pred) accuracies.append(acc) # Print average accuracy print(f"Accuracies for each fold: {accuracies}") print(f"Average accuracy: {np.mean(accuracies):.3f}")
Using shuffle=True is important to get random splits, especially if data is ordered.
K-fold cross-validation gives a better idea of model performance than a single train-test split.
Higher n_splits means more training rounds but takes more time.
K-fold cross-validation splits data into parts to test model many times.
It helps check model's ability to work on new data.
Use it to get reliable performance and avoid overfitting.
Practice
K-fold cross-validation in machine learning?Solution
Step 1: Understand K-fold cross-validation concept
K-fold cross-validation splits the data into K parts and trains the model K times, each time using a different part as test data.Step 2: Identify the main goal
This process helps evaluate how well the model performs on unseen data by testing on different subsets.Final Answer:
To evaluate model performance on different subsets of data -> Option AQuick Check:
Cross-validation = model evaluation [OK]
- Thinking it increases training data size
- Confusing it with feature selection
- Assuming it speeds up training
Solution
Step 1: Recall the current scikit-learn module for KFold
KFold is part of themodel_selectionmodule in scikit-learn.Step 2: Check correct import syntax
The correct syntax isfrom sklearn.model_selection import KFold. Other options use outdated or incorrect modules or syntax.Final Answer:
from sklearn.model_selection import KFold -> Option CQuick Check:
Correct import = from sklearn.model_selection import KFold [OK]
- Using deprecated sklearn.cross_validation module
- Wrong import syntax like 'import KFold from ...'
- Confusing module names
from sklearn.model_selection import KFold
import numpy as np
X = np.array([10, 20, 30, 40, 50])
kf = KFold(n_splits=5)
for train_index, test_index in kf.split(X):
print(test_index)Solution
Step 1: Understand KFold with n_splits=5 on 5 elements
With 5 splits, each fold uses 4 elements for training and 1 element for testing.Step 2: Check test indices printed in each fold
Each fold's test index is a single element index from 0 to 4, printed one per line.Final Answer:
[0] [1] [2] [3] [4] -> Option DQuick Check:
Each fold tests one unique index [OK]
- Expecting multiple indices per test set
- Confusing train and test indices
- Misunderstanding KFold split behavior
from sklearn.model_selection import KFold
kf = KFold(n_splits=5)
X = [1, 2, 3, 4]
for train_idx, test_idx in kf.split(X):
print(train_idx, test_idx)Solution
Step 1: Check n_splits vs data size
n_splits=5 but X has only 4 samples (5 > 4).Step 2: Understand KFold requirement
KFold requires n_splits to be less than or equal to the number of samples, otherwise it raises a ValueError.Final Answer:
n_splits cannot be greater than the number of samples -> Option AQuick Check:
n_splits ≤ samples [OK]
- Using n_splits larger than dataset size
- Thinking list input causes error
- Swapping train and test indices
Solution
Step 1: Understand the trade-off between folds and training time
More folds mean more training rounds, increasing time. Reducing folds reduces training rounds.Step 2: Evaluate options for reducing training time
Using 5-fold halves the number of training rounds compared to 10-fold, still providing reliable evaluation.Step 3: Check other options
Using entire data without validation loses evaluation, shuffle=False doesn't reduce folds, ignoring folds loses reliability.Final Answer:
Use 5-fold cross-validation instead of 10-fold -> Option BQuick Check:
Fewer folds = faster training [OK]
- Skipping validation entirely
- Ignoring folds reduces reliability
- Thinking shuffle affects speed
Ready to prove it?
Pass the test and this pattern moves unknown
