我找到了一种似乎可行的解决方案!
看一下: 用h5py增量写入hdf5 !
为了将数据附加到特定数据集,必须首先在相应的轴上调整特定数据集的大小,然后在“旧” nparray的末尾附加新数据。
因此,解决方案如下所示:
with h5py.File('.\PreprocessedData.h5', 'a') as hf:
hf["X_train"].resize((hf["X_train"].shape[0] + X_train_data.shape[0]), axis = 0)
hf["X_train"][-X_train_data.shape[0]:] = X_train_data
hf["X_test"].resize((hf["X_test"].shape[0] + X_test_data.shape[0]), axis = 0)
hf["X_test"][-X_test_data.shape[0]:] = X_test_data
hf["Y_train"].resize((hf["Y_train"].shape[0] + Y_train_data.shape[0]), axis = 0)
hf["Y_train"][-Y_train_data.shape[0]:] = Y_train_data
hf["Y_test"].resize((hf["Y_test"].shape[0] + Y_test_data.shape[0]), axis = 0)
hf["Y_test"][-Y_test_data.shape[0]:] = Y_test_data
但是,请注意,您应该使用maxshape=(None,)
创建数据集,例如
h5f.create_dataset('X_train', data=orig_data, compression="gzip", chunks=True, maxshape=(None,))
否则无法扩展数据集。
0
我正在寻找一种使用Python(
h5py
)将数据附加到.h5
文件内的现有数据集的可能性。我的项目的简短介绍:我尝试使用医学图像数据来训练CNN。由于在将数据转换为NumPy数组的过程中大量数据和大量内存的使用,我需要将“转换”分为几个数据块:加载和预处理前100张医学图像,并将NumPy数组保存到hdf5文件,然后加载接下来的100个数据集并附加现有的
.h5
文件,依此类推。现在,我尝试按以下方式存储前100个转换的NumPy数组:
可以看出,将转换后的NumPy数组分为四个不同的“组”,这些“组”存储在四个
hdf5
数据集[X_train, X_test, Y_train, Y_test]
。LoadIPV()
函数执行医学图像数据的预处理。我的问题是我想将下100个NumPy数组存储到同一
.h5
文件中,并存储到现有数据集中:这意味着我X_train
现有的形状为[100, 512, 512, 9]
X_train
数据集[100, 512, 512, 9]
和接下来的100个NumPy数组,使得X_train
的形状为[200, 512, 512, 9]
X_train
[200, 512, 512, 9]
。其他三个数据集X_test
,Y_train
和Y_test
。