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
谢谢! :)
你好,有什么即时寻找的是一个分层抽样。如果我没有错,那么sklearn中的函数会为整个数据集生成分层折叠。所以尺寸仍然是一样的。 例如,原始数据集:100A 20B 10C 分层样本:10A 2B 1C – Wboy
在我的示例中,“X_eval”和“y_eval”将包含大小为0.1 * total_dataset_size的分层子采样。这不是你想要的吗? –
刚刚更新了示例,您可以马上运行它,还打印输出,以便您可以看到它需要子采样大小,但它保留了比例 –