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

在python函数中分割数据时保持比率,python,function,numpy,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_len

我有一些数据,我想把它们分成更小的组,保持一个共同的比率。我编写了一个函数,该函数将接受两个数组的输入并计算大小比,然后告诉我可以将其拆分为多少组的选项(如果所有组的大小相同),函数如下:

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"
现在,当您将这些列相加时,您会看到:
351144


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

在另一个问题中,作者希望进行与您类似的交叉验证。请找出你问题的答案,就像:

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 ]])

您将拥有与
test\u data
中定义的间隔相对应的
train\u data
,我认为这是一个可能适合您的算法

取测试长度和训练长度除以它们的GCD,得到一个简单的分数。你把分子和分母加在一起,这就是你的分组的大小因子

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

然后取总长度除以折叠数,得到第一组的理想大小,这可能是一个浮点数。你发现5的最大倍数小于或等于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)
最后,groups将是一个元组列表,其中包含每个组的test_大小和train_大小


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

您的意思是要使用不同的训练集进行交叉验证吗?这听起来有点不确定?通常在实践中进行吗?是的,这是交叉验证。不,这是为了测试测试和训练集之间的相似性,以检查测试数据中是否有不在训练数据中的内容。通常,交叉验证只在一个训练集上进行,这也可以应用于他们的训练集,而不是两个阵列,你可以在训练数组和训练数组中给出列,它会这样做。如果你的两个数组的大小分别为
m
n
,并且
m
除以
n
的不可约分数是
p/q
,那么
m=k*p
n=k*q
。一旦有了
k
,其中任何一项都会导致原始数据的分割,从而保持元素的比例。如果你需要我详细说明,请告诉我。啊,好的旧数论……不幸的是,这是有限的。我希望能够有任意数量的组,即使是一个不能平均划分的数字,因为只要一个数据集与另一个数据集的比率是一致的,大小可以不同。这有意义吗?这根本不是我想要的…我的分组对这样的东西很有效,但是我需要我的函数取另一个变量,即数组的组数,数组的大小可以不同,只要它们从训练数据到测试数据的比率相同,所以我想我没有领会你的意思。这一个适用于不同的大小,但是没有变量告诉组的数量(这是由你给出的测试数据控制的…基本上我需要另一个变量,x,其中x=组的数量。行的数量可以不同,但在每个组中,来自测试数据的行和来自训练数据的行的比率必须相同。这样交叉验证中就没有偏差。你能提供inp吗ut文件或变量,以便我们可以使用它?(使用Dropbox之类的工具很方便)这对任何类型的数据都很重要。所以我想说,只需加入2个numpy数组,一个都是1,另一个都是0,每个数组都有相同数量的列,并且像这样乱七八糟!这也很容易看出它混合了来自单独数组的行几乎完美!!!它在大多数情况下都非常有效,等等最重要的问题是,如果分数不能简化,它会将所有元组返回为
(0,0)
除了最后一个,它只是原始的数字。如果比率不可能,我是否可以向函数中添加任何东西,使其稍微打破比率?还要添加
total_length=train_length+test_length
在开始时,您没有定义
total_length
我使用的是
total_length
来自您的原始代码,但已将其添加到示例中以澄清。还使用一些附加代码更新了答案,以在数据不足时调整比率。我应该补充一点,如果您的数据没有被请求的折叠数平均分割,您将在最后留下一些数据。是的,我知道,但unf很重要的是,并不是每两个数据集都有足够数量的折叠。现在唯一的错误是,当它稍微调整数字和比率时,偶尔其中一个输出会增加到比以前更大的总数。这将使用一个不存在的行。我一直在胡闹,但总是让它保持不变下面的原文似乎不起作用…我不确定我是否理解你。你能给出一些发生这种情况的示例值。我只是指测试长度、训练长度和折叠数。
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)
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