gpt4 book ai didi

python - 将 numpy memmap 刷新到 npy 文件

转载 作者:太空宇宙 更新时间:2023-11-03 12:45:36 25 4
gpt4 key购买 nike

有没有一种方法可以将 numpy 内存映射数组保存到 .npy 文件中?显然,有一种方法可以从 .npy 文件中加载这样的数组,如下所示

data = numpy.load("input.npy", mmap_mode='r')

但是刷新文件并不等同于以.npy格式存储它。

如果刷新是唯一的方法,那么有没有办法推断存储数组的形状?我更喜欢在另一个脚本中自动存储和检索(可能再次作为 memmap)的动态形状。

我在各个地方都搜索过这个,但没有找到任何结果。我存储到 .npy 的方法是

numpy.save(output.filename, output.copy())

这打败了使用 memmap 的想法,但保留了形状。

注意:我知道 hdf5 和 h5py,但我想知道是否有一个纯粹的 numpy 解决方案。

最佳答案

is there a way to infer the shape of the stored array?

No .就 np.memmap 而言,文件只是一个缓冲区 - 它存储数组的内容,但不存储维度、dtype 等。除非以某种方式包含在其中,否则无法推断该信息数组本身。如果您已经创建了一个由简单二进制文件支持的 np.memmap,那么您需要将其内容写入磁盘上的新 .npy 文件。

您可以通过使用 numpy.lib.format.open_memmap 打开新的 .npy 文件作为另一个内存映射数组来避免在内存中生成副本。 :

import numpy as np
from numpy.lib.format import open_memmap

# a 10GB memory-mapped array
x = np.memmap('/tmp/x.mm', mode='w+', dtype=np.ubyte, shape=(int(1E10),))

# create a memory-mapped .npy file with the same dimensions and dtype
y = open_memmap('/tmp/y.npy', mode='w+', dtype=x.dtype, shape=x.shape)

# copy the array contents
y[:] = x[:]

关于python - 将 numpy memmap 刷新到 npy 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36769378/

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