加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 具有非常大的数组的numpy tofile()保存全零

发布时间:2020-12-20 13:36:02 所属栏目:Python 来源:网络整理
导读:当我尝试保存一个非常大的(20000 x 20000元素)数组时,我得到了所有的零: In [2]: shape = (2e4,)*2In [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.dataIn [6]: r[:
当我尝试保存一个非常大的(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,5,[6,6],[4,7],[8,3,9],6,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]])

np.save()做了类似的奇怪事情.

搜索网后,我发现OSX中存在一个已知错误:

https://github.com/numpy/numpy/issues/2806

当我尝试使用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(),mmap.MAP_SHARED,mmap.PROT_READ)
... 
>>> r = np.frombuffer(m,dtype='int64')
>>> r = r.reshape(shape)
>>> r[:6,:6]
array([[7,5],[2,2,[9,[7,5]])

请注意,此处r是内存映射数据的视图,这使得它更具内存效率,但具有自动获取文件内容更改的副作用.如果你想让它指向数据的私有副本,就像np.fromfile返回的数组一样,添加一个r = np.copy(r).

(另外,正如所写,这不会在Windows下运行,这需要稍微不同的mmap标志.)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读