我正在使用sklearn进行多分类任务。我需要将alldata拆分为train_set和test_set。我想从每个班级中随机抽取相同的样本编号。 实际上,我正在使用这个功能
X_train, X_test, y_train, y_test = cross_validation.train_test_split(Data, Target, test_size=0.3, random_state=0)
但它提供了不平衡的数据集!任何建议。
答案 0 :(得分:16)
您可以使用StratifiedShuffleSplit创建与原始类别相同百分比的数据集:
import numpy as np
from sklearn.cross_validation import StratifiedShuffleSplit
X = np.array([[1, 3], [3, 7], [2, 4], [4, 8]])
y = np.array([0, 1, 0, 1])
stratSplit = StratifiedShuffleSplit(y, 1, test_size=0.5,random_state=42)
StratifiedShuffleSplit(y, n_iter=1, test_size=0.5)
for train_idx,test_idx in stratSplit:
X_train=X[train_idx]
y_train=y[train_idx]
print(X_train)
print(y_train)
//[[3 7]
// [2 4]]
//[1 0]
答案 1 :(得分:16)
虽然克里斯蒂安的建议是正确的,但技术上train_test_split
应该使用stratify
参数给你分层结果。
所以你可以这样做:
X_train, X_test, y_train, y_test = cross_validation.train_test_split(Data, Target, test_size=0.3, random_state=0, stratify=Target)
这里的诀窍是从0.17
中的版本 sklearn
开始。
有关参数stratify
的文档:
分层:类似数组或无(默认为无) 如果不是None,则数据以分层方式分割,使用此作为标签数组。 版本0.17中的新功能:分层拆分
答案 2 :(得分:2)
如果课程不平衡但你想要平衡分裂,那么分层就无济于事了。似乎没有一种方法可以在sklearn中进行平衡采样,但是使用基本的numpy很容易,例如像这样的函数可能对你有帮助:
def split_balanced(data, target, test_size=0.2):
classes = np.unique(target)
# can give test_size as fraction of input data size of number of samples
if test_size<1:
n_test = np.round(len(target)*test_size)
else:
n_test = test_size
n_train = max(0,len(target)-n_test)
n_train_per_class = max(1,int(np.floor(n_train/len(classes))))
n_test_per_class = max(1,int(np.floor(n_test/len(classes))))
ixs = []
for cl in classes:
if (n_train_per_class+n_test_per_class) > np.sum(target==cl):
# if data has too few samples for this class, do upsampling
# split the data to training and testing before sampling so data points won't be
# shared among training and test data
splitix = int(np.ceil(n_train_per_class/(n_train_per_class+n_test_per_class)*np.sum(target==cl)))
ixs.append(np.r_[np.random.choice(np.nonzero(target==cl)[0][:splitix], n_train_per_class),
np.random.choice(np.nonzero(target==cl)[0][splitix:], n_test_per_class)])
else:
ixs.append(np.random.choice(np.nonzero(target==cl)[0], n_train_per_class+n_test_per_class,
replace=False))
# take same num of samples from all classes
ix_train = np.concatenate([x[:n_train_per_class] for x in ixs])
ix_test = np.concatenate([x[n_train_per_class:(n_train_per_class+n_test_per_class)] for x in ixs])
X_train = data[ix_train,:]
X_test = data[ix_test,:]
y_train = target[ix_train]
y_test = target[ix_test]
return X_train, X_test, y_train, y_test
请注意,如果您使用此项并为每个类采样的点数多于输入数据中的点数,则会对这些点进行上采样(带替换的样本)。结果,一些数据点将出现多次,这可能会对精度度量等产生影响。如果某个类只有一个数据点,则会出现错误。您可以使用np.unique(target, return_counts=True)
答案 3 :(得分:0)
这是我用来获取训练/测试数据索引的实现
def get_safe_balanced_split(target, trainSize=0.8, getTestIndexes=True, shuffle=False, seed=None):
classes, counts = np.unique(target, return_counts=True)
nPerClass = float(len(target))*float(trainSize)/float(len(classes))
if nPerClass > np.min(counts):
print("Insufficient data to produce a balanced training data split.")
print("Classes found %s"%classes)
print("Classes count %s"%counts)
ts = float(trainSize*np.min(counts)*len(classes)) / float(len(target))
print("trainSize is reset from %s to %s"%(trainSize, ts))
trainSize = ts
nPerClass = float(len(target))*float(trainSize)/float(len(classes))
# get number of classes
nPerClass = int(nPerClass)
print("Data splitting on %i classes and returning %i per class"%(len(classes),nPerClass ))
# get indexes
trainIndexes = []
for c in classes:
if seed is not None:
np.random.seed(seed)
cIdxs = np.where(target==c)[0]
cIdxs = np.random.choice(cIdxs, nPerClass, replace=False)
trainIndexes.extend(cIdxs)
# get test indexes
testIndexes = None
if getTestIndexes:
testIndexes = list(set(range(len(target))) - set(trainIndexes))
# shuffle
if shuffle:
trainIndexes = random.shuffle(trainIndexes)
if testIndexes is not None:
testIndexes = random.shuffle(testIndexes)
# return indexes
return trainIndexes, testIndexes