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

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

概述当我尝试保存一个非常大的(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 J 当我尝试保存一个非常大的(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[: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标志.)

总结

以上是内存溢出为你收集整理的python – 具有非常大的数组的numpy tofile()保存全零全部内容,希望文章能够帮你解决python – 具有非常大的数组的numpy tofile()保存全零所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1196871.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-03
下一篇 2022-06-03

发表评论

登录后才能评论

评论列表(0条)

保存