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}")
相关推荐
F_D_Z1 小时前
Stacked Generalization 堆叠泛化
人工智能·机器学习·集成学习·stacking
BB学长2 小时前
LBM vs FVM:谁才是 CFD 的未来?
人工智能·算法·机器学习
智能交通技术2 小时前
iTSTech:自动驾驶、无人机与机器人在物流中的协同应用场景分析 2026
人工智能·机器学习·机器人·自动驾驶·无人机
Learn Beyond Limits2 小时前
循环神经网络的问题:梯度消失与梯度爆炸|Problems with RNNs: Vanishing and Exploding Gradients
人工智能·rnn·深度学习·神经网络·机器学习·自然语言处理·nlp
哥布林学者2 小时前
高光谱成像(十一)异常检测算法 RX 与 KRX
机器学习·高光谱成像
wáng bēn3 小时前
2025 AI 打卡 Day5:Seaborn 数据可视化基础(Matplotlib 升级版 + Titanic 真实业务全案例 + 完整参数调优)
人工智能·机器学习·信息可视化·matplotlib·seaborn
纤纡.4 小时前
Python 实战:基于朴素贝叶斯的苏宁易购评价情感分析
开发语言·python·机器学习
Alsian4 小时前
Day45 神经网络调参
深度学习·神经网络·机器学习
Yeats_Liao4 小时前
OpenClaw(二):配置教程
大数据·网络·人工智能·深度学习·机器学习
ComputerInBook6 小时前
几何学基本概念——超平面(hyperplane)
算法·机器学习·平面·几何学