gpt4 book ai didi

python - 如何将多维 h5py 数据集复制到平面一维 Python 列表而不制作任何中间副本?

转载 作者:行者123 更新时间:2023-12-03 02:13:30 26 4
gpt4 key购买 nike

问题

如何将数据从 N x N x N x... h5py 数据集复制到一维标准 Python 列表,而不制作数据的中间副本?

我可以想出几种不同的方法来使用中间副本来做到这一点。例如:

import h5py
import numpy as np

# initialize list, put some initial data in it
myList = ['foo']

# open up an h5py dataset from a file on disk
myFile = h5py.File('/path-to-my-data', 'r')
myData = myFile['bar']
myData.shape # returns, for example, (5,15,7)

# copy dataset over to a numpy array
arr = np.zeros(myData.shape)
myData.read_direct(arr)

# finally, add data from copied dataset to myList
myList.extend(arr.flatten())

可以在不中间复制到 numpy 数组的情况下完成此操作吗?

一些背景

(除非你很好奇,否则你绝对不必阅读本文)

我正在尝试通过 Python API 将数据从 HDF5 文件复制到 Protocol Buffers 文件。这些都是用于编写您自己的复杂、可序列化数据结构的库/框架。就其 Python API 而言,HDF5 假装其数组是 numpy 数组,而 Protocol Buffers 假装其数组是标准的一维 Python 列表(遗憾的是,Protocol Buffers 中没有对简单多维数组的 native 支持)。因此我需要从 h5py 数据集转换为 Python 列表。

编辑

有人要求澄清我的意思

HDF5 pretends that its arrays are numpy arrays, whereas Protocol Buffers pretends that its arrays are standard 1D Python lists

我的意思是,h5py 数据集向用户公开的接口(interface)类似于 numpy 数组公开的接口(interface),而 Python Protobuf 重复数字字段公开的接口(interface)类似于标准 Python 列表的接口(interface)。然而,两者都没有实现其原型(prototype)的完整行为,甚至完整接口(interface)。例如,h5py 数据集没有 .flatten() 方法,如果您尝试将其他列表分配为元素,Pybuf 重复字段会报错(例如 myBuf.repIntField[2] = [1,2,3] 总是会引发错误)。

这是 Pybuf documentation 中的相关行:

Repeated fields are represented as an object that acts like a Python sequence.

以及 h5py documentation 中的相关行(强调):

Datasets are very similar to NumPy arrays. They are homogenous collections of data elements, with an immutable datatype and (hyper)rectangular shape. Unlike NumPy arrays, they support a variety of transparent storage features such as compression, error-detection, and chunked I/O.

最佳答案

对于 numpy 数组,我建议使用 ndarray.flat,但 h5py 数据集没有 flat/flatten 属性。

您可以创建一个生成器,它将 block 作为 numpy 数组放入内存,然后从展平的值中生成值。然后可以将其转换为列表。例如,简单地沿着外部维度分块:

def yield_chunks(x):
for chunk in iter(x):
yield chunk.flat

myGenerator = itertools.chain(yield_chunk(arr))

myGenerator 将从 arr 中生成各个值。您可以使用 list(myGenerator) 将其转换为列表。

关于python - 如何将多维 h5py 数据集复制到平面一维 Python 列表而不制作任何中间副本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30993145/

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