使用PyTables构建一个巨大的NumPy数组

7

如何使用PyTables创建一个巨大的numpy数组。我尝试过以下方法,但是会出现"ValueError: array is too big."错误:

import numpy as np
import tables as tb
ndim = 60000
h5file = tb.openFile('test.h5', mode='w', title="Test Array")
root = h5file.root
h5file.createArray(root, "test", np.zeros((ndim,ndim), dtype=float))
h5file.close()
2个回答

15

在 @b1r3k 的回答基础上,如果你要创建一个不会一次性访问所有元素(即不将整个数组加载到内存中)的数组,你需要使用 CArray(分块数组)。思路是你可以逐步填充和访问它:

import numpy as np
import tables as tb
ndim = 60000
h5file = tb.openFile('test.h5', mode='w', title="Test Array")
root = h5file.root
x = h5file.createCArray(root,'x',tb.Float64Atom(),shape=(ndim,ndim))
x[:100,:100] = np.random.random(size=(100,100)) # Now put in some data
h5file.close()

8
你可以尝试使用tables.CArray类,因为它支持压缩,但是......
我认为问题更多涉及numpy而不是pytables,因为在使用pytables存储之前,你要使用numpy创建数组。
这样,你需要大量的ram来执行np.zeros((ndim,ndim),这可能是引发“ValueError:array is too big.”异常的地方。
如果矩阵/数组不是密集的,那么可以使用scipy中提供的稀疏矩阵表示方式:http://docs.scipy.org/doc/scipy/reference/sparse.html
另一个解决办法是,如果你不需要一次性使用整个数组,可以通过块访问数组,请查看此线程:Very large matrices using Python and NumPy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接