2016-04-15 112 views
0

我一直试图做一个函数,从数据集生成分层样本(因为sklearn没有这样的功能),我已经出现了与一个。Pandas by []抛出索引超出界限错误,但.ix不是

了以下功能生成的索引,我希望切片与原始数据集,但由于某些原因,当它到达

sampleData = dataset[indexes] 

线,它抛出一个

IndexError: indices are out-of-bounds 

错误。然而,

sampleData = dataset.ix[indexes] 

的作品。但是,我有一种感觉,这是错误的,并搞砸我后来的过程。任何人有任何想法? :)

下面是完整的代码到这一点:

def stratifiedSampleGenerator(dataset,target,subsample_size=0.1): 
    print('Generating stratified sample of size ' + str(round(len(dataset)*subsample_size,2))) 
    dic={} 
    indexes = np.array([]) 
    # find number of classes in sample 
    for label in target.unique(): 
     labelSize = len(target[target==label]) 
     dic[label] = int(labelSize * subsample_size) 
    # make a dataset of size sizeSample with ratio of classes in dic 
    for label in dic: 
     classIndex = target[target==label].index #obtain indexes of class 
     counts = dic[label] #get number of times class occurs 
     newIndex = np.random.choice(classIndex,counts,replace=False) 
     indexes = np.concatenate((indexes,newIndex),axis=0) 

    indexes = indexes.astype(int) 
    sampleData = dataset[indexes] #throws error 
    sampleData = dataset.ix[indexes] #doesnt 

谢谢! :)

回答

1

实际上,sklearn的确有分层数据集的方式。

在你的情况下不会有这样的事情吗?

from sklearn.cross_validation import train_test_split 

dataset = ['A']*100 + ['B']*20 + ['C']*10 
target = [0]*100 + [1]*20 + [2]*10 
X_fit,X_eval,y_fit,y_eval= train_test_split(dataset,target,test_size=0.1,stratify=target) 
print X_eval.count('A') # output: 10 
print X_eval.count('B') # output: 2 
print X_eval.count('C') # output: 1 

检查文档在这里:http://scikit-learn.org/stable/modules/generated/sklearn.cross_validation.train_test_split.html

+0

你好,有什么即时寻找的是一个分层抽样。如果我没有错,那么sklearn中的函数会为整个数据集生成分层折叠。所以尺寸仍然是一样的。 例如,原始数据集:100A 20B 10C 分层样本:10A 2B 1C – Wboy

+0

在我的示例中,“X_eval”和“y_eval”将包含大小为0.1 * total_dataset_size的分层子采样。这不是你想要的吗? –

+0

刚刚更新了示例,您可以马上运行它,还打印输出,以便您可以看到它需要子采样大小,但它保留了比例 –