Kaggle Intermediate ML Part Four——Cross-Validation

What is it?

Cross-validation is a technique used to evaluate the generalizability of a machine learning model. In simpler terms, it helps you understand how well your model will perform on unseen data, which is crucial for real-world applications.

Here's how it works:

  1. Split the data: Your original dataset is divided into folds (usually equally sized).
  2. Train-Test Split: In each fold, one fold is kept for testing (hold-out set), while the remaining folds are used for training the model.
  3. Evaluate and Repeat: The model is trained on the training data and evaluated on the hold-out set. This process is repeated for each fold, ensuring every data point is used for both training and testing.
  4. Combine and Analyze: The performance metrics (e.g., accuracy, precision, recall) from each fold are combined to get an overall estimate of the model's performance on unseen data.

Common Cross-Validation Techniques:

  • K-Fold Cross-validation: The data is split into k folds, and the training-testing process is repeated k times.
  • Stratified K-Fold: Similar to k-fold, but ensures each fold has a similar distribution of class labels (important for imbalanced datasets).
  • Leave-One-Out Cross-validation (LOOCV): Each data point is used as the testing set once, while all other points are used for training. This is computationally expensive for large datasets.

Production Use and Examples:

  • Model Selection: Compare different models and choose the one with the best cross-validation performance.
  • Hyperparameter Tuning: Optimize hyperparameters (model settings) by evaluating their impact on cross-validation performance.
  • Feature Selection: Identify and remove irrelevant or redundant features that may lead to overfitting.

python 复制代码
from sklearn.model_selection import KFold
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score

# Load the Iris dataset
iris = load_iris()
X = iris.data
y = iris.target

# Define the model
model = LogisticRegression()

# Define the K-Fold cross-validation strategy
kfold = KFold(n_splits=5, shuffle=True, random_state=42)

# Track performance metrics
auc_scores = []

# Iterate through each fold
for train_index, test_index in kfold.split(X):
    # Split data into training and testing sets
    X_train, X_test = X[train_index], X[test_index]
    y_train, y_test = y[train_index], y[test_index]

    # Train the model on the training data
    model.fit(X_train, y_train)

    # Make predictions on the testing data
    y_proba = model.predict_proba(X_test)[:, 1]  # Probability of positive class

    # Calculate AUC
    auc = roc_auc_score(y_test, y_proba)
    auc_scores.append(auc)

# Print the average AUC across all folds
print(f"Average AUC: {sum(auc_scores) / len(auc_scores):.2f}")
相关推荐
cxr82819 小时前
数学的本质:关系、模式与不变量的结构世界
人工智能·算法·机器学习
W_3260021 小时前
Python-OpenCV HSV颜色空间与inRange颜色分割:按颜色提取目标物体
图像处理·人工智能·python·opencv·机器学习
147API1 天前
蒸馏训练效果差,怎样判断问题是不是出在数据
人工智能·深度学习·机器学习
SomeB1oody1 天前
【RustyML入门】7.2. 深入模型持久化
开发语言·后端·机器学习·rust·教程
zhanghaha13141 天前
Python进阶教程:13_math 模块 —— 新手完全指南
数据库·python·机器学习
学学酱快乐1 天前
2026年PMP考试生命周期选择决策树精讲:从需求判断到混合型统一框架的应试全攻略
算法·决策树·机器学习·pmp新版考试大纲·pmp新题型·pmp培训哪家好·pmp培训机构推荐
Rocky Ding*1 天前
【三年面试五年模拟】2026-08-18_哔哩哔哩AI应用岗Agent开发一面面经全解析(含完整答案)
论文阅读·人工智能·深度学习·机器学习·aigc·ai-native·ai agent
呆萌很1 天前
Sigmoid 与 Tanh 激活函数(S 型饱和激活函数)
人工智能·深度学习·机器学习
Eric.461 天前
本地AI漫剧部署与稳定量产实操教程
人工智能·神经网络·机器学习
不可求~2 天前
用 AI 读论文别只看摘要:建立可追溯的证据链
人工智能·深度学习·机器学习