【问题标题】:How to generate a large array based on permutations如何根据排列生成大数组
【发布时间】:2019-09-24 04:07:14
【问题描述】:

我正在根据数字 0、1 和 2 生成一个非常大的排列矩阵。理想情况下,我希望它们 48 宽,但甚至对 20 感到满意。现在,我的内存用完了,所以想看看有没有是一个非基于内存的选项可用。

我确实在大型内存机器上尝试过,但我更喜欢使用磁盘的选项(我有一个快速的 SSD),即使它需要很长时间。如您所见,我已经将其设置为 int8 而不是 int32 以节省一些空间,但即便如此也仅此而已。 18 的 Grid_size 是 6.5G,而 19 是 21G,所以我知道它呈指数增长,我很快就会成为 TB。

import numpy as np

class LargeGrid():
    def permgrid(self, m, n):
        inds = np.indices((m,) * n, dtype=np.int8)
        arr = inds.reshape(n, -1).T
        arr[arr == 2] = -1
        return arr

    def save(self):
        grid_size = 24
        grid = self.permgrid(3,grid_size)
        np.save('grid', grid)

lg = LargeGrid()
lg.save()

预计磁盘上有一个非常大的文件,但结果是:

Python 3.7.3 (default, Apr 24 2019, 15:29:51) [MSC v.1915 64 bit (AMD64)] on win32
MemoryError: Unable to allocate array with shape (24, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3) and data type int8

【问题讨论】:

  • numpy 最多允许 32 个维度。
  • 当您询问此类错误时,提供回溯是有礼貌的。我继续测试了您的部分代码,并在np.indices 中得到了错误,它尝试在res = np.empty(24,followed by 24 3's) 中。它必须在某个地方所有这些索引。
  • 使用sparse=Truenp.indices 将返回一个包含 24 个数组的元组,每个数组包含 3 个元素和 ndim=24
  • 你可以试试for i in itertools.product([0,1,3], repeat=24): <do your thing one permuation at a time>
  • @hpaulj - 这是一个很好的建议,并给了我重构的想法 - 我的方法并不理想,使用如此大的矩阵将无法扩展。

标签: python numpy


【解决方案1】:

看起来你的问题是数组的大小。因此,制作更小的数组并使用h5py 将它们写入hdf5(分层数据格式)文件。

这将允许您管理当前阵列从内存中占用的空间量,同时能够将整个大型阵列存储在文件系统上的 hdf5 文件 (largefile.h5) 中。

或者,您也可以使用 pyTables 代替 h5py 以 hdf5 文件格式存储数据。

参考文献

我建议你看看这些:

h5py

  1. Input and output numpy arrays to h5py
  2. h5py Intro
  3. h5py Documentation

pyTables

  1. Python: how to store a numpy multidimensional array in PyTables?
  2. pyTables Documentation
  3. Example of storing numpy array using pytables

【讨论】:

  • @hpaulj 感谢您指出。让我详细看一下。
  • 谢谢,我依靠 numpy.indices 来生成排列。我在其他库中找不到等效方法。
猜你喜欢
  • 1970-01-01
  • 2014-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-08
  • 2014-11-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多