【发布时间】:2018-07-12 21:29:43
【问题描述】:
我一直在玩 numpy memmaps,我注意到如果我生成一些数据并将其转储到磁盘上:
from os.path import join
import numpy as np
import tempfile
print('Generate dummy data')
N = 4
D = 3
x, y = np.meshgrid(np.arange(0, N), np.arange(0, N))
data = np.ascontiguousarray((np.dstack([x] * D) % 256).astype(np.uint8))
print('Make temp directory')
dpath = tempfile.mkdtemp()
mem_fpath = join(dpath, 'foo.npy')
print('Dump memmap')
np.save(mem_fpath, data)
那么np.memmap和np.load产生的数据就不同了。
file1 = np.memmap(mem_fpath, dtype=data.dtype.name, shape=data.shape,
mode='r')
file2 = np.load(mem_fpath)
print('file1 =\n{!r}'.format(file1[0]))
print('file2 =\n{!r}'.format(file2[0]))
导致
file1 =
memmap([[147, 78, 85],
[ 77, 80, 89],
[ 1, 0, 118],
[ 0, 123, 39]], dtype=uint8)
file2 =
array([[0, 0, 0],
[1, 1, 1],
[2, 2, 2],
[3, 3, 3]], dtype=uint8)
这让我很困惑,但最终我发现我需要将 np.memmap 中的 offset 参数设置为 128 才能使其工作:
for i in range(0, 1000):
file1 = np.memmap(mem_fpath, dtype=data.dtype.name, shape=data.shape,
offset=i, mode='r')
if np.all(file1 == data):
print('i = {!r}'.format(i))
break
print('file1 =\n{!r}'.format(file1[0]))
执行结果
i = 128
file1 =
memmap([[0, 0, 0],
[1, 1, 1],
[2, 2, 2],
[3, 3, 3]], dtype=uint8)
我的问题是这个 128 号码是从哪里来的。我检查了 np.save 文档,但没有看到对它的引用。我也尝试修改数据的 dtype 和 shape,但我总是发现偏移量是 128。我可以假设使用np.save 保存的任何单个数组都将始终具有这个 128 偏移量吗?如果不是,我如何确定偏移量应该是多少。
我问的原因是因为我发现使用 np.memmap 比 np.load 快得多,因为我从磁盘上的大文件中裁剪小区域的特定用例。
感谢您的帮助!
【问题讨论】: