【问题标题】:A fast way to fill an dataset with same values of compound data in h5py在 h5py 中用相同的复合数据值填充数据集的快速方法
【发布时间】:2013-06-21 10:31:21
【问题描述】:

我在 hdf 文件中有一个大型复合数据数据集。复合数据的类型如下:

    numpy.dtype([('Image', h5py.special_dtype(ref=h5py.Reference)), 
                 ('NextLevel', h5py.special_dtype(ref=h5py.Reference))])

这样,我创建了一个数据集,其中包含对每个位置的图像和另一个数据集的引用。 这些数据集的维度为 n x n,n 通常至少为 256,但更有可能 > 2000。 我必须最初用相同的值填充这些数据集的每个位置:

    [[(image.ref, dataset.ref)...(image.ref, dataset.ref)],
      .
      .
      .
     [(image.ref, dataset.ref)...(image.ref, dataset.ref)]]

我尽量避免用两个 for 循环填充它:

    for i in xrange(0,n):
      for j in xrange(0,n):
         daset[i,j] =(image.ref, dataset.ref)

因为性能很差。 所以我正在寻找类似numpy.fillnumpy.shapenumpy.reshapenumpy.arraynumpy.arrange[:] 之类的东西。我以各种方式尝试了这些函数,但它们似乎都只适用于数字和字符串数据类型。 有什么方法可以比 for 循环更快地填充这些数据集?

提前谢谢你。

【问题讨论】:

    标签: numpy hdf5 h5py


    【解决方案1】:

    您可以使用 numpy broadcastingnumpy.repeatnumpy.reshape 的组合:

    my_dtype = numpy.dtype([('Image', h5py.special_dtype(ref=h5py.Reference)), 
                 ('NextLevel', h5py.special_dtype(ref=h5py.Reference))])
    ref_array = array( (image.ref, dataset.ref), dtype=my_dtype)
    dataset = numpy.repeat(ref_array, n*n)
    dataset = dataset.reshape( (n,n) )
    

    注意numpy.repeat 返回一个扁平数组,因此使用numpy.reshape。看来repeat 比广播要快:

    %timeit empty_dataset=np.empty(2*2,dtype=my_dtype); empty_dataset[:]=ref_array
    100000 loops, best of 3: 9.09 us per loop
    
    %timeit repeat_dataset=np.repeat(ref_array, 2*2).reshape((2,2))
    100000 loops, best of 3: 5.92 us per loop
    

    【讨论】:

      猜你喜欢
      • 2017-05-30
      • 2011-03-02
      • 2011-07-18
      • 2013-01-12
      • 2014-02-06
      • 1970-01-01
      • 2014-09-28
      • 1970-01-01
      • 2020-11-10
      相关资源
      最近更新 更多