自然语言处理_样本处理_Stratified k-fold

Stratified k-fold
StratifiedKFold is a variation of k-fold which returns stratified folds: each set contains approximately the same percentage of samples of each target class as the complete set.

from sklearn.model_selection import StratifiedKFold, KFold
import numpy as np
X, y = np.ones((50, 1)), np.hstack(([0] * 45, [1] * 5))
skf = StratifiedKFold(n_splits=3)
for train, test in skf.split(X, y):
    print('train -  {}   |   test -  {}'.format(
        np.bincount(y[train]), np.bincount(y[test])))
kf = KFold(n_splits=3)
for train, test in kf.split(X, y):
    print('train -  {}   |   test -  {}'.format(
        np.bincount(y[train]), np.bincount(y[test])))

在这里插入图片描述

Stratified 表示分层,是在k折的基础上增加了分层的约束
简单理解是分层k折抽样
在这里插入图片描述

### Stratified K-Fold 交叉验证的定义 Stratified K-Fold 是 K-Fold 交叉验证的一种变体,专门用于**保持每个子集中类别分布与原始数据集一致**的场景。该方法在将数据划分为 K 个子集时,确保每个子集中的各类样本比例与整个数据集中保持一致。这种策略尤其适用于**类别不平衡的数据集**,以避免因某个子集中某一类样本过少或缺失而导致模型评估偏差。 相比之下,普通 K-Fold 交叉验证在划分数据时**不考虑类别分布**,只是将数据随机均分为 K 个子集。这种方式可能导致某些子集中某些类别样本数量过少,尤其在类别分布不均的情况下,容易影响模型评估的稳定性。 ### 区别分析 Stratified K-Fold 与普通 K-Fold 的主要区别体现在以下方面: - **类别分布控制**:Stratified K-Fold 在每次划分时都确保每个子集的类别分布与原始数据集一致,而普通 K-Fold 无法保证这一点[^3]。 - **适用场景**:Stratified K-Fold 更适合于类别不平衡问题,例如医学诊断、欺诈检测等需要对少数类进行准确预测的任务。普通 K-Fold 更适用于类别分布均衡或对类别比例不敏感的问题[^3]。 - **模型评估的稳定性**:由于类别分布更一致,Stratified K-Fold 往往能提供更稳定和可靠的模型性能评估结果,尤其是在小样本或类别不平衡数据中表现更优[^3]。 ### 示例代码:Stratified K-Fold 与普通 K-Fold 的对比实现 以下代码展示了如何使用 `scikit-learn` 实现 Stratified K-Fold 与普通 K-Fold 的划分: ```python from sklearn.model_selection import KFold, StratifiedKFold import numpy as np # 假设X为特征数据,y为类别标签(存在类别不平衡) X = np.random.rand(10, 2) y = np.array([0, 0, 0, 0, 0, 1, 1, 1, 1, 1]) # 普通 K-Fold kf = KFold(n_splits=3) print("普通 K-Fold 的划分:") for train_index, test_index in kf.split(X): print("Train:", train_index, "Test:", test_index) # Stratified K-Fold skf = StratifiedKFold(n_splits=3) print("\nStratified K-Fold 的划分:") for train_index, test_index in skf.split(X, y): print("Train:", train_index, "Test:", test_index) ``` ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值