python - 删除 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 不是参数。
我期待着建议。
最好的,詹尼斯
解决方案
您可以使用 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)])
推荐阅读
- linux - 如何修复“配置:不兼容的霓虹灯库版本 0.29.3:想要 0.25 26 27 28”
- sql - 将两列合并为月和年作为 MMM-YYYY
- redirect - 修改 SEO 模式后如何在 PrestaShop 中将旧 URL 重定向到新 URL
- php - 无法抓取搜索结果,谷歌不断更改 html 结构
- r - 将列表列表写入单独的 CSV 文件
- android - 带有少量项目的 RecyclerView 滚动侦听器
- ios - 如何绘制高斯模糊效果?
- c# - C# Outlook 处理 ReportItems 的到来?
- c# - How I can do a reference code in my C# documentation?
- c# - 使用 Reactive Subject 触发 DynamicData 缓存更新