首页 > 解决方案 > 在 Python 中实现引导程序的内存有效方式?

问题描述

我有一个数据集加载到内存中,并想从中引导。目前我使用 sklearnresample默认实现。我使用生成器从驻留在内存中的数据集生成引导批处理。

然而,这非常耗费内存,因为每次引导迭代都会创建一个新数组。有没有更有效的方法来从存储在磁盘或内存中的数据实现引导程序?

标签: pythonnumpyscikit-learn

解决方案


只需创建索引,这些索引将分割您的原始特征和目标,并在您每次需要引导数据集时应用它们。

这是使用 sklearn 的波士顿数据集的示例实现:

import numpy as np
from sklearn.datasets import load_boston


def get_bootstrap_indices(dataset, datasets: int):
    for _ in range(datasets):
        yield np.random.choice(np.arange(len(dataset)), size=len(dataset), replace=True)


dataset = load_boston().data
print(f"Original dataset shape: {dataset.shape}")

for indices in get_bootstrap_indices(dataset, 10):
    print(dataset[indices].shape)

推荐阅读