gpt4 book ai didi

python - 部分读取大型 numpy 文件的有效方法?

转载 作者:行者123 更新时间:2023-12-02 10:44:10 25 4
gpt4 key购买 nike

我有一个巨大的 numpy 3D 张量,它存储在我磁盘上的一个文件中(我通常使用 np.load 读取该文件)。这是一个二进制 .npy 文件。在使用 np.load 时,我很快就用完了大部分内存。

幸运的是,在程序的每次运行中,我只需要巨大张量的某一部分。切片具有固定大小,其尺寸由外部模块提供。

最好的方法是什么?我能想到的唯一方法是以某种方式将这个 numpy 矩阵存储到 MySQL 数据库中。但我确信有更多更好/更简单的方法。如果有帮助的话,我也很乐意以不同的方式构建我的 3D 张量文件。

<小时/>

如果我的张量本质上是稀疏的,答案会改变吗?

最佳答案

使用numpy.load正常,但请务必指定 mmap_mode 关键字,以便数组保留在磁盘上,并且在访问时仅将必要的位加载到内存中。

mmap_mode : {None, ‘r+’, ‘r’, ‘w+’, ‘c’}, optional If not None, then memory-map the file, using the given mode (see numpy.memmap for a detailed description of the modes). A memory-mapped array is kept on disk. However, it can be accessed and sliced like any ndarray. Memory mapping is especially useful for accessing small fragments of large files without reading the entire file into memory.

这些模式在numpy.memmap中描述。 :

mode : {‘r+’, ‘r’, ‘w+’, ‘c’}, optional The file is opened in this mode: ‘r’ Open existing file for reading only. ‘r+’ Open existing file for reading and writing. ‘w+’ Create or overwrite existing file for reading and writing. ‘c’ Copy-on-write: assignments affect data in memory, but changes are not saved to disk. The file on disk is read-only.

*请务必不要使用“w+”模式,因为它会删除文件的内容。

关于python - 部分读取大型 numpy 文件的有效方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42727412/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com