首页 > 解决方案 > 删除 x 值时的数组组合

问题描述

我正在实现一种方法来获取交叉验证折叠并拥有一个大小为 s 的 numpy 数组列表。我想将 x 数组用作测试折叠,因此将 sx 数组用作训练折叠。对于正确的交叉验证方法,每个数组都应该是一次测试折叠,其他 x-1 数组的所有组合作为测试折叠。通过这样做,我在训练中保留了完整的数组。我想测试使用从 sx 数组到 x 数组的数据训练的回归量的可转移性。这个问题可以简化为一个问题,当删除任何 x 值时,会生成大小为 s 的 numpy 数组的所有可能组合。

示例代码:

s = 4
x = 2
array = np.arange(0, s)
drop_out = x
combinations(array, drop_out)
## output (I hope, I didn't forget a combination)
array([[2, 3], [1, 3], [1, 2], [0, 3], [0, 2], [0, 1]])

是否有任何预构建功能可以做到这一点?到目前为止,我想出的唯一解决方案是使用 x-loops 来做到这一点。但是 x 不是参数。

我期待着建议。

最好的,詹尼斯

标签: pythonarraysnumpycombinations

解决方案


您可以使用 itertools 生成组合:

import numpy as np
import itertools


def combinations(a, drop_out):
    """
    >>> print(combinations(range(4), 2))
    [[0 1]
     [0 2]
     [0 3]
     [1 2]
     [1 3]
     [2 3]]
    """
    a = np.asarray(a)
    return np.array([r for r in itertools.combinations(a, a.size - drop_out)])

推荐阅读