为大型密集方阵的列表切片赋值 (Python)

Assigning values to list slices of large dense square matrices (Python)

我正在处理大小为 NxN ~(100k x 100k) 的大型密集方阵,它们太大而无法放入内存。

经过一些研究,我发现大多数人通过使用 numpy 的 memappytables 包来处理大型矩阵。但是,我发现这些软件包似乎有很大的局限性。他们似乎都不提供支持 ASSIGN 值来沿多维列出磁盘上矩阵的切片。

我想寻找一种有效的方法来为大型密集方阵 M 赋值,例如:

M[0, [1,2,3], [8,15,30]] = np.zeros((3, 3)) # or

M[0, [1,2,3,1,2,3,1,2,3], [8,8,8,15,15,15,30,30,30]] = 0 # for memmap

The Leaf ``/M`` is exceeding the maximum recommended rowsize (104857600 bytes);
be ready to see PyTables asking for *lots* of memory and possibly slow
I/O.  You may want to reduce the rowsize by trimming the value of
dimensions that are orthogonal (and preferably close) to the *main*
dimension of this leave.  Alternatively, in case you have specified a
very small/large chunksize, you may want to increase/decrease it.

我只是想知道是否有更好的解决方案来为大型矩阵的任意二维切片赋值?

首先,请注意在 numpy(不确定 pytables)中 M[0, [1,2,3], [8,15,30]] 将 return 一个形状为 (3,) 的数组对应于元素 M[0,1,8]M[0,2,15]M[0,3,30],因此将 np.zeros((3,3)) 分配给它会引发错误。

现在,以下对我来说工作正常:

np.save('M.npy', np.random.randn(5,5,5))  # create some dummy matrix
M = np.load('M.npy', mmap_mode='r+')  # load such matrix as a memmap
M[[0,1,2],[1,2,3],[2,3,4]] = 0
M.flush()  # make sure thing is updated on disk
del M
M = np.load('M.npy', mmap_mode='r+')  # re-load matrix
print(M[[0,1,2],[1,2,3],[2,3,4]])  # should show array([0., 0., 0.])