使用Keras在Python中加载.mat数据

3
我想在Python上使用Keras运行一个神经网络样本程序。我的数据以Matlab .mat文件的形式存在。
train_data.mat (size: 32x32x10,000 single)
train_label.mat (size: 1x10,000 single)
test_data.mat (size: 32x32x2,000 single)
test_label.mat (size: 1x2,000 single)

我该如何使用Keras在Python中加载上述.mat数据以替换MNIST数据集?
from keras.datasets import mnist
(train_data, train_label), (test_data, test_label) = mnist.load_data()

编辑(仅供说明)

假设我的.train_data文件是.mat格式,其中包含三个数据,大小为2x2x3。

val(:,:,1) =

     1     1
     1     1


val(:,:,2) =

     2     2
     2     2


val(:,:,3) =

     3     3
     3     3

使用scipy.io.loadmat加载后,它的大小为(2L,2L,3L)。

>>> A
array([[[1, 2, 3],
        [1, 2, 3]],

       [[1, 2, 3],
        [1, 2, 3]]], dtype=uint8)

如何将它重塑为(3L,2L,2L),这意味着三个形状为(2L,2L)的数据? 答案
>>> import scipy.io
>>> A = scipy.io.loadmat('train_data')
>>> B = A.flatten(1)  # flatten to vector
>>> C = B.reshape(3,2,2) # reshape

>>> C
array([[[1, 1],
        [1, 1]],

       [[2, 2],
        [2, 2]],

       [[3, 3],
        [3, 3]]], dtype=uint8)
2个回答

2

正如 @Krishna 所说,您可以使用 scipy.io.loadmat 将 Matlab 文件加载为 numpy 数组。然后,您需要重新整理数据,例如, train_data 需要被整理成 (10000,32,32) 的形状。

但是,如果您拥有的 Matlab 文件是 v7 格式, scipy.io.loadmat 可能会给出错误。在这种情况下,Matlab 文件实际上是以 hdf5 格式存在。您需要使用 h5py 来加载数据。


scipy.io.loadmat 没有报错,这意味着格式是正确的。但是无法重新调整其形状。 - tarako

0

您可以使用scipy.io.loadmat读取.mat文件。请阅读相关文档以获取详细信息。


我已经阅读了它,但不确定如何重新塑造数据。请查看我的编辑。 - tarako

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接