在python函数中拆分数据时保持比率

时间:2013-04-18 22:25:52

标签: python function numpy

我有一些数据,我想把它分成更小的组,保持一个共同的比例。我写了一个函数,它将输入两个数组并计算大小比例,然后告诉我可以将它分成多少组的选项(如果所有组的大小相同),这里是函数:

def cross_validation_group(train_data, test_data):
    import numpy as np
    from calculator import factors
    test_length = len(test_data)
    train_length = len(train_data)
    total_length = test_length + train_length
    ratio = test_length/float(total_length)
    possibilities = factors(total_length)
    print possibilities
    print possibilities[len(possibilities)-1] * ratio
    super_count = 0
    for i in possibilities:
        if i < len(possibilities)/2:
            pass
        else: 
            attempt = float(i * ratio)
            if attempt.is_integer():
                print str(i) + " is an option for total size with " +  str(attempt) + " as test size and " + str(i - attempt) + " as train size! This is with " + str(total_length/i) + " folds."
            else:
                pass
    folds = int(raw_input("So how many folds would you like to use? If no possibilities were given that would be sufficient, type 0: "))
    if folds != 0:
        total_size = total_length/folds
        test_size = float(total_size * ratio)
        train_size = total_size - test_size
        columns = train_data[0]
        columns= len(columns)
        groups = np.empty((folds,(test_size + train_size),columns))
        i = 0
        a = 0
        b = 0
        for j in range (0,folds):
            test_size_new = test_size * (j + 1)
            train_size_new = train_size * j
            total_size_new = (train_size + test_size) * (j + 1)
            cut_off = total_size_new - train_size
            p = 0
            while i < total_size_new:
                if i < cut_off:
                    groups[j,p] = test_data[a]
                    a += 1
                else:
                    groups[j,p] = train_data[b]
                    b += 1
                i += 1
                p += 1
        return groups
    else:
        print "This method cannot be used because the ratio cannot be maintained with equal group sizes other than for the options you were givens"

所以我的问题是如何才能使它成为函数的第三个输入,它将是折叠数并改变函数,而不是迭代以确保每个组具有相同的数量正确的比例,它只会有正确的比例,但大小不一?

为@JamesHolderness添加

所以你的方法几乎是完美的,但这是一个问题:

长度为357和143,有9折,这是返回列表:

[(39, 16), (39, 16), (39, 16), (39, 16), (39, 16), (39, 16), (39, 16), (39, 16), (39, 16)]

现在,当您添加列时,您会得到:351 144

351很好,因为它小于357,但144不起作用,因为它大于143!原因是357和143是数组的长度,因此该数组的第144行不存在......

2 个答案:

答案 0 :(得分:3)

在另一个问题中,作者想要进行与您类似的交叉验证。请take a look to this answer。找出问题的答案,就像:

import numpy as np
# in both train_data the first line is used for the cross-validation,
# and the other lines will follow, so you can add as many lines as you want
test_data = np.array([ 0.,  1.,  2.,  3.,  4.,  5.])
train_data  = np.array([[ 0.09,  1.9,  1.1,  1.5,  4.2,  3.1,  5.1],
                       [    3,    4,  3.1,   10,   20,    2,    3]])

def cross_validation_group( test_data, train_data):
    om1,om2 = np.meshgrid(test_data,train_data[0])
    dist = (om1-om2)**2
    indexes = np.argsort( dist, axis=0 )
    return train_data[:, indexes[0]]

print cross_validation_group( test_data, train_data )
# array([[  0.09,   1.1 ,   1.9 ,   3.1 ,   4.2 ,   5.1 ],
#        [     3 ,  3.1 ,     4 ,     2 ,    20 ,     3 ]])

您将train_datatest_data中定义的时间间隔相对应。

答案 1 :(得分:3)

这是我认为可能适合您的算法。

您将test_length和train_length除以它们的GCD以获得该比率作为一个简单的分数。你拿分子和分母然后将它们加在一起,这就是你的小组的大小因素。

例如,如果比例为3:2,则每组的大小必须是5的倍数。

然后取total_length并将其除以折叠数,得到第一组的理想大小,这可能是一个浮点数。你发现5的最大倍数小于或等于那个,这是你的第一个小组。

从总数中减去该值,然后除以folds-1以获得下一组的理想大小。再次找到5的最大倍数,从总数中减去,并继续直到计算完所有组。

一些示例代码:

total_length = test_length + train_length          
divisor = gcd(test_length,train_length)
test_multiple = test_length/divisor
train_multiple = train_length/divisor
total_multiple = test_multiple + train_multiple 

# Adjust the ratio if there isn't enough data for the requested folds
if total_length/total_multiple < folds:
  total_multiple = total_length/folds
  test_multiple = int(round(float(test_length)*total_multiple/total_length))
  train_multiple = total_multiple - test_multiple

groups = []
for i in range(folds,0,-1):
  float_size = float(total_length)/i
  int_size = int(float_size/total_multiple)*total_multiple
  test_size = int_size*test_multiple/total_multiple
  train_size = int_size*train_multiple/total_multiple
  test_length -= test_size    # keep track of the test data used
  train_length -= train_size  # keep track of the train data used
  total_length -= int_size
  groups.append((test_size,train_size))

# If the test_length or train_length are negative, we need to adjust the groups
# to "give back" some of the data.
distribute_overrun(groups,test_length,0)
distribute_overrun(groups,train_length,1)

这已经更新,以跟踪每个组(测试和火车)使用的大小,但如果我们最初使用太多,请不要担心。

然后在最后,如果有任何超限(即test_lengthtrain_length已经消极),我们通过在多个项目中递减比率的适当方面将该超限分配回组中因为需要将超限恢复到零。

distribute_overrun功能包含在下面。

def distribute_overrun(groups,overrun,part):
    i = 0
    while overrun < 0:
      group = list(groups[i])
      group[part] -= 1
      groups[i] = tuple(group)
      overrun += 1
      i += 1

最后,groups将是一个元组列表,其中包含每个组的test_size和train_size。

如果这听起来像你想要的那样,但是你需要我扩展代码示例,请告诉我。