【问题标题】:how to split train and test data from a .mat file in sklearn?如何从 sklearn 中的 .mat 文件中拆分训练和测试数据?
【发布时间】:2021-12-23 07:34:16
【问题描述】:

我有一个 mnist 数据集作为 .mat 文件,并且想使用 sklearn 拆分训练和测试数据。 sklearn 读取 .mat 文件如下:

{'__header__': b'MATLAB 5.0 MAT-file, Platform: GLNXA64, Created on: Sat Oct  8 18:13:47 2016',
 '__version__': '1.0',
 '__globals__': [],
 'train_fea1': array([[0, 0, 0, ..., 0, 0, 0],
        [0, 0, 0, ..., 0, 0, 0],
        [0, 0, 0, ..., 0, 0, 0],
        ...,
        [0, 0, 0, ..., 0, 0, 0],
        [0, 0, 0, ..., 0, 0, 0],
        [0, 0, 0, ..., 0, 0, 0]], dtype=uint8),
 'train_gnd1': array([[ 1],
        [ 1],
        [ 1],
        ...,
        [10],
        [10],
        [10]], dtype=uint8),
 'test_fea1': array([[ 0,  0,  0, ...,  0,  0,  0],
        [ 0,  0,  0, ...,  0,  0,  0],
        [ 0,  0,  0, ...,  0,  0,  0],
        ...,
        [ 0,  0,  0, ...,  0,  0,  0],
        [ 0,  0,  0, ..., 64,  0,  0],
        [ 0,  0,  0, ..., 25,  0,  0]], dtype=uint8),
 'test_gnd1': array([[ 1],
        [ 1],
        [ 1],
        ...,
        [10],
        [10],
        [10]], dtype=uint8)}

怎么做?

【问题讨论】:

    标签: scikit-learn mnist mat train-test-split


    【解决方案1】:

    我猜你的意思是你使用scipy而不是sklearn.mat数据文件加载到Python中。本质上,.mat 数据文件可以像这样加载:

    import scipy.io
    scipy.io.loadmat('your_dot_mat_file')
    

    scipy 将其读取为 Python 字典。因此,在您的情况下,您读取的数据分为训练:train_fea1,具有训练标签train_gnd1 和测试:test_fea1 具有测试标签test_gnd1

    要访问您的数据,您可以:

    import scipy.io as sio
    data = sio.loadmat('filename.mat')
    
    train = data['train_fea1']
    trainlabel = data['train_gnd1']
    
    test = data['test_fea1']
    testlabel = data['test_gnd1']
    

    如果你想用sklearntrain-test-split分割你的数据,你可以先从你的数据中组合特征和标签,然后像这样随机分割(在加载数据后如上所述):

    import numpy as np
    from sklearn.model_selection import train_test_split
    
    X = np.vstack((train,test))
    y = np.vstack((trainlabel, testlabel))
    
    X_train, X_test, y_train, y_test = train_test_split(X, y, \
         test_size=0.2, random_state=42) #random seed for reproducible split
    

    【讨论】:

    • 这完全是一个不同的问题。我建议你发布另一个问题。
    猜你喜欢
    • 1970-01-01
    • 2021-06-28
    • 2018-04-30
    • 2019-08-01
    • 1970-01-01
    • 2021-03-23
    • 2017-09-27
    • 2017-02-20
    • 1970-01-01
    相关资源
    最近更新 更多