python - 如何使用 h5py 在 python 中导入 .mat -v7.3 文件但具有相同的维度顺序?

标签 python h5py

我有几个 .mat 文件,每个文件都包含一个矩阵。我需要使用 h5py 将它们导入到 python 中,因为它们已被 -v7.3 保存。
例如:

*myfile.mat  includes matrix X with the size of (10, 20)*

我在 python 中使用以下命令:

*import numpy np,h5py
f=h5py.File('myfile.mat','r')
data=np.array(f['X'])
data.shape*    ->    **(20, 10)  Here is the problem!**

矩阵 X 已转置。如何在不转置的情况下导入 X?

最佳答案

我认为你必须忍受转置。 MATLAB 如果 F 有序,numpy C 有序(默认情况下)。在 loadmat 线上的某个地方进行了转置。 h5py 没有,因此您必须进行某种转置或重新排序。

顺便说一句,转置numpy数组上最便宜的操作之一。

在 Octave 中保存 (2,3) 数组

octave:27> x=[0,1,2;3,4,5]
octave:28> save 'x34_7.mat' '-7' x
octave:33> save 'x34_h5.mat' '-hdf5' x
octave:32> reshape(x,[1,6])
ans =   0   3   1   4   2   5

加载它。形状是(2,3),但如果F下令:

In [102]: x7=loadmat('x34_7.mat')

In [103]: x7['x']
Out[103]: 
array([[ 0.,  1.,  2.],
       [ 3.,  4.,  5.]])

In [104]: _.flags
Out[104]: 
  C_CONTIGUOUS : False
  F_CONTIGUOUS : True
  ...

查看h5版本:

In [110]: f=h5py.File('x34_h5.mat','r')

In [111]: x5=f['x']['value'][:]
Out[111]: 
array([[ 0.,  3.],
       [ 1.,  4.],
       [ 2.,  5.]])
# C_contiguous

并且x5缓冲区中的数据与Octave中的顺序相同:

In [134]: np.frombuffer(x5.data, float)
Out[134]: array([ 0.,  3.,  1.,  4.,  2.,  5.])

来自 loadmat 的数据也是如此(尽管我必须转置才能使用 frombuffer 查看它(要连续)

In [139]: np.frombuffer(x7.T.data,float)
Out[139]: array([ 0.,  3.,  1.,  4.,  2.,  5.])

(是否有更好的方法来验证 x5.datax7.data 具有相同的内容?)

<小时/>

这种模式适用于更高的维度。在 MATLAB 中,第一维变化最快。由 h5py 加载,该维度对应于最后一个维度。因此,x(:,2,2,2) 对应于 x[1,1,1,:]x.T[:, 1,1,1].

关于python - 如何使用 h5py 在 python 中导入 .mat -v7.3 文件但具有相同的维度顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28785596/

相关文章:

python - 没有名为 'django_simple.todo' 的模块

python - 根据不同数据框中的条件从数据框中读取日期

python - 通过 pip install h5pyViewer 安装 h5pyViewer 时出错

python - 在 h5py 中压缩文件更大

python - 如何使用 h5py 将数据附加到 hdf5 文件中的一个特定数据集

python - h5py 中的引用数组

python - numpy dtype 中的 > < 符号是什么意思?

python - Python中如何让递归程序长时间运行不报RunTimeError

python - 如何在使用 Flask/Socketio 中服务器接口(interface)的服务器端生成 'dummy clients'

tensorflow - Keras 模型到 tensorflow