python - 提高h5py的阅读速度

标签 python numpy hdf5

我在使用 python 的 h5py 包时遇到了一个小问题。我正在处理存储在 hdf5 文件中的非常大的数据集(约 250k 小图像片段),其尺寸为(num_images x color_channels x width x height)

此数据集被随机分为训练数据和验证数据。因此,我需要在训练分类器时读出该数据的随机元素。

对我来说,我有一个奇怪的发现,即加载整个数据集(所有 250k 图像)比读取该数据的特定子集快得多。具体来说,将整个数组读取为:

data = h5py.File("filename.h5", "r")["images"][:]

比我只读出这些图像(25k 图像)的随机、非顺序子集快了大约 5 倍:

indices = [3, 23, 31, 105, 106, 674, ...]
data = h5py.File("filename.h5", "r")["images"][indices, :, :, :]

这是设计使然吗?是因为hdf5文件被压缩了吗?

最佳答案

http://docs.h5py.org/en/latest/high/dataset.html#fancy-indexing

A subset of the NumPy fancy-indexing syntax is supported. Use this with caution, as the underlying HDF5 mechanisms may have different performance than you expect.

Very long lists (> 1000 elements) may produce poor performance

高级索引需要在这里读取一个数据 block ,然后跳过一段距离再读取另一个,依此类推。如果该数据全部在内存中,如在 ndarray 数据缓冲区中,则可以相对较快地完成,尽管比在一个连续 block 中读取相同数量的字节要慢。当该数据在文件中时,您必须包括文件查找和 block 读取。

此外,如果您正在使用分块和压缩:

Chunking has performance implications. It’s recommended to keep the total size of your chunks between 10 KiB and 1 MiB, larger for larger datasets. Also keep in mind that when any element in a chunk is accessed, the entire chunk is read from disk.

我想知道将图像保存为单独的数据集是否会提高性能。然后您将按名称而不是第一维索引检索它们。您必须将它们加入 4d 数组,但我怀疑 h5py 无论如何都必须这样做(它将单独读取它们)。

关于python - 提高h5py的阅读速度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41856463/

相关文章:

python - 我想在应用程序关闭时保存 PyQt5 设置

Python跨平台隐藏文件

python - 如何在 pytables/hdf5 中存储宽表

python - 为什么在神经网络中将误差乘以 sigmoid 的导数?

python - 使用 numpy.random.normal 时如何指定上限和下限

python - HDF5格式的时间序列存储

c++ - 在 hdf5 中使用 std::string 会产生不可读的输出

python 正则表达式 : replacing <number>st, <number>and, <number>the etc in an address with a single sub

python - (Discord.py) 固定消息

python - 使用 sum、np.sum 和 fsum 对数组列表求和时会得到不同的结果吗?