如何从h5数据集中访问随机指数?

2024-06-26 13:30:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些h5数据,我想通过使用一些随机生成的指数进行采样。然而,如果指数的增长顺序不正确,那么努力就会失败。是否可以从h5数据集中选择随机生成的指数

以下是引用错误的MWE:

import h5py
import numpy as np
arr = np.random.random(50).reshape(10,5)
with h5py.File('example1.h5', 'w') as h5fw:
    h5fw.create_dataset('data', data=arr)

random_subset = h5py.File('example1.h5', 'r')['data'][[3, 1]]

# TypeError: Indexing elements must be in increasing order

可以对指数进行排序,但这样我们就失去了随机性成分


Tags: 数据importdata顺序as错误nprandom
2条回答

正如hpaulj提到的,随机索引对于内存中的numpy数组不是问题。因此,可以从读取到numpy阵列的h5数据集中选择随机生成索引的数据。关键是有足够的内存将数据集保存在内存中。下面的代码显示了如何执行此操作:

#random_subset = h5py.File('example1.h5', 'r')['data'][[3, 1]]
arr = h5py.File('example1.h5', 'r')['data'][:]
random_subset = arr[[3,1]]

一种可能的解决方案是对所需索引进行预排序,如下所示:

idx = np.sort([3,1])
random_subset = h5py.File('example1.h5', 'r')['data'][idx]

相关问题 更多 >