pytorch读取HDF5,并自制DataSet
前因
之所以会用到HDF5,是因为我在使用Matlab保存较大的数据文件时,出现了以下警告
警告: 未保存变量 'data'。对于大于 2GB 的变量,请使用 MAT 文件版本 7.3 或更高版本。
在baidu之后,按照如下方式解决了这个问题
但与此同时也出现了新的问题,在我用python读取的时候
import scipy.io
mat = scipy.io.loadmat('test.mat')
提示我一个错误
NotImplementedError: Please use HDF reader for matlab v7.3 files
在百度后,得知需要使用h5py库来进行读取
# 安装h5py
pip install h5py
而对于python读取h5py有一点需要注意:读取入python后,该数组会转置,例如x->(4,3,2) 读取后会变成(2,3,4)
解决方法1、在python中进行转置;2、在matlab进行转置 (均使用permute来进行转置)
h5py dataset编写
class Hdf5DataSet(Dataset):
def __init__(self, data_name, y_name, dataset_data_path, dataset_y_path):
super(Hdf5DataSet, self).__init__()
with h5py.File(dataset_data_path, 'r') as f:
self.length = len(f[data_name]) # to get the length, do not load
self.dataset_data_path = dataset_data_path
self.dataset_y_path = dataset_y_path
self.data_name = data_name
self.y_name = y_name
def __len__(self):
return self.length
def open_data_hdf5(self):
self.data_hdf5 = h5py.File(self.dataset_data_path, 'r')
self.dataset_data = self.data_hdf5[self.data_name][:] # if you want dataset.
def open_y_hdf5(self):
self.y_hdf5 = h5py.File(self.dataset_y_path, 'r')
self.dataset_y = self.y_hdf5[self.y_name][:] # if you want dataset.
def __getitem__(self, index):
if not hasattr(self, 'data_hdf5'):
self.open_data_hdf5()
if not hasattr(self, 'y_hdf5'):
self.open_y_hdf5()
out_data = self.dataset_data[index] # Do loading here
out_y = self.dataset_y[index]
return out_data, out_y
dataset自制的话,需要重写 len 与 getitem 函数
此外, self.data_hdf5[self.data_name][:] 后面的[:] 是因为进行切片操作可以返回一个numpy数组,大大提高后续读取的效率