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}")
相关推荐
郝学胜-神的一滴8 小时前
深度学习优化核心:梯度下降与网络训练全解析
数据结构·人工智能·python·深度学习·算法·机器学习
罗西的思考16 小时前
【GUI-Agent】阿里通义MAI-UI 代码阅读(1)— 总体
人工智能·机器学习·ui·transformer
薛定e的猫咪18 小时前
(AAMAS 2023)基于广义策略改进优先级的高效多目标学习 GPI - LS/PD
人工智能·学习·机器学习
沪漂阿龙18 小时前
机器学习面试超详细实战指南(2026版)——不懂高数也能看懂的硬核干货,建议从头看到尾
人工智能·机器学习·面试
JQLvopkk18 小时前
C# 工业级数据可视化:用ScottPlot让10万个点流畅显示的实战秘籍
人工智能·算法·机器学习
迁旭20 小时前
claude code 规划模式(Plan Mode)完整指南
人工智能·机器学习·文心一言·知识图谱
沪漂阿龙20 小时前
大模型为什么越来越“听话”?一文讲透强化学习、SFT、DPO
人工智能·机器学习
小白小宋21 小时前
从“被砍掉的频谱“到无码间串扰:升余弦滚降滤波器的完全解读
人工智能·算法·机器学习
Dfreedom.1 天前
【实战篇】分类任务全流程演示——决策树
人工智能·算法·决策树·机器学习·分类
2zcode1 天前
原创文档:基于MATLAB深度学习与传统机器学习的脑肿瘤MRI图像分类系统
深度学习·机器学习·分类