Python代码:
import h5py
import hdf5storage
from functools import reduce
import numpy as np
from operator import mul
sz = 128,256,512
a = np.random.normal(size=reduce(mul,sz)).reshape(sz)
save_dict = {'data':a}
spath = r"test.mat"
hdf5storage.savemat(spath, mdict=save_dict, append_mat=False,
store_python_metadata=True, format='7.3')
with h5py.File(spath, 'r') as file:
b = np.array(file['data'])
# Reads in the correct shape, but is F-contiguous. Scipy doesn't work with v7.3 files.
c = hdf5storage.loadmat(spath)['data']创建a时,它具有一个形状(128,256,512)。但是,当我使用.mat将a保存到hdf5storage文件,然后使用h5py将其加载到b中时,b会被转换为形状为(512,256,128)的位置。两个数组在检查它们的标志时都是C-连续的。
有什么办法可以防止这种转位的发生吗?我的印象是hdf5格式节省了行-专业。
发布于 2018-09-06 01:10:55
我再次查看了在以下文件中描述的abc.h5文件:
how to import .mat-v7.3 file using h5py
它是在八达屋创建的,包括:
>> A = [1,2,3;4,5,6];
>> B = [1,2,3,4];
>> save -hdf5 abc.h5 A B使用h5py
In [102]: f = h5py.File('abc.h5','r')
In [103]: A = f['A']['value'][:]
In [104]: A
Out[104]:
array([[1., 4.],
[2., 5.],
[3., 6.]])
In [105]: A.shape
Out[105]: (3, 2)
In [106]: A.flags
Out[106]:
C_CONTIGUOUS : True
F_CONTIGUOUS : False
...
In [107]: A.ravel()
Out[107]: array([1., 4., 2., 5., 3., 6.])所以它是一个转置的C级数组。显然,这就是MATLAB开发人员选择在HDF5中存储矩阵的方式。
我可以把它装在朗皮里:
In [108]: At = A.T
In [109]: At
Out[109]:
array([[1., 2., 3.],
[4., 5., 6.]])
In [110]: At.flags
Out[110]:
C_CONTIGUOUS : False
F_CONTIGUOUS : True
....正常情况下,当转换时,C级数组变成F级.
用旧的.mat格式保存的八度矩阵
In [115]: data = io.loadmat('../abc.mat')
In [116]: data['A']
Out[116]:
array([[1., 2., 3.],
[4., 5., 6.]])
In [117]: _.flags
Out[117]:
C_CONTIGUOUS : False
F_CONTIGUOUS : True因此,转换后的h5py数组与io.loadmat使用了相当一段时间的约定相匹配。
我没有在这个操作系统上安装hdf5storage。但是通过您的测试,它遵循了io.loadmat惯例--正确的形状,但F顺序。
https://stackoverflow.com/questions/52194210
复制相似问题