【问题标题】:how can I split matrix into training testing data whilst ensuring there is at least one value present in the rows and columns of the training matrix?如何将矩阵拆分为训练测试数据,同时确保训练矩阵的行和列中至少存在一个值?
【发布时间】:2019-08-28 19:43:02
【问题描述】:

我想将稀疏矩阵随机拆分为相同维度的训练和测试数据,同时确保训练集中没有全零的列或行。

为了使我的算法正常工作,我需要在训练集的每一行和每一列中至少有一个值。

我尝试过使用这个库函数: 从 sklearn.model_selection 导入 train_test_split

例如给定矩阵:

[[0, 1, 3, 1],
[0, 0, 0, 1],
[8, 0, 0, 1]]

矩阵可以被拆分以产生这个训练矩阵:

[[0, 1, 0, 1],
[0, 0, 0, 0],
[0, 0, 0, 8]]

其中第二行仅包含 0。我怎样才能避免这种情况?

【问题讨论】:

    标签: python machine-learning cross-validation train-test-split


    【解决方案1】:
    from sklearn.model_selection import KFold 
    import numpy as np 
    
    # Create some dummy data
    X = np.array([[1, 2], [3, 4], [1, 2], [3, 4], [0, 0])
    
    # Remove rows having all of their columns equal to 0
    X = X[~np.all(X == 0, axis=1)]
    
    # Assuming 2-fold cross-validation
    kf = KFold(n_splits=2)
    kf.get_n_splits(X)
    

    现在kf 有两个训练/测试折叠:

    for training, testing in kf.split(X):
        X_train, X_test = X[training], X[testing]
    
        # Do whatever you want with your model ...
    
        print(“Training:”, training, “Testing:”, testing)
    
    
    >>> ('Training:', array([2, 3]), 'Testing:', array([0, 1]))
    >>> ('Training:', array([0, 1]), 'Testing:', array([2, 3]))
    

    【讨论】:

    • 非常感谢,最后一个问题,如果我要增加拆分,我将如何定义更多的训练样本?
    • @SophiaBouchama 在交叉验证中,您会生成多个训练和测试实例。你不能接受比测试折叠更多的训练。如果要增加折叠次数,请在实例化 KFold 时更改 n_splits 参数
    • 我仍然得到只有 0 的行和列的矩阵,有没有办法确保训练和测试样本中每行/列至少有一个值?
    • @SophiaBouchama 您能否编辑您的问题并包含一些示例数据?
    • 编辑了我的问题
    猜你喜欢
    • 1970-01-01
    • 2020-01-11
    • 1970-01-01
    • 2020-03-19
    • 1970-01-01
    • 2015-05-25
    • 2016-09-07
    • 2018-04-15
    • 2015-09-23
    相关资源
    最近更新 更多