【问题标题】:How to get a non-shuffled train_test_split in sklearn如何在 sklearn 中获得非洗牌的 train_test_split
【发布时间】:2017-10-05 21:21:13
【问题描述】:

如果我想要随机训练/测试拆分,我使用 sklearn 辅助函数:

In [1]: from sklearn.model_selection import train_test_split
   ...: train_test_split([1,2,3,4,5,6])
   ...:
Out[1]: [[1, 6, 4, 2], [5, 3]]

获得非洗牌训练/测试拆分的最简洁方法是什么,即

[[1,2,3,4], [5,6]]

编辑目前我正在使用

train, test = data[:int(len(data) * 0.75)], data[int(len(data) * 0.75):] 

但希望有更好的东西。我在 sklearn 上打开了一个问题 https://github.com/scikit-learn/scikit-learn/issues/8844

编辑 2:我的 PR 已经合并,在 scikit-learn 0.19 版本中,您可以将参数 shuffle=False 传递给 train_test_split 以获得非随机拆分。

【问题讨论】:

    标签: python scikit-learn


    【解决方案1】:

    除了易于复制的粘贴功能外,我不会对 Psidom 的回答添加太多内容:

    def non_shuffling_train_test_split(X, y, test_size=0.2):
        i = int((1 - test_size) * X.shape[0]) + 1
        X_train, X_test = np.split(X, [i])
        y_train, y_test = np.split(y, [i])
        return X_train, X_test, y_train, y_test
    

    更新: 在某些时候,此功能已内置,所以现在您可以这样做:

    from sklearn.model_selection import train_test_split
    train_test_split(X, y, test_size=0.2, shuffle=False)
    

    【讨论】:

      【解决方案2】:

      你需要做的就是将shuffle参数设置为False,将stratify参数设置为None:

          In [49]: train_test_split([1,2,3,4,5,6],shuffle = False, stratify = None)
          Out[49]: [[1, 2, 3, 4], [5, 6]]
      

      【讨论】:

      • 嘿 mayank 实际上 stratify=None 是默认值(请参阅我在原始问题中的“编辑 2”)
      【解决方案3】:

      使用numpy.split:

      import numpy as np
      data = np.array([1,2,3,4,5,6])
      
      np.split(data, [4])           # modify the index here to specify where to split the array
      # [array([1, 2, 3, 4]), array([5, 6])]
      

      如果要按百分比拆分,可以根据数据的形状计算拆分指数:

      data = np.array([1,2,3,4,5,6])
      p = 0.6
      
      idx = int(p * data.shape[0]) + 1      # since the percentage may end up to be a fractional 
                                            # number, modify this as you need, usually shouldn't
                                            # affect much if data is large
      np.split(data, [idx])
      # [array([1, 2, 3, 4]), array([5, 6])]
      

      【讨论】:

      • 谢谢,这看起来就像我想要的,但如果我不知道我想要吐痰的价值怎么办?即说我只想进行 60/40 拆分?
      • 嗯,是的,我希望避免这样的事情,但在这种情况下可能是不可能的,你认为这样做可能更清楚data[:int(len(data)*p)], data[int(len(data)*p):]
      • lenshape 慢吗?
      • 我认为它们在性能方面非常接近。一个简短的时序表明,len1e8 的数组上实际上比shape 快。
      猜你喜欢
      • 1970-01-01
      • 2012-05-26
      • 1970-01-01
      • 2019-03-25
      • 2013-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-28
      相关资源
      最近更新 更多