使用 np.load 进度条加载 .npy 文件

Load .npy file with np.load progress bar

我有一个非常大的 .npy 文件(之前用 np.save 保存),我正在加载它:

np.load(open('file.npy'))

有什么办法可以看到加载进度吗?我知道 tqdm 和其他一些用于监控进度的库,但不知道如何使用它们来解决这个问题。

谢谢!

据我所知,np.load 不提供任何回调或挂钩来监控进度。但是,有一个解决方法可能会起作用:np.load 可以将文件作为内存映射文件打开,这意味着数据保留在磁盘上并且仅在需要时加载到内存中。我们可以滥用这种机制,使用一个可以监控进度的循环,手动将内存映射文件中的数据复制到实际内存中。

这是一个带有粗略进度监视器的示例:

import numpy as np

x = np.random.randn(8096, 4096)
np.save('file.npy', x)

blocksize = 1024  # tune this for performance/granularity

try:
    mmap = np.load('file.npy', mmap_mode='r')
    y = np.empty_like(mmap)
    n_blocks = int(np.ceil(mmap.shape[0] / blocksize))
    for b in range(n_blocks):
        print('progress: {}/{}'.format(b, n_blocks))  # use any progress indicator
        y[b*blocksize : (b+1) * blocksize] = mmap[b*blocksize : (b+1) * blocksize]
finally:
    del mmap  # make sure file is closed again

assert np.all(y == x)

将任何进度条库插入循环应该很简单。

由于内存限制,我无法使用特别大的数组对此进行测试,因此我无法确定这种方法是否存在任何性能问题。