【问题标题】:Load .mat data in Python using Keras使用 Keras 在 Python 中加载 .mat 数据
【发布时间】:2020-04-26 15:09:48
【问题描述】:

我想使用 Keras 在 Python 上运行一个神经网络示例程序。我的数据是 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)

如何加载上面的 .mat 数据以使用 Keras 替换 Python 中的 MNIST 数据集?

from keras.datasets import mnist
(train_data, train_label), (test_data, test_label) = mnist.load_data()

编辑(用于说明目的)

假设我在 .mat 中的 train_data 包含三个数据,大小为 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)

【问题讨论】:

    标签: python matlab keras


    【解决方案1】:

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

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

    【讨论】:

    • scipy.io.loadmat 没有给出任何错误,所以这意味着格式是好的。但没能重塑它。
    【解决方案2】:

    您可以使用scipy.io.loadmat 读取matfiles。详情请阅读相关文档。

    【讨论】:

    • 我已经阅读过,但我不确定如何重塑数据。请查看我的编辑。
    猜你喜欢
    • 2020-06-08
    • 2017-10-14
    • 2018-01-13
    • 2018-05-14
    • 2020-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多