Python 具有非常大数组的numpy tofile()保存所有零

Python 具有非常大数组的numpy tofile()保存所有零,python,file-io,numpy,out-of-memory,Python,File Io,Numpy,Out Of Memory,当我尝试保存一个非常大(20000 x 20000个元素)的数组时,我得到了所有的零: In [2]: shape = (2e4,)*2 In [3]: r = np.random.randint(0, 10, shape) In [4]: r.tofile('r.data') In [5]: ls -lh r.data -rw-r--r-- 1 whg staff 3.0G 23 Jul 16:18 r.data In [6]: r[:6,:6] Out[6]: array([

当我尝试保存一个非常大(20000 x 20000个元素)的数组时,我得到了所有的零:

In [2]: shape = (2e4,)*2

In [3]: r = np.random.randint(0, 10, shape)

In [4]: r.tofile('r.data')

In [5]: ls -lh r.data
-rw-r--r--  1 whg  staff   3.0G 23 Jul 16:18 r.data

In [6]: r[:6,:6]
Out[6]:
array([[6, 9, 8, 7, 4, 4],
       [5, 9, 5, 0, 9, 4],
       [6, 0, 9, 5, 7, 6],
       [4, 0, 8, 8, 4, 7],
       [8, 3, 3, 8, 7, 9],
       [5, 6, 1, 3, 1, 4]])

In [7]: r = np.fromfile('r.data', dtype=np.int64)

In [8]: r = r.reshape(shape)

In [9]: r[:6,:6]
Out[9]:
array([[0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0]])
np.save()执行类似的奇怪操作

搜索网络后,我发现OSX中有一个已知的bug:

当我试图使用Python的read()从文件中读取tostring()数据时,我得到一个内存错误


有更好的方法吗?有人能推荐一个解决这个问题的实用方法吗

使用
mmap
内存映射文件,使用
np.frombuffer
创建指向缓冲区的数组。在x86_64 Linux上测试:

# `r.data` created as in the question
>>> import mmap
>>> with open('r.data') as f:
...   m = mmap.mmap(f.fileno(), 0, mmap.MAP_SHARED, mmap.PROT_READ)
... 
>>> r = np.frombuffer(m, dtype='int64')
>>> r = r.reshape(shape)
>>> r[:6, :6]
array([[7, 5, 9, 5, 3, 5],
       [2, 7, 2, 6, 7, 0],
       [9, 4, 8, 2, 5, 0],
       [7, 2, 4, 6, 6, 7],
       [2, 9, 2, 2, 2, 6],
       [5, 2, 2, 6, 1, 5]])
请注意,这里的
r
是内存映射数据的视图,这使其内存效率更高,但附带的副作用是自动获取对文件内容的更改。如果希望它指向数据的私有副本,就像
np.fromfile
返回的数组那样,请添加
r=np.copy(r)

(另外,如前所述,这不会在Windows下运行,因为Windows需要稍微不同的
mmap
标志。)