The user wants a program that implements cross-validation for model evaluation.
I need to decide on the language and the library. Python with scikit-learn is the standard for this.
I should provide a clear, complete, and runnable example.
Key components of the program:
- Data Generation/Loading: I need a dataset to work with. Using
scikit-learn's built-in datasets (like Iris or the Breast Cancer dataset) is best for a standalone example.
- Model Selection: A standard classifier is needed.
RandomForestClassifier or LogisticRegression are good choices. Let's go with RandomForest for robustness.
- Cross-Validation Strategy:
- K-Fold: The most common.
- Stratified K-Fold: Better for classification to handle class imbalance.
- Evaluation Metrics: Accuracy is standard, but showing Precision, Recall, and F1-score adds value.
- Implementation details:
- Import necessary libraries.
- Load data.
- Initialize the model.
- Perform CV using
cross_val_score (simple) and cross_validate (more detailed).
- Print the results.
Structure of the response:
- Introduction: Briefly explain what cross-validation is and why it's used.
- Code Example: The Python script.
- Step 1: Imports.
- Step 2: Data loading.
- Step 3: Model definition.
- Step 4: Execution of CV.
- Step 5: Reporting.
- Explanation: Break down the code parts.
- Advanced Section (Optional but good): Mentioning custom loops (using
StratifiedKFold manually) is helpful for understanding what's happening under the hood or for complex preprocessing steps.
Refining the Code:
I will provide two versions:
- The "Quick & Easy" way: Using
cross_validate. This is what 90% of users want.
- The "Under the Hood" way: Using a manual
KFold loop. This shows how to handle data splitting manually, which is crucial if preprocessing (like scaling) needs to happen inside the training fold to prevent data leakage.
Drafting the Code (Mental or Scratchpad):
Version 1 (Standard):
from sklearn.model_selection import cross_validate
from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import load_iris
data = load_iris()
X, y = data.data, data.target
model = RandomForestClassifier()
scoring = ['accuracy', 'precision_macro', 'recall_macro']
results = cross_validate(model, X, y, cv=5, scoring=scoring)
# print results
Version 2 (Manual Loop - good for explaining the logic):
from sklearn.model_selection import StratifiedKFold
# ... imports ...
skf = StratifiedKFold(n_splits=5)
for train_index, test_index in skf.split(X, y):
# split data
# train
# score
I will stick to the "Standard" approach as the primary answer because it's the best practice, but I'll add a note about data leakage and pipelines, as that's a common pitfall in CV.
Final Plan:
- Prerequisites: Mention
scikit-learn, pandas, numpy.
- Main Script: A complete Python script using
cross_validate on the Iris dataset. It will calculate multiple metrics (Accuracy, F1, etc.).
- Detailed Explanation: Explain
cv, scoring, and the output dictionary.
- Manual Implementation (Bonus): Show how to write the loop manually using
StratifiedKFold for educational purposes or specific control.
Let's write the response.
Here is a complete Python program using the Scikit-Learn library, which is the industry standard for this type of task.
I have provided two approaches:
- The Standard Approach: Using the built-in
cross_validate function (best for quick evaluation).
- The Manual Approach: Using a loop to control the splits (best for understanding the logic or custom preprocessing).
Prerequisites
You will need scikit-learn installed:
pip install scikit-learn pandas numpy
Python Program
import numpy as np
import pandas as pd
from sklearn.datasets import load_iris
from sklearn.model_selection import cross_validate, StratifiedKFold
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline
from sklearn.ensemble import RandomForestClassifier
def run_cross_validation():
# 1. Load Dataset
# We use the Iris dataset, but you can load your own via pd.read_csv()
data = load_iris()
X = data.data
y = data.target
# 2. Define the Model
# We use a Random Forest, but this could be Logistic Regression, SVM, etc.
model = RandomForestClassifier(n_estimators=50, random_state=42)
# 3. Define the Cross-Validation Strategy
# StratifiedKFold ensures that each fold has the same proportion of class labels.
# K=5 means we split the data into 5 parts (Train on 4, Test on 1, repeat 5 times).
cv_strategy = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
# 4. Define Metrics
# We want to measure Accuracy and the F1-Score (weighted handles multi-class)
scoring_metrics = ['accuracy', 'f1_weighted']
print("Starting 5-Fold Cross-Validation...")
# 5. Run Cross-Validation
# We use a Pipeline here to scale data *inside* the CV loop.
# This prevents "data leakage" (using test data stats to scale training data).
pipeline = make_pipeline(StandardScaler(), model)
results = cross_validate(
estimator=pipeline,
X=X,
y=y,
cv=cv_strategy,
scoring=scoring_metrics,
return_train_score=True # Optional: Check for overfitting
)
# 6. Display Results
results_df = pd.DataFrame(results)
print("\n--- Individual Fold Results ---")
print(results_df[['test_accuracy', 'test_f1_weighted']])
print("\n--- Aggregate Statistics ---")
print(f"Mean Accuracy: {results_df['test_accuracy'].mean():.4f}")
print(f"Std Deviation: {results_df['test_accuracy'].std():.4f}")
print(f"Mean F1 Score: {results_df['test_f1_weighted'].mean():.4f}")
if __name__ == "__main__":
run_cross_validation()
How It Works
StratifiedKFold: This splits your data into K parts (folds).
- It shuffles the data first (
shuffle=True).
- It ensures the "Stratification" part: if your dataset is 80% Class A and 20% Class B, every single fold will maintain that 80/20 ratio. This is crucial for imbalanced datasets.
make_pipeline: We wrap the scaler and the model together.
- Why? If you scale your data before splitting, the mean and standard deviation of the test set leaks into your training set. The pipeline ensures the scaler is fit only on the training portion of the specific fold it is processing.
cross_validate: This automates the process:
- Split data into Train/Test.
- Fit the pipeline on Train.
- Score on Test.
- Repeat 5 times.
Manual Implementation (For Learning)
If you want to see exactly how the loop works under the hood without the helper function, here is the logic:
from sklearn.datasets import load_iris
from sklearn.model_selection import StratifiedKFold
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
import numpy as np
data = load_iris()
X, y = data.data, data.target
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
model = RandomForestClassifier(random_state=42)
scores = []
# The split() method generates the indices for train and test sets
for fold_number, (train_idx, test_idx) in enumerate(cv.split(X, y), 1):
X_train, X_test = X[train_idx], X[test_idx]
y_train, y_test = y[train_idx], y[test_idx]
# Train
model.fit(X_train, y_train)
# Predict
preds = model.predict(X_test)
# Evaluate
acc = accuracy_score(y_test, preds)
scores.append(acc)
print(f"Fold {fold_number}: Accuracy = {acc:.4f}")
print(f"\nFinal Mean Accuracy: {np.mean(scores):.4f}")