【问题标题】:Subsampling an .hdf5 file with multiple datasets对具有多个数据集的 .hdf5 文件进行二次采样
【发布时间】:2017-12-11 02:13:08
【问题描述】:

我正在尝试从一个大的 .h5 文件中提取一些“行”,以创建一个较小的示例文件。

为了确保我的示例看起来像原始文件,我正在随机提取行。

#Get length of files and prepare samples
 source_file = h5py.File(args.data_path, "r")
 dataset = source_file['X']
 indices = np.sort(np.random.choice(dataset.shape[0],args.nb_rows))

#checking we're extracting a subsample
if args.nb_rows > dataset.shape[0]:
    raise ValueError("Can't extract more rows than dataset contains. Dataset has %s rows" % dataset.shape[0] )

target_file =  h5py.File(target, "w")
for k in source_file.keys():
    dataset = source_file[k]
    dataset = dataset[indices,:,:,:]
    dest_dataset = target_file.create_dataset(k, shape=(dataset.shape), dtype=np.float32)
dest_dataset.write_direct(dataset)
target_file.close()
source_file.close()

但是,当 nb_rows 达到(例如 10,000)时,我会收到 TypeError("Indexing elements must be in increasing order")。索引是排序的,所以我认为我不应该得到这个错误。我是不是误会了什么?

【问题讨论】:

    标签: hdf5 h5py


    【解决方案1】:

    我认为你得到了重复。

    显然你会在args.nb_rows > dataset.shape[0] 案例中得到重复:

    In [499]: np.random.choice(10, 20)
    Out[499]: array([2, 4, 1, 5, 2, 8, 4, 3, 7, 0, 2, 6, 6, 8, 9, 3, 8, 4, 2, 5])
    In [500]: np.sort(np.random.choice(10, 20))
    Out[500]: array([1, 1, 1, 2, 2, 2, 4, 4, 4, 5, 5, 5, 5, 6, 6, 7, 8, 8, 8, 9])
    

    但是当数字较小时你仍然可以得到重复:

    In [502]: np.sort(np.random.choice(10, 9))
    Out[502]: array([0, 0, 1, 1, 1, 5, 5, 9, 9])
    

    关闭replace

    In [504]: np.sort(np.random.choice(10, 9, replace=False))
    Out[504]: array([0, 1, 2, 3, 4, 5, 6, 7, 8])
    

    【讨论】:

    • h5py 和 python 的所有版本都是这样吗?我不明白为什么在使用 python 3.7 的配置上获取重复甚至乱序索引没有问题,但在另一台使用 python 3.5 的机器上却没有......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-26
    • 2021-02-17
    • 2018-09-18
    • 1970-01-01
    • 2012-06-06
    • 1970-01-01
    相关资源
    最近更新 更多