scikit-learn中的随机分层k-fold交叉验证?

时间:2013-05-08 19:46:53

标签: python machine-learning scikit-learn cross-validation

是否有任何内置方法可以让scikit-learn进行改组分层k-fold交叉验证?这是最常见的CV方法之一,我很惊讶我找不到这样做的内置方法。

我看到cross_validation.KFold()有一个拖曳的旗帜,但它没有分层。很遗憾,cross_validation.StratifiedKFold()没有这样的选项,cross_validation.StratifiedShuffleSplit()不会产生不相交的折叠。

我错过了什么吗?这是计划好的吗?

(显然我可以自己实现)

4 个答案:

答案 0 :(得分:5)

cross_validation.StratifiedKFold的随机标记已在当前版本0.15中引入:

http://scikit-learn.org/0.15/modules/generated/sklearn.cross_validation.StratifiedKFold.html

可以在Changelog中找到:

http://scikit-learn.org/stable/whats_new.html#new-features

  

cross_validation.StratifiedKFold的随机播放选项。杰弗里   布莱克。

答案 1 :(得分:2)

我想我会发布我的解决方案,以防它对其他人有用。

from collections import defaultdict
import random
def strat_map(y):
    """
    Returns permuted indices that maintain class
    """
    smap = defaultdict(list)
    for i,v in enumerate(y):
        smap[v].append(i)
    for values in smap.values():
        random.shuffle(values)
    y_map = np.zeros_like(y)
    for i,v in enumerate(y):
        y_map[i] = smap[v].pop()
    return y_map

##########
#Example Use
##########
skf = StratifiedKFold(y, nfolds)
sm = strat_map(y)
for test, train in skf:
    test,train = sm[test], sm[train]
    #then cv as usual


#######
#tests#
#######
import numpy.random as rnd
for _ in range(100):
    y = np.array( [0]*10 + [1]*20 + [3] * 10)
    rnd.shuffle(y)
    sm = strat_map(y)
    shuffled = y[sm]
    assert (sm != range(len(y))).any() , "did not shuffle"
    assert (shuffled == y).all(), "classes not in right position"
    assert (set(sm) == set(range(len(y)))), "missing indices"


for _ in range(100):
    nfolds = 10
    skf = StratifiedKFold(y, nfolds)
    sm = strat_map(y)
    for test, train in skf:
        assert (sm[test] != test).any(), "did not shuffle"
        assert (y[sm[test]] == y[test]).all(), "classes not in right position"

答案 2 :(得分:1)

这是我实施的分层洗牌分为训练和测试集:

import numpy as np

def get_train_test_inds(y,train_proportion=0.7):
    '''Generates indices, making random stratified split into training set and testing sets
    with proportions train_proportion and (1-train_proportion) of initial sample.
    y is any iterable indicating classes of each observation in the sample.
    Initial proportions of classes inside training and 
    test sets are preserved (stratified sampling).
    '''

    y=np.array(y)
    train_inds = np.zeros(len(y),dtype=bool)
    test_inds = np.zeros(len(y),dtype=bool)
    values = np.unique(y)
    for value in values:
        value_inds = np.nonzero(y==value)[0]
        np.random.shuffle(value_inds)
        n = int(train_proportion*len(value_inds))

        train_inds[value_inds[:n]]=True
        test_inds[value_inds[n:]]=True

    return train_inds,test_inds


y = np.array([1,1,2,2,3,3])
train_inds,test_inds = get_train_test_inds(y,train_proportion=0.5)
print y[train_inds]
print y[test_inds]

此代码输出:

[1 2 3]
[1 2 3]

答案 3 :(得分:-3)

据我所知,这实际上是在scikit-learn中实现的。

“”” 分层ShuffleSplit交叉验证迭代器

提供列车/测试索引以在列车测试集中分割数据。

这个交叉验证对象是StratifiedKFold和的合并 ShuffleSplit,返回分层随机折叠。折叠 通过保留每个班级的样本百分比来制作。

注意:像ShuffleSplit策略一样,分层随机分割 不保证所有折叠都会有所不同,尽管如此 仍然非常可能适用于相当大的数据集。 “”“