是否有任何内置的方法让scikit-learn执行洗牌分层k-fold交叉验证?这是最常见的CV方法之一,我很惊讶我找不到一个内置的方法来做到这一点。
我看到cross_validation.KFold()
有一个洗牌标志,但它不是分层的。不幸的是,cross_validation.StratifiedKFold()
没有这样的选择,cross_validation.StratifiedShuffleSplit()
不会产生不相交的褶皱。
我错过了什么吗?这是有计划的吗?
(显然我可以自己实现)
cross_validation.StratifiedKFold
的洗牌标志已在当前版本0.15中引入:
这可以在Changelog中找到:
http://scikit-learn.org/stable/whats_new.html新特性
cross_validation.StratifiedKFold的Shuffle选项。由杰弗里Blackburne .
我想我应该把我的解决方案贴出来,以防它对其他人有用。
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"
这是我将分层洗牌分为训练集和测试集的实现:
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]
据我所知,这实际上是在scikit-learn中实现的。
" " "分层ShuffleSplit交叉验证迭代器
提供训练/测试索引来分割训练测试集中的数据。
这个交叉验证对象是StratifiedKFold和ShuffleSplit,它返回分层随机折叠。折叠的是通过保留每个类别的样本百分比来制作的。
注:像ShuffleSplit策略一样,分层随机分裂不保证所有的折叠都是不同的,虽然这是对于大数据集来说仍然是很有可能的。" " "