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

ser*_*chu 5 python numpy progress-bar

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

np.load(open('file.npy'))
Run Code Online (Sandbox Code Playgroud)

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

谢谢!

kaz*_*ase 6

据我所知,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)
Run Code Online (Sandbox Code Playgroud)

将任何进度条库插入循环应该是直接的。

由于内存限制,我无法使用异常大的数组来测试这一点,因此我无法真正判断这种方法是否存在任何性能问题。